Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- # AI Trading Engine — Reference Architecture
- ## "Strategies as Context, AI as Brain"
- Instead of binary buy/sell signals from traditional strategies, the AI receives a **Market Context Dashboard** — continuous scores across multiple dimensions that always have something to say. The AI synthesizes the dashboard with raw bar data into trading decisions.
- This architecture is platform-agnostic. Swap in any broker/exchange SDK that provides bar data and quote streams.
- ## High-Level Flow
- ```
- ┌─────────────────────────────────────────────────────────────┐
- │ STREAMING PLATFORM │
- │ (Any broker / exchange / data feed) │
- │ │
- │ Provides: │
- │ • Real-time quotes (WebSocket / streaming API) │
- │ • Historical bar data (REST / batch API) │
- │ • Fill / position events │
- └──────────┬──────────────────────────────────────┬───────────┘
- │ Real-time stream │ REST / batch
- │ Quotes, Events │ Bar data
- ▼ ▼
- ┌─────────────────────────────────────────────────────────────┐
- │ DATA ADAPTER LAYER │
- │ │
- │ Normalizes broker-specific data into standard format: │
- │ │
- │ Bar { timestamp, open, high, low, close, volume } │
- │ Quote { bid, ask, last, size } │
- │ │
- │ Handles: │
- │ • Stream reconnection / health monitoring │
- │ • REST fallback when stream is dead │
- │ • Deduplication (prevent processing same bar twice) │
- │ • Race condition prevention (lock on bar processing) │
- └────────────────────────┬────────────────────────────────────┘
- │
- ▼
- ┌─────────────────────────────────────────────────────────────┐
- │ BAR BUILDER │
- │ │
- │ Rolling window of completed bars (e.g. 120× 5-min) │
- │ │
- │ • Rebuilt from REST data on each cycle (single source) │
- │ • Last bar dropped (in-progress, partial volume) │
- │ • Dedup by completed bar timestamp │
- │ • Multiple timeframes fetched separately: │
- │ - Primary (5-min) — 15 bars for pattern detection │
- │ - Short (1-min) — 15 bars for micro-structure │
- │ - Long (hourly) — 12 bars for big picture │
- └────────────────────────┬────────────────────────────────────┘
- │
- ▼
- ┌─────────────────────────────────────────────────────────────┐
- │ TECHNICAL INDICATORS │
- │ │
- │ Standard indicators computed from bar arrays: │
- │ │
- │ Trend: EMA 9/21, SMA 50, EMA cross │
- │ Momentum: RSI 14, MACD (12/26/9), MACD histogram │
- │ Volatility: ATR 14, Bollinger Bands (20, 2σ) │
- │ Volume: Session-aware ratio (see below) │
- │ Price: VWAP + standard deviation bands │
- │ Structure: Pivot points, support/resistance levels │
- │ Regime: Trending up / down / ranging / volatile │
- │ │
- │ All indicators always computed — no "no signal" state. │
- │ Raw values passed to the scorer, not buy/sell labels. │
- └────────────────────────┬────────────────────────────────────┘
- │
- ▼
- ┌─────────────────────────────────────────────────────────────┐
- │ MARKET CONTEXT SCORER │
- │ │
- │ Transforms raw indicators into continuous dimensions. │
- │ Every dimension ALWAYS has something to say: │
- │ │
- │ 1. Trend (-100 to +100) │
- │ │ Composite of EMA cross, MACD direction, VWAP │
- │ │ position, RSI bias. Labels: STRONG_BULL, BULL, │
- │ │ NEUTRAL, BEAR, STRONG_BEAR │
- │ │ │
- │ 2. Momentum (-100 to +100) │
- │ │ Rate of change, acceleration/deceleration. │
- │ │ Catches when moves are speeding up or fading. │
- │ │ │
- │ 3. Mean Reversion (0 to 100) │
- │ │ How extended price is from mean. Includes snap │
- │ │ direction (UP/DOWN). High values = likely to revert. │
- │ │ │
- │ 4. Volatility (label: LOW / NORMAL / HIGH / EXTREME) │
- │ │ ATR relative to recent history. Compression or │
- │ │ expansion detection. │
- │ │ │
- │ 5. Volume (ratio + label) │
- │ │ Session-aware: compared to same time-of-day bucket. │
- │ │ Labels: DEAD / BELOW_AVG / NORMAL / ABOVE_AVG / SURGE │
- │ │ │
- │ 6. S/R Proximity (nearest level + ATR distance) │
- │ │ Distance to nearest support/resistance in ATR units. │
- │ │ Alerts AI when price is near key decision points. │
- │ │ │
- │ 7. Key Levels (prices) │
- │ VWAP, EMA 9/21, SMA 50, BB upper/lower, pivot, S/R. │
- │ Raw levels for AI to reason about. │
- │ │
- │ Optional overlay — GAMMA EXPOSURE (GEX): │
- │ │ If you have access to options data: │
- │ │ • Gamma regime (positive = mean reversion expected, │
- │ │ negative = trending expected) │
- │ │ • Call Wall (resistance), Put Wall (support) │
- │ │ • Zero-Gamma strike (regime flip level) │
- │ │ Only include when data is fresh. Exclude if stale. │
- │ │
- │ Output: Formatted text dashboard for the AI prompt. │
- │ Human-readable, not JSON — the LLM interprets it. │
- └──────────────────────────┬──────────────────────────────────┘
- │
- ▼
- ┌─────────────────────────────────────────────────────────────┐
- │ AI CONTEXT BUILDER │
- │ │
- │ Assembles everything the LLM needs to make a decision: │
- │ │
- │ ┌──────────────────────────────────────────────────┐ │
- │ │ SYSTEM PROMPT │ │
- │ │ • Role: disciplined futures trader │ │
- │ │ • Rules: risk limits, position sizing, hours │ │
- │ │ • Output format: structured JSON response │ │
- │ └──────────────────────────────────────────────────┘ │
- │ │
- │ ┌──────────────────────────────────────────────────┐ │
- │ │ MARKET CONTEXT DASHBOARD │ │
- │ │ • 7 dimension scores (from scorer above) │ │
- │ │ • GEX overlay (if fresh) │ │
- │ └──────────────────────────────────────────────────┘ │
- │ │
- │ ┌──────────────────────────────────────────────────┐ │
- │ │ BAR DATA (multi-timeframe) │ │
- │ │ • 15× primary bars (e.g. 5-min OHLCV) │ │
- │ │ • 15× short bars (e.g. 1-min OHLCV) │ │
- │ │ • 12× long bars (e.g. hourly OHLCV) │ │
- │ └──────────────────────────────────────────────────┘ │
- │ │
- │ ┌──────────────────────────────────────────────────┐ │
- │ │ ACCOUNT STATE │ │
- │ │ • Current P&L, trade count, balance │ │
- │ │ • Open position (if any) │ │
- │ │ • Risk budget remaining │ │
- │ └──────────────────────────────────────────────────┘ │
- │ │
- │ ┌──────────────────────────────────────────────────┐ │
- │ │ INTRA-SESSION TRADE FEEDBACK │ │
- │ │ • Rolling summary of today's closed trades │ │
- │ │ • Pattern detection: losing streaks, directional │ │
- │ │ bias, repeated thesis failures │ │
- │ │ • Helps AI avoid repeating mistakes │ │
- │ └──────────────────────────────────────────────────┘ │
- └──────────────────────────┬──────────────────────────────────┘
- │
- ▼
- ┌─────────────────────────────────────────────────────────────┐
- │ AI TRADER (LLM) │
- │ │
- │ Any capable LLM (Claude, GPT-4, etc.) │
- │ │
- │ Input: System prompt + context (above) │
- │ Output: Structured JSON decision │
- │ │
- │ ┌──────────────────────────────────────────────────┐ │
- │ │ DECISION SCHEMA │ │
- │ │ │ │
- │ │ { │ │
- │ │ "action": "trade" | "hold", │ │
- │ │ "direction": "LONG" | "SHORT", │ │
- │ │ "confidence": 0.0 - 1.0, │ │
- │ │ "size": 1-10, │ │
- │ │ "sl_ticks": int, │ │
- │ │ "tp_ticks": int, │ │
- │ │ "reasoning": "string" │ │
- │ │ } │ │
- │ └──────────────────────────────────────────────────┘ │
- │ │
- │ Key design principles: │
- │ • AI sees everything — don't hide data behind hard gates │
- │ • Confidence is continuous, not binary │
- │ • Reasoning is required — forces the LLM to justify │
- │ • Trade feedback prevents repeating intra-day mistakes │
- │ • No post-decision AI review — let bracket orders manage │
- │ exits to avoid second-guessing │
- └─────────────────────────────────────────────────────────────┘
- │
- ▼
- YOUR EXECUTION LAYER
- (implement as needed for
- your broker / exchange)
- ```
- ## Session-Aware Volume
- Volume varies dramatically by time of day. Comparing a midnight bar to a market-open bar
- is meaningless. Instead, compare each bar only to its time-of-day bucket:
- | Bucket | Example Hours | Character |
- |--------|---------------|-----------|
- | Open | First 2h of RTH | Highest volume |
- | Midday | Middle of session | Moderate |
- | Afternoon | Last 3h of RTH | Winding down |
- | Overnight | Off-hours / Globex | Lowest volume |
- Adjust buckets to your market's hours. Use IQR-based outlier removal within each bucket
- to prevent restart artifacts or data glitches from distorting averages.
- ## Design Decisions & Why
- **Why continuous scores, not binary signals?**
- Binary strategies (buy/sell/flat) are usually FLAT. The AI gets nothing to work with. Continuous scores always have information — the AI can weigh a trend score of +30 differently than +80.
- **Why no trend guard or hard gates?**
- The AI already sees the trend score. A hard gate that blocks counter-trend trades also blocks valid mean reversion entries. Trust the AI's synthesis — it can weigh trend against other dimensions.
- **Why no AI position review loop?**
- In testing, the AI second-guessed its own bracket exits and closed positions prematurely. SL/TP brackets set at entry are more disciplined than real-time AI judgment under P&L pressure.
- **Why balance-delta P&L instead of trade sums?**
- Trade-level P&L sums miss commissions, fees, slippage, and fills from prior sessions. Account balance is the only number that's always correct.
- **Why exclude stale GEX data?**
- Old gamma exposure data is worse than no data — it gives the AI false confidence about support/resistance levels that may have shifted. If it's not fresh, don't send it.
- **Why format the dashboard as text, not JSON?**
- LLMs reason better with human-readable text. A formatted dashboard with labels like "STRONG_BEAR (-72)" is more interpretable than `{"trend_score": -72, "trend_label": "STRONG_BEAR"}`.
- ## Adapting This Architecture
- **To use with a different broker:**
- 1. Replace the data adapter layer with your broker's SDK
- 2. Normalize bars to `{ timestamp, open, high, low, close, volume }`
- 3. Implement your own execution layer below the AI output
- **To use with a different instrument:**
- 1. Adjust session-aware volume buckets for your market's hours
- 2. Tune ATR-based SL minimums for your instrument's volatility
- 3. Adjust tick size references in the position monitor
- **To use with a different LLM:**
- 1. Swap the API call in the AI trader module
- 2. Keep the structured JSON output schema — parse it the same way
- 3. Adjust the system prompt for the model's strengths
- **Optional components you can add:**
- - GEX overlay (requires options data access)
- - News/sentiment feed (inject into context builder)
- - Multiple instrument support (run parallel scorers)
Add Comment
Please, Sign In to add comment