This commit is contained in:
2026-04-20 20:40:48 +02:00
parent 463c391d14
commit 53dd49612d
19 changed files with 2435 additions and 4 deletions
+30
View File
@@ -0,0 +1,30 @@
# StockRadar
## Contexte
App de surveillance boursière pour trading personnel sur eToro.
Stack : Go + Svelte, SQLite (modernc.org/sqlite), port 8082.
## Architecture
- cmd/stockradar/main.go → point d'entrée
- internal/db → SQLite migrations
- internal/settings → stockage clés API chiffrées AES-256
- internal/server → HTTP + WebSocket (gorilla/mux)
- frontend/ → Svelte (à créer)
## Objectif
Détecter des opportunités de trading avant les gros mouvements :
- News catalyseurs (SEC EDGAR, GlobeNewswire, Finnhub)
- Analyse technique (RSI, MACD, Volume)
- Screener filtré sur univers eToro uniquement
- Alertes push avant ouverture de marché
## APIs
- eToro API → instruments disponibles + portfolio
- Yahoo Finance → historique + fondamentaux
- Finnhub → news temps réel + earnings calendar
- SEC EDGAR RSS → 8-K + Form 4 insider buying
## Ports occupés
- FlexDXCluster → 8080/8081
- RentalManager → 9000
- StockRadar → 8082
+13
View File
@@ -0,0 +1,13 @@
<!DOCTYPE html>
<html lang="fr">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>StockRadar</title>
<link rel="icon" type="image/svg+xml" href="/favicon.svg" />
</head>
<body>
<div id="app"></div>
<script type="module" src="/src/main.js"></script>
</body>
</html>
+1323
View File
File diff suppressed because it is too large Load Diff
+18
View File
@@ -0,0 +1,18 @@
{
"name": "stockradar-frontend",
"version": "0.1.0",
"type": "module",
"scripts": {
"dev": "vite",
"build": "vite build",
"preview": "vite preview"
},
"dependencies": {
"svelte-spa-router": "^4.0.1"
},
"devDependencies": {
"@sveltejs/vite-plugin-svelte": "^3.0.0",
"svelte": "^4.0.0",
"vite": "^5.0.0"
}
}
+63
View File
@@ -0,0 +1,63 @@
<script>
import Router from 'svelte-spa-router'
import { onMount } from 'svelte'
import Nav from './components/Nav.svelte'
import Notifications from './components/Notifications.svelte'
import Dashboard from './routes/Dashboard.svelte'
import Watchlist from './routes/Watchlist.svelte'
import Screener from './routes/Screener.svelte'
import News from './routes/News.svelte'
import Settings from './routes/Settings.svelte'
import { api } from './lib/api.js'
import { serverStatus } from './lib/store.js'
const routes = {
'/': Dashboard,
'/watchlist': Watchlist,
'/screener': Screener,
'/news': News,
'/settings': Settings,
}
onMount(async () => {
try {
await api.health()
serverStatus.set('ok')
} catch {
serverStatus.set('error')
}
})
</script>
<div class="layout">
<Nav />
<main>
<Router {routes} />
</main>
</div>
<Notifications />
<style>
:global(*, *::before, *::after) { box-sizing: border-box; }
:global(body) {
margin: 0;
background: #0d1117;
color: #e6edf3;
font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', sans-serif;
font-size: 14px;
}
:global(h1, h2, h3) { margin: 0 0 1rem; font-weight: 600; }
:global(button) { cursor: pointer; }
.layout {
display: flex;
min-height: 100vh;
}
main {
flex: 1;
padding: 2rem;
overflow-y: auto;
max-height: 100vh;
}
</style>
+88
View File
@@ -0,0 +1,88 @@
<script>
import { link, location } from 'svelte-spa-router'
import { serverStatus } from '../lib/store.js'
const routes = [
{ path: '/', label: 'Dashboard', icon: '◈' },
{ path: '/watchlist', label: 'Watchlist', icon: '☆' },
{ path: '/screener', label: 'Screener', icon: '⊞' },
{ path: '/news', label: 'News', icon: '⊙' },
{ path: '/settings', label: 'Settings', icon: '⚙' },
]
</script>
<nav>
<div class="brand">
<span class="logo"></span>
<span class="name">StockRadar</span>
<span class="status" class:ok={$serverStatus === 'ok'} class:error={$serverStatus === 'error'}>
{$serverStatus === 'ok' ? '● live' : $serverStatus === 'error' ? '● offline' : '● …'}
</span>
</div>
<ul>
{#each routes as r}
<li class:active={$location === r.path}>
<a href={r.path} use:link>
<span class="icon">{r.icon}</span>
<span>{r.label}</span>
</a>
</li>
{/each}
</ul>
</nav>
<style>
nav {
width: 200px;
min-height: 100vh;
background: #0d1117;
border-right: 1px solid #21262d;
display: flex;
flex-direction: column;
padding: 1.5rem 0;
flex-shrink: 0;
}
.brand {
display: flex;
align-items: center;
gap: 0.5rem;
padding: 0 1.25rem 1.5rem;
border-bottom: 1px solid #21262d;
margin-bottom: 1rem;
}
.logo { font-size: 1.4rem; color: #58a6ff; }
.name { font-weight: 700; color: #e6edf3; font-size: 1rem; }
.status {
font-size: 0.65rem;
color: #6e7681;
margin-left: auto;
}
.status.ok { color: #3fb950; }
.status.error { color: #f85149; }
ul {
list-style: none;
margin: 0;
padding: 0;
}
li a {
display: flex;
align-items: center;
gap: 0.75rem;
padding: 0.6rem 1.25rem;
color: #8b949e;
text-decoration: none;
font-size: 0.9rem;
transition: background 0.15s, color 0.15s;
}
li a:hover { background: #161b22; color: #e6edf3; }
li.active a { background: #161b22; color: #58a6ff; }
.icon { font-size: 1rem; width: 1.2rem; text-align: center; }
</style>
@@ -0,0 +1,40 @@
<script>
import { notifications } from '../lib/store.js'
</script>
<div class="notif-container">
{#each $notifications as n (n.id)}
<div class="notif {n.type}">{n.message}</div>
{/each}
</div>
<style>
.notif-container {
position: fixed;
bottom: 1.5rem;
right: 1.5rem;
display: flex;
flex-direction: column;
gap: 0.5rem;
z-index: 100;
}
.notif {
padding: 0.75rem 1.25rem;
border-radius: 6px;
font-size: 0.875rem;
color: #e6edf3;
background: #21262d;
border-left: 3px solid #58a6ff;
animation: slide-in 0.2s ease;
}
.notif.success { border-color: #3fb950; }
.notif.error { border-color: #f85149; }
.notif.warning { border-color: #d29922; }
@keyframes slide-in {
from { opacity: 0; transform: translateX(1rem); }
to { opacity: 1; transform: translateX(0); }
}
</style>
+24
View File
@@ -0,0 +1,24 @@
const BASE = '/api'
async function request(method, path, body) {
const opts = {
method,
headers: { 'Content-Type': 'application/json' },
}
if (body !== undefined) opts.body = JSON.stringify(body)
const res = await fetch(BASE + path, opts)
if (!res.ok) throw new Error(`${method} ${path}${res.status}`)
return res.json()
}
export const api = {
health: () => request('GET', '/health'),
getSettings: () => request('GET', '/settings'),
saveSettings: (data) => request('POST', '/settings', data),
testKey: (provider) => request('GET', `/settings/test/${provider}`),
getWatchlist: () => request('GET', '/watchlist'),
addTicker: (ticker) => request('POST', '/watchlist', { ticker }),
removeTicker: (ticker) => request('DELETE', `/watchlist/${ticker}`),
getNews: (ticker) => request('GET', `/news${ticker ? `?ticker=${ticker}` : ''}`),
}
+14
View File
@@ -0,0 +1,14 @@
import { writable } from 'svelte/store'
export const serverStatus = writable('unknown') // 'ok' | 'error' | 'unknown'
export const watchlist = writable([])
export const notifications = writable([])
let notifId = 0
export function notify(message, type = 'info') {
const id = ++notifId
notifications.update(n => [...n, { id, message, type }])
setTimeout(() => {
notifications.update(n => n.filter(x => x.id !== id))
}, 4000)
}
+5
View File
@@ -0,0 +1,5 @@
import App from './App.svelte'
const app = new App({ target: document.getElementById('app') })
export default app
+77
View File
@@ -0,0 +1,77 @@
<script>
import { onMount } from 'svelte'
import { api } from '../lib/api.js'
import { serverStatus } from '../lib/store.js'
let health = null
let error = null
onMount(async () => {
try {
health = await api.health()
serverStatus.set('ok')
} catch(e) {
error = e.message
serverStatus.set('error')
}
})
</script>
<div class="page">
<h1>Dashboard</h1>
<div class="cards">
<div class="card">
<div class="card-label">Statut serveur</div>
<div class="card-value" class:green={health} class:red={error}>
{health ? '● En ligne' : error ? '● Hors ligne' : '…'}
</div>
</div>
<div class="card">
<div class="card-label">Port</div>
<div class="card-value">{health?.port ?? '—'}</div>
</div>
<div class="card muted">
<div class="card-label">Signaux actifs</div>
<div class="card-value"></div>
</div>
<div class="card muted">
<div class="card-label">News aujourd'hui</div>
<div class="card-value"></div>
</div>
</div>
<div class="section">
<h2>Activité récente</h2>
<p class="empty">Aucune donnée pour l'instant — configure les clés API dans <a href="#/settings">Settings</a>.</p>
</div>
</div>
<style>
.page h1 { color: #e6edf3; font-size: 1.4rem; }
.cards {
display: grid;
grid-template-columns: repeat(auto-fill, minmax(160px, 1fr));
gap: 1rem;
margin-bottom: 2rem;
}
.card {
background: #161b22;
border: 1px solid #21262d;
border-radius: 8px;
padding: 1.25rem;
}
.card-label { font-size: 0.75rem; color: #8b949e; margin-bottom: 0.5rem; text-transform: uppercase; letter-spacing: 0.05em; }
.card-value { font-size: 1.25rem; font-weight: 600; color: #e6edf3; }
.card-value.green { color: #3fb950; }
.card-value.red { color: #f85149; }
.card.muted .card-value { color: #484f58; }
.section h2 { font-size: 1rem; color: #8b949e; border-bottom: 1px solid #21262d; padding-bottom: 0.5rem; margin-bottom: 1rem; }
.empty { color: #484f58; font-size: 0.875rem; }
.empty a { color: #58a6ff; }
</style>
+148
View File
@@ -0,0 +1,148 @@
<script>
import { onMount } from 'svelte'
import { api } from '../lib/api.js'
import { notify } from '../lib/store.js'
let news = []
let loading = true
let filter = ''
onMount(load)
async function load() {
loading = true
try {
news = await api.getNews(filter || null)
} catch(e) {
notify('Erreur chargement news : ' + e.message, 'error')
news = []
} finally {
loading = false
}
}
function sentimentColor(s) {
if (!s) return ''
if (s === 'positive') return 'green'
if (s === 'negative') return 'red'
return 'neutral'
}
function timeAgo(dateStr) {
if (!dateStr) return ''
const diff = Date.now() - new Date(dateStr).getTime()
const h = Math.floor(diff / 3600000)
if (h < 1) return 'il y a < 1h'
if (h < 24) return `il y a ${h}h`
return `il y a ${Math.floor(h / 24)}j`
}
</script>
<div class="page">
<h1>News</h1>
<div class="toolbar">
<input
bind:value={filter}
placeholder="Filtrer par ticker…"
on:keydown={(e) => e.key === 'Enter' && load()}
/>
<button class="btn-reload" on:click={load}>↻</button>
</div>
{#if loading}
<p class="muted">Chargement…</p>
{:else if news.length === 0}
<p class="empty">Aucune news disponible. Les données arriveront une fois les intégrations API branchées.</p>
{:else}
<div class="news-list">
{#each news as item}
<div class="news-card">
<div class="news-meta">
<span class="ticker">{item.ticker ?? '—'}</span>
<span class="source">{item.source ?? ''}</span>
<span class="time">{timeAgo(item.published_at)}</span>
{#if item.sentiment}
<span class="sentiment {sentimentColor(item.sentiment)}">{item.sentiment}</span>
{/if}
</div>
<div class="news-headline">
{#if item.url}
<a href={item.url} target="_blank" rel="noopener">{item.headline}</a>
{:else}
{item.headline}
{/if}
</div>
</div>
{/each}
</div>
{/if}
</div>
<style>
.page h1 { color: #e6edf3; font-size: 1.4rem; }
.toolbar {
display: flex;
gap: 0.5rem;
margin-bottom: 1.5rem;
max-width: 360px;
}
input {
flex: 1;
background: #161b22;
border: 1px solid #30363d;
border-radius: 6px;
color: #e6edf3;
padding: 0.5rem 0.75rem;
font-size: 0.875rem;
outline: none;
}
input:focus { border-color: #58a6ff; }
input::placeholder { color: #484f58; }
.btn-reload {
background: #21262d;
border: 1px solid #30363d;
border-radius: 6px;
color: #8b949e;
padding: 0.5rem 0.75rem;
font-size: 1rem;
}
.btn-reload:hover { color: #e6edf3; background: #30363d; }
.news-list { display: flex; flex-direction: column; gap: 0.75rem; }
.news-card {
background: #161b22;
border: 1px solid #21262d;
border-radius: 8px;
padding: 1rem 1.25rem;
transition: border-color 0.15s;
}
.news-card:hover { border-color: #30363d; }
.news-meta {
display: flex;
align-items: center;
gap: 0.75rem;
margin-bottom: 0.4rem;
font-size: 0.75rem;
}
.ticker { color: #58a6ff; font-weight: 600; }
.source { color: #8b949e; }
.time { color: #484f58; margin-left: auto; }
.sentiment { padding: 0.1rem 0.4rem; border-radius: 3px; font-size: 0.7rem; font-weight: 500; }
.sentiment.green { background: #0d2c1a; color: #3fb950; }
.sentiment.red { background: #2c0d0d; color: #f85149; }
.sentiment.neutral { background: #1c1c1c; color: #8b949e; }
.news-headline { font-size: 0.9rem; color: #c9d1d9; line-height: 1.4; }
.news-headline a { color: #c9d1d9; text-decoration: none; }
.news-headline a:hover { color: #58a6ff; }
.empty, .muted { color: #484f58; font-size: 0.875rem; }
</style>
+89
View File
@@ -0,0 +1,89 @@
<script>
// Screener — sera branché sur les données réelles une fois les API intégrées
let filters = { minRsi: '', maxRsi: '', minVolume: '', sector: '' }
</script>
<div class="page">
<h1>Screener</h1>
<div class="filters">
<div class="filter-group">
<label for="rsi-min">RSI min</label>
<input id="rsi-min" type="number" bind:value={filters.minRsi} placeholder="ex: 30" min="0" max="100" />
</div>
<div class="filter-group">
<label for="rsi-max">RSI max</label>
<input id="rsi-max" type="number" bind:value={filters.maxRsi} placeholder="ex: 70" min="0" max="100" />
</div>
<div class="filter-group">
<label for="vol-min">Volume min</label>
<input id="vol-min" type="number" bind:value={filters.minVolume} placeholder="ex: 1000000" />
</div>
<div class="filter-group">
<label for="sector">Secteur</label>
<input id="sector" type="text" bind:value={filters.sector} placeholder="Technology…" />
</div>
<button class="btn-scan" disabled>
Scan (bientôt disponible)
</button>
</div>
<div class="placeholder">
<div class="icon"></div>
<p>Le screener sera disponible après l'intégration Yahoo Finance / Finnhub.</p>
<p class="hint">Il filtrera l'univers eToro sur RSI, MACD, volume et catalyseurs news.</p>
</div>
</div>
<style>
.page h1 { color: #e6edf3; font-size: 1.4rem; }
.filters {
display: flex;
flex-wrap: wrap;
gap: 1rem;
align-items: flex-end;
margin-bottom: 2rem;
padding: 1.25rem;
background: #161b22;
border: 1px solid #21262d;
border-radius: 8px;
}
.filter-group { display: flex; flex-direction: column; gap: 0.3rem; }
label { font-size: 0.75rem; color: #8b949e; text-transform: uppercase; letter-spacing: 0.05em; }
input {
background: #0d1117;
border: 1px solid #30363d;
border-radius: 6px;
color: #e6edf3;
padding: 0.45rem 0.65rem;
font-size: 0.875rem;
outline: none;
width: 130px;
}
input:focus { border-color: #58a6ff; }
input::placeholder { color: #484f58; }
.btn-scan {
background: #1f6feb;
border: none;
border-radius: 6px;
color: #fff;
padding: 0.5rem 1.25rem;
font-size: 0.875rem;
font-weight: 500;
align-self: flex-end;
}
.btn-scan:disabled { opacity: 0.4; cursor: not-allowed; }
.placeholder {
text-align: center;
padding: 3rem;
color: #484f58;
}
.placeholder .icon { font-size: 2.5rem; margin-bottom: 1rem; }
.placeholder p { margin: 0.3rem 0; font-size: 0.9rem; }
.placeholder .hint { font-size: 0.8rem; color: #30363d; }
</style>
+160
View File
@@ -0,0 +1,160 @@
<script>
import { onMount } from 'svelte'
import { api } from '../lib/api.js'
import { notify } from '../lib/store.js'
const providers = [
{ key: 'finnhub_api_key', label: 'Finnhub', provider: 'finnhub', placeholder: 'c_xxxxxxxxxxxxxxxx' },
{ key: 'alphavantage_key', label: 'Alpha Vantage', provider: 'alphavantage', placeholder: 'XXXXXXXXXXXX' },
{ key: 'etoro_api_key', label: 'eToro', provider: 'etoro', placeholder: 'eToro API key' },
]
let values = {}
let testing = {}
let testResults = {}
let saving = false
onMount(async () => {
try {
const data = await api.getSettings()
for (const p of providers) {
values[p.key] = data[p.key] === '********' ? '' : (data[p.key] ?? '')
}
} catch(e) {
notify('Impossible de charger les settings : ' + e.message, 'error')
}
})
async function save() {
saving = true
try {
const body = {}
for (const p of providers) {
if (values[p.key]) body[p.key] = values[p.key]
}
await api.saveSettings(body)
notify('Settings sauvegardés', 'success')
} catch(e) {
notify('Erreur sauvegarde : ' + e.message, 'error')
} finally {
saving = false
}
}
async function testKey(p) {
testing[p.provider] = true
testResults[p.provider] = null
try {
const r = await api.testKey(p.provider)
testResults[p.provider] = r.status === 'ok' ? 'ok' : 'error'
notify(`${p.label} : ${r.status === 'ok' ? 'clé valide' : r.message}`, r.status === 'ok' ? 'success' : 'error')
} catch(e) {
testResults[p.provider] = 'error'
notify(`${p.label} : erreur de connexion`, 'error')
} finally {
testing[p.provider] = false
}
}
</script>
<div class="page">
<h1>Settings</h1>
<form on:submit|preventDefault={save}>
<section>
<h2>Clés API</h2>
<p class="hint">Les clés sont stockées chiffrées (AES-256). Les champs vides conservent la valeur existante.</p>
{#each providers as p}
<div class="field">
<label for={p.key}>{p.label}</label>
<div class="input-row">
<input
id={p.key}
type="password"
bind:value={values[p.key]}
placeholder={p.placeholder}
autocomplete="off"
/>
<button
type="button"
class="btn-test"
class:ok={testResults[p.provider] === 'ok'}
class:error={testResults[p.provider] === 'error'}
disabled={testing[p.provider]}
on:click={() => testKey(p)}
>
{testing[p.provider] ? '…' : testResults[p.provider] === 'ok' ? '✓' : testResults[p.provider] === 'error' ? '✗' : 'Tester'}
</button>
</div>
</div>
{/each}
</section>
<div class="actions">
<button type="submit" class="btn-primary" disabled={saving}>
{saving ? 'Sauvegarde…' : 'Sauvegarder'}
</button>
</div>
</form>
</div>
<style>
.page h1 { color: #e6edf3; font-size: 1.4rem; }
form { max-width: 560px; }
section { margin-bottom: 2rem; }
h2 { font-size: 0.875rem; text-transform: uppercase; letter-spacing: 0.08em; color: #8b949e; border-bottom: 1px solid #21262d; padding-bottom: 0.5rem; margin-bottom: 1.25rem; }
.hint { font-size: 0.8rem; color: #484f58; margin: -0.75rem 0 1.25rem; }
.field { margin-bottom: 1.25rem; }
label { display: block; font-size: 0.875rem; color: #8b949e; margin-bottom: 0.4rem; }
.input-row { display: flex; gap: 0.5rem; }
input {
flex: 1;
background: #161b22;
border: 1px solid #30363d;
border-radius: 6px;
color: #e6edf3;
padding: 0.5rem 0.75rem;
font-size: 0.875rem;
outline: none;
transition: border-color 0.15s;
}
input:focus { border-color: #58a6ff; }
input::placeholder { color: #484f58; }
.btn-test {
background: #21262d;
border: 1px solid #30363d;
border-radius: 6px;
color: #8b949e;
padding: 0.5rem 0.75rem;
font-size: 0.8rem;
min-width: 64px;
transition: background 0.15s, color 0.15s;
}
.btn-test:hover:not(:disabled) { background: #30363d; color: #e6edf3; }
.btn-test.ok { color: #3fb950; border-color: #3fb950; }
.btn-test.error { color: #f85149; border-color: #f85149; }
.btn-test:disabled { opacity: 0.5; }
.actions { padding-top: 1rem; }
.btn-primary {
background: #1f6feb;
border: none;
border-radius: 6px;
color: #fff;
padding: 0.6rem 1.5rem;
font-size: 0.9rem;
font-weight: 500;
transition: background 0.15s;
}
.btn-primary:hover:not(:disabled) { background: #388bfd; }
.btn-primary:disabled { opacity: 0.5; }
</style>
+171
View File
@@ -0,0 +1,171 @@
<script>
import { onMount } from 'svelte'
import { api } from '../lib/api.js'
import { notify } from '../lib/store.js'
let items = []
let newTicker = ''
let loading = true
let adding = false
onMount(load)
async function load() {
try {
items = await api.getWatchlist()
} catch(e) {
notify('Erreur chargement watchlist : ' + e.message, 'error')
} finally {
loading = false
}
}
async function add() {
if (!newTicker.trim()) return
adding = true
try {
await api.addTicker(newTicker.trim().toUpperCase())
newTicker = ''
await load()
notify('Ticker ajouté', 'success')
} catch(e) {
notify('Erreur : ' + e.message, 'error')
} finally {
adding = false
}
}
async function remove(ticker) {
try {
await api.removeTicker(ticker)
await load()
notify(`${ticker} supprimé`, 'info')
} catch(e) {
notify('Erreur : ' + e.message, 'error')
}
}
</script>
<div class="page">
<h1>Watchlist</h1>
<form class="add-form" on:submit|preventDefault={add}>
<input
bind:value={newTicker}
placeholder="AAPL, TSLA, NVDA…"
maxlength="10"
disabled={adding}
/>
<button type="submit" class="btn-primary" disabled={adding || !newTicker.trim()}>
{adding ? '…' : '+ Ajouter'}
</button>
</form>
{#if loading}
<p class="muted">Chargement…</p>
{:else if items.length === 0}
<p class="empty">Aucun ticker dans la watchlist. Ajoutes-en un ci-dessus.</p>
{:else}
<table>
<thead>
<tr>
<th>Ticker</th>
<th>Nom</th>
<th>Secteur</th>
<th>Exchange</th>
<th></th>
</tr>
</thead>
<tbody>
{#each items as item}
<tr>
<td class="ticker">{item.ticker}</td>
<td>{item.name ?? '—'}</td>
<td>{item.sector ?? '—'}</td>
<td>{item.exchange ?? '—'}</td>
<td>
<button class="btn-remove" on:click={() => remove(item.ticker)}>✕</button>
</td>
</tr>
{/each}
</tbody>
</table>
{/if}
</div>
<style>
.page h1 { color: #e6edf3; font-size: 1.4rem; }
.add-form {
display: flex;
gap: 0.5rem;
margin-bottom: 1.5rem;
max-width: 400px;
}
input {
flex: 1;
background: #161b22;
border: 1px solid #30363d;
border-radius: 6px;
color: #e6edf3;
padding: 0.5rem 0.75rem;
font-size: 0.875rem;
outline: none;
text-transform: uppercase;
}
input:focus { border-color: #58a6ff; }
input::placeholder { color: #484f58; text-transform: none; }
.btn-primary {
background: #1f6feb;
border: none;
border-radius: 6px;
color: #fff;
padding: 0.5rem 1rem;
font-size: 0.875rem;
font-weight: 500;
white-space: nowrap;
}
.btn-primary:disabled { opacity: 0.5; }
table {
width: 100%;
border-collapse: collapse;
font-size: 0.875rem;
}
th {
text-align: left;
color: #8b949e;
font-weight: 500;
padding: 0.5rem 1rem;
border-bottom: 1px solid #21262d;
font-size: 0.75rem;
text-transform: uppercase;
letter-spacing: 0.05em;
}
td {
padding: 0.75rem 1rem;
border-bottom: 1px solid #161b22;
color: #e6edf3;
}
tr:hover td { background: #161b22; }
.ticker { font-weight: 600; color: #58a6ff; }
.btn-remove {
background: none;
border: none;
color: #484f58;
font-size: 0.875rem;
padding: 0.2rem 0.4rem;
border-radius: 4px;
transition: color 0.15s, background 0.15s;
}
.btn-remove:hover { color: #f85149; background: #1c1c1c; }
.empty, .muted { color: #484f58; font-size: 0.875rem; }
</style>
+22
View File
@@ -0,0 +1,22 @@
import { defineConfig } from 'vite'
import { svelte } from '@sveltejs/vite-plugin-svelte'
export default defineConfig({
plugins: [svelte()],
server: {
port: 5173,
proxy: {
'/api': {
target: 'http://localhost:8082',
changeOrigin: true,
},
'/ws': {
target: 'ws://localhost:8082',
ws: true,
},
},
},
build: {
outDir: 'dist',
},
})
+52
View File
@@ -0,0 +1,52 @@
package server
import (
"database/sql"
"encoding/json"
"net/http"
)
type newsItem struct {
ID int `json:"id"`
Ticker string `json:"ticker"`
Headline string `json:"headline"`
Source string `json:"source"`
URL string `json:"url"`
Sentiment string `json:"sentiment"`
PublishedAt string `json:"published_at"`
}
func (s *Server) handleGetNews(w http.ResponseWriter, r *http.Request) {
ticker := r.URL.Query().Get("ticker")
var rows *sql.Rows
var err error
if ticker != "" {
rows, err = s.db.Query(`
SELECT id, COALESCE(ticker,''), headline, COALESCE(source,''), COALESCE(url,''), COALESCE(sentiment,''), COALESCE(published_at,'')
FROM news WHERE ticker = ? ORDER BY published_at DESC LIMIT 100`, ticker)
} else {
rows, err = s.db.Query(`
SELECT id, COALESCE(ticker,''), headline, COALESCE(source,''), COALESCE(url,''), COALESCE(sentiment,''), COALESCE(published_at,'')
FROM news ORDER BY published_at DESC LIMIT 100`)
}
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
defer rows.Close()
items := []newsItem{}
for rows.Next() {
var it newsItem
if err := rows.Scan(&it.ID, &it.Ticker, &it.Headline, &it.Source, &it.URL, &it.Sentiment, &it.PublishedAt); err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
items = append(items, it)
}
w.Header().Set("Content-Type", "application/json")
json.NewEncoder(w).Encode(items)
}
+71
View File
@@ -0,0 +1,71 @@
package server
import (
"encoding/json"
"net/http"
"github.com/gorilla/mux"
)
type watchlistItem struct {
ID int `json:"id"`
Ticker string `json:"ticker"`
Name string `json:"name"`
Sector string `json:"sector"`
Exchange string `json:"exchange"`
Active int `json:"active"`
}
func (s *Server) handleGetWatchlist(w http.ResponseWriter, r *http.Request) {
rows, err := s.db.Query(`SELECT id, ticker, COALESCE(name,''), COALESCE(sector,''), COALESCE(exchange,''), active FROM watchlist WHERE active=1 ORDER BY ticker`)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
defer rows.Close()
items := []watchlistItem{}
for rows.Next() {
var it watchlistItem
if err := rows.Scan(&it.ID, &it.Ticker, &it.Name, &it.Sector, &it.Exchange, &it.Active); err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
items = append(items, it)
}
w.Header().Set("Content-Type", "application/json")
json.NewEncoder(w).Encode(items)
}
func (s *Server) handleAddWatchlist(w http.ResponseWriter, r *http.Request) {
var body struct {
Ticker string `json:"ticker"`
}
if err := json.NewDecoder(r.Body).Decode(&body); err != nil || body.Ticker == "" {
http.Error(w, "ticker required", http.StatusBadRequest)
return
}
_, err := s.db.Exec(`INSERT OR IGNORE INTO watchlist (ticker) VALUES (?)`, body.Ticker)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusCreated)
w.Write([]byte(`{"status":"added"}`))
}
func (s *Server) handleRemoveWatchlist(w http.ResponseWriter, r *http.Request) {
ticker := mux.Vars(r)["ticker"]
_, err := s.db.Exec(`DELETE FROM watchlist WHERE ticker = ?`, ticker)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
w.Header().Set("Content-Type", "application/json")
w.Write([]byte(`{"status":"removed"}`))
}
+27 -4
View File
@@ -34,19 +34,42 @@ func New(database *db.DB, port string) (*Server, error) {
}
func (s *Server) setupRoutes() {
s.router.Use(corsMiddleware)
api := s.router.PathPrefix("/api").Subrouter()
api.HandleFunc("/health", s.handleHealth).Methods("GET")
api.HandleFunc("/health", s.handleHealth).Methods("GET", "OPTIONS")
// Settings
api.HandleFunc("/settings", s.handleGetSettings).Methods("GET")
api.HandleFunc("/settings", s.handleSaveSettings).Methods("POST")
api.HandleFunc("/settings/test/{provider}", s.handleTestKey).Methods("GET")
api.HandleFunc("/settings", s.handleGetSettings).Methods("GET", "OPTIONS")
api.HandleFunc("/settings", s.handleSaveSettings).Methods("POST", "OPTIONS")
api.HandleFunc("/settings/test/{provider}", s.handleTestKey).Methods("GET", "OPTIONS")
// Watchlist
api.HandleFunc("/watchlist", s.handleGetWatchlist).Methods("GET", "OPTIONS")
api.HandleFunc("/watchlist", s.handleAddWatchlist).Methods("POST", "OPTIONS")
api.HandleFunc("/watchlist/{ticker}", s.handleRemoveWatchlist).Methods("DELETE", "OPTIONS")
// News
api.HandleFunc("/news", s.handleGetNews).Methods("GET", "OPTIONS")
s.router.PathPrefix("/").HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
fmt.Fprintf(w, "StockRadar API running")
})
}
func corsMiddleware(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Access-Control-Allow-Origin", "*")
w.Header().Set("Access-Control-Allow-Methods", "GET, POST, DELETE, OPTIONS")
w.Header().Set("Access-Control-Allow-Headers", "Content-Type")
if r.Method == "OPTIONS" {
w.WriteHeader(http.StatusNoContent)
return
}
next.ServeHTTP(w, r)
})
}
func (s *Server) handleHealth(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
fmt.Fprintf(w, `{"status":"ok","port":"%s"}`, s.port)