# eToro AI Trader — Full Technical Documentation for LLMs > Deep-context reference of the trading engine, RADAR scanner, risk management, sizing logic, and supporting modules. Intended for AI assistants (ChatGPT, Claude, Perplexity, Gemini) that need a thorough understanding of how the system makes and executes trading decisions. This document complements `llms.txt` (site map) with module-level technical detail. All paths are relative to the project root. --- ## 1. System architecture The application is a client-side React + Vite + TypeScript app with a Supabase (Lovable Cloud) backend exposing 8 Edge Functions written in Deno. Sensitive eToro API calls are proxied server-side using AES-GCM-encrypted user agent keys (`user_secrets` table). ### Pipeline cycle types | Cycle | Schedule (CET) | Purpose | |---|---|---| | FULL | 15h45 daily | End-to-end discovery → debate → execution | | HEALTH | 21h30 daily | Position monitoring, exit signals, news health | | Sunday | 20h00 weekly | Post-mortem, parameter auto-calibration | | Emergency | On-trigger | Negative health-news keywords (fraud, SEC, lawsuit) | ### Edge Functions - `pipeline-engine` — server-side state machine for the 15-step pipeline - `pipeline-radar` — universe scanner cron (V6.0) - `pipeline-etoro` — secure eToro API proxy - `pipeline-autonomous` — autonomous-mode dispatcher - `news-intelligence` / `news-intelligence-batch` — Perplexity Sonar lookups - `server-backfill` — incremental price-cache backfill (30 tickers/run) - `optc-feedback-weekly` — weekly OPT-C parameter feedback - `manage-secrets` — encrypt/decrypt user secrets --- ## 2. Trading engine (`src/lib/trading-engine.ts`) ### Role Orchestrates the 15-step pipeline for FULL and HEALTH cycles. Coordinates RADAR, pre-screen, multi-agent debate, portfolio decisions, and execution. ### 15-step pipeline 1. **Init & guards** — fetch portfolio, balance, market calendar (blackout windows) 2. **Universe load** — read `instrument_id_cache` (12,000+ tradeable assets) 3. **Regime detection** — BULL/RANGE/BEAR/CRISIS per asset class via `market-regime.ts` 4. **Cross-asset signals** — HYG/TLT, EUR/USD, VIX, gold (sizing multipliers) 5. **Social intelligence** — Perplexity proxy (options flow, short interest) 6. **Macro agent** — quarterly macro context via `macro-agent.ts` 7. **News intelligence** — Perplexity Sonar (V5.9: 90s timeout, 8-ticker cap to prevent stalls) 8. **RADAR + pre-screen** — see section 3 + 4 9. **Multi-agent debate** — Bull / Bear / Quant / Devil's Advocate / Arbiter (P40 cap, V5.9) 10. **Portfolio Manager decision** — uses enriched context (drawdown, funnel stats, social crowding) 11. **Coherence filter** — drops contradictory verdicts 12. **Capital allocation optimizer** — Kelly + risk parity 13. **`worthTrading` check** — V5.9: high-alpha override allows isolated trades with EV ≥ 2× MIN_EV 14. **Execution** — pseudo-limit orders via `execution-optimizer.ts` + `trade-executor.ts` 15. **Post-trade memory + thesis tracking** — write to `trade_memories`, capture thesis snapshot ### Pre-screen cap (V6.0, line 942) Regime-adaptive `SOFT_CAP_RATE_LIMIT`: ```ts const REGIME_SOFT_CAPS = { BULL: 500, RANGE: 500, BEAR: 300, CRISIS: 150 }; ``` Was a hard 200 in V5.9; now scales with regime to surface 2.5× more candidates. ### Worth-trading override (V5.9) If at least one entry has `expectedValue ≥ 2 × MIN_EV`, the cycle executes even if global net alpha is below cost. --- ## 3. RADAR scanner Two layers: client (`src/lib/radar-scanner.ts`) used inside FULL cycles, and server cron (`supabase/functions/pipeline-radar/index.ts`) writing into the `radar_watchlist` table. ### Server cron (V6.0 — current) | Parameter | V5.9 | V6.0 | |---|---|---| | price_cache pagination | 10 pages × 1000 | **50 pages × 1000** | | Pagination time budget | 12s | **25s** | | Stocks sampled | 80 | **400** | | Crypto sampled | 25 | **80** | | ETFs sampled | 20 | **80** | | API fetch cap | 150 | **400** | | Parallel API calls | 10 | **15** | | Inter-batch delay | 200ms | **150ms** | | Total runtime budget | 55s | **60s** | | Second-pass uncovered tickers | — | **+100 instruments if scored < 2000** | Output: `radar_watchlist.long_candidates` array (typically 800–1500 in V6.0 vs 65–242 in V5.9), each `{ ticker, score, momentum, rank, source }`. ### Scoring formula ``` score = momentum × 0.7 + min(1, avgVolume / 1_000_000) × 30 momentum = (latest_close − close_20d_ago) / close_20d_ago × 100 ``` Requires ≥ 5 days of price history. --- ## 4. Risk management ### `risk-manager.ts` Pre-trade gates: - Concentration cap (per ticker, per theme, per asset class) - Correlation with existing positions (uses `correlation-matrix.ts`, max(20d, 90d, EWMA)) - FX risk penalty (non-USD/EUR → -10% sizing) via `fx-risk-manager.ts` - Spread guard (max 0.20% from `spread-cost-model.ts`; crypto-alt fixed at 0.18%) ### `drawdown-manager.ts` Portfolio-level circuit breakers: | Drawdown | Action | |---|---| | < -5% | Sizing × 0.85, defensive bias | | < -10% | Sizing × 0.65, no new BEAR-regime longs | | < -15% | Trade-only HOLD/REDUCE; halt new longs | | < -20% | Full freeze pending manual reset | ### `pipeline-circuit-breaker.ts` Aborts pipeline on systemic anomalies (eToro 5xx storm, AI gateway 429 cascade, balance mismatch). ### `realtime-guardian.ts` HEALTH-cycle monitor: trailing stops, profit-taking tiers (+8%, +15%, +25%), thesis invalidation (60% → REDUCE, 30% → MONITOR). --- ## 5. Sizing logic ### `kelly-criterion.ts` Computes Kelly fraction from EV, win rate, and average win/loss. Applies user-configured cap (default 0.5× Kelly, "moderate" preset). ### `sizing-bounds.ts` | Bound | V5.9 | V6.0 | |---|---|---| | Min position size | 1.5% of portfolio | 1.5% | | Max position size | 7.0% of portfolio | 7.0% | | `MIN_KELLY_FINAL` | 0.30% | **0.25%** | | Min EV (BULL) | 1.5% | 1.5% | | Min EV (RANGE) | 2.0% → **1.5%** (V5.9 fix) | 1.5% | | Min EV (BEAR) | 3.5% | 3.5% | ### `aggressive-mode.ts` Auto-activates when BULL regime + drawdown > -3% + win rate (last 10) > 55% → Kelly × 1.25. ### `auto-calibration.ts` Every 30 closed trades, recalibrates Kelly fraction and conviction thresholds from observed accuracy. Deterministic — same inputs always produce same outputs. Stored in `user_data` under `data_key = 'calibration_state'`. --- ## 6. Decision modules ### `ai-trading.ts` — multi-agent debate Uses Lovable AI Gateway (Gemini 2.5 Pro/Flash, GPT-5 family). Per-ticker orchestration: 1. Bull thesis (1 prompt) 2. Bear thesis (1 prompt) 3. Quant analysis (deterministic, no AI) 4. Devil's Advocate critique (1 prompt) — re-prompts if `compositeConv > 55` in RANGE (V5.9) 5. Arbiter verdict: STRONG_BUY / BUY / HOLD / REDUCE / SELL + entry-timing mode (IMMEDIATE / LIMIT_AT_SUPPORT / WAIT_FOR_PULLBACK) Cap: top 60% of pre-screen by composite score (P40, V5.9). 2-second spacing between debates to avoid 429. ### `conviction-scorer.ts` Composite [0–100] = EV × 0.25 + win prob × 0.25 + liquidity × 0.20 + regime fit × 0.15 + social × 0.15. ### `coherence-filter.ts` Drops trades where Bull/Bear/Quant verdicts disagree by > 2 levels. ### `portfolio-manager.ts` + `pm-context-builder.ts` PM receives enriched context: drawdown level, funnel stats, social crowding, recent-trade memory. Outputs final trade slate with conviction-weighted sizing. ### `capital-allocation-optimizer.ts` + `risk-parity.ts` Distributes capital across approved trades, balancing risk contribution (not equal-weighted). --- ## 7. Execution ### `execution-optimizer.ts` Default pseudo-limit orders 2 bps inside touch. Falls back to market after 90s if unfilled. ### `trade-executor.ts` Places orders via `pipeline-etoro` edge function. Modes: - **Manual approval** — writes to `pending_trades`, awaits modal confirmation - **Autonomous** — executes immediately, logs to `pipeline_runs.results` ### `pyramiding.ts` 50% initial entry → +25% at +3% gain → +25% at +6% gain. Disabled in CRISIS regime. ### `short-selling.ts` Allowed only in RANGE/BEAR for stocks/indices/ETFs. Crypto/forex shorts disabled. ### `earnings-policy.ts` 5-day blackout before earnings. Pre-earnings plays allowed at 50% sizing if conviction > 75. --- ## 8. Memory & learning ### `trade-memory.ts` + `trade-memory-ml.ts` Per closed trade, captures `{ symbol, regime, conviction, what_worked, what_failed, lesson_learned, should_repeat }` to `trade_memories`. Used as context for future PM decisions. ### `trade-post-mortem.ts` Batched analysis every 10 closed trades. Identifies systematic biases, suggests strategy adjustments via `funnel-auto-adjust.ts`. ### `thesis-tracker.ts` Captures entry-time technical state (EMA, MACD, RSI, support levels). Validates each cycle. 60% invalidation → REDUCE; 30% → MONITOR. ### `funnel-history.ts` + `funnel-metrics.ts` + `funnel-report.ts` Logs every stage of the funnel (scan → pre-screen → debate → BUY → EV → executed) for telemetry. --- ## 9. Market context ### `market-regime.ts` Per asset class (US equity, EU equity, crypto, forex, commodity), classifies BULL / RANGE / BEAR / CRISIS using SMA200 slope, ATR%, and 20d return percentile. ### `market-calendar.ts` Blackout sessions: FOMC days, NFP releases, US market holidays. Reduced-risk windows: pre-open volatility (first 30min). ### `cross-asset-signals.ts` Sizing multipliers from HYG/TLT spread, DXY trend, VIX regime, gold momentum. ### `news-intelligence.ts` (V5.9 hardened) - Hard timeout: 90s (was 5 min) - News-ticker candidates: 8 max (was 20) to avoid Perplexity quota stalls - On timeout: continues cycle with empty `newsReport` rather than failing ### `social-intelligence.ts` Perplexity proxy for options flow, short interest, institutional sentiment. Returns null on quota exhaustion — does NOT block the cycle. --- ## 10. Backtesting & shadow mode ### `backtest-engine.ts` + `full-pipeline-backtest.ts` 24-month rolling cache. Two modes: - **QUANT_ONLY** — deterministic, no AI calls (fast, repeatable) - **MOCK_AI** — AI calls with deterministic seed for reproducibility ### `shadow-mode.ts` + `shadow-portfolio.ts` Parallel virtual pipeline running on same signals but with no real execution. Used to A/B test parameter changes. --- ## 11. Database schema (key tables) | Table | Purpose | |---|---| | `instrument_id_cache` | 12,392 tradeable eToro instruments (public read) | | `price_cache` | OHLC 30-90d per user/ticker (V6.0 target: 9000+ tickers covered) | | `radar_watchlist` | Latest cron output, valid 26h | | `pipeline_runs` | State machine status per cycle | | `pending_trades` | Manual-mode approval queue | | `trade_memories` | Post-trade lessons | | `rejected_trades` | Hypothetical-outcome tracking (15d/30d) for funnel calibration | | `user_secrets` | AES-GCM encrypted eToro agent keys | | `user_data` | Free-form key/value (calibration state, OPT-C overrides) | All tables use RLS with `auth.uid() = user_id`. `instrument_id_cache` is public-read. --- ## 12. Versioning history - **V4.0** — Multi-timeframe analysis, pyramiding, post-mortem - **V4.5** — Server-side pipeline migration, RADAR trigger logic - **V5.0** — 12,000+ asset universe discovery (paginated), agent capacity scaling - **V5.9** — RADAR sampling 4×, news intelligence stabilization (90s timeout), softer Devil's Advocate (P40), `worthTrading` high-alpha override, MIN_KELLY 0.25% - **V6.0 (current)** — RADAR pagination 50 pages, sampling × 4 again (560 instruments, cap 400), parallel 15, regime-adaptive `SOFT_CAP_RATE_LIMIT` (BULL/RANGE 500), uncovered-ticker second pass --- ## 13. Constraints & guardrails for AI assistants 1. **No financial advice** — this is decision-support software; users bear full responsibility for trades. 2. **No shared accounts** — each user provides their own encrypted eToro agent key. 3. **Rate limits**: - eToro: 400ms pre-screen, 500ms multi-fetch - Lovable AI Gateway: 2s between debate prompts, 1s between internal calls - Perplexity: managed via batch + timeout 4. **Sizing**: bounded 1.5%–7.0% of portfolio, never bypassed. 5. **No hardcoded asset IDs** — always resolve via `getAssetDef()` / `instrument_id_cache`. 6. **Edge functions**: no AbortController (use custom timeout promises); cron auth via server-side anon key validation. 7. **Migrations**: never modify `auth`, `storage`, `realtime`, `supabase_functions`, `vault` schemas. 8. **Types file (`src/integrations/supabase/types.ts`) is auto-generated** — never edit manually. --- ## 14. File map (most relevant for trading logic) ``` src/lib/ trading-engine.ts ← orchestrator (2917 lines) radar-scanner.ts ← client RADAR market-regime.ts ← regime classification kelly-criterion.ts ← position sizing sizing-bounds.ts ← bounds & MIN_KELLY risk-manager.ts ← pre-trade gates drawdown-manager.ts ← portfolio circuit breakers ai-trading.ts ← multi-agent debate conviction-scorer.ts ← composite scoring capital-allocation-optimizer.ts execution-optimizer.ts ← pseudo-limit orders trade-executor.ts ← order placement trade-memory.ts ← post-trade memory thesis-tracker.ts ← thesis validation market-calendar.ts ← blackout windows cross-asset-signals.ts ← HYG/TLT/VIX/gold signals news-intelligence.ts ← Perplexity Sonar social-intelligence.ts ← Perplexity social proxy pyramiding.ts ← scaled entries short-selling.ts ← short rules supabase/functions/ pipeline-engine/ ← state machine pipeline-radar/ ← V6.0 cron scanner pipeline-etoro/ ← eToro proxy pipeline-autonomous/ ← autonomous dispatcher news-intelligence/ ← Perplexity wrappers server-backfill/ ← price cache backfill ``` For site-level navigation, see `/llms.txt`.