367 Commits

Author SHA1 Message Date
OpenSquared
50ba75e468 feat: Phase 3 — indicateurs techniques calibrés par horizon option
- technical_indicators.py (nouveau) : compute_indicators() calcule RSI, MA fast/slow,
  Bollinger Bands, ATR — périodes calibrées automatiquement selon horizon_days
- config.py : endpoints GET/PUT /config/tech-indicators (activé, liste, auto-calibration)
- useApi.ts : useTechIndicatorsConfig + useSaveTechIndicatorsConfig hooks
- Config.tsx : carte "Indicateurs techniques" dans Options—Paramètres avec toggles
- auto_cycle.py : compute top-5 tickers à chaque cycle si tech_indicators_enabled=true
- ai_analyzer.py : tech_indicators_block injecté dans suggestion + scoring prompts

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-06-20 16:41:42 +02:00
OpenSquared
d5e31bc897 feat: Phase 1 — delta temporel + decay news + cycle_meta dans prompts IA
- database.py: get_last_completed_cycle_ts() pour mesurer le delta entre cycles
- auto_cycle.py: calcul delta_minutes + cycle_meta dict transmis aux fonctions IA
- ai_analyzer.py: apply_news_decay() (halflife par catégorie), partition_news_by_age()
  (3 buckets: inter_cycle / recent_24h / older), _build_temporal_news_block() pour
  le prompt suggestion; cycle_meta injecté aussi dans score_patterns_with_context()

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-06-20 16:36:54 +02:00
OpenSquared
fff0c15316 fix: P&L Réalisé dashboard — source useClosedTrades au lieu de mtmTrades
get_trade_entry_prices filtre WHERE status='open', les trades fermés n'y
apparaissaient jamais. Réalisé branche maintenant sur useClosedTrades(90)
avec calcul EUR = capital * pnl_realized% / 100 et affichage avg %.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-06-20 11:34:07 +02:00
OpenSquared
d4a016a535 feat: P&L côte à côte (Ouvert|Réalisé) + filtres journal + suppression trades fermés
- Dashboard: P&L card séparé en deux colonnes (Ouvertes/Réalisées) pour Simulé et Portfolio
- Dashboard: closed trades P&L locked from pnl_realized, ne fluctue plus après fermeture
- Journal Ouvert: filtres ticker/stratégie + classe d'actif + direction (haussier/baissier)
- Journal Fermés: mêmes filtres + filtre P&L (gagnants/perdants) + bouton supprimer par ligne
- Journal Non loggés: filtres ticker + classe d'actif + raison de skip
- Backend: DELETE /api/journal/trades/{id} + delete_trade() dans database.py

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-06-20 11:00:31 +02:00
OpenSquared
39da3b8945 feat: Config tab "Options — Paramètres" with IV gate controls + exit params
- New tab replaces "Journal & Sortie" — consolidates all options-specific settings
- IV Gate section: toggle on/off + 3 sliders (IVR High/Extreme/Skew threshold)
  with live color-coded summary and interdependency guards (high < extreme)
- Exit params section: target, stop-loss, reversal mode + threshold (moved from removed journal tab)
- Backend: GET/PUT /api/config/options-gate endpoint reads/writes 4 config DB keys
- useApi.ts: useOptionsGate + useSaveOptionsGate hooks

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-06-20 10:23:31 +02:00
OpenSquared
c7ccf237d7 feat: IV gate — block ALERT trades before logging + configurable thresholds
- auto_cycle.py: pre-fetch IV snapshots at step 1.9; _apply_iv_gate() runs
  before log_trade_entries, removes ALERT-verdict trades (not just reports)
- options_technical_agent.py: _IVR_HIGH/_IVR_EXTREME/_SKEW_THRESH as
  module-level vars; straddle/strangle penalty -60 (vs -56 naked) at extreme IVR
  so Long Straddle at IVR ≥ 80% → ALERT; thresholds respected in rule engine
- database.py: seed 4 iv_gate config keys (iv_gate_enabled, iv_gate_ivr_high=60,
  iv_gate_ivr_extreme=80, iv_gate_skew_threshold=8) — editable from Config page
- Blocked trades logged as skipped_trades with [IV_GATE] detail + optimal strategy

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-06-20 10:15:45 +02:00
OpenSquared
3ee39d5f08 feat: options technical agent — IV/skew/term structure validation per trade
- New options_technical_agent.py: rule engine (IVR, skew, term structure, flow)
  + GPT-4o narrative per trade; verdict OK/WARN/ALERT + fit_score
- options_trade_assessments table in DB for Journal badge persistence
- auto_cycle.py step 5.2: assess newly logged trades after log_trade_entries;
  results embedded in cycle report
- suggest_patterns_from_market_context: +iv_context param + explicit IV→strategy
  rules in prompt (IVR<30%→Long, 30-60%→Spread, >60%→no naked long, >80%→short)
- Pre-fetch iv_context at step 1.9 so suggestion step gets strategy rules
- reports.py: /api/reports/assessments/latest + /assessments/{run_id} endpoints
- RapportIA.tsx: "Validation Technique Options" section with per-trade IVBar,
  VerdictBadge, issues list, GPT-4o analysis, optimal strategy suggestion

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-06-20 09:36:35 +02:00
OpenSquared
1aadf98fe4 fix: unhashable dict dans context narrative + normalisation tickers EUR/USD pour VaR
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-06-20 09:08:54 +02:00
OpenSquared
e2d5bebef4 feat: Rapport de Cycle — auto-généré à chaque run avec contexte IA, delta, PnL/VaR snapshot
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-06-20 07:57:41 +02:00
OpenSquared
85975f6248 feat: Derniers Cycles liste + Derniers trades loggés + Derniers Patterns
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-06-20 07:10:02 +02:00
OpenSquared
a27949e9f7 fix: hauteur fixe égale (288px) sur les 4 cards Command Center
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-06-20 06:58:47 +02:00
OpenSquared
2a77007dc3 feat: jauges macro + signaux déclencheurs dans card Régime Macro
Partie basse de la card : 5 indicateurs clés expliquant le régime
(VIX, S&P vs 200j MA, Pente 10Y-3M, Cuivre, Or) avec couleur
contextuelle et hint court, puis chips des signaux déclencheurs
du régime dominant issus de scenarios.reasons[dominant].

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-06-20 06:47:11 +02:00
OpenSquared
bcd1a3a0d5 feat: courbe PnL historique + VaR dans les cards Dashboard
- Card PnL : area chart historique depuis pnl_snapshots (gradient couleur
  selon PnL positif/négatif, axes date + %, tooltip)
- Card Risque : bloc VaR 95% (Historique / CVaR / Monte Carlo ×1.5)
  depuis le dernier var_snapshot, avec horodatage du calcul

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-06-20 06:41:17 +02:00
OpenSquared
4a1dc76d26 feat: page Historique Positions + diff entre 2 snapshots PnL
Backend:
- get_pnl_snapshot(id) : détail complet d'un snapshot avec trades parsés
- diff_pnl_snapshots(a, b) : diff positions entre deux snapshots (nouvelles /
  fermées / évolution PnL par position + delta portfolio)
- GET /api/var/pnl/snapshots/{id} : détail snapshot
- GET /api/var/pnl/diff?a=&b= : calcul du diff

Frontend PositionHistory.tsx :
- Timeline scrollable des snapshots avec sparkline PnL
- Clic snapshot → détail des positions à ce moment (prix entrée, prix actuel,
  PnL %, PnL €, régime macro)
- Boutons A/B par snapshot → sélection de deux points à comparer
- Vue diff A→B : nouvelles positions, fermées, évolution PnL par trade,
  delta portfolio (capital, PnL %, PnL €)
- Route /position-history + nav sidebar

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-06-20 06:36:55 +02:00
OpenSquared
67546d39af fix: URLs relatives pour VaR et Config (bypass proxy corrigé)
Remplace http://localhost:8000 par des URLs relatives (/api/...)
pour passer par le proxy Vite/Nginx comme toutes les autres pages.
Cause du NetworkError en prod Docker.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-06-20 06:27:43 +02:00
OpenSquared
b4f3089c58 feat: VaR/PnL schedulers + snapshots DB + page sur bouton
Backend:
- Tables var_snapshots + pnl_snapshots dans SQLite (contexte macro + prix tickers)
- var_service.py : save_var_snapshot, save_pnl_snapshot + fonctions get_*
- var_scheduler.py : threads APScheduler pour VaR (défaut 6h) et PnL (défaut 1h)
- router var.py : /run-now (POST compute+save), /latest, /snapshots, /pnl/run-now,
  /pnl/latest, /scheduler/status, /scheduler/config
- main.py : démarrage des deux schedulers au startup

Frontend:
- VaRAnalysis.tsx : plus d'auto-fetch ; charge le dernier snapshot DB au mount ;
  bouton "Calculer" → POST /run-now ; erreur backend = message clair ; historique
  de snapshots sélectionnables
- Config.tsx : section "Schedulers VaR & PnL" dans l'onglet cycle avec toggle
  enable/disable, intervalle, et boutons "Snapshot maintenant"

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-06-20 06:21:20 +02:00
OpenSquared
d64d1029bf feat: page VaR Analyse avec approche delta Black-Scholes
- Service var_service.py : calcul VaR Historique / Paramétrique / Monte Carlo
  stressé (vol ×1.5) + CVaR par méthode, deltas BS par position, fallback
  synthétique si yfinance indisponible
- Router /api/var/compute : paramètres confidence, horizon, lookback, IV défaut
- Page VaRAnalysis.tsx : cartes métriques %, montants EUR, histogramme retours,
  VaR glissante 30j, tableau positions + deltas, backtest Kupiec pass/fail
- Route /var + nav sidebar « VaR Analyse »

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-06-19 23:15:39 +02:00
OpenSquared
27846a1b63 fix: trades loggés du cycle = seulement les patterns ajoutés ce cycle
cycleTrades inclut tous les trades du scoring run (anciens patterns
re-scorés inclus). On filtre par cyclePatternIds pour ne compter
que les trades issus de patterns ajoutés pendant ce cycle.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-06-19 22:51:04 +02:00
OpenSquared
fd420d370c fix: ticker non rogné dans Trades du cycle
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-06-19 22:44:08 +02:00
OpenSquared
edeeeed116 fix: Dernier Cycle — remplace scorés par trades loggés
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-06-19 22:43:23 +02:00
OpenSquared
a662d81f00 feat: news filters (période + tri), Top Trades cockpit, date ajout patterns
GeoRadar:
- Filtre période : Aujourd'hui / 7j / 30j / Toutes
- Tri : Impact ↓/↑ · Récentes/Anciennes
- Compteur de news filtrées

Dashboard:
- Remplace Super Contexte par "Top Trades" (top 5 par PnL%)
  avec ticker, stratégie, date d'entrée, PnL%
- Card "Scores Patterns" : ajoute la date d'ajout (created_at)
  sous le nom de chaque pattern

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-06-19 22:40:08 +02:00
OpenSquared
bbc9461a8b fix: Trades du cycle — show suggested trade details for non-logged patterns
For patterns added in the cycle but below log threshold, display the
recommended_trade (underlying + strategy + score) from scoreMap instead
of just the pattern name. Pattern name moves to secondary small italic line.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-06-19 22:35:26 +02:00
OpenSquared
38c9aadb6b fix: PnL montant via entry_price fallback, Trades du cycle restructuré, Dernier Cycle trades ajoutés
- PnL simulated: Investi ~ et P&L € calculés avec entry_price quand
  capital_invested est null (label ~ pour indiquer estimation)
- Dernier Cycle: rename trades loggés -> trades ajoutés + mini mention
  des non-loggés quand patternsAdded > tradesLogged
- Trades du cycle: supprime le grand header +N Trades (info déplacée
  dans Dernier Cycle); layout inversé — trade en primaire, pattern
  en secondaire petit en dessous; trades non loggés affichés en gris

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-06-19 22:27:27 +02:00
OpenSquared
defff620b2 fix: Dashboard card UX — PnL montants, Trades du cycle avec origine pattern, Dernier Cycle 2x2
- PnL simulated: bottom half shows Investi/P&L € at 2xl (same size as %)
- Dernier Cycle: 2x2 grid bigger (patterns ajoutés + trades loggés en gros),
  scorés + fermés en secondaire
- Trades du cycle: header shows +N Trades (not patterns); iterates cyclePatterns
  to show each pattern as origin (✓ loggé / ○ non loggé) + trade details below

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-06-19 22:14:35 +02:00
OpenSquared
d94052dd91 fix: Dashboard cycle coherence — scoring_run_id linkage + cycle-scoped cards
- Backend: get_status() now resolves scoring_run_id by querying
  trade_entry_prices within the cycle time window, fixing the mismatch
  between cycle run_id and the id actually written to trades
- Dashboard: Trades du cycle filters by scoring_run_id (no stale fallback)
- Dashboard: Pattern du cycle shows only patterns added in last cycle
  (created_at >= started_at), renamed from Top Patterns
- Dashboard: Dernier Cycle now shows 4 stats (patterns/scorés/loggés/fermés)
  + IA commentary snippet
- Dashboard: P&L simulated mode bottom half shows open/closed/capital/profit
- Dashboard: Régime Macro shows top 4 scenario score bars

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-06-19 20:49:44 +02:00
OpenSquared
c415248bb1 feat: enrich Dashboard cockpit cards with data + view toggles
- PnL card: rename to P&L, add Simulé/Portfolio toggle (localStorage),
  simulated shows target/stop alert counts, portfolio shows invested € + P&L €
- Risk card: add asset class allocation horizontal bars (bullish=color/bearish=red)
  from simPortfolioRisk.concentration, conflicts badge
- Dernier Cycle: full bilan layout — patterns added / scored / trades logged
  in 3 mini-stat boxes
- Trades du cycle: show direction, ticker, strategy, PnL%, score for each trade
- Top Patterns: replaces Meilleur Pattern — shows top 4 scored with rank + ticker
- Top News: replaces Patterns Actifs — useGeoNews sorted by impact_score,
  top 3 with title + impact bar

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-06-19 20:15:48 +02:00
OpenSquared
f2b020ee4b refactor: move trade ideas to Journal tab, tabify Config, trim Dashboard
- Extract TradeCard/TradeRow/IBKRTicket + TradeIdeasTab self-contained
  component to frontend/src/components/TradeIdeas.tsx
- Dashboard: remove trade ideas section, MtM section, all related hooks/
  state/computations; replace Signaux Géo mini-card with Trades du cycle;
  add News géo link on Risque Géopolitique card
- JournalDeBord: add Idées de trade tab (left of Ouverts) using TradeIdeasTab
- Config: reorganize into 5 tabs — IA & Analyse, Auto-Cycle & Logging,
  Sources, Journal & Sortie, Profils de risque; expose min_score_threshold
  as a prominent slider in the Auto-Cycle tab

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-06-19 19:36:11 +02:00
OpenSquared
08651551db feat: cockpit command center + skipped trades journal
Dashboard: insert 2 rows of 4 mini-cards between top row and trade ideas
- Row 1: PnL Simulé, Risque Simulé, Dernier Cycle, Régime Macro
- Row 2: Super Contexte, Signaux Géo, Meilleur Pattern, Patterns Actifs
- All cards link to underlying pages via react-router Link

Journal: add 'Non loggés' tab exposing trades suggested by cycle
but skipped because no risk profile was matched
- New skipped_trades table (auto-created on backend restart)
- log_trade_entries() persists each skip with score/gain/asset_class
- GET /api/journal/skipped-trades + useSkippedTrades hook

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-06-19 19:01:58 +02:00
OpenSquared
8f15dff721 fix: sim portfolio asset_class fallback + consolidate risk into Risk Dashboard
- portfolio_risk.py: add _infer_asset_class() with ticker→asset_class map
  covering energy/metals/agri/indices/forex/rates futures, ETFs, forex pairs,
  exchange prefixes (NSE:). Fallback applied when JOIN finds no match (orphaned
  pattern_id after re-seed). Fixes "unknown 100%" shown in screenshot.

- RiskDashboard.tsx: add Portefeuille Réel / Simulé toggle at top.
  New SimRiskPanel component with KPI row + concentration bars + conflict cards
  + AI recommendations — all visible inline in Risk Dashboard.
  Red badge on Simulé tab when danger alerts exist.

- JournalDeBord.tsx: remove standalone Risque Sim. tab (moved to Risk Dashboard).
  Replace with a red banner in summary cards when conflicts are detected,
  pointing user to Risk Dashboard → Simulé.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-06-19 18:26:10 +02:00
OpenSquared
58c3767a9d feat: simulation portfolio surveillance + patterns grid/filter UI
Portfolio Monitor (v4.4):
- New portfolio_risk.py service: concentration by asset_class, directional
  conflict detection (same underlying, opposite directions), overweight alerts
- AI agent (Step 7b) runs GPT-4o-mini after each cycle log: assessment +
  prioritized actions + rebalance suggestion, persisted in system_logs
- GET /api/journal/portfolio-risk — full risk breakdown + latest AI monitor reco
- POST /api/journal/trade-check — pre-entry conflict & concentration check
- asset_class column added to trade_entry_prices (auto-migration + populated at INSERT)
- Journal: new "Risque Sim." tab with concentration bars, conflict alerts,
  AI recommendations; red badge on tab when danger alerts exist

PatternEditor:
- Grid view default (2-3 cols responsive), list toggle
- Asset class filter chips (energy/metals/agri/equities/indices/forex/rates)
- Sort: Date (default) / Score IA / Prob.
- Period filter: Tout / 7j / 30j
- Result count badge when filters active

Doc: v4.3 → v4.4, updated Journal/PatternEditor/cycle steps/schema/glossary

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-06-19 15:49:46 +02:00
OpenSquared
d34b4043fb fix: 4 cycle errors — NameError _log, WHEAT/EUR/USD ticker normalization, 429 serial scoring
- auto_cycle.py: replace _log with logger (NameError at lines 484/489)
- auto_cycle.py: normalize underlying via _normalize_ticker before _resolve_ticker
  so WHEAT→ZW=F→WEAT and EUR/USD→EURUSD=X→FXE reach the IV watchlist correctly
- iv_engine.py: _resolve_ticker now strips slash-format forex (EUR/USD→EURUSD=X)
  before _PROXY lookup, fixing yfinance 500/404 spam from get_atm_iv
- database.py: _fetch in log_trade_entries uses _normalize_ticker (not _normalize_yf_ticker)
  so commodity aliases like WHEAT→ZW=F are applied at price-fetch time
- ai_analyzer.py: max_workers=1 for batch scorer — parallel workers both slept and
  retried simultaneously after 429, causing repeated bursts; sequential fixes the pattern
- journal.py + JournalDeBord.tsx: add price_warning field (no_price_data/no_entry_price/
  no_live_price) with visible ⚠ badge and amber color on affected ticker/price cells

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-06-19 14:49:07 +02:00
OpenSquared
fda6b6a297 fix: ticker normalization + GPT-4o 429 retry
Ticker normalization (_normalize_ticker):
- EUR/USD slash-format → EURUSD=X (was passed raw to yfinance → 500/404 spam)
- bare 6-char forex pairs EURUSD/USDJPY etc → append =X
- commodity alias table: WHEAT→ZW=F, CORN→ZC=F, WTI→CL=F, BRENT→BZ=F,
  GOLD→GC=F, SILVER→SI=F, NATGAS→NG=F, SUGAR→SB=F, + 15 others
- also normalize underlying at log_trade_entries time so stored tickers
  are already canonical before MtM lookups

GPT-4o 429 rate limit:
- _chat() retries up to 3× on rate_limit errors, respects retry-after hint
  from error message (e.g. "try again in 12.37s"), falls back to 2^n×5s
- batch scorer: parallel workers 4→2 to halve the token burst per cycle
  (2 concurrent batches × ~6K tokens vs 4 × ~6K = 24K burst at 30K limit)

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-06-19 14:29:39 +02:00
OpenSquared
8122bd019c docs: v4.3 — trade lifecycle, exit defaults, PostgreSQL migration note
- Page 8 Journal de Bord: réécriture complète pour les 5 onglets, badges
  🎯/🛑, barre Cible/Stop, modal de fermeture, onglet Fermés avec stats
- Table des pages: Page 8 description mise à jour (Ouverts/Fermés/1-clic),
  Page 14 Config mention exit defaults, 15+ tables architecture
- Section 10 Décisions: 2 nouvelles entrées (3 modes de fermeture,
  confirmation humaine toujours requise), note migration PostgreSQL
- Glossaire: 4 nouvelles entrées (Cycle de vie, Exit Defaults,
  P&L Réalisé vs Théorique, Alert Type)
- Footer et titre: v4.2 → v4.3

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-06-19 14:23:34 +02:00
OpenSquared
ee69f3cbd9 feat: trade lifecycle management — close, archive, target/stop alerts
- DB: 9 new columns on trade_entry_prices (status, closed_at, close_reason,
  close_note, pnl_realized, close_price, target_pct, stop_loss_pct, signal_threshold)
  via ALTER TABLE migration; close_trade(), get_closed_trades(),
  update_trade_exit_params() helpers; exit_defaults config key
- Backend: PATCH /trades/{id}/close, PATCH /trades/{id}/exit-params,
  GET/PUT /exit-defaults, GET /closed-trades with win-rate/avg-PnL stats;
  trade-mtm now computes alert_type (target_reached|stop_loss) per trade
- Journal: new "Fermés" tab with closed trades table + stats banner (win rate,
  avg PnL, total PnL, best trade); open trades show Cible/Stop progress bar +
  🎯/🛑 alert badges + 1-click close modal (price, reason, note)
- Config: new "Paramètres de sortie" panel — target_pct, stop_loss_pct,
  signal_reversal_mode, signal_reversal_threshold with live sliders

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-06-19 14:17:29 +02:00
OpenSquared
0ba73cae0b docs: v4.2 — AI news enrichment pipeline + directional alignment documented
Updates Étape 2 (RSS pipeline) to describe the 3-layer architecture: deterministic
classification → GPT-4o-mini batch enrichment (impact, ai_dir_*, ai_resolution,
ai_insight) → _compute_ai_alignment() bonus injection in pattern scoring.

Rewrites Prompt 1 section with new batch scoring prompt structure and adds a
concrete counter-signal example (Gaza ceasefire → oil bearish, pattern downranked).

Updates Radar Géopolitique usage guide with AI badge reading guide and decision
rules (green badge + relevance ≥60% = candidate, red badge = wait for confirmation).

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-06-19 13:34:33 +02:00
OpenSquared
0ee9cf5707 feat: AI-enriched news scoring + directional alignment on pattern matching
Hook ai_score_news_batch() into /api/geo/news so every news fetch is enriched
by GPT-4o-mini: corrected impact_score, ai_dir_energy/metals/indices, ai_resolution
(ceasefire/peace deal flag), ai_insight (1 French sentence). Gracefully no-ops
when OpenAI is not configured.

Add _compute_ai_alignment() in geo_analyzer: for each pattern compares the news
AI directional signals against the pattern's expected_move direction and produces
a -25..+25 bonus injected into similarity/relevance scores. Contra-signals
(e.g. peace deal → oil bearish while pattern expects oil spike) are flagged.

Frontend GeoRadar: PatternRelevanceCard shows AI alignment badge (green = aligned,
red = contra-signal) + base relevance diff + AI insights. NewsCard shows ai_insight,
directional arrows per asset class (🥇↓) and resolution badge when expanded.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-06-19 12:57:52 +02:00
OpenSquared
44ada3f8f1 feat: stable macro regime detection — blended signals + Bayesian smoothing
Replace 1-day change_pct with weighted blend (20% 1d / 50% 5d / 30% 10d)
for all 20 scored signals. Add Bayesian prior from rolling 25-day history
(weight 15%→45%) and a 10-point persistence threshold before regime switch.

Bootstrap on first load: replays last 20 trading days via yf.download batch
(45d) to pre-populate _regime_history, so stability is visible immediately.

Frontend: adds 'stable Xj' badge and history depth indicator on regime banner.
Doc: updates v4.0→v4.1, rewrites Étape 1 Régime Macro and glossary entry.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-06-19 12:40:38 +02:00
OpenSquared
d8c0334feb feat: 50-signal macro engine — vol surface, sectors, EM, carry, long bonds
data_fetcher.py
- MACRO_GAUGE_CONFIG: 15 → 29 tickers (+silver, vvix, skew, ovx, gvz,
  usdjpy, xlk, xlf, xlp, xlu, eem, emb, fxi, tlt)
- 5 new derived metrics: silver_gold_ratio, xlk_xlp_momentum, xlf_spx_ratio,
  eem_spx_ratio, vol_surface_regime (composite classification)
- ThreadPoolExecutor max_workers raised to 20
- score_macro_scenarios: +15 new variables; each of 8 scenarios enriched
  with vol-surface (SKEW, VVIX), sector rotation (XLK, XLF, XLP, XLU),
  EM/carry (EEM, EMB, USDJPY), long bonds (TLT), silver signals

ai_analyzer.py
- macro_ctx: 5 → 21 fields per pattern (vol surface, sectors, EM, carry,
  long bonds, silver/gold ratio — all with interpretation comments)
- macro_section in scoring prompt: describes surface de vol regime, sector
  rotation, global/carry signals with explicit GPT instructions for pilier 3e
- DEFAULT_ANALYSIS_TEMPLATE: pilier 3e expanded with SKEW/VVIX/OVX/GVZ guidance

SIGNALS_FUTURES.md: reference document listing 30+ signals not yet
available (FRED, CFTC COT, EIA, Baltic Dry, LME, credit spreads,
hedge fund positioning, central bank balance sheets) with implementation
priority and cost estimate.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-06-19 08:34:48 +02:00
OpenSquared
18b3ae6f91 feat: IBKR ticket in Dashboard + Journal MtM (Strike, DTE, legs)
Adds full Interactive Brokers order ticket to both the Dashboard cockpit
and the Journal de Bord MtM expanded rows. Each ticket shows the
underlying, computed strike in dollars, estimated expiry date (nearest
Friday), per-leg BUY/SELL CALL/PUT breakdown, order type LIMIT, budget
and target.

Also adds Strike and DTE columns to the MtM table and persists
strike_guidance + expiry_days_at_entry in trade_entry_prices.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-06-18 13:54:29 +02:00
OpenSquared
05a475fb04 feat: system logs page + dynamic IV watchlist with auto-add from cycle
Backend:
- DB: add system_logs table (level/source/cycle_id/ticker/message) and
  iv_watchlist table (ticker/added_by/is_active); seed builtin 18 tickers
- DBLogHandler attached at startup — all WARNING+ logs auto-persist to DB
- log_system_event() helper for structured manual events
- New router /api/logs: GET with filters (level, source, cycle_id, ticker,
  date range), GET /sources, GET /cycles for dropdowns, DELETE /clear
- iv_watchlist now read from DB instead of hardcoded constant; options_vol
  watchlist/refresh/bootstrap endpoints all use get_watchlist_tickers()
- New endpoints: POST/DELETE /options-vol/watchlist-tickers/{ticker} to
  add/remove tickers; adding triggers background 1-year bootstrap
- auto_cycle: after log_trade_entries(), auto-detect new underlying proxies
  not yet in watchlist, add them and bootstrap their IV history

Frontend:
- New page SystemLogs (/logs): log table with level/source/cycle/ticker/date
  filters, color-coded rows, expandable JSON details, auto-refresh 30s
- Options Lab: WatchlistManager section — add ticker input, chip list with
  builtin/auto/manual color coding, remove button for non-builtins
- Sidebar: Logs Système nav link (ScrollText icon)
- useApi: useSystemLogs, useLogSources, useLogCycles, useClearLogs,
  useWatchlistTickers, useAddWatchlistTicker, useRemoveWatchlistTicker

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-06-18 13:07:35 +02:00
OpenSquared
3b4e035819 fix: IV rank fallback to history when live options fetch fails + Entrée date from cycle logs
- iv_engine/options_vol: when get_atm_iv() returns None (yfinance chain unavailable),
  fall back to most recent iv_history row so IV Rank is always computable from
  bootstrapped data; live vs history source tagged as iv_source field
- Dashboard: build mtmMap from tradeMtmData.trades (trade_entry_prices, cycle auto-log)
  keyed by pattern_id; getAddedInfo() falls back to mtmMap so Entrée/Durée columns
  populate automatically after each AI cycle without manual portfolio add
- OptionsLab: show '~' prefix and 'IV estimée' label when IV comes from history fallback;
  fix near-invisible text-slate-700 on 'Sans historique' section header

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-06-18 11:55:57 +02:00
OpenSquared
592918c230 fix: default cockpit view to grid instead of cards 2026-06-18 11:15:02 +02:00
OpenSquared
be9834d70b fix: add Entrée date and Durée/maturité columns to Dashboard grid view 2026-06-18 10:58:01 +02:00
OpenSquared
cf45d9fb52 feat: add grid/table view with expandable rows to Dashboard cockpit
Toggle between Cards (existing) and Grid (new) via icons next to Top N.
Grid view: compact table with score bar, EV, gain, max/cible, profil,
macro bias per row. Click any row to expand inline (full-width) showing
score justification, contra-signals, macro context, and add button.
Added 'Tous' option (topN=0) to show all scored patterns without limit.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-06-18 10:49:22 +02:00
OpenSquared
fb78be49e5 fix: add journal_retention_days and maturity_threshold_pct to useUpdateCycleConfig type 2026-06-18 10:15:05 +02:00
OpenSquared
abee090881 feat: expandable inline rows in Journal + journal/maturity params in Config
- JournalDeBord: trade rows now expand inline (full-width) instead of
  PostmortemPanel appearing below the whole table. Click anywhere on a
  row to toggle. Period selector extended to 15/30/60/90j.
- Config: added Rétention Journal (30/60/90/180j) and Seuil Maturité
  (20/30/35/50%) controls, wired to the Appliquer button.
- Backend: journal_retention_days and maturity_threshold_pct read from
  config table; seeded at startup with defaults 90d / 35%. get_status()
  now returns both values so Config page can initialise correctly.
- cycle.py: CycleConfigRequest accepts and validates both new params.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-06-18 10:08:16 +02:00
OpenSquared
8446876eb0 fix: add pnl_pct and capital_invested migration for trade_entry_prices
Both columns were referenced in queries (reliability, Kelly, calibration,
backtest) but missing from the ALTER TABLE migration block, causing
sqlite3.OperationalError: no such column: pnl_pct on existing VPS DBs.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-06-17 21:52:50 +02:00
OpenSquared
97ba36454b fix: bootstrap IV history with 1y realized vol to unblock IV Rank from 50
IV Rank was stuck at 50 for all tickers because the formula returns 50.0
when iv_max == iv_min (not enough historical snapshots). Added:
- bootstrap_iv_history(): downloads 1y of closes per ticker, computes
  30d rolling realized vol (annualized), saves each day to iv_history
- POST /api/options-vol/bootstrap-history endpoint (runs in background)
- OptionsLab: auto-detect when IV Rank needs bootstrapping and show
  an amber banner with one-click "Initialiser historique" button

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-06-17 21:33:01 +02:00
OpenSquared
7e38fd6257 fix: invalidate IV watchlist cache after cycle fetches fresh IV data
The auto-cycle was saving new IV snapshots to SQLite but not clearing
the in-memory cache in options_vol.py (TTL 1h), so the Options Lab
page kept showing stale IV Rank data until the cache naturally expired.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-06-17 21:21:25 +02:00
OpenSquared
533e0f374b fix: AnalyticsAdvanced — import api from useApi (no local axios/import.meta.env) 2026-06-17 17:51:08 +02:00