Crypto Trading Bot Architecture Explained
A deep dive into crypto trading bot architecture: from exchange APIs and strategy engines to risk management, backtesting, and production deployment.
Architecture Overview
A production crypto trading bot has five core components:
`` Market Data → Strategy Engine → Risk Manager → Order Executor → Portfolio Tracker ↑ ↓ ↓ WebSocket Signal Generator Exchange API
`
Each component runs independently and communicates through an event bus.
1. Market Data Pipeline
Real-time data ingestion via WebSocket:
`python
import websockets
import json
async def binance_stream(symbol="BTCUSDT"):
url = f"wss://stream.binance.com:9443/ws/{symbol.lower()}@kline_1m"
async with websockets.connect(url) as ws:
async for msg in ws:
data = json.loads(msg)
candle = {
"time": data["k"]["t"],
"open": float(data["k"]["o"]),
"high": float(data["k"]["h"]),
"low": float(data["k"]["l"]),
"close": float(data["k"]["c"]),
"volume": float(data["k"]["v"]),
}
yield candle
`
Data Storage
Store candles in TimescaleDB for efficient time-series queries. Keep at least 1 year of 1-minute data for backtesting.
2. Strategy Engine
Strategies generate buy/sell signals based on market data:
`python
class MACrossoverStrategy:
def __init__(self, fast=12, slow=26):
self.fast = fast
self.slow = slow
def analyze(self, candles):
fast_ma = self.sma(candles, self.fast)
slow_ma = self.sma(candles, self.slow)
if fast_ma[-1] > slow_ma[-1] and fast_ma[-2] <= slow_ma[-2]:
return Signal.BUY
elif fast_ma[-1] < slow_ma[-1] and fast_ma[-2] >= slow_ma[-2]:
return Signal.SELL
return Signal.HOLD
`
Built-in Strategies
3. Risk Management
The most critical component. Without proper risk management, even a profitable strategy will blow up your account.
Position Sizing
Never risk more than 1-2% of your portfolio on a single trade:
`python
def calculate_position_size(portfolio_value, risk_percent, entry, stop_loss):
risk_amount = portfolio_value * (risk_percent / 100)
price_diff = abs(entry - stop_loss)
position_size = risk_amount / price_diff
return position_size
`
Stop Loss / Take Profit
Portfolio Limits
4. Backtesting
Test strategies against historical data before going live:
` class Backtester: def run(self, strategy, data, initial_balance=10000): balance = initial_balance positions = [] for i in range(len(data)): signal = strategy.analyze(data[:i+1]) if signal == Signal.BUY and not positions: positions.append(data[i]["close"]) elif signal == Signal.SELL and positions: pnl = data[i]["close"] - positions.pop() balance += pnl return { "final_balance": balance, "return": (balance - initial_balance) / initial_balance * 100, "max_drawdown": self.calc_max_drawdown(), "sharpe_ratio": self.calc_sharpe(), }python
``
5. Production Deployment
Infrastructure
Exchange Support
Our Trading Bot Package
The Crypto Trading Bot includes all components above: data pipeline, 5 strategies, risk manager, backtester, and production deployment scripts. Telegram integration for real-time alerts.
Starter ($99/mo): 1 exchange, 3 strategies, spot trading.
Professional ($299/mo): Multi-exchange, all strategies, futures support, custom strategy development.
