mfn

architecture llm polymarket

mfn
Apr 9th, 2026
38
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 18.63 KB | None | 0 0
  1. # AI Trading Engine — Reference Architecture
  2.  
  3. ## "Strategies as Context, AI as Brain"
  4.  
  5. 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.
  6.  
  7. This architecture is platform-agnostic. Swap in any broker/exchange SDK that provides bar data and quote streams.
  8.  
  9. ## High-Level Flow
  10.  
  11. ```
  12. ┌─────────────────────────────────────────────────────────────┐
  13. │ STREAMING PLATFORM │
  14. │ (Any broker / exchange / data feed) │
  15. │ │
  16. │ Provides: │
  17. │ • Real-time quotes (WebSocket / streaming API) │
  18. │ • Historical bar data (REST / batch API) │
  19. │ • Fill / position events │
  20. └──────────┬──────────────────────────────────────┬───────────┘
  21. │ Real-time stream │ REST / batch
  22. │ Quotes, Events │ Bar data
  23. ▼ ▼
  24. ┌─────────────────────────────────────────────────────────────┐
  25. │ DATA ADAPTER LAYER │
  26. │ │
  27. │ Normalizes broker-specific data into standard format: │
  28. │ │
  29. │ Bar { timestamp, open, high, low, close, volume } │
  30. │ Quote { bid, ask, last, size } │
  31. │ │
  32. │ Handles: │
  33. │ • Stream reconnection / health monitoring │
  34. │ • REST fallback when stream is dead │
  35. │ • Deduplication (prevent processing same bar twice) │
  36. │ • Race condition prevention (lock on bar processing) │
  37. └────────────────────────┬────────────────────────────────────┘
  38. │
  39. ▼
  40. ┌─────────────────────────────────────────────────────────────┐
  41. │ BAR BUILDER │
  42. │ │
  43. │ Rolling window of completed bars (e.g. 120× 5-min) │
  44. │ │
  45. │ • Rebuilt from REST data on each cycle (single source) │
  46. │ • Last bar dropped (in-progress, partial volume) │
  47. │ • Dedup by completed bar timestamp │
  48. │ • Multiple timeframes fetched separately: │
  49. │ - Primary (5-min) — 15 bars for pattern detection │
  50. │ - Short (1-min) — 15 bars for micro-structure │
  51. │ - Long (hourly) — 12 bars for big picture │
  52. └────────────────────────┬────────────────────────────────────┘
  53. │
  54. ▼
  55. ┌─────────────────────────────────────────────────────────────┐
  56. │ TECHNICAL INDICATORS │
  57. │ │
  58. │ Standard indicators computed from bar arrays: │
  59. │ │
  60. │ Trend: EMA 9/21, SMA 50, EMA cross │
  61. │ Momentum: RSI 14, MACD (12/26/9), MACD histogram │
  62. │ Volatility: ATR 14, Bollinger Bands (20, 2σ) │
  63. │ Volume: Session-aware ratio (see below) │
  64. │ Price: VWAP + standard deviation bands │
  65. │ Structure: Pivot points, support/resistance levels │
  66. │ Regime: Trending up / down / ranging / volatile │
  67. │ │
  68. │ All indicators always computed — no "no signal" state. │
  69. │ Raw values passed to the scorer, not buy/sell labels. │
  70. └────────────────────────┬────────────────────────────────────┘
  71. │
  72. ▼
  73. ┌─────────────────────────────────────────────────────────────┐
  74. │ MARKET CONTEXT SCORER │
  75. │ │
  76. │ Transforms raw indicators into continuous dimensions. │
  77. │ Every dimension ALWAYS has something to say: │
  78. │ │
  79. │ 1. Trend (-100 to +100) │
  80. │ │ Composite of EMA cross, MACD direction, VWAP │
  81. │ │ position, RSI bias. Labels: STRONG_BULL, BULL, │
  82. │ │ NEUTRAL, BEAR, STRONG_BEAR │
  83. │ │ │
  84. │ 2. Momentum (-100 to +100) │
  85. │ │ Rate of change, acceleration/deceleration. │
  86. │ │ Catches when moves are speeding up or fading. │
  87. │ │ │
  88. │ 3. Mean Reversion (0 to 100) │
  89. │ │ How extended price is from mean. Includes snap │
  90. │ │ direction (UP/DOWN). High values = likely to revert. │
  91. │ │ │
  92. │ 4. Volatility (label: LOW / NORMAL / HIGH / EXTREME) │
  93. │ │ ATR relative to recent history. Compression or │
  94. │ │ expansion detection. │
  95. │ │ │
  96. │ 5. Volume (ratio + label) │
  97. │ │ Session-aware: compared to same time-of-day bucket. │
  98. │ │ Labels: DEAD / BELOW_AVG / NORMAL / ABOVE_AVG / SURGE │
  99. │ │ │
  100. │ 6. S/R Proximity (nearest level + ATR distance) │
  101. │ │ Distance to nearest support/resistance in ATR units. │
  102. │ │ Alerts AI when price is near key decision points. │
  103. │ │ │
  104. │ 7. Key Levels (prices) │
  105. │ VWAP, EMA 9/21, SMA 50, BB upper/lower, pivot, S/R. │
  106. │ Raw levels for AI to reason about. │
  107. │ │
  108. │ Optional overlay — GAMMA EXPOSURE (GEX): │
  109. │ │ If you have access to options data: │
  110. │ │ • Gamma regime (positive = mean reversion expected, │
  111. │ │ negative = trending expected) │
  112. │ │ • Call Wall (resistance), Put Wall (support) │
  113. │ │ • Zero-Gamma strike (regime flip level) │
  114. │ │ Only include when data is fresh. Exclude if stale. │
  115. │ │
  116. │ Output: Formatted text dashboard for the AI prompt. │
  117. │ Human-readable, not JSON — the LLM interprets it. │
  118. └──────────────────────────┬──────────────────────────────────┘
  119. │
  120. ▼
  121. ┌─────────────────────────────────────────────────────────────┐
  122. │ AI CONTEXT BUILDER │
  123. │ │
  124. │ Assembles everything the LLM needs to make a decision: │
  125. │ │
  126. │ ┌──────────────────────────────────────────────────┐ │
  127. │ │ SYSTEM PROMPT │ │
  128. │ │ • Role: disciplined futures trader │ │
  129. │ │ • Rules: risk limits, position sizing, hours │ │
  130. │ │ • Output format: structured JSON response │ │
  131. │ └──────────────────────────────────────────────────┘ │
  132. │ │
  133. │ ┌──────────────────────────────────────────────────┐ │
  134. │ │ MARKET CONTEXT DASHBOARD │ │
  135. │ │ • 7 dimension scores (from scorer above) │ │
  136. │ │ • GEX overlay (if fresh) │ │
  137. │ └──────────────────────────────────────────────────┘ │
  138. │ │
  139. │ ┌──────────────────────────────────────────────────┐ │
  140. │ │ BAR DATA (multi-timeframe) │ │
  141. │ │ • 15× primary bars (e.g. 5-min OHLCV) │ │
  142. │ │ • 15× short bars (e.g. 1-min OHLCV) │ │
  143. │ │ • 12× long bars (e.g. hourly OHLCV) │ │
  144. │ └──────────────────────────────────────────────────┘ │
  145. │ │
  146. │ ┌──────────────────────────────────────────────────┐ │
  147. │ │ ACCOUNT STATE │ │
  148. │ │ • Current P&L, trade count, balance │ │
  149. │ │ • Open position (if any) │ │
  150. │ │ • Risk budget remaining │ │
  151. │ └──────────────────────────────────────────────────┘ │
  152. │ │
  153. │ ┌──────────────────────────────────────────────────┐ │
  154. │ │ INTRA-SESSION TRADE FEEDBACK │ │
  155. │ │ • Rolling summary of today's closed trades │ │
  156. │ │ • Pattern detection: losing streaks, directional │ │
  157. │ │ bias, repeated thesis failures │ │
  158. │ │ • Helps AI avoid repeating mistakes │ │
  159. │ └──────────────────────────────────────────────────┘ │
  160. └──────────────────────────┬──────────────────────────────────┘
  161. │
  162. ▼
  163. ┌─────────────────────────────────────────────────────────────┐
  164. │ AI TRADER (LLM) │
  165. │ │
  166. │ Any capable LLM (Claude, GPT-4, etc.) │
  167. │ │
  168. │ Input: System prompt + context (above) │
  169. │ Output: Structured JSON decision │
  170. │ │
  171. │ ┌──────────────────────────────────────────────────┐ │
  172. │ │ DECISION SCHEMA │ │
  173. │ │ │ │
  174. │ │ { │ │
  175. │ │ "action": "trade" | "hold", │ │
  176. │ │ "direction": "LONG" | "SHORT", │ │
  177. │ │ "confidence": 0.0 - 1.0, │ │
  178. │ │ "size": 1-10, │ │
  179. │ │ "sl_ticks": int, │ │
  180. │ │ "tp_ticks": int, │ │
  181. │ │ "reasoning": "string" │ │
  182. │ │ } │ │
  183. │ └──────────────────────────────────────────────────┘ │
  184. │ │
  185. │ Key design principles: │
  186. │ • AI sees everything — don't hide data behind hard gates │
  187. │ • Confidence is continuous, not binary │
  188. │ • Reasoning is required — forces the LLM to justify │
  189. │ • Trade feedback prevents repeating intra-day mistakes │
  190. │ • No post-decision AI review — let bracket orders manage │
  191. │ exits to avoid second-guessing │
  192. └─────────────────────────────────────────────────────────────┘
  193.  
  194. │
  195. ▼
  196.  
  197. YOUR EXECUTION LAYER
  198. (implement as needed for
  199. your broker / exchange)
  200. ```
  201.  
  202. ## Session-Aware Volume
  203.  
  204. Volume varies dramatically by time of day. Comparing a midnight bar to a market-open bar
  205. is meaningless. Instead, compare each bar only to its time-of-day bucket:
  206.  
  207. | Bucket | Example Hours | Character |
  208. |--------|---------------|-----------|
  209. | Open | First 2h of RTH | Highest volume |
  210. | Midday | Middle of session | Moderate |
  211. | Afternoon | Last 3h of RTH | Winding down |
  212. | Overnight | Off-hours / Globex | Lowest volume |
  213.  
  214. Adjust buckets to your market's hours. Use IQR-based outlier removal within each bucket
  215. to prevent restart artifacts or data glitches from distorting averages.
  216.  
  217. ## Design Decisions & Why
  218.  
  219. **Why continuous scores, not binary signals?**
  220. 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.
  221.  
  222. **Why no trend guard or hard gates?**
  223. 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.
  224.  
  225. **Why no AI position review loop?**
  226. 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.
  227.  
  228. **Why balance-delta P&L instead of trade sums?**
  229. Trade-level P&L sums miss commissions, fees, slippage, and fills from prior sessions. Account balance is the only number that's always correct.
  230.  
  231. **Why exclude stale GEX data?**
  232. 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.
  233.  
  234. **Why format the dashboard as text, not JSON?**
  235. 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"}`.
  236.  
  237. ## Adapting This Architecture
  238.  
  239. **To use with a different broker:**
  240. 1. Replace the data adapter layer with your broker's SDK
  241. 2. Normalize bars to `{ timestamp, open, high, low, close, volume }`
  242. 3. Implement your own execution layer below the AI output
  243.  
  244. **To use with a different instrument:**
  245. 1. Adjust session-aware volume buckets for your market's hours
  246. 2. Tune ATR-based SL minimums for your instrument's volatility
  247. 3. Adjust tick size references in the position monitor
  248.  
  249. **To use with a different LLM:**
  250. 1. Swap the API call in the AI trader module
  251. 2. Keep the structured JSON output schema — parse it the same way
  252. 3. Adjust the system prompt for the model's strengths
  253.  
  254. **Optional components you can add:**
  255. - GEX overlay (requires options data access)
  256. - News/sentiment feed (inject into context builder)
  257. - Multiple instrument support (run parallel scorers)
  258.  
Add Comment
Please, Sign In to add comment