|
1 | 1 | # Trading Bot System - LLM Guide |
2 | 2 |
|
| 3 | +Trading Bot Framework — Research Briefing |
| 4 | +This is a Python-based automated trading framework running on Kubernetes. Bots run as CronJobs, fetch market data, make decisions, and execute |
| 5 | + paper/live trades stored in PostgreSQL. |
| 6 | + |
| 7 | + --- |
| 8 | + Bot Interface — Two Patterns |
| 9 | + |
| 10 | + Pattern A: decisionFunction(row) -> int (simple, backtestable) |
| 11 | + - Override this method; the base class handles data fetching, looping, and execution |
| 12 | + - Called once per OHLCV row. Return 1 (buy), -1 (sell), 0 (hold) |
| 13 | + - The framework buys/sells self.symbol automatically |
| 14 | + - Supports local_backtest(), local_optimize(), hyperparameter tuning |
| 15 | + - Single-asset only — self.symbol must be set in __init__ |
| 16 | + |
| 17 | + class MyBot(Bot): |
| 18 | + def __init__(self): |
| 19 | + super().__init__("MyBot", symbol="QQQ", interval="1d", period="1y") |
| 20 | + |
| 21 | + def decisionFunction(self, row) -> int: |
| 22 | + if row["momentum_rsi"] < 30: |
| 23 | + return 1 |
| 24 | + elif row["momentum_rsi"] > 70: |
| 25 | + return -1 |
| 26 | + return 0 |
| 27 | + |
| 28 | + Pattern B: makeOneIteration() -> int (complex, not backtestable) |
| 29 | + - Override this method directly for multi-asset bots or external data sources |
| 30 | + - Manually call self.buy(symbol), self.sell(symbol), self.rebalancePortfolio(weights) |
| 31 | + - Use when: portfolio rebalancing across N symbols, signals come from a DB table, external API (Fear & Greed), AI agent flows |
| 32 | + |
| 33 | + --- |
| 34 | + Data Available |
| 35 | + |
| 36 | + 1. Yahoo Finance OHLCV — via self.getYFDataWithTA(interval, period) |
| 37 | + - Returns a DataFrame with timestamp, open, high, low, close, volume + ~150 TA indicators |
| 38 | + - Intervals: 1m, 5m, 15m, 30m, 1h, 4h, 1d, 1wk, 1mo |
| 39 | + - Periods: 1d, 5d, 7d, 1mo, 3mo, 6mo, 1y, 2y, max (minute data capped at 60 days by Yahoo) |
| 40 | + - Multi-symbol: self.getYFDataMultiple(symbols, interval, period) — returns long-format DataFrame |
| 41 | + |
| 42 | + 2. Technical Indicators — via ta library (add_all_ta_features) |
| 43 | + All ~150 indicators are pre-computed and available as columns. Key ones: |
| 44 | + - Momentum: momentum_rsi, momentum_stoch, momentum_stoch_signal, momentum_macd, momentum_macd_signal, momentum_cci, momentum_williams_r |
| 45 | + - Trend: trend_macd, trend_macd_signal, trend_macd_diff, trend_sma_fast, trend_sma_slow, trend_ema_fast, trend_ema_slow, trend_adx, |
| 46 | + trend_adx_pos, trend_adx_neg, trend_ichimoku_*, trend_aroon_up/down |
| 47 | + - Volatility: volatility_bbm, volatility_bbh, volatility_bbl, volatility_bbw, volatility_atr, volatility_kcp, volatility_dcp |
| 48 | + - Volume: volume_obv, volume_adi, volume_cmf, volume_fi, volume_mfi, volume_em, volume_vpt |
| 49 | + |
| 50 | + 3. PostgreSQL Tables |
| 51 | + |
| 52 | + ┌──────────────────────┬───────────────────────────────────────────────────┬────────────────────────┐ |
| 53 | + │ Table │ Contents │ Used by │ |
| 54 | + ├──────────────────────┼───────────────────────────────────────────────────┼────────────────────────┤ |
| 55 | + │ bots │ Portfolio state JSON per bot │ All bots │ |
| 56 | + ├──────────────────────┼───────────────────────────────────────────────────┼────────────────────────┤ |
| 57 | + │ trades │ Trade history (symbol, price, qty, isBuy) │ All bots │ |
| 58 | + ├──────────────────────┼───────────────────────────────────────────────────┼────────────────────────┤ |
| 59 | + │ run_logs │ Execution history, success/error │ All bots │ |
| 60 | + ├──────────────────────┼───────────────────────────────────────────────────┼────────────────────────┤ |
| 61 | + │ portfolio_worth │ Daily portfolio value snapshots │ Dashboard │ |
| 62 | + ├──────────────────────┼───────────────────────────────────────────────────┼────────────────────────┤ |
| 63 | + │ historic_data │ Cached OHLCV (avoids re-fetching) │ All bots │ |
| 64 | + ├──────────────────────┼───────────────────────────────────────────────────┼────────────────────────┤ |
| 65 | + │ stock_news │ Recent news headlines per symbol from yfinance │ StockNewsSentimentBot │ |
| 66 | + ├──────────────────────┼───────────────────────────────────────────────────┼────────────────────────┤ |
| 67 | + │ stock_earnings │ Earnings dates, EPS estimate vs actual, surprise% │ EarningsInsiderTiltBot │ |
| 68 | + ├──────────────────────┼───────────────────────────────────────────────────┼────────────────────────┤ |
| 69 | + │ stock_insider_trades │ Insider buy/sell transactions │ EarningsInsiderTiltBot │ |
| 70 | + ├──────────────────────┼───────────────────────────────────────────────────┼────────────────────────┤ |
| 71 | + │ telegram_messages │ Telegram channel messages + AI summaries + symbol │ TelegramSignalsBankBot │ |
| 72 | + └──────────────────────┴───────────────────────────────────────────────────┴────────────────────────┘ |
| 73 | + |
| 74 | + 4. AI — via OpenRouter |
| 75 | + - Cheap model (default openai/gpt-oss-120b): self.run_ai_simple(system, user) — classification, extraction, single-turn |
| 76 | + - Main model (default deepseek/deepseek-v3.2): self.run_ai(system, user) — multi-turn with tools (portfolio lookup, market data, trade |
| 77 | + history, news lookup) |
| 78 | + - Fallback wrapper: self.run_ai_simple_with_fallback(system, user, sanity_check) — cheap first, retries with main if output fails sanity check |
| 79 | + |
| 80 | + 5. Regime / Sentiment Utilities |
| 81 | + - utils.regime — detects bull/bear/sideways regime from price data |
| 82 | + - utils.ta_regime — TA-based regime via ADX + trend filters |
| 83 | + - utils.sentiment — fear/greed or other sentiment adapters |
| 84 | + |
| 85 | + 6. Tradeable Universe — utils.portfolio.TRADEABLE |
| 86 | + - Pre-defined list of liquid ETFs/stocks suitable for the portfolio rebalancing bots |
| 87 | + |
| 88 | + --- |
| 89 | + Portfolio Operations |
| 90 | + |
| 91 | + self.buy(symbol, quantityUSD=-1) # -1 = all cash |
| 92 | + self.sell(symbol, quantityUSD=-1) # -1 = all holdings |
| 93 | + self.rebalancePortfolio({"QQQ": 0.6, "GLD": 0.3, "USD": 0.1}) |
| 94 | + self.getLatestPrice(symbol) # float |
| 95 | + self.getLatestPricesBatch(symbols) # dict[str, float] |
| 96 | + |
| 97 | + Portfolio state is a JSON dict in PostgreSQL: {"USD": 8432.10, "QQQ": 12.5, "GC=F": 0.03}. |
| 98 | + |
| 99 | + --- |
| 100 | + Guardrails & Limitations |
| 101 | + |
| 102 | + Hard limitations: |
| 103 | + 1. Single-asset decisionFunction only — local_backtest() requires symbol != None. Multi-asset bots (makeOneIteration) cannot be backtested |
| 104 | + with the built-in engine. |
| 105 | + 2. No short selling — sell() only sells existing holdings; going short is not supported. |
| 106 | + 3. No leverage — position sizing is bounded by available cash. |
| 107 | + 4. No fractional lot enforcement — the framework buys fractional quantities; fine for crypto/forex, may not reflect reality for equities. |
| 108 | + 5. Minute data capped at 60 days — Yahoo Finance hard limit for intervals ≤ 90m. |
| 109 | + 6. Backtest warmup skip — first ~26 bars are skipped when trend_adx == 0.0 (TA warmup period); strategies that need very few bars may lose |
| 110 | + meaningful data. |
| 111 | + |
| 112 | + Backtest realism (recently fixed): |
| 113 | + - Slippage: 0.05% per side (configurable via slippage_pct) |
| 114 | + - Commission: 0% default (configurable via commission_pct) |
| 115 | + - Risk-free rate: 0% default for Sharpe (configurable via risk_free_rate) |
| 116 | + - No look-ahead bias — bfill() removed from TA computation |
| 117 | + |
| 118 | + Practical constraints: |
| 119 | + - Bots run as Kubernetes CronJobs — no real-time streaming, no intra-bar execution |
| 120 | + - Minimum meaningful trade: quantityUSD > $10 (enforced in signal bots) |
| 121 | + - All times are UTC; market hours not enforced (strategy must handle weekends/holidays if needed) |
| 122 | + - acted_on flag pattern is used for event-driven bots (Telegram signals, stock news) to prevent double-execution on crash |
| 123 | + |
| 124 | + --- |
| 125 | + Existing Strategies (don't duplicate) |
| 126 | + |
| 127 | + ┌────────────────────────┬──────────────┬────────────────────────────────────────────────┐ |
| 128 | + │ Bot │ Asset │ Strategy │ |
| 129 | + ├────────────────────────┼──────────────┼────────────────────────────────────────────────┤ |
| 130 | + │ EURUSDTreeBot │ EURUSD │ Decision tree on TA indicators │ |
| 131 | + ├────────────────────────┼──────────────┼────────────────────────────────────────────────┤ |
| 132 | + │ XAUZenBot │ Gold (GC=F) │ Multi-indicator TA threshold rules │ |
| 133 | + ├────────────────────────┼──────────────┼────────────────────────────────────────────────┤ |
| 134 | + │ XAUAISyntheticMetalBot │ Gold │ AI agent with TA + market data tools │ |
| 135 | + ├────────────────────────┼──────────────┼────────────────────────────────────────────────┤ |
| 136 | + │ SwingTitaniumBot │ configurable │ Swing highs/lows detection on close │ |
| 137 | + ├────────────────────────┼──────────────┼────────────────────────────────────────────────┤ |
| 138 | + │ TARegimeBot │ configurable │ TA regime (ADX + trend) → buy/sell │ |
| 139 | + ├────────────────────────┼──────────────┼────────────────────────────────────────────────┤ |
| 140 | + │ FearGreedBot │ QQQ │ CNN Fear & Greed Index thresholds │ |
| 141 | + ├────────────────────────┼──────────────┼────────────────────────────────────────────────┤ |
| 142 | + │ RegimeAdaptiveBot │ multi │ AI decides allocation by market regime │ |
| 143 | + ├────────────────────────┼──────────────┼────────────────────────────────────────────────┤ |
| 144 | + │ AIHedgeFundBot │ multi │ Full AI hedge fund analysis → rebalance │ |
| 145 | + ├────────────────────────┼──────────────┼────────────────────────────────────────────────┤ |
| 146 | + │ AIDeepSeekToolBot │ configurable │ AI agent with full tool suite │ |
| 147 | + ├────────────────────────┼──────────────┼────────────────────────────────────────────────┤ |
| 148 | + │ EarningsInsiderTiltBot │ multi │ Equal-weight + tilt by earnings/insider scores │ |
| 149 | + ├────────────────────────┼──────────────┼────────────────────────────────────────────────┤ |
| 150 | + │ TelegramSignalsBankBot │ multi │ AI classifies Telegram signals → trade │ |
| 151 | + ├────────────────────────┼──────────────┼────────────────────────────────────────────────┤ |
| 152 | + │ StockNewsSentimentBot │ multi │ AI classifies news headlines → trade │ |
| 153 | + └────────────────────────┴──────────────┴────────────────────────────────────────────────┘ |
| 154 | + |
| 155 | + --- |
| 156 | + What a New Strategy Should Specify |
| 157 | + |
| 158 | + 1. Pattern: A (decisionFunction) or B (makeOneIteration)? |
| 159 | + 2. Symbol(s): single ticker or portfolio? |
| 160 | + 3. Interval + period: what data granularity? |
| 161 | + 4. Signal logic: what columns/data drive the decision? |
| 162 | + 5. Hyperparameter grid (optional): dict of lists for local_optimize() to tune |
| 163 | + 6. Schedule: how often to run (cron string)? |
| 164 | + |
3 | 165 | This document provides essential information for LLMs working with this trading bot codebase. It explains the architecture, the Bot class system, and how to effectively work with the code. |
4 | 166 |
|
5 | 167 | ## Repository Overview |
|
0 commit comments