How to Build an AI Trading Bot: Complete Architecture Guide
Data layer, LLM decision engine, critic agent, risk management, infrastructure. Complete guide with real code and lessons from our simulated paper trading bot.
What you'll build: An autonomous trading bot with LLM decision-making, adversarial risk review, and hard-coded safety controls. This architecture was run in paper mode only and the bot has since been retired. Here's every component.
Why Most Crypto Trading Bots Fail
Before the architecture, it's worth being specific about why most trading bots don't make it to a stable live deployment. There are four failure modes we see repeatedly:
Failure Mode 1: Curve-fitting
A strategy that was optimized on historical data until it fit perfectly. The backtest looks exceptional. Live performance is flat or negative because the strategy learned noise, not signal. The fix: out-of-sample testing and walk-forward validation before you trust any backtest result.
Failure Mode 2: No risk management
A bot with a positive-expectancy strategy but no position sizing or drawdown controls can still blow up an account. One bad trade with too-large position size erases weeks of gains. Risk management is not optional — it is the difference between a system and a gamble.
Failure Mode 3: Strategy deployed in the wrong regime
A trend-following strategy loses money in a ranging market. A mean reversion strategy loses money in a trending market. Strategies have regimes. Deploy a strategy without a regime filter and you'll spend half your time fighting the market conditions.
Failure Mode 4: Infrastructure failure
Exchange API rate limits hit mid-position. Network timeout during order submission. Exchange goes down during high volatility (when you need it most). Handling these edge cases is unglamorous engineering work — but ignoring it is how you end up with an open position you can't manage.
The Architecture (Overview)
Our trading bot has 5 layers. Each layer is independent — you can swap components without breaking the whole system.
1. Data Layer
Multiple APIs (crypto, Polymarket, sentiment, on-chain)
2. Strategy Layer
Independent strategies (mean reversion, momentum, RSI, etc.)
3. Decision Layer
LLM (Qwen/GPT) + critic agent validation
4. Risk Layer
Hard-coded rules (position limits, circuit breakers, cooldowns)
5. Execution Layer
Paper trading engine → live (only if paper results hold up)
Let's build each layer.
Layer 1: Data Layer
The data layer polls market data from multiple sources. A typical bot uses several APIs across 4 categories:
Price Data
- • Binance API (BTC, ETH, SOL spot + futures)
- • Coinbase Pro API (backup price source)
- • Polymarket API (prediction market odds)
Sentiment Data
- • Twitter API v2 (crypto influencer sentiment)
- • CryptoPanic API (news aggregation)
- • LunarCrush API (social volume metrics)
On-Chain Data
- • Etherscan API (whale movements, large transfers)
- • Glassnode API (exchange flows, holder metrics)
Market Regime
- • Fear & Greed Index API
- • TradingView technical analysis (via scraping)
- • Polymarket event probabilities (macro risk)
Key implementation detail: Rate limit management is critical. Each API has different limits. A priority queue works well:
1. Price data (highest priority)
2. Regime data
3. Sentiment data
4. On-chain data (lowest priority)
Poll interval: every 15 minutes. Fast enough to catch opportunities, slow enough to stay within rate limits. Each of these automated polling loops is an autonomous AI agent consuming live web data — exactly the kind of autonomous traffic reshaping how the internet works.
Layer 2: Strategy Layer
Each strategy runs independently and generates signals with confidence scores. Example strategy types:
Each strategy outputs a signal object:
{ strategy: "mean_reversion", asset: "BTC-USD", action: "BUY", confidence: 0.82, entry_price: 68420, stop_loss: 67200, take_profit: 71000, reasoning: "RSI < 30, price below lower BB" }
Layer 3: Decision Layer (LLM + Critic)
This is where AI comes in. The LLM reviews every signal before it executes.
Step 1: Primary LLM Review
We send the signal to an LLM (Qwen3.5-plus or GPT) with this prompt:
"You are reviewing a trading signal. Context: Strategy is [strategy_name], Asset is [asset], Signal is [action]. Technical indicators: [indicators]. Market regime: [regime]. Recent P&L: [recent_pnl]. Task: 1. Identify contradictions. 2. Assess confidence (0-100%). 3. Recommend: Execute, Queue for Review, or Reject. Reasoning first. Decision second."
The LLM returns a confidence score and recommendation. If confidence is >85%, the trade auto-executes. If 65-84%, it queues for human review. If <65%, it's rejected.
Step 2: Critic Agent Validation
Here's where we're different. After the primary LLM approves a trade, a second LLM (the critic) reviews it adversarially.
The critic can return 5 verdicts:
Trade proceeds
Proceed but flag for post-trade watch
Suggests smaller size or tighter stop
Blocks trade entirely
Sends to human review
The critic can veto trades. Typical reasons include trend disagreement, consecutive loss escalation, open-interest squeeze risk, and correlated-signal detection.
Layer 4: Risk Layer
Even if the LLM and critic approve a trade, the risk layer can still veto it. The bot used a set of hard-coded rules. For the interface between this layer and the execution path, see our AI trading bot architecture diagram:
Position Limits:
- • Max 5% per trade
- • Max 7% total exposure per asset
- • Max 10% crypto exposure
Circuit Breakers:
- • Pause after 3 consecutive losses
- • Halt after 4% daily drawdown
Trading Limits:
- • 45-minute cooldown per asset
- • 65% min LLM confidence
- • 85%+ for auto-execute
Market Conditions:
- • Regime-based strategy suspension
- • OI squeeze veto (score ≥ 80)
- • Polymarket min $10K volume
- • Ambiguous resolution veto
These rules can't be overridden. No config flags. No "just this once" exceptions.
Layer 5: Execution Layer
If a trade passes all 4 previous layers, it reaches execution. There are two modes:
Paper Mode
Trades are logged but not sent to the exchange. A paper engine should model slippage rather than assume perfect fills. Illustrative assumptions:
• 0.1% slippage on major pairs (BTC, ETH)
• 0.3% on mid-cap alts
• 0.5-2% on thin Polymarket order books
Live Mode (Only If Paper Results Hold Up)
Same execution logic, but orders go to the exchange. Our own bot never went live; it stayed in paper mode and has been retired.
Infrastructure
A trading bot does not need heavy infrastructure to start. You need a machine that stays on, a process supervisor so the bot restarts if it crashes, an async polling loop for market data, a messaging channel for alerts (Telegram works well), and a dashboard for equity curves and logs. Costs depend on your hosting and LLM usage, so estimate them for your own setup. See our infrastructure post for more.
Python Backtesting Tools Compared (Backtrader, Backtesting.py, Zipline)
Before any AI layer or live deployment, you need a reliable backtesting environment. Python dominates this space because of its ecosystem, but choosing the right framework depends on your strategy complexity, data volume, and latency requirements. Here's how the three most popular open-source backtesting libraries stack up in 2026.
1. Backtrader
Best for: Custom indicators, event-driven backtesting, multi-asset strategies
Backtrader is the veteran of Python backtesting. It uses an event-driven architecture that closely mimics live trading, making it ideal for strategies that need to react to tick-level data or multiple asset classes simultaneously. It supports custom indicators, live trading integration (via IBKR, OANDA), and a flexible optimization engine. The downside: the API is somewhat dated, documentation is sparse, and the learning curve is steep for beginners.
2. Backtesting.py
Best for: Quick prototyping, clean API, interactive charts
Backtesting.py is lightweight and fast. It uses a vectorized approach under the hood but exposes a clean, event-like API. Its standout feature is the built-in interactive HTML charting, which makes debugging and presenting strategy results effortless. It's excellent for quick validation of simple momentum or mean-reversion ideas. However, it lacks native support for multiple assets in a single run and has limited order types compared to Backtrader.
3. Zipline (reloaded)
Best for: Institutional-grade pipelines, Quantopian legacy, large datasets
Originally built by Quantopian, Zipline is now maintained as zipline-reloaded. It's designed for algorithmic trading at scale, with a strict data pipeline system and event-driven execution. It integrates seamlessly with pandas and supports complex portfolio constraints. The trade-off is heavy setup, rigid structure, and slower iteration speed. It's overkill for simple strategies but unmatched for rigorous, reproducible research.
| Feature | Backtrader | Backtesting.py | Zipline |
|---|---|---|---|
| Architecture | Event-driven | Vectorized/Event-hybrid | Event-driven |
| Multi-Asset | Yes | Limited | Yes |
| Learning Curve | Steep | Low | High |
| Live Trading | Yes (IB, OANDA, etc.) | No (research only) | No (research only) |
| Charting | Matplotlib (basic) | Interactive HTML | Matplotlib/Bokeh |
| Best For | Production-ready algos | Quick prototyping | Institutional pipelines |
Recommendation: Start with Backtesting.py to validate your hypothesis quickly. Move to Backtrader when you need live execution hooks and complex position sizing. Reserve Zipline for research-heavy, institutional-grade strategy development where reproducibility and strict data pipelines are non-negotiable.
An Example Tech Stack
Here is an example stack for a bot like this, with alternatives where applicable. These are illustrative choices, not a recommendation or a benchmark.
| Component | Example | Alternatives |
|---|---|---|
| Language | Python | TypeScript, Go |
| Exchange connectivity | CCXT Pro | Direct exchange SDKs |
| LLM layer | Claude (Anthropic) | GPT-4o, Gemini |
| Data pipeline | Custom + Glassnode | Nansen, Dune |
| Backtesting | Backtrader | VectorBT, Zipline |
| Infrastructure | VPS + cron jobs | AWS Lambda, Modal |
| Monitoring | Custom dashboards | Grafana, Datadog |
| Paper trading | Custom sandbox | Alpaca, exchange testnet |
What We'd Do Differently
Building this from scratch, here's what we'd change:
- Start with paper trading: Don't go live until you've tested for a meaningful stretch of time.
- Code risk rules first: Before any strategies, code the circuit breakers and position limits. Survival first.
- Use Telegram for alerts: Dashboards are passive. Telegram pushes alerts to you.
- Log everything: Every decision, every veto, every bug. You'll need this data to debug.
- Build the critic early: The adversarial LLM layer catches mistakes the primary LLM misses.
Our Simulated Result
Our Paper Bot, Simulated
42
Calendar Days (Feb 26 - Apr 8)
Net loss
Both books ended below start
Paper
Simulated
$10,000
Starting Balance (per book)
Simulated paper trading, not live results. Not financial advice. Trading carries risk of loss, and past or simulated performance does not predict future results.
Is that impressive? No. The run ended net negative on simulated capital. The numbers and caveats are in the retired-project case study.
What's worth building toward: reliability, correlated-signal controls, regime-aware strategy weights, and logging every decision.
Next Steps
If you're building your own trading bot, here's a suggested order:
- Set up data layer (start with 2-3 APIs, expand later)
- Code 1-2 simple strategies (mean reversion, momentum)
- Implement risk layer (position limits, circuit breakers)
- Add LLM decision layer (start with simple prompts)
- Build critic agent (adversarial review)
- Run in paper mode for 30+ days
- Iterate based on bugs and edge cases
- Consider live mode only after proven track record
Our own bot stopped at paper trading and has been retired; see why in the retirement post.
Related Reading
This is the architecture behind our simulated paper trading bot, which has been retired. Read why, and how paper trading differs from live.