import { useMemo, useState } from 'react' import { useQuery } from '@tanstack/react-query' import { useGeoRiskScore, useAllQuotes, useCalendar, usePortfolioSummary, useLastScores, useAllPatterns, useMacroRegime, useTradeMtm, useRiskDashboard, useGeoNews, useSimPortfolioRisk, useCycleStatus, useClosedTrades, } from '../hooks/useApi' import { Clock, Globe, ShieldAlert, ArrowUpRight, Brain, Newspaper } from 'lucide-react' import { Link } from 'react-router-dom' import clsx from 'clsx' import type { Quote } from '../types' import { format } from 'date-fns' import { fr } from 'date-fns/locale' import { RadarChart, PolarGrid, PolarAngleAxis, Radar, ResponsiveContainer, AreaChart, Area, XAxis, YAxis, Tooltip, CartesianGrid, } from 'recharts' import { scoreColor } from '../components/TradeIdeas' const riskGauge = (score: number) => { if (score < 25) return { color: 'text-emerald-400', bg: 'bg-emerald-500', label: 'FAIBLE' } if (score < 50) return { color: 'text-yellow-400', bg: 'bg-yellow-500', label: 'MODÉRÉ' } if (score < 75) return { color: 'text-orange-400', bg: 'bg-orange-500', label: 'ÉLEVÉ' } return { color: 'text-red-400', bg: 'bg-red-500', label: 'EXTRÊME' } } const assetEmoji: Record = { energy: '⛽', metals: '🥇', agriculture: '🌾', equities: '📈', indices: '📊', forex: '💱', crypto: '₿', rates: '📉', } const ASSET_COLORS: Record = { energy: '#f97316', metals: '#eab308', agriculture: '#22c55e', indices: '#3b82f6', equities: '#06b6d4', forex: '#8b5cf6', rates: '#64748b', unknown: '#334155', } const REGIME_LABELS: Record = { goldilocks: 'Goldilocks', desinflation: 'Désinflation', stagflation: 'Stagflation', recession: 'Récession', crise_liquidite: 'Crise liq.', reflation: 'Reflation', soft_landing: 'Soft Landing', inflation_shock: 'Infl. Choc', incertain: 'Incertain', } function ViewToggle({ value, onChange }: { value: 'simulated' | 'portfolio'; onChange: (v: 'simulated' | 'portfolio') => void }) { const click = (v: 'simulated' | 'portfolio') => (e: React.MouseEvent) => { e.preventDefault(); e.stopPropagation(); onChange(v) } return (
) } function QuoteRow({ q }: { q: Quote }) { if (!q.price) return null const pos = q.change_pct >= 0 return (
{q.name || q.symbol}
{q.price.toFixed(2)}
{pos ? '+' : ''}{q.change_pct.toFixed(2)}%
) } export default function Dashboard() { const { data: riskScore, isLoading: riskLoading } = useGeoRiskScore() const { data: allQuotes } = useAllQuotes() const { data: calendar } = useCalendar() const { data: portfolio } = usePortfolioSummary() const { data: lastScoresData } = useLastScores() const { data: allPatternsData } = useAllPatterns() const { data: macroData } = useMacroRegime() const { data: tradeMtmData } = useTradeMtm(30) const { data: closedTradesData } = useClosedTrades(90) const { data: riskDashboard } = useRiskDashboard() const { data: simRisk } = useSimPortfolioRisk() const { data: cycleStatusData } = useCycleStatus() const { data: geoNews } = useGeoNews() // Cycle history (last 5 for "Derniers Cycles" card) const { data: cycleHistoryData } = useQuery({ queryKey: ['dash-cycle-history'], queryFn: () => fetch('/api/cycle/history?limit=5').then(r => r.ok ? r.json() : { runs: [] }), staleTime: 60_000, retry: 1, }) // Historical PnL curve + latest VaR snapshot const { data: pnlHistoryData } = useQuery({ queryKey: ['dash-pnl-history'], queryFn: () => fetch('/api/var/pnl/snapshots?limit=200').then(r => r.ok ? r.json() : { snapshots: [] }), staleTime: 120_000, retry: 1, }) const { data: latestVarData } = useQuery({ queryKey: ['dash-var-latest'], queryFn: () => fetch('/api/var/latest').then(r => r.ok ? r.json() : { snapshot: null }), staleTime: 120_000, retry: 1, }) const [pnlView, setPnlView] = useState<'simulated' | 'portfolio'>(() => (localStorage.getItem('dash_pnl_view') as any) ?? 'simulated' ) const [riskView, setRiskView] = useState<'simulated' | 'portfolio'>(() => (localStorage.getItem('dash_risk_view') as any) ?? 'simulated' ) const setPnlViewPersist = (v: 'simulated' | 'portfolio') => { setPnlView(v); localStorage.setItem('dash_pnl_view', v) } const setRiskViewPersist = (v: 'simulated' | 'portfolio') => { setRiskView(v); localStorage.setItem('dash_risk_view', v) } const allPatterns: any[] = allPatternsData ?? [] const scoreMap = useMemo(() => { const map: Record = {} for (const sp of (lastScoresData?.scored_patterns ?? [])) { if (sp.pattern_id) map[sp.pattern_id] = sp } return map }, [lastScoresData]) const macroInfo = useMemo(() => { if (!macroData?.scenarios) return null const sc = macroData.scenarios const dom = sc.dominant ?? 'incertain' const m = sc.meta?.[dom] ?? { label: dom, color: '#94a3b8', emoji: '?' } const assetBias: Record = sc.asset_bias?.[dom] ?? {} // Top 3 scenario scores (excluding dominant, sorted desc) const ranked: [string, number][] = (sc.ranked ?? []).slice(0, 4) return { dominant: dom, label: m.label, color: m.color, emoji: m.emoji, assetBias, ranked } }, [macroData]) const gauge = riskScore ? riskGauge(riskScore.score) : null const radarData = riskScore?.breakdown ? Object.entries(riskScore.breakdown).map(([k, v]) => ({ subject: k.replace('_', ' '), score: v })) : [] // Cycle trades: use scoring_run_id (which differs from cycle run_id) const lastCycle = (cycleStatusData as any)?.last_cycle ?? null const scoringRunId: string | null = lastCycle?.scoring_run_id ?? null const mtmTrades: any[] = (tradeMtmData as any)?.trades ?? [] const cycleTrades = scoringRunId ? mtmTrades.filter((t: any) => t.run_id === scoringRunId) : [] // Patterns from the last cycle only (filter by created_at >= cycle started_at) const cyclePatterns = useMemo(() => { const started = lastCycle?.started_at ?? null if (!started) return [] return [...allPatterns] .filter(p => p.created_at && p.created_at >= started) .sort((a, b) => (scoreMap[b.id]?.score ?? -1) - (scoreMap[a.id]?.score ?? -1)) .slice(0, 4) }, [allPatterns, scoreMap, lastCycle]) // Trades grouped by run_id for cycle history card const tradesByRun = useMemo(() => { const map: Record = {} for (const t of mtmTrades) { if (!t.run_id) continue if (!map[t.run_id]) map[t.run_id] = { logged: 0, closed: 0 } map[t.run_id].logged++ if (t.status === 'closed') map[t.run_id].closed++ } return map }, [mtmTrades]) // Top impactful news const topNews = useMemo(() => [...(geoNews ?? [])] .sort((a, b) => b.impact_score - a.impact_score) .slice(0, 3) , [geoNews]) return (
{/* Header */}

Cockpit GeoOptions

{format(new Date(), "EEEE d MMMM yyyy · HH:mm", { locale: fr })}

{portfolio && portfolio.open_positions > 0 && (
= 0 ? 'text-emerald-400' : 'text-red-400')}> Portfolio: {portfolio.unrealized_pnl >= 0 ? '+' : ''}{portfolio.unrealized_pnl?.toFixed(0)}€
)}
Live
{/* Risk concentration banner */} {(riskDashboard as any)?.concentration_alerts?.length > 0 && (
{((riskDashboard as any).concentration_alerts as any[]).slice(0, 2).map((alert: any, i: number) => (
{alert.message} Risk Dashboard →
))}
)} {/* Top row */}
{/* Geo Risk */}
Risque Géopolitique
News géo
{riskLoading ? (
) : riskScore && gauge ? ( <>
{riskScore.score}
{gauge.label}
{riskScore.top_risks?.map(([cat, val]) => (
{(cat as string).replace('_', ' ')} {Math.round((val as number) * 100)}%
))}
) :
Backend requis
}
{/* Radar */}
Cartographie risques
{radarData.length > 0 ? ( ) :
Chargement...
}
{/* Patterns — AI scores */}
Scores patterns {allPatterns.length > 0 && {allPatterns.length} patterns}
{allPatterns.length === 0 ? (
Backend requis
) : ( [...allPatterns] .sort((a, b) => { const spA = scoreMap[a.id], spB = scoreMap[b.id] const effA = spA ? Math.max(...[0, ...(spA.trade_rankings ?? []).map((r: any) => (spA.score ?? 0) + (r.score_delta ?? 0))]) : -1 const effB = spB ? Math.max(...[0, ...(spB.trade_rankings ?? []).map((r: any) => (spB.score ?? 0) + (r.score_delta ?? 0))]) : -1 return effB - effA }) .map(p => { const sp = scoreMap[p.id] const rawScore = sp?.score ?? null const bestEff = sp ? Math.max(rawScore ?? 0, ...(sp.trade_rankings ?? []).map((r: any) => Math.max(0, Math.min(100, (rawScore ?? 0) + (r.score_delta ?? 0))))) : null const addedDate = p.created_at ? p.created_at.slice(0, 10) : null return (
{p.name} {addedDate && {addedDate}}
{bestEff !== null ? ( {bestEff} ) : ( )}
) }) )}
{/* Calendrier */}
Prochains catalyseurs
{calendar?.slice(0, 4).map((ev, i) => (
{'!'.repeat(ev.importance === 'high' ? 3 : ev.importance === 'medium' ? 2 : 1)}
{ev.title}
{ev.date?.slice(0, 10)}
))}
{/* ── Command Center: Résumé Opérationnel ── */}
{/* PnL */} {(() => { // Unrealized — open trades only (get_trade_entry_prices excludes closed) const openTrades = mtmTrades const openWithPnl = openTrades.filter((t: any) => t.pnl_pct != null) const openCapital = openTrades.reduce((s: number, t: any) => s + (t.capital_invested ?? t.entry_price ?? 0), 0) const openProfit = openWithPnl.reduce((s: number, t: any) => s + ((t.capital_invested ?? t.entry_price ?? 0) * t.pnl_pct / 100), 0) const openPnlPct = openCapital > 0 ? openProfit / openCapital * 100 : null const openWinners = openWithPnl.filter((t: any) => t.pnl_pct > 0).length const openLosers = openWithPnl.filter((t: any) => t.pnl_pct < 0).length const targetHit = openTrades.filter((t: any) => t.alert_type === 'target_reached').length const stopHit = openTrades.filter((t: any) => t.alert_type === 'stop_loss').length // Realized — from dedicated closed-trades endpoint (pnl_realized in %, capital for EUR) const closedTrades = (closedTradesData as any)?.trades ?? [] const closedCapital = closedTrades.reduce((s: number, t: any) => s + (t.capital_invested ?? t.entry_price ?? 0), 0) const closedProfitEur = closedTrades.reduce((s: number, t: any) => { const cap = t.capital_invested ?? t.entry_price ?? 0 return s + (cap * (t.pnl_realized ?? 0) / 100) }, 0) const closedWithPnl = closedTrades.filter((t: any) => t.pnl_realized != null) const avgClosedPct = closedWithPnl.length > 0 ? closedWithPnl.reduce((s: number, t: any) => s + t.pnl_realized, 0) / closedWithPnl.length : null const closedWinners = closedTrades.filter((t: any) => (t.pnl_realized ?? 0) > 0).length const closedLosers = closedTrades.filter((t: any) => (t.pnl_realized ?? 0) < 0).length const isEstimated = openTrades.some((t: any) => t.capital_invested == null && t.entry_price != null) const totalCapital = openCapital + closedCapital const totalProfit = openProfit + closedProfitEur const pf = portfolio as any const pfPnlPct = pf?.unrealized_pnl_pct ?? null const pfPnl = pf?.unrealized_pnl ?? null const pfInvest = pf?.total_invested ?? null const pfReal = pf?.realized_pnl ?? null const pfNet = pf?.net_pnl ?? null return (
📊 P&L
{/* ── Side-by-side: Unrealized | Realized ── */}
{/* Left: Unrealized */}
Ouvertes
{pnlView === 'simulated' ? ( <>
= 0 ? 'text-emerald-400' : 'text-red-400')}> {openPnlPct !== null ? `${openPnlPct >= 0 ? '+' : ''}${openPnlPct.toFixed(1)}%` : '—'}
= 0 ? 'text-emerald-500' : 'text-red-400')}> {openCapital > 0 ? `${openProfit >= 0 ? '+' : ''}${openProfit.toFixed(0)}€` : '—'}
{openTrades.length} trades · {openWinners}✓{' '} {openLosers}✗
) : ( <>
= 0 ? 'text-emerald-400' : 'text-red-400')}> {pfPnlPct !== null ? `${pfPnlPct >= 0 ? '+' : ''}${pfPnlPct.toFixed(1)}%` : '—'}
= 0 ? 'text-emerald-500' : 'text-red-400')}> {pfPnl != null ? `${pfPnl >= 0 ? '+' : ''}${pfPnl.toFixed(0)}€` : '—'}
{pf?.open_positions ?? 0} positions
)} {(targetHit > 0 || stopHit > 0) && (
{targetHit > 0 && 🎯{targetHit}} {stopHit > 0 && ⛔{stopHit}}
)}
{/* Right: Realized */}
Réalisé
{pnlView === 'simulated' ? ( <>
= 0 ? 'text-emerald-400' : 'text-red-400')}> {avgClosedPct !== null ? `${avgClosedPct >= 0 ? '+' : ''}${avgClosedPct.toFixed(2)}%` : closedTrades.length === 0 ? '—' : '+0.00%'}
= 0 ? 'text-emerald-500' : 'text-red-400')}> {closedCapital > 0 ? `${closedProfitEur >= 0 ? '+' : ''}${closedProfitEur.toFixed(0)}€` : closedTrades.length > 0 ? 'sans capital' : ''}
{closedTrades.length} fermés · {closedWinners}✓{' '} {closedLosers}✗
) : ( <>
0 ? 'text-emerald-400' : 'text-red-400')}> {pfReal != null && pfReal !== 0 ? `${pfReal >= 0 ? '+' : ''}${pfReal.toFixed(0)}€` : '—'}
{pfNet != null && (
= 0 ? 'text-emerald-500/70' : 'text-red-400/70')}> net {pfNet >= 0 ? '+' : ''}{pfNet.toFixed(0)}€
)}
{pf?.closed_positions ?? 0} fermées
)}
{/* Total line */}
Investi{isEstimated ? ' ~' : ''} {pnlView === 'simulated' ? (totalCapital > 0 ? `${totalCapital.toFixed(0)}€` : '—') : (pfInvest != null ? `${pfInvest.toFixed(0)}€` : '—')} = 0 ? 'text-emerald-400' : 'text-red-400')}> Total {pnlView === 'simulated' ? (totalCapital > 0 ? `${totalProfit >= 0 ? '+' : ''}${totalProfit.toFixed(0)}€` : '—') : (pfNet != null ? `${pfNet >= 0 ? '+' : ''}${pfNet.toFixed(0)}€` : '—')}
{/* PnL historical sparkline */} {(() => { const snaps: any[] = [...(pnlHistoryData?.snapshots ?? [])].reverse() if (snaps.length < 2) return null const chartData = snaps.map(s => ({ date: s.snapped_at?.slice(5, 10), pnl: s.total_pnl_pct ?? 0, })) const minVal = Math.min(...chartData.map(d => d.pnl)) const maxVal = Math.max(...chartData.map(d => d.pnl)) const isPositive = chartData[chartData.length - 1]?.pnl >= 0 const strokeColor = isPositive ? '#34d399' : '#f87171' const gradId = 'pnlGrad' return (
Courbe PnL historique ({snaps.length} pts)
[`${v >= 0 ? '+' : ''}${Number(v).toFixed(3)}%`, 'PnL']} />
) })()} ) })()} {/* Risk */} {(() => { const risk = simRisk as any const alertCount: number = risk?.alerts?.length ?? 0 const conflictCount: number = risk?.conflicts?.length ?? 0 const openCount: number = risk?.open_count ?? 0 const concentration: Record = risk?.concentration ?? {} const sortedClasses = Object.entries(concentration) .sort(([, a], [, b]) => (b as any).pct - (a as any).pct) .slice(0, 5) return (
🛡️ Risque
0 ? 'text-red-400' : 'text-emerald-400')}> {alertCount > 0 ? `${alertCount} alerte${alertCount > 1 ? 's' : ''}` : 'OK'}
{sortedClasses.length > 0 && (
{sortedClasses.map(([cls, data]: [string, any]) => (
{cls}
{data.bullish > 0 && (
)} {data.bearish > 0 && (
)}
{data.pct}%
))}
haussier baissier {conflictCount > 0 && {conflictCount} conflit{conflictCount > 1 ? 's' : ''}}
)} {sortedClasses.length === 0 && (
{openCount > 0 ? `${openCount} positions` : 'Aucune position'}
)} {/* Latest VaR snapshot */} {(() => { const snap = latestVarData?.snapshot if (!snap) return null const hv = snap.hist_var_1d_pct const cv = snap.hist_cvar_pct const mv = snap.mc_var_1d_pct const ts = snap.computed_at?.slice(0, 16).replace('T', ' ') return (
VaR 95% · {ts} UTC
{[ { label: 'Hist.', val: hv, color: 'text-blue-400' }, { label: 'CVaR', val: cv, color: 'text-orange-400' }, { label: 'MC×1.5', val: mv, color: 'text-red-400' }, ].map(({ label, val, color }) => (
{label}
{val != null ? `${val >= 0 ? '+' : ''}${val.toFixed(2)}%` : '—'}
))}
) })()} ) })()} {/* Derniers Cycles — liste */} {(() => { const runs: any[] = cycleHistoryData?.runs ?? [] return (
🔄 Derniers Cycles
{/* Column headers */}
Date Pat. Log. Clos Régime
{runs.length > 0 ? (
{runs.map((r: any, i: number) => { const dt = r.started_at ? new Date(r.started_at.endsWith('Z') ? r.started_at : r.started_at + 'Z') : null const dateStr = dt ? `${String(dt.getDate()).padStart(2,'0')}/${String(dt.getMonth()+1).padStart(2,'0')} ${String(dt.getHours()).padStart(2,'0')}:${String(dt.getMinutes()).padStart(2,'0')}` : '—' const pat: number = r.patterns_added ?? 0 const tStats = tradesByRun[r.run_id] ?? { logged: 0, closed: 0 } const regime = r.dominant_regime ? (REGIME_LABELS[r.dominant_regime] ?? r.dominant_regime) : '—' const ok = r.status === 'completed' return (
{dateStr} 0 ? 'text-blue-400' : 'text-slate-600')}> +{pat} 0 ? 'text-emerald-400' : 'text-slate-600')}> {tStats.logged} 0 ? 'text-slate-400' : 'text-slate-600')}> {tStats.closed} {regime}
) })}
) : (
Aucun cycle enregistré
)} ) })()} {/* Régime Macro */} {(() => { const dom = macroInfo?.dominant const colorClass = dom === 'growth' || dom === 'goldilocks' || dom === 'soft_landing' ? 'text-emerald-400' : dom === 'stagflation' || dom === 'recession' || dom === 'crise_liquidite' ? 'text-red-400' : dom === 'deflation' || dom === 'desinflation' ? 'text-blue-300' : dom === 'inflation_shock' ? 'text-orange-400' : 'text-slate-400' const ranked = macroInfo?.ranked ?? [] // Key gauges from macroData const gauges = (macroData as any)?.gauges ?? {} const reasons: string[] = dom ? ((macroData as any)?.scenarios?.reasons?.[dom] ?? []) : [] // 5 key indicators that explain the regime const KEY_GAUGES = [ { key: 'vix', label: 'VIX', color: (v: number) => v < 18 ? 'text-emerald-400' : v < 25 ? 'text-yellow-400' : 'text-red-400', fmt: (v: number) => v.toFixed(1), hint: (v: number) => v < 18 ? '↓ risque bas' : v < 25 ? '↑ alerte' : '↑ crise', }, { key: 'spx_vs_200d', label: 'S&P/200j', color: (v: number) => v >= 0 ? 'text-emerald-400' : 'text-red-400', fmt: (v: number) => `${v >= 0 ? '+' : ''}${v.toFixed(1)}%`, hint: (v: number) => v >= 5 ? 'bull fort' : v >= 0 ? 'bull mod.' : 'bear', }, { key: 'slope_10y3m', label: 'Pente 10Y-3M', color: (v: number) => v >= 0.5 ? 'text-emerald-400' : v >= 0 ? 'text-yellow-400' : 'text-red-400', fmt: (v: number) => `${v >= 0 ? '+' : ''}${v.toFixed(2)}`, hint: (v: number) => v >= 0.5 ? 'normale' : v >= 0 ? 'plate' : 'inversée', }, { key: 'copper', label: 'Cuivre', color: (v: number, chg: number) => chg >= 0 ? 'text-emerald-400' : 'text-red-400', fmt: (v: number, chg: number) => `${chg >= 0 ? '+' : ''}${chg.toFixed(2)}%`, hint: (v: number, chg: number) => chg >= 0 ? '↑ croissance' : '↓ ralentis.', }, { key: 'gold', label: 'Or', color: (v: number, chg: number) => chg >= 1 ? 'text-amber-400' : chg <= -1 ? 'text-emerald-400' : 'text-slate-400', fmt: (v: number, chg: number) => `${chg >= 0 ? '+' : ''}${chg.toFixed(2)}%`, hint: (v: number, chg: number) => chg >= 1 ? '↑ refuge' : chg <= -1 ? '↓ risk-on' : '≈ neutre', }, ] return (
🌐 Régime Macro
{macroInfo ? `${macroInfo.emoji} ${macroInfo.label}` : '—'}
{ranked.length > 0 && (
{ranked.slice(0, 4).map(([key, score]: [string, number]) => { const maxScore = ranked[0]?.[1] ?? 1 const pct = Math.round((score / Math.max(maxScore, 1)) * 100) const isDom = key === dom return (
{REGIME_LABELS[key] ?? key}
{score}
) })}
)} {/* Key macro gauges */} {Object.keys(gauges).length > 0 && (
{KEY_GAUGES.map(({ key, label, color, fmt, hint }) => { const g = gauges[key] if (!g) return null const val: number = g.value ?? 0 const chg: number = g.change_pct ?? 0 const c = color(val, chg) const h = hint(val, chg) return (
{label} {fmt(val, chg)} {h}
) })}
)} {/* Trigger signals for dominant regime */} {reasons.length > 0 && (
{reasons.slice(0, 4).map((r: string, i: number) => ( {r} ))}
)} ) })()}
{/* ── Command Center: Intelligence & Contexte ── */}
{/* Top 5 trades loggés */} {(() => { const top5 = [...mtmTrades] .sort((a, b) => (b.pnl_pct ?? -999) - (a.pnl_pct ?? -999)) .slice(0, 5) return (
🏆 Top Trades
{top5.length > 0 ? (
{top5.map((t: any, i: number) => { const pnl: number | null = t.pnl_pct ?? null const isBear = t.strategy?.toLowerCase().includes('put') || t.strategy?.toLowerCase().includes('bear') const entryDate = t.entry_date ? t.entry_date.slice(0, 10) : null return (
{i + 1} {isBear ? '🐻' : '🐂'} {t.underlying ?? '—'} {t.strategy ?? ''} {entryDate && {entryDate}} {pnl !== null ? ( = 0 ? 'text-emerald-400' : 'text-red-400')}> {pnl >= 0 ? '+' : ''}{pnl.toFixed(1)}% ) : ( )}
) })}
) : (
Aucun trade loggé
)} ) })()} {/* Derniers trades loggés */} {(() => { const recent = [...mtmTrades] .filter((t: any) => t.entry_date) .sort((a: any, b: any) => (b.entry_date ?? '').localeCompare(a.entry_date ?? '')) .slice(0, 3) return (
📥 Derniers trades loggés
{recent.length > 0 ? (
{recent.map((t: any, i: number) => { const pnl: number | null = t.pnl_pct ?? null const isBear = t.strategy?.toLowerCase().includes('put') || t.strategy?.toLowerCase().includes('bear') const entryDate = t.entry_date ? t.entry_date.slice(0, 10) : null const score: number | null = t.score_at_entry ?? null return (
{isBear ? '🐻' : '🐂'} {t.underlying ?? '—'} {t.strategy ?? ''} {score !== null && ( {score} )} {pnl !== null ? ( = 0 ? 'text-emerald-400' : 'text-red-400')}> {pnl >= 0 ? '+' : ''}{pnl.toFixed(1)}% ) : ( en cours )}
{entryDate && (
{entryDate} · {t.pattern_name ? {t.pattern_name} : ''}
)}
) })}
) : (
Aucun trade loggé
)} ) })()} {/* Derniers Patterns ajoutés */} {(() => { const recent = [...allPatterns] .filter((p: any) => p.created_at) .sort((a: any, b: any) => (b.created_at ?? '').localeCompare(a.created_at ?? '')) .slice(0, 3) return (
⭐ Derniers Patterns ajoutés
{recent.length > 0 ? (
{recent.map((p: any, i: number) => { const sp = scoreMap[p.id] const score: number | null = sp?.score ?? null const ticker: string | null = sp?.recommended_trade?.underlying ?? null const dateStr = p.created_at ? p.created_at.slice(0, 10) : null return (
{i + 1}
{p.name}
{score !== null ? ( {score} ) : ( )}
{ticker && {ticker}} {ticker && dateStr && ' · '} {dateStr}
) })}
) : (
Aucun pattern enregistré
)} ) })()} {/* Top news impactantes */} {(() => { return (
Top News
{topNews.length > 0 ? (
{topNews.map((n, i) => { const impact = Math.round(n.impact_score * 100) const impactColor = impact >= 70 ? 'text-red-400' : impact >= 40 ? 'text-orange-400' : 'text-yellow-400' const barColor = impact >= 70 ? 'bg-red-500' : impact >= 40 ? 'bg-orange-500' : 'bg-yellow-500' return (
{i + 1}

{n.title}

{impact}
) })}
) : (
Chargement des news…
)} ) })()}
{/* Markets mini overview */}
{['energy', 'metals', 'indices', 'forex'].map(cls => (
{assetEmoji[cls]} {cls}
{allQuotes?.[cls]?.map(q => ) ?? (
Chargement...
)}
))}
) }