Algorithm Trading System Architecture

Agencio Predict - Complete UX/UI, Business Logic & System Documentation

375 DSL Primitives | 13 Categories | 5-Layer Guardrails | Full Backtesting Integration

System Statistics

375
DSL Primitives
13
Primitive Categories
5
Guardrail Layers
12
UI Modals
9
Anti-Hallucination Defenses
4
Strategy Horizons

1. Complete User Journey

End-to-end user journey from algorithm creation through backtesting, paper trading, and graduation to live.

journey title Algorithm Trading User Journey section Create Algorithm Navigate to /admin/algorithms: 5: User Click "New Algorithm": 5: User Choose: From English or Manual DSL: 4: User Describe strategy in natural language: 4: User Review translated DSL: 4: User Save algorithm: 5: User section Configure & Backtest Click "Backtest" on algorithm card: 5: User Select lookback period (90/180/365/730): 5: User Optionally select dataset: 4: User Click "Tune" for risk overrides: 3: User Click "Run Backtest": 5: User View loading spinner: 3: User section Analyze Results Review equity curve chart: 5: User Check 13 metrics in grid: 5: User Examine drawdown chart: 4: User View trades table: 4: User Check guardrail kills: 4: User Review factor attribution: 3: User section Paper Trading Click "Paper Trade" button: 5: User Algorithm starts in paper mode: 5: User Monitor daily equity updates: 4: User Check EOD critic reports: 3: User Complete 30 days + 50 trades: 4: User section Graduation Verify Sharpe >= 1.0: 4: User Verify Max DD <= 15%: 4: User Verify PSR >= 0.95: 4: User Verify Walk-Forward >= 0.70: 4: User Complete MFA + Risk Ack: 5: User section Live Trading Click "Go Live": 5: User Algorithm executes on broker: 5: User Daily EOD critic reviews: 4: User Monitor via dashboard: 5: User

2. UI Component Hierarchy

React component tree for the algorithms page and all modals.

flowchart TB subgraph AlgorithmsPage["AlgorithmsPage (page.tsx)"] Header["Page Header + Help Link"] Tabs["Tabs: Algorithms | Datasets"] subgraph AlgoTab["Algorithms Tab"] AlgoGrid["Algorithm Cards Grid"] NewAlgoBtn["+ New Algorithm Button"] end subgraph DatasetTab["Datasets Tab"] DatasetList["Dataset Cards"] UploadBtn["Upload Dataset"] CompareBtn["Compare Mode"] end end subgraph Modals["Modal Components (12 total)"] BacktestModal["BacktestModal"] PaperModal["PaperTradeModal"] CritiqueModal["CritiqueModal"] ModifyModal["ModificationsModal"] AuditModal["AuditModal"] WalkFwdModal["WalkForwardModal"] MonteCarloModal["MonteCarloModal"] StressTestModal["StressTestModal"] FromEnglishModal["FromEnglishModal"] DeleteModal["DeleteConfirmModal"] TunePanel["Risk Tuning Panel"] FactorPanel["Factor Attribution Panel"] end AlgoGrid --> BacktestModal AlgoGrid --> PaperModal AlgoGrid --> CritiqueModal AlgoGrid --> ModifyModal AlgoGrid --> AuditModal AlgoGrid --> WalkFwdModal AlgoGrid --> MonteCarloModal AlgoGrid --> StressTestModal NewAlgoBtn --> FromEnglishModal BacktestModal --> TunePanel BacktestModal --> FactorPanel

Modal Purposes

Modal Purpose Key Features
BacktestModal Run historical backtests Lookback selector, dataset picker, tune panel, 13 metrics, charts, trades table
FromEnglishModal Natural language to DSL translation Text input, LLM translation, retry loop, DSL preview
CritiqueModal LLM analysis of strategy Proposer/critic views, suggestions, risk assessment
ModificationsModal AI-proposed modifications LLM jury decisions, cross-validation results
AuditModal Audit trail review 3 tabs: Rejections, Jury decisions, EOD critic
WalkForwardModal Walk-forward optimization In-sample/out-of-sample splits, OOS/IS ratio
MonteCarloModal Bootstrap simulation 1000 paths, confidence intervals, tail risk
StressTestModal Regime stress testing Crisis scenarios, VIX spikes, drawdown analysis

3. UI State Machine

React state transitions within BacktestModal and paper trading flows.

stateDiagram-v2 [*] --> Idle: Modal opens state Idle { [*] --> ConfigReady ConfigReady --> DatasetsLoading: Fetch datasets DatasetsLoading --> ConfigReady: Loaded ConfigReady --> TuningOpen: Click "Tune" TuningOpen --> ConfigReady: Close tune panel ConfigReady --> DatasetPreview: Select dataset DatasetPreview --> ConfigReady: Close preview } Idle --> Running: Click "Run Backtest" Running --> ComputingMetrics: Bars processed ComputingMetrics --> Success: API 200 Running --> Error: API error ComputingMetrics --> Error: Metrics error state Success { [*] --> DisplayMetrics DisplayMetrics --> RenderEquityCurve RenderEquityCurve --> RenderDrawdown RenderDrawdown --> RenderTradesTable RenderTradesTable --> ComputeFactors ComputeFactors --> Done } Success --> Idle: Modify config Error --> Idle: Retry/modify state PaperTrading { [*] --> Starting Starting --> Active: startRun() success Active --> Ticking: Every market tick Ticking --> Active: Tick processed Active --> Stopping: Stop requested Stopping --> Stopped: flattenAllPositions() Active --> Killed: Guardrail triggered Killed --> Stopped: Emergency flatten }

4. Modal Interaction Flows

Detailed interaction flow for key modals.

flowchart TB subgraph BacktestFlow["Backtest Modal Flow"] B1["Open Modal"] --> B2["Load datasets list"] B2 --> B3["Select lookback: 90/180/365/730 days"] B3 --> B4{"Dataset?"} B4 -->|"Yes"| B5["Load dataset preview (100 bars)"] B4 -->|"No"| B6["Use live price data"] B5 --> B7["Configure tune overrides?"] B6 --> B7 B7 --> B8["Click Run Backtest"] B8 --> B9["POST /algorithms/:id/backtest"] B9 --> B10["Display: Metrics + Charts + Trades"] end subgraph FromEnglishFlow["From English Flow"] E1["Open Modal"] --> E2["Enter strategy description"] E2 --> E3["Click Translate"] E3 --> E4["POST /algorithms/from-english"] E4 --> E5{"Parse success?"} E5 -->|"Yes"| E6["Display DSL preview"] E5 -->|"No"| E7["Retry with feedback (max 3)"] E7 --> E4 E6 --> E8["Save algorithm"] end subgraph CritiqueFlow["Critique Modal Flow"] C1["Open Modal"] --> C2["POST /algorithms/:id/critique"] C2 --> C3["LLM Proposer: Strengths"] C3 --> C4["LLM Critic: Weaknesses"] C4 --> C5["Display with citations"] C5 --> C6["User can request modifications"] end

5. "From English" Translation Flow

Natural language to DSL translation with anti-hallucination defenses.

sequenceDiagram participant U as User participant UI as FromEnglishModal participant API as /from-english endpoint participant LLM as Claude (translate.ts) participant Parser as DSL Parser participant DB as algorithm_llm_rejections U->>UI: Enter: "Buy NVDA when RSI<30, sell when RSI>70" UI->>API: POST { description } API->>LLM: Translate to StrategyAST LLM-->>API: Return JSON AST API->>Parser: Validate AST structure alt Parse Success Parser-->>API: Valid AST API->>Parser: Check primitives against whitelist Parser-->>API: All primitives valid API-->>UI: { ast, dsl } UI->>U: Show DSL preview else Unknown Primitive Parser-->>API: Error: "unknown_primitive" not in registry API->>DB: Log rejection API->>LLM: Retry with specific error Note over LLM: Max 3 attempts LLM-->>API: Corrected AST else Syntax Error Parser-->>API: Parse error API->>DB: Log rejection API-->>UI: { error } UI->>U: Show error, suggest fixes end

9 Anti-Hallucination Defenses

# Defense Implementation
1 Zod Schema Validation All LLM output validated against strict Zod schemas
2 Primitive Whitelist 375 primitives in PRIMITIVES registry, reject unknown
3 Cite-or-Refuse Critiques must name specific primitive or metric
4 Deterministic Cross-Validation Sharpe/DD/return gates before accepting modifications
5 LLM-Jury Proposer/Critic/Judge pattern for modifications
6 Confidence Threshold 0.85 threshold forces human escalation
7 Rejection Audit Log All rejections persisted to algorithm_llm_rejections
8 asOf-Frozen Context Evaluator context locked to bar timestamp, no look-ahead
9 Adversarial Review Explicit "find what's wrong" prompt in critic phase

6. DSL Primitive Categories

375 primitives organized into 13 categories for signal generation and strategy construction.

mindmap root((DSL Primitives)) Price price vwap volume_z Technical rsi macd bb_upper/lower atr obv adx sma roc garch_volatility hurst_exponent egarch_volatility rough_vol_hurst Sentiment sentiment whale_activity funding_rate human_automation_score fear_greed_index pump_dump_detected Macro vix treasury_2y10y_spread curve_slope_2s10s fed_blackout cpi_release_today markov_regime Position position_age_hours position_pnl_pct position_size drawdown_from_peak underwater_bars Pattern fvg_present is_bullish_engulfing is_hammer is_doji support_nearby Sizing kelly half_kelly fixed_usd volatility_scaled risk_parity_weight Options iv_rank put_call_ratio gamma_exposure iv_rv_spread variance_risk_premium Prediction Market polymarket_yes_price kalshi_yes_prob pm_consensus_bullish Fundamental factor_alpha factor_beta_market pe_ratio debt_to_equity institutional_ownership_pct PINN pinn_predicted_price pinn_liquidation_risk pinn_model_uncertainty LLM llm_signal Composer and or not if_then_else

Primitive Count by Category

Category Count Examples Status
technical ~80 rsi, macd, garch_volatility, hurst_exponent, egarch Fully Wired
sentiment ~35 whale_activity, funding_rate, fear_greed_index Partial
macro ~30 vix, treasury spreads, markov_regime Fully Wired
position ~25 position_age_hours, pnl_pct, drawdown_from_peak Fully Wired
pattern ~40 fvg_present, is_hammer, support_nearby Fully Wired
sizing ~15 kelly, fixed_usd, volatility_scaled Fully Wired
options ~20 iv_rank, put_call_ratio, gamma_exposure Partial
prediction_market ~15 polymarket_yes_price, kalshi_yes_prob Fully Wired
fundamental ~35 factor_alpha, pe_ratio, institutional_ownership Partial
pinn ~10 pinn_predicted_price, pinn_liquidation_risk Fully Wired

7. Strategy AST Structure

The StrategyAST type defines the complete structure of an algorithm.

classDiagram class StrategyAST { +string strategy +RunMode mode +StrategyHorizon horizon +string[] universe +DSLAssetClass asset_class +number leverage +Record~string,Expression[]~ signals +EntryRule entry +ExitRule exit +RiskLimits risk +SelfModifySpec self_modify } class EntryRule { +Expression when +Expression size +direction: long|short } class ExitRule { +Expression when } class RiskLimits { +number max_position_usd +number max_daily_loss_pct +number max_drawdown_pct +number stop_loss_pct +number trailing_stop_pct +TargetAllocation target_allocation +number rebalance_interval_days +number min_holding_period_days } class Expression { <> } class LiteralExpr { +type: literal +value: number|string|boolean } class FunctionCallExpr { +type: call +string name +Expression[] args } class BinaryOpExpr { +type: binop +BinaryOp op +Expression left +Expression right } StrategyAST --> EntryRule StrategyAST --> ExitRule StrategyAST --> RiskLimits EntryRule --> Expression ExitRule --> Expression Expression <|-- LiteralExpr Expression <|-- FunctionCallExpr Expression <|-- BinaryOpExpr

Strategy Horizons

Horizon Timeframe Recommended Primitives Risk Features
intraday Minutes to hours rsi, macd, volume_spike, fvg_present Tight stops, quick exits
swing Days to weeks sentiment, hurst_exponent, cointegrated Trailing stops, position sizing
position Weeks to months markov_regime, factor_alpha, macro indicators Regime filtering, correlation checks
long_term Months to years factor_beta_market, target_allocation, rebalancing Portfolio allocation, drift thresholds

8. Expression Evaluation Flow

How the DSL evaluator processes expressions with no-look-ahead guarantee.

flowchart TB subgraph Input["Input (per bar)"] AST["Expression AST"] Bar["Current OHLCV Bar"] History["Historical bars[0..idx]"] AsOf["asOf timestamp"] end subgraph BuildContext["Build EvalContext"] Prices["prices: Record"] Indicators["IndicatorBundle"] Position["Current position state"] Macro["Macro overlays (VIX, yields)"] Sentiment["Sentiment scores"] end subgraph Evaluate["evaluate(expr, ctx)"] Switch{"expr.type?"} Literal["Return expr.value"] Identifier["Look up in ctx.prices"] subgraph FunctionCall["Function Call"] Lookup["PRIMITIVES[expr.name]"] Args["Evaluate args recursively"] Dispatch["Dispatch to handler"] end subgraph BinaryOp["Binary Operation"] Left["evaluate(expr.left)"] Right["evaluate(expr.right)"] Apply["Apply operator"] end end subgraph Handlers["Primitive Handlers"] Tech["Technical: ctx.indicators.rsi(14)"] Macro2["Macro: ctx.vix()"] Pos["Position: ctx.position.*"] Pattern["Pattern: detectFVG(ctx.bars)"] end AST --> Switch Bar --> BuildContext History --> BuildContext AsOf --> BuildContext BuildContext --> Indicators BuildContext --> Position BuildContext --> Macro Switch -->|"literal"| Literal Switch -->|"identifier"| Identifier Switch -->|"call"| FunctionCall Switch -->|"binop"| BinaryOp FunctionCall --> Handlers Handlers --> Result["boolean | number"]
No-Look-Ahead Guarantee: The evaluator only has access to bars[0..idx] where idx is the current bar index. All indicators compute against historical data only. The asOf timestamp is used to filter overlays and macro data.

9. Risk Management Pipeline

Multi-layer risk checks from entry signal to execution.

flowchart TB subgraph EntrySignal["Entry Signal Generated"] Signal["entry.when == true"] Size["Calculate size via kelly/fixed"] end subgraph PreTradeChecks["Pre-Trade Risk Checks"] MaxPos["max_position_usd check"] DailyLoss["max_daily_loss_pct check"] Drawdown["max_drawdown_pct check"] Correlation["Portfolio correlation check"] Slippage["Slippage-aware sizing"] end subgraph Execution["Trade Execution"] SlippageCalc["Almgren-Chriss slippage"] Execute["Execute trade"] Record["Record to algorithm_trades"] end subgraph PostTradeMonitor["Post-Trade Monitoring"] StopLoss["stop_loss_pct monitoring"] TrailingStop["trailing_stop_pct tracking"] HoldingPeriod["Holding period checks"] EODCritic["EOD LLM critic (live only)"] end subgraph ExitTriggers["Exit Triggers"] SignalExit["exit.when == true"] StopHit["Stop loss hit"] TrailingHit["Trailing stop hit"] GuardrailKill["Guardrail kill"] Liquidation["Leverage liquidation"] end Signal --> Size --> MaxPos MaxPos -->|"Pass"| DailyLoss MaxPos -->|"Fail"| Reject["Reject trade"] DailyLoss -->|"Pass"| Drawdown DailyLoss -->|"Fail"| Reject Drawdown -->|"Pass"| Correlation Correlation -->|"Pass"| Slippage Slippage --> Execute --> Record Record --> StopLoss StopLoss --> TrailingStop TrailingStop --> HoldingPeriod SignalExit --> Exit["Close position"] StopHit --> Exit TrailingHit --> Exit GuardrailKill --> Exit Liquidation --> Exit

10. Graduation Gates

Requirements for promoting algorithms from paper to live trading.

flowchart LR subgraph BacktestPhase["Backtest Phase"] BT["Run backtest"] BTMetrics["Calculate metrics"] BTPass{"Sharpe >= 0.5?"} end subgraph PaperPhase["Paper Trading Phase"] Paper["Paper trade 30 days"] Trades["Complete 50+ trades"] PaperMetrics["Real-time metrics"] end subgraph GraduationGates["Graduation Gates"] G1["Sharpe >= 1.0"] G2["Max DD <= 15%"] G3["PSR >= 0.95"] G4["Walk-Forward OOS/IS >= 0.70"] G5["MFA Verification"] G6["Risk Acknowledgement"] end subgraph LivePhase["Live Trading"] Live["Execute on broker"] EOD["Daily EOD critic"] Monitor["Real-time monitoring"] end BT --> BTMetrics --> BTPass BTPass -->|"Yes"| Paper BTPass -->|"No"| Iterate["Iterate strategy"] Paper --> Trades --> PaperMetrics PaperMetrics --> G1 --> G2 --> G3 --> G4 --> G5 --> G6 G6 -->|"All Pass"| Live G1 -->|"Fail"| Continue["Continue paper trading"] Live --> EOD --> Monitor

Gate Requirements

Gate Threshold Purpose
Sharpe Ratio >= 1.0 Risk-adjusted return quality
Max Drawdown <= 15% Capital preservation
Probabilistic Sharpe Ratio >= 0.95 Statistical significance of Sharpe
Walk-Forward OOS/IS >= 0.70 Out-of-sample performance vs in-sample
MFA Verification Required Identity confirmation
Risk Acknowledgement Required User accepts trading risks

11. Full Stack Overview

Complete system architecture from UI to database.

flowchart TB subgraph Frontend["Frontend (Next.js App Router)"] UI["/admin/algorithms page"] Modals["12 Modal Components"] Charts["Recharts Visualizations"] end subgraph APILayer["API Layer (Route Handlers)"] Routes["apps/web/src/app/api/predict/v1/algorithms/*"] Handlers["packages/be/src/algorithms/api/handlers.ts"] end subgraph CoreEngine["Core Engine"] subgraph DSL["DSL Layer"] Types["types.ts (375 primitives)"] Evaluator["evaluator.ts (AST walker)"] Translator["llm/translate.ts"] end subgraph Backtest["Backtest Engine"] Engine["engine.ts (~1700 lines)"] Indicators["indicators.ts"] Metrics["metrics.ts (~1870 lines)"] Enhanced["enhanced-metrics.ts"] end subgraph Paper["Paper Executor"] Executor["executor.ts (~3800 lines)"] Guardrails["guardrails/"] SlippageFit["slippage-fitter.ts"] CorrHaircut["correlation-haircut.ts"] end subgraph LLM["LLM Layer"] Client["client.ts (Anthropic/Router)"] Critique["critique.ts"] Jury["jury.ts"] EODCritic["eod-critic.ts"] end end subgraph DataSources["Data Sources"] Prices["price-service.ts"] Datasets["datasets/repository.ts"] Overlays["overlays/data-fetcher.ts"] AllSeeingEye["all-seeing-eye/"] end subgraph Storage["Storage"] Postgres[(PostgreSQL)] S3["S3 (datasets)"] end UI --> Routes --> Handlers Handlers --> Engine Handlers --> Executor Handlers --> Translator Engine --> Evaluator --> Types Engine --> Indicators Engine --> Metrics Executor --> Evaluator Executor --> Guardrails Executor --> Client Engine --> Prices Engine --> Datasets Engine --> Overlays Executor --> AllSeeingEye Handlers --> Postgres Datasets --> S3

12. Backtest Engine Data Flow

Bar-by-bar backtest execution with L1 guardrails.

flowchart TB subgraph Input["Input"] AST["StrategyAST"] DataSource{"datasetId?"} LoadDS["loadImportedBars()"] LoadLive["getHistoricalPrices()"] Overlays["fetchSeriesData() for VIX, yields"] end subgraph BarLoop["Bar-by-Bar Loop"] ForEach["for idx = 0 to bars.length"] subgraph BuildCtx["Build EvalContext"] Prices["prices[symbol] = bar.close"] Inds["Compute indicators (RSI, MACD, etc.)"] MacroCtx["Load macro overlays at asOf"] PosState["Load position state"] end subgraph Evaluate["Evaluate Strategy"] Signals["Evaluate signal groups"] EntryCheck{"entry.when?"} ExitCheck{"exit.when?"} end subgraph Execute["Execute Trade"] SizingCalc["Calculate position size"] SlippageCalc["calculateSlippage(mode)"] TradeExec["Record trade"] UpdatePos["Update position state"] end subgraph Guardrails["L1 Guardrails"] StopLoss["Check stop_loss_pct"] TrailingStop["Check trailing_stop_pct"] MaxDD["Check max_drawdown_pct"] DailyLoss["Check max_daily_loss_pct"] end end subgraph Output["Output"] CalcMetrics["calculateMetrics()"] CalcEnhanced["calculateEnhancedMetrics()"] Result["AlgorithmBacktestResult"] end DataSource -->|"Yes"| LoadDS DataSource -->|"No"| LoadLive LoadDS --> ForEach LoadLive --> ForEach Overlays --> MacroCtx ForEach --> BuildCtx --> Evaluate EntryCheck -->|"Yes"| SizingCalc EntryCheck -->|"No"| ExitCheck ExitCheck -->|"Yes"| TradeExec SizingCalc --> SlippageCalc --> TradeExec --> UpdatePos UpdatePos --> Guardrails --> ForEach ForEach -->|"Done"| CalcMetrics --> CalcEnhanced --> Result

Metrics Calculated

13
Core Metrics
8
Enhanced Metrics
5
Risk Metrics
Core Metrics Enhanced Metrics Risk Metrics
Total Return, Annualized Return VaR 95/99, CVaR Max Drawdown
Sharpe Ratio, Sortino Ratio Cornish-Fisher VaR Drawdown Duration
Calmar Ratio, Volatility Monthly Returns Heatmap Win/Loss Streaks
Win Rate, Profit Factor Day-of-Week Seasonality Kelly Fraction
Avg Trade %, Total Trades Factor Attribution (Alpha, Beta, R²) Information Ratio

13. Paper Trading Executor

Real-time paper trading with tick-by-tick execution.

flowchart TB subgraph StartRun["startRun()"] ValidateAST["Validate StrategyAST"] CheckCredits["Reserve credits"] InitState["Initialize run state"] InsertDB["INSERT algorithm_runs"] InsertStatus["INSERT algorithm_run_status"] end subgraph TickLoop["tickRun() - Every Market Tick"] FetchPrices["Fetch live prices for universe"] ValidatePrices["Price validation (bounds, spike)"] subgraph PerSymbol["For Each Symbol"] BuildCtx["Build EvalContext"] EvalSignals["Evaluate signals"] CheckEntry{"Entry signal?"} CheckExit{"Exit signal?"} end subgraph ExecuteTrade["Execute Trade"] CalcSize["Calculate size (Kelly/fixed)"] CalcSlippage["Almgren-Chriss slippage"] SimFill["Simulate fill"] RecordTrade["INSERT algorithm_trades"] end subgraph UpdateState["Update State"] UpdatePos["Update positions"] CalcEquity["Calculate total equity"] InsertTelem["INSERT algorithm_telemetry"] SyncCredits["Sync credits with equity"] RecordLatency["Record decision latency"] end subgraph Guardrails["L1-L5 Guardrails"] L1["L1: Stop loss, trailing stop"] L2["L2: Daily loss, drawdown"] L3["L3: Event blackouts"] L4["L4: LLM anomaly (future)"] L5["L5: Human override"] end end subgraph StopRun["stopRun()"] FlattenPos["flattenAllPositions()"] RecordClosing["Record closing trades"] ReleaseCredits["Release credits + P/L"] DeleteStatus["DELETE algorithm_run_status"] UpdateRunStatus["UPDATE algorithm_runs SET status"] end StartRun --> TickLoop FetchPrices --> ValidatePrices --> PerSymbol CheckEntry -->|"Yes"| CalcSize CheckExit -->|"Yes"| SimFill CalcSize --> CalcSlippage --> SimFill --> RecordTrade RecordTrade --> UpdatePos --> CalcEquity --> InsertTelem --> SyncCredits SyncCredits --> Guardrails Guardrails -->|"Kill"| StopRun Guardrails -->|"Continue"| TickLoop

14. 5-Layer Guardrail System

Multi-layer protection for autonomous trading.

flowchart TB subgraph L1["Layer 1: Per-Trade Guards"] StopLoss["Stop Loss %"] TrailingStop["Trailing Stop %"] MaxPosition["Max Position USD"] Slippage["Slippage-Aware Sizing"] end subgraph L2["Layer 2: Run-Level Guards"] DailyLoss["Max Daily Loss %"] MaxDD["Max Drawdown %"] ConsecutiveLoss["Consecutive Loss Count"] CorrHaircut["Correlation Haircut"] end subgraph L3["Layer 3: Event Blackouts"] FedBlackout["FOMC Blackout Window"] CPIRelease["CPI Release Day"] EarningsBlackout["Earnings Within 2h"] HighVIX["VIX > Threshold"] end subgraph L4["Layer 4: LLM Anomaly Detection"] EODCritic["EOD Critic Review"] AnomalyDetect["Pattern Anomaly Detection"] JuryEscalation["Jury Escalation"] end subgraph L5["Layer 5: Human Override"] PanicButton["PANIC Kill Button"] AdminKill["Admin Kill Switch"] HardwareButton["Hardware Kill Switch"] PlatformKill["Platform-Wide Kill"] end Trade["Trade Signal"] --> L1 L1 -->|"Pass"| L2 L1 -->|"Fail"| Reject1["Reject Trade"] L2 -->|"Pass"| L3 L2 -->|"Fail"| Kill2["Kill Run"] L3 -->|"Clear"| L4 L3 -->|"Blackout"| Pause3["Pause Trading"] L4 -->|"Normal"| Execute["Execute Trade"] L4 -->|"Anomaly"| Escalate4["Escalate to Human"] L5 --> KillAll["Kill All Runs Immediately"]

Guardrail Implementations

Layer File Location Key Functions
L1: Per-Trade algorithms/guardrails/slippage-fitter.ts fitSlippageModel(), predictSlippage(), adjustSizeForSlippage()
L2: Run-Level algorithms/guardrails/correlation-haircut.ts computeCorrelationHaircut(), getEffectivePositionScale()
L3: Blackouts algorithms/paper/executor.ts checkEventBlackout(), isFedBlackoutWindow()
L4: LLM Anomaly algorithms/llm/eod-critic.ts runEODCritic(), evaluateRunHealth()
L5: Human Override trading/services/ai-kill-switch.ts activateKillSwitch(), isKillSwitchActive()

15. All Seeing Eye Integration

Unified AI orchestration providing DSL primitives for algorithmic trading.

flowchart TB subgraph AllSeeingEye["All Seeing Eye (packages/be/src/all-seeing-eye/)"] Orchestrator["orchestrator.ts"] TrustLayer["Trust Layer"] BlackSwan["Black Swan Detector"] subgraph Signals["Signal Providers"] HumanAuto["Human Automation Score"] ParadoxRisk["Paradox Risk"] BlackSwanSeverity["Black Swan Severity"] DivergenceClass["Divergence Class"] end end subgraph DSLPrimitives["DSL Primitives (exposed to algorithms)"] P1["human_automation_score(symbol)"] P2["paradox_risk()"] P3["black_swan_severity()"] P4["divergence_class()"] P5["is_crisis_regime()"] end subgraph Integration["Algorithm Integration"] Evaluator["DSL Evaluator"] BacktestEngine["Backtest Engine"] PaperExecutor["Paper Executor"] end Orchestrator --> TrustLayer Orchestrator --> BlackSwan TrustLayer --> HumanAuto TrustLayer --> DivergenceClass BlackSwan --> BlackSwanSeverity BlackSwan --> ParadoxRisk HumanAuto --> P1 ParadoxRisk --> P2 BlackSwanSeverity --> P3 DivergenceClass --> P4 P1 --> Evaluator P2 --> Evaluator P3 --> Evaluator P4 --> Evaluator Evaluator --> BacktestEngine Evaluator --> PaperExecutor

All Seeing Eye DSL Primitives

Primitive Return Type Description
human_automation_score(symbol) number [-1, +1] -1 = bot-dominated, +1 = human-driven market activity
paradox_risk() number [0, 1] Market divergence risk score
black_swan_severity() number [0, 10] Crisis severity level (0 = calm, 10 = extreme)
divergence_class() string HUMAN-DRIVEN | BOT-LIKELY | SOCIAL-NOISE | QUIET | INSUFFICIENT

16. Primitive to Engine Wiring

How DSL primitives connect through the evaluator to the backtest engine.

flowchart LR subgraph Registration["Primitive Registration"] Types["types.ts: PRIMITIVES registry"] Spec["PrimitiveSpec: name, args, returns"] end subgraph Evaluator["evaluator.ts"] Parse["Parse expression"] Lookup["Lookup primitive by name"] Validate["Validate arg types"] Dispatch["Dispatch to handler"] end subgraph Handlers["Handler Categories"] subgraph TechHandlers["Technical"] RSI["rsi() → ctx.indicators.rsi(period)"] MACD["macd() → ctx.indicators.macd()"] GARCH["garch_volatility() → garch.fitGarch()"] end subgraph MacroHandlers["Macro"] VIX["vix() → ctx.vix()"] Yield["treasury_2y10y_spread() → ctx.treasurySpread()"] Regime["markov_regime() → markovRegime.detectRegime()"] end subgraph PatternHandlers["Pattern"] FVG["fvg_present() → detectFVG(ctx.bars)"] Candle["is_hammer() → detectCandlePattern()"] end subgraph SentimentHandlers["Sentiment"] Whale["whale_activity() → ctx.whaleActivity()"] Funding["funding_rate() → ctx.fundingRate()"] end end subgraph Engine["Backtest Engine"] BuildBundle["Build IndicatorBundle"] BuildContext["Build EvalContext"] EvalEntry["Evaluate entry.when"] EvalExit["Evaluate exit.when"] end Types --> Evaluator Evaluator --> Handlers Engine --> BuildBundle --> BuildContext BuildContext --> Evaluator Evaluator --> EvalEntry Evaluator --> EvalExit

17. Indicator Bundle

Pre-computed technical indicators passed to the evaluator.

flowchart TB subgraph Input["Input Data"] Bars["OHLCV bars[0..idx]"] Prices["Close prices array"] end subgraph Compute["indicators.ts Computation"] RSI["computeRSI(prices, period)"] MACD["computeMACD(prices)"] BB["computeBollingerBands(prices, period, stdDev)"] ATR["computeATR(bars, period)"] OBV["computeOBV(bars)"] ADX["computeADX(bars, period)"] SMA["computeSMA(prices, period)"] ROC["computeROC(prices, period)"] end subgraph Advanced["Advanced Indicators"] GARCH["garch.fitGarch(prices)"] Hurst["hurst.computeHurst(prices)"] EGARCH["egarch.fitEGarch(prices)"] Regime["markovRegime.detectRegime(prices)"] Coint["cointegration.testCointegration(y, x)"] end subgraph Bundle["IndicatorBundle"] B1["rsi: (period) => number"] B2["macd: () => number"] B3["bbUpper/Lower: (period, stdDev) => number"] B4["atr: (period) => number"] B5["garchVolatility: (lookback) => number"] B6["hurstExponent: (lookback) => number"] B7["markovRegime: (lookback) => string"] end Bars --> Compute Prices --> Compute Compute --> Bundle Advanced --> Bundle

Key Indicator Files

File Indicators Lines
backtest/indicators.ts RSI, MACD, Bollinger, ATR, OBV, ADX, SMA, ROC ~500
backtest/garch.ts GARCH(1,1), GJR-GARCH volatility ~300
backtest/hurst.ts Hurst exponent (R/S analysis) ~150
backtest/egarch.ts EGARCH, leverage effect, news impact ~250
backtest/markov-regime.ts HMM regime detection (bull/bear/sideways/crisis) ~400
backtest/cointegration.ts Engle-Granger, Johansen tests ~350

18. Database Schema

Key tables for algorithm storage and execution tracking.

erDiagram user_algorithms ||--o{ algorithm_versions : has user_algorithms ||--o{ algorithm_runs : executes algorithm_runs ||--o{ algorithm_trades : generates algorithm_runs ||--o{ algorithm_telemetry : records algorithm_runs ||--o| algorithm_run_status : has_current user_algorithms ||--o{ algorithm_llm_rejections : logs user_algorithms ||--o{ algorithm_llm_jury : decides algorithm_runs ||--o{ algorithm_eod_critic : reviewed_by user_algorithms { uuid id PK uuid user_id FK string name jsonb ast string mode string status timestamp created_at } algorithm_versions { uuid id PK uuid algorithm_id FK jsonb ast string change_reason timestamp created_at } algorithm_runs { uuid id PK uuid algorithm_id FK string mode "backtest|paper|live" string status "running|stopped|killed" numeric starting_equity numeric current_equity jsonb metrics timestamp started_at timestamp ended_at } algorithm_trades { uuid id PK uuid run_id FK string symbol string side "buy|sell" numeric requested_price numeric executed_price numeric executed_qty numeric pnl numeric slippage_bps string exit_reason timestamp ts } algorithm_telemetry { uuid id PK uuid run_id FK numeric equity numeric drawdown_pct jsonb positions timestamp ts } algorithm_run_status { uuid run_id PK numeric current_equity jsonb positions timestamp last_tick_at } algorithm_eod_critic { uuid id PK uuid run_id FK date critic_date UK string verdict "continue|warn|escalate|kill" text reasoning timestamp created_at }

19. API Routes

Algorithm-related API endpoints.

Route Method Handler Purpose
/algorithms GET handleListAlgorithms List user's algorithms
/algorithms POST handleCreateAlgorithm Create new algorithm
/algorithms/from-english POST handleFromEnglish NL to DSL translation
/algorithms/:id/backtest POST handleBacktestAlgorithm Run backtest
/algorithms/:id/walk-forward POST handleWalkForwardBacktest Walk-forward optimization
/algorithms/:id/monte-carlo POST handleMonteCarloBacktest Bootstrap simulation
/algorithms/:id/stress-test POST handleStressTestAlgorithm Regime stress test
/algorithms/:id/critique POST handleCritique LLM critique
/algorithms/:id/paper/start POST handleStartPaperRun Start paper trading
/algorithms/:id/paper/stop POST handleStopPaperRun Stop paper trading
/algorithms/:id/live/start POST handleStartLiveRun Start live trading (gated)
/ai-kill-switch/activate POST handleActivateKillSwitch Emergency stop all trading

20. Credits System

Trading credits lifecycle for paper and live trading.

sequenceDiagram participant User participant StartRun as startRun() participant Credits as user_credits participant Executor as Paper Executor participant StopRun as stopRun() User->>StartRun: Start paper trading StartRun->>Credits: Check available credits Credits-->>StartRun: Available: $100,000 StartRun->>Credits: Reserve $10,000 for run Note over Credits: available: $90,000
reserved: $10,000 StartRun-->>Executor: Run started loop Every Tick Executor->>Executor: Calculate equity Executor->>Credits: Sync reserved with equity Note over Credits: If equity = $10,500
reserved syncs to $10,500 end User->>StopRun: Stop run StopRun->>Executor: flattenAllPositions() Executor->>Executor: Close all positions at market StopRun->>Credits: Release credits + P/L Note over Credits: available: $100,500
reserved: $0
(+$500 profit applied)

Credits Table Structure

Column Type Description
user_id UUID User reference
available_credits NUMERIC Credits available for new runs
reserved_credits NUMERIC Credits locked in active runs
total_pnl NUMERIC Lifetime P&L across all runs
updated_at TIMESTAMP Last update time

Primitives Requiring Data Sources

Some DSL primitives require external data feeds that may not be fully configured.

Note: The following primitives may return default/stubbed values if the required data source is not configured:
Primitive Required Data Source Status
dcc_correlation Multi-asset price history Needs multi-symbol loader
fama_french_* Kenneth French Data Library Needs FF factor data
wallet_* (crypto) Alchemy/Polygonscan API Needs API key
polymarket_* Polymarket API Fully wired
iv_rank, gamma_exposure Options data (Polygon/Schwab) Needs API key
institutional_* SEC EDGAR 13F Fully wired
activist_* SEC EDGAR 13D/13G Fully wired