feat: option lab

This commit is contained in:
OpenSquared
2026-07-21 17:23:55 +02:00
parent b6e9b96dc4
commit 78eda311f8
7 changed files with 275 additions and 82 deletions

View File

@@ -151,6 +151,20 @@ export const useRemoveWatchlistInstrument = () => {
})
}
export const useSetWatchlistSaxoLink = () => {
const qc = useQueryClient()
return useMutation({
mutationFn: ({ ticker, saxoSymbol }: { ticker: string; saxoSymbol: string | null }) =>
api.put(`/watchlist/${encodeURIComponent(ticker)}/saxo-link`, { saxo_symbol: saxoSymbol }).then(r => r.data),
onSuccess: () => {
qc.invalidateQueries({ queryKey: ['instruments-watchlist'] })
qc.invalidateQueries({ queryKey: ['instruments-watchlist-quotes'] })
qc.invalidateQueries({ queryKey: ['saxo-iv-watchlist'] })
qc.invalidateQueries({ queryKey: ['saxo-watchlist'] })
},
})
}
// Latest cycle report — shares the 'cycle-report-latest' queryKey with RapportIA.tsx
export const useLatestCycleReport = () =>
useQuery({

View File

@@ -1,7 +1,7 @@
import { useState, useEffect } from 'react'
import { Link } from 'react-router-dom'
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query'
import { useSources, useUpdateSources, useUpdateApiKeys, useConfig, useAiStatus, useAnalysisConfig, useSaveAnalysisConfig, useCycleStatus, useUpdateCycleConfig, useTriggerCycle, useCycleStepCatalog, useRiskProfiles, useUpsertProfile, useDeleteProfile, useExitDefaults, useSaveExitDefaults, useOptionsGate, useSaveOptionsGate, useTechIndicatorsConfig, useSaveTechIndicatorsConfig, useInstrumentsWatchlist, useAddWatchlistInstrument, useRemoveWatchlistInstrument, validateTicker, useSaxoStatus, useDisconnectSaxo, useSaxoWatchlist, useUpdateSaxoWatchlist, useSnapshotSaxoNow, useValidateSaxoWatchlist, useSaxoCatalog, useSaxoCatalogSummary, useRefreshSaxoCatalog, useTestSaxoQuote, useSaxoSettings, useUpdateSaxoSettings, useSnapshotAllSaxoNow, useExpandSaxoWatchlist, type CycleStepDef } from '../hooks/useApi'
import { useSources, useUpdateSources, useUpdateApiKeys, useConfig, useAiStatus, useAnalysisConfig, useSaveAnalysisConfig, useCycleStatus, useUpdateCycleConfig, useTriggerCycle, useCycleStepCatalog, useRiskProfiles, useUpsertProfile, useDeleteProfile, useExitDefaults, useSaveExitDefaults, useOptionsGate, useSaveOptionsGate, useTechIndicatorsConfig, useSaveTechIndicatorsConfig, useInstrumentsWatchlist, useAddWatchlistInstrument, useRemoveWatchlistInstrument, useSetWatchlistSaxoLink, validateTicker, useSaxoStatus, useDisconnectSaxo, useSaxoWatchlist, useUpdateSaxoWatchlist, useSnapshotSaxoNow, useValidateSaxoWatchlist, useSaxoCatalog, useSaxoCatalogSummary, useRefreshSaxoCatalog, useTestSaxoQuote, useSaxoSettings, useUpdateSaxoSettings, useSnapshotAllSaxoNow, useExpandSaxoWatchlist, type CycleStepDef } from '../hooks/useApi'
import { Settings, Key, Globe, CheckCircle, XCircle, AlertCircle, Save, Eye, EyeOff, Brain, SlidersHorizontal, RefreshCw, Zap, Plus, Trash2, Pencil, X, Lock, Gauge, DollarSign, TrendingUp, ShieldAlert, DatabaseBackup, Radar, Link2, Unlink, Camera, ShieldCheck, ExternalLink } from 'lucide-react'
import clsx from 'clsx'
@@ -331,6 +331,54 @@ function RiskProfilesCard() {
)
}
// Inline Saxo-symbol link editor for one watchlist row — lets Options Lab's Saxo section
// show only broker data for instruments actually tracked here, instead of relying on an
// independently-managed Saxo watchlist. Linking auto-adds the symbol to the Saxo
// scheduler's watchlist (Config -> Saxo below) so it starts getting snapshotted.
function SaxoLinkPicker({ ticker, saxoSymbol }: { ticker: string; saxoSymbol: string | null }) {
const [editing, setEditing] = useState(false)
const [value, setValue] = useState(saxoSymbol ?? '')
const { mutate: setLink, isPending } = useSetWatchlistSaxoLink()
const { data: catalogMatches } = useSaxoCatalog(undefined, value.length >= 2 ? value : undefined)
const datalistId = `saxo-symbols-${ticker}`
const save = () => {
const sym = value.trim().toUpperCase() || null
setLink({ ticker, saxoSymbol: sym }, { onSuccess: () => setEditing(false) })
}
if (!editing) {
return saxoSymbol ? (
<button onClick={() => setEditing(true)} className="flex items-center gap-1 text-[9px] text-emerald-400 hover:text-emerald-300 bg-emerald-900/20 border border-emerald-700/30 px-1.5 py-0.5 rounded">
<Link2 className="w-2.5 h-2.5" /> {saxoSymbol}
</button>
) : (
<button onClick={() => setEditing(true)} className="flex items-center gap-1 text-[9px] text-slate-500 hover:text-slate-300 border border-slate-700/40 px-1.5 py-0.5 rounded">
<Unlink className="w-2.5 h-2.5" /> Link Saxo
</button>
)
}
return (
<div className="flex items-center gap-1">
<input
autoFocus
list={datalistId}
value={value}
onChange={e => setValue(e.target.value)}
onKeyDown={e => { if (e.key === 'Enter') save(); if (e.key === 'Escape') setEditing(false) }}
onBlur={save}
placeholder="Saxo symbol"
className="bg-dark-800 border border-slate-700/40 rounded px-1.5 py-0.5 text-[9px] text-white w-24 focus:outline-none focus:border-blue-500/50"
/>
<datalist id={datalistId}>
{(catalogMatches ?? []).map((c: any) => <option key={c.symbol} value={c.symbol}>{c.description}</option>)}
</datalist>
{isPending && <span className="text-[9px] text-slate-600"></span>}
</div>
)
}
function WatchlistCard() {
const { data: items, isLoading } = useInstrumentsWatchlist()
const { mutateAsync: addTicker, isPending: adding } = useAddWatchlistInstrument()
@@ -399,9 +447,12 @@ function WatchlistCard() {
<span className="text-[10px] text-slate-500 truncate">{item.name}</span>
<span className="text-[9px] text-slate-700 bg-dark-700 px-1.5 py-0.5 rounded capitalize">{item.asset_class}</span>
</div>
<button onClick={() => removeTicker(item.ticker)} className="text-slate-600 hover:text-red-400 transition-colors">
<X className="w-3.5 h-3.5" />
</button>
<div className="flex items-center gap-2 shrink-0">
<SaxoLinkPicker ticker={item.ticker} saxoSymbol={item.saxo_symbol ?? null} />
<button onClick={() => removeTicker(item.ticker)} className="text-slate-600 hover:text-red-400 transition-colors">
<X className="w-3.5 h-3.5" />
</button>
</div>
</div>
))}
</div>

View File

@@ -5,10 +5,10 @@ import {
useEcoCalendar, usePortfolioSummary, useLastScores, useAllPatterns, useMacroRegime,
useTradeMtm, useRiskDashboard, useGeoNews,
useSimPortfolioRisk, useCycleStatus, useClosedTrades,
useInstrumentsWatchlist, useInstrumentsWatchlistQuotes, useIvBatch, useLatestCycleReport,
useInstrumentsWatchlist, useInstrumentsWatchlistQuotes, useSaxoIvWatchlist, useLatestCycleReport,
useWaveletWatchlistSignals,
} from '../hooks/useApi'
import { Clock, Globe, ShieldAlert, ArrowUpRight, Newspaper, Waves } from 'lucide-react'
import { Clock, Globe, ShieldAlert, ArrowUpRight, Newspaper, Waves, Link2 } from 'lucide-react'
import { Link } from 'react-router-dom'
import clsx from 'clsx'
import type { Quote } from '../types'
@@ -122,16 +122,18 @@ function EcoEventRow({ ev, showActual }: { ev: any; showActual: boolean }) {
<div className="flex items-center gap-1.5 text-[10px]">
<span className="shrink-0">{CURRENCY_FLAGS[ev.currency] ?? ev.currency}</span>
<span className={clsx('w-1.5 h-1.5 rounded-full shrink-0', IMPACT_DOT[ev.impact] ?? 'bg-slate-400')} />
<span className="text-slate-200 truncate flex-1 line-clamp-1 max-w-[108px]" title={ev.event_name}>{ev.event_name}</span>
{showActual && ev.actual_value ? (
<span className="text-[10px] font-mono shrink-0">
<span className="text-white font-semibold">{ev.actual_value}</span>
{ev.forecast_value && <span className="text-slate-400"> /{ev.forecast_value}</span>}
</span>
) : ev.forecast_value ? (
<span className="text-[10px] font-mono text-slate-400 shrink-0">F {ev.forecast_value}</span>
) : null}
{ev.event_time && <span className="text-slate-500 text-[9px] shrink-0 font-mono">{ev.event_time}</span>}
<span className="text-slate-200 truncate line-clamp-1 max-w-[130px] shrink-0" title={ev.event_name}>{ev.event_name}</span>
<div className="ml-auto flex items-center gap-2.5 shrink-0">
{showActual && ev.actual_value ? (
<span className="text-[10px] font-mono">
<span className="text-white font-semibold">{ev.actual_value}</span>
{ev.forecast_value && <span className="text-slate-400"> /{ev.forecast_value}</span>}
</span>
) : ev.forecast_value ? (
<span className="text-[10px] font-mono text-slate-400">F {ev.forecast_value}</span>
) : null}
{ev.event_time && <span className="text-slate-500 text-[9px] font-mono">{ev.event_time}</span>}
</div>
</div>
)
}
@@ -154,8 +156,7 @@ export default function Dashboard() {
const { data: watchlistQuotesData } = useInstrumentsWatchlistQuotes()
const { data: latestCycleReportData } = useLatestCycleReport()
const { data: waveletSignalsData } = useWaveletWatchlistSignals()
const watchlistTickers: string[] = (watchlistItems ?? []).map((w: any) => w.ticker)
const { data: ivBatchData } = useIvBatch(watchlistTickers.join(','))
const { data: saxoIvWatchlistData } = useSaxoIvWatchlist()
// Historical PnL curve + latest VaR snapshot
const { data: pnlHistoryData } = useQuery({
@@ -272,6 +273,11 @@ export default function Dashboard() {
})
}, [watchlistQuotesData])
const watchlistAsOf = useMemo(() => {
const items: any[] = (watchlistQuotesData as any)?.items ?? []
return fmtAsOf(items.map((it: any) => it.timestamp).filter(Boolean).sort().pop())
}, [watchlistQuotesData])
// FF economic events — today (with actual/forecast as they release) + rest of the
// current week (Mon-Sun), grouped by date. Past events beyond today are dropped —
// the point of this card is "am I up to date", not a historical log.
@@ -412,9 +418,12 @@ export default function Dashboard() {
<div ref={watchlistCardRef} className="card col-span-1">
<div className="flex items-center justify-between mb-2">
<div className="section-title mb-0">📡 Watchlist Radar</div>
<Link to="/config" className="flex items-center gap-0.5 text-[10px] text-slate-400 hover:text-slate-300 transition-colors">
Manage <ArrowUpRight className="w-2.5 h-2.5" />
</Link>
<div className="flex items-center gap-1.5">
{watchlistAsOf && <span className="text-[9px] text-slate-500" title="Last quote refresh">MAJ {watchlistAsOf}</span>}
<Link to="/config" className="flex items-center gap-0.5 text-[10px] text-slate-400 hover:text-slate-300 transition-colors">
Manage <ArrowUpRight className="w-2.5 h-2.5" />
</Link>
</div>
</div>
{watchlistRadarData.length > 0 ? (
<>
@@ -435,6 +444,14 @@ export default function Dashboard() {
<span className={clsx('font-mono font-bold w-12 text-right', (it.change_pct ?? 0) >= 0 ? 'text-emerald-400' : 'text-red-400')}>
{it.change_pct != null ? `${it.change_pct >= 0 ? '+' : ''}${it.change_pct.toFixed(2)}%` : '—'}
</span>
<span className="font-mono text-slate-500 w-16 text-right" title="20d realized volatility (annualized) · change vs D-1">
{it.volatility_pct != null ? `σ${it.volatility_pct.toFixed(1)}%` : '—'}
{it.volatility_change_pct != null && Math.abs(it.volatility_change_pct) >= 0.1 && (
<span className={it.volatility_change_pct > 0 ? 'text-orange-400' : 'text-blue-400'}>
{' '}{it.volatility_change_pct >= 0 ? '+' : ''}{it.volatility_change_pct.toFixed(1)}
</span>
)}
</span>
</div>
</div>
))}
@@ -501,7 +518,12 @@ export default function Dashboard() {
style={row1Height ? { height: row1Height } : undefined}>
<div className="flex items-center justify-between mb-1">
<span className="section-title mb-0 text-[10px]">🌐 Macro Regime</span>
<ArrowUpRight className="w-3 h-3 text-slate-500" />
<div className="flex items-center gap-1.5">
{fmtAsOf((macroData as any)?.fetched_at) && (
<span className="text-[9px] text-slate-500" title="Gauges computed at">MAJ {fmtAsOf((macroData as any)?.fetched_at)}</span>
)}
<ArrowUpRight className="w-3 h-3 text-slate-500" />
</div>
</div>
<div className={clsx('text-base font-bold mt-1', colorClass)}>
{macroInfo ? `${macroInfo.emoji} ${macroInfo.label}` : '—'}
@@ -945,41 +967,42 @@ export default function Dashboard() {
)
})()}
{/* Options Lab — IV highlights scoped to the watchlist */}
{/* Options Lab — Saxo-only IV highlights, scoped to watchlist instruments that have
a Saxo symbol linked (Config -> Instruments Watchlist). Deliberately not the
yfinance-based IV batch — matches Options Lab itself, which now only shows Saxo. */}
{(() => {
const watchlist: any[] = watchlistItems ?? []
const snapshots: Record<string, any> = (ivBatchData as any)?.snapshots ?? {}
const highlights = watchlist
.map((w: any) => snapshots[w.ticker])
const linked = watchlist.filter((w: any) => w.saxo_symbol)
const bySaxoSymbol: Record<string, any> = {}
for (const item of ((saxoIvWatchlistData as any)?.items ?? [])) bySaxoSymbol[item.ticker] = item
const highlights = linked
.map((w: any) => bySaxoSymbol[w.saxo_symbol] ? { ...bySaxoSymbol[w.saxo_symbol], watchlistTicker: w.ticker } : null)
.filter(Boolean)
.sort((a: any, b: any) => Math.abs((b.iv_rank ?? 50) - 50) - Math.abs((a.iv_rank ?? 50) - 50))
const asOf = fmtAsOf(highlights.map((h: any) => h.fetched_at).filter(Boolean).sort().pop())
return (
<Link to="/options" ref={optionsLabCardRef} className="card flex flex-col hover:border-slate-600/60 transition-all cursor-pointer">
<div className="flex items-center justify-between mb-1">
<span className="section-title mb-0 text-[10px]">🧪 Options Lab</span>
<div className="flex items-center gap-1.5">
{asOf && <span className="text-[9px] text-slate-600" title="Données IV mises à jour à">MAJ {asOf}</span>}
<ArrowUpRight className="w-3 h-3 text-slate-600" />
<div className="flex items-center gap-1 text-[9px] text-slate-600">
<Link2 className="w-2.5 h-2.5" /> Saxo
</div>
</div>
{watchlist.length === 0 ? (
{linked.length === 0 ? (
<div className="text-[10px] text-slate-600 mt-1">
Add instruments to your watchlist (Config) to see IV highlights
Link a watchlist instrument to a Saxo symbol (Config Instruments Watchlist) to see IV highlights here
</div>
) : highlights.length > 0 ? (
<div className="space-y-1.5 mt-1">
{highlights.map((h: any) => {
const rank = h.iv_rank
const skewPct = h.skew?.skew_pct
const ivCur = h.iv_current_pct
const ivChg = h.iv_change_1d_pct
return (
<div key={h.ticker} className="pb-1 border-b border-slate-700/20 last:border-0">
<div className="flex items-center gap-1.5 text-[10px]">
<span>{rank != null && rank > 80 ? '🔴' : rank != null && rank < 20 ? '🟢' : '⚪'}</span>
<span className="font-mono text-slate-200 font-bold shrink-0">{h.ticker}</span>
<span className="font-mono text-slate-200 font-bold shrink-0">{h.watchlistTicker}</span>
<span className="text-slate-500">IVR {rank != null ? rank.toFixed(0) : '—'}</span>
{ivCur != null && <span className="text-slate-600">· IV {ivCur.toFixed(1)}%</span>}
{ivChg != null && Math.abs(ivChg) >= 0.1 && (
@@ -987,10 +1010,8 @@ export default function Dashboard() {
{ivChg >= 0 ? '+' : ''}{ivChg.toFixed(1)}pt
</span>
)}
{skewPct != null && Math.abs(skewPct) > 3 && (
<span className={clsx('ml-auto text-[9px]', skewPct > 0 ? 'text-orange-400' : 'text-blue-400')}>
skew {skewPct >= 0 ? '+' : ''}{skewPct.toFixed(1)}
</span>
{h.history_days > 0 && (
<span className="ml-auto text-[8px] text-slate-700">{h.history_days}d</span>
)}
</div>
</div>
@@ -998,7 +1019,7 @@ export default function Dashboard() {
})}
</div>
) : (
<div className="text-[10px] text-slate-600 mt-1">Loading IV data</div>
<div className="text-[10px] text-slate-600 mt-1">Waiting for Saxo snapshots to accumulate</div>
)}
</Link>
)

View File

@@ -530,37 +530,44 @@ function WatchlistManager() {
// ── Main page ─────────────────────────────────────────────────────────────────
export default function OptionsLab() {
const { data, isLoading, refetch, isFetching } = useIvWatchlist()
// yfinance-based IV watchlist — disabled per user request (2026-07-21): Options Lab
// should only show Saxo broker data now, linked from Config -> Instruments Watchlist.
// Kept commented out rather than deleted in case yfinance coverage is wanted again
// later (e.g. for symbols with no Saxo link).
//
// const { data, isLoading, refetch, isFetching } = useIvWatchlist()
// const [bootstrapping, setBootstrapping] = useState(false)
// const [bootstrapMsg, setBootstrapMsg] = useState<string | null>(null)
// const items: any[] = data?.items || []
//
// const sellVol = items.filter(i => (i.iv_rank ?? 50) >= 80)
// const buyVol = items.filter(i => i.iv_rank != null && i.iv_rank < 20)
// const neutral = items.filter(i => i.iv_rank != null && i.iv_rank >= 20 && i.iv_rank < 80)
// const noData = items.filter(i => i.iv_rank == null)
//
// const handleBootstrap = async () => {
// setBootstrapping(true)
// setBootstrapMsg(null)
// try {
// await api.post('/options-vol/bootstrap-history')
// setBootstrapMsg('Bootstrap started (~60s) — refresh in 1 minute to see updated IV Ranks.')
// setTimeout(() => refetch(), 70_000)
// } catch {
// setBootstrapMsg('Error during bootstrap.')
// } finally {
// setBootstrapping(false)
// }
// }
//
// // Show bootstrap banner if most items have no meaningful IV Rank (stuck at 50 or null)
// const needsBootstrap = items.length > 0 && items.filter(i => i.iv_rank == null || i.iv_rank === 50).length > items.length * 0.6
const { data: saxoData, isLoading: saxoLoading, refetch: refetchSaxo, isFetching: saxoFetching } = useSaxoIvWatchlist()
const [bootstrapping, setBootstrapping] = useState(false)
const [bootstrapMsg, setBootstrapMsg] = useState<string | null>(null)
const items: any[] = data?.items || []
const saxoItems: any[] = saxoData?.items || []
const sellVol = items.filter(i => (i.iv_rank ?? 50) >= 80)
const buyVol = items.filter(i => i.iv_rank != null && i.iv_rank < 20)
const neutral = items.filter(i => i.iv_rank != null && i.iv_rank >= 20 && i.iv_rank < 80)
const noData = items.filter(i => i.iv_rank == null)
const handleBootstrap = async () => {
setBootstrapping(true)
setBootstrapMsg(null)
try {
await api.post('/options-vol/bootstrap-history')
setBootstrapMsg('Bootstrap started (~60s) — refresh in 1 minute to see updated IV Ranks.')
setTimeout(() => refetch(), 70_000)
} catch {
setBootstrapMsg('Error during bootstrap.')
} finally {
setBootstrapping(false)
}
}
// Show bootstrap banner if most items have no meaningful IV Rank (stuck at 50 or null)
const needsBootstrap = items.length > 0 && items.filter(i => i.iv_rank == null || i.iv_rank === 50).length > items.length * 0.6
return (
<div className="p-6 space-y-5">
{/* yfinance bootstrap banner — disabled along with the yfinance section below.
{needsBootstrap && !bootstrapMsg && (
<div className="flex items-center justify-between gap-3 px-4 py-3 rounded border border-amber-700/40 bg-amber-900/10 text-xs text-amber-300">
<span>⚠️ Insufficient IV history — IV Rank stuck at 50%. Bootstrap 1 year of realized data to calibrate the Rank.</span>
@@ -579,6 +586,7 @@ export default function OptionsLab() {
{bootstrapMsg}
</div>
)}
*/}
<div className="flex items-center justify-between">
<div>
@@ -586,17 +594,9 @@ export default function OptionsLab() {
<Activity className="w-5 h-5 text-blue-400" /> Options Lab
</h1>
<p className="text-xs text-slate-500 mt-0.5">
IV Rank · IV Percentile · Term Structure · Skew · Options Flow
Saxo broker data · IV Rank · Term Structure · Skew
</p>
</div>
<button
onClick={() => refetch()}
disabled={isFetching}
className="flex items-center gap-1.5 text-xs border border-slate-600 text-slate-400 hover:text-slate-200 hover:border-slate-500 px-3 py-1.5 rounded transition-all disabled:opacity-50"
>
<RefreshCw className={clsx('w-3.5 h-3.5', isFetching && 'animate-spin')} />
{isFetching ? 'Loading...' : 'Refresh'}
</button>
</div>
{/* Légende */}
@@ -622,6 +622,7 @@ export default function OptionsLab() {
<strong className="text-slate-500"> Skew +</strong> = puts more expensive than calls (institutional bearish bias)
</div>
{/* yfinance IV watchlist rows — disabled along with the hooks/state above.
{isLoading ? (
<div className="space-y-2">
{[...Array(6)].map((_, i) => <div key={i} className="h-12 animate-pulse bg-dark-700 rounded-lg" />)}
@@ -673,12 +674,13 @@ export default function OptionsLab() {
)}
</div>
)}
*/}
{/* ── Saxo section — deliberately separate from the yfinance watchlist above.
Symbols come from the Saxo watchlist (Config → Saxo), not from IV Watchlist
Manager below — everything here is computed purely from our own accumulated
saxo_option_snapshots, never blended with yfinance IV. ── */}
<div className="pt-2 border-t border-slate-700/40">
{/* ── Saxo section — the only IV data source now. Symbols come from the Saxo
watchlist (Config → Saxo), auto-populated by linking a tracked instrument to a
Saxo symbol (Config → Instruments Watchlist). Computed purely from our own
accumulated saxo_option_snapshots, never blended with yfinance IV. ── */}
<div>
<div className="flex items-center justify-between mb-3">
<div>
<div className="text-sm font-bold text-white flex items-center gap-2">
@@ -713,7 +715,9 @@ export default function OptionsLab() {
)}
</div>
{/* yfinance IV Watchlist Manager — disabled along with the section above.
<WatchlistManager />
*/}
</div>
)
}