Building Automated Trading Systems
End-to-end system architecture: data pipeline, signal generation, execution engine, risk management layer, monitoring, and deployment with Docker and failover.
From Thrive on YouTube
Watch the matching Thrive video
Daily and Weekly Loss Limits: Building Circuit Breakers Into Your Trading
Part of Trading Journal and Performance Review. Education only. Not financial advice.
End-to-End System Architecture
An automated trading system is not a single script. It is a pipeline of specialized modules that each handle one responsibility. The data pipeline ingests and cleans real-time market data. The signal generator computes indicators and emits trading signals. The execution engine translates signals into orders and manages their lifecycle. The risk management layer enforces position limits, drawdown circuit breakers, and exposure caps. The monitoring system watches everything and alerts you when something breaks. Each module communicates through well-defined interfaces, making the system testable, debuggable, and replaceable piece by piece.
The most common mistake is building a monolithic script that does everything in one loop. This works for a weekend prototype but fails catastrophically in production. When your data feed drops, your signal generator should not crash. When an order fills, your risk manager should update position limits before the next signal fires. Separation of concerns is not an academic ideal. It is a survival requirement for systems handling real money.
Architecture overview
Data Pipeline
The data pipeline is the foundation. It connects to exchange WebSocket feeds for real-time price data, normalizes the data into a standard format, stores it for historical analysis, and distributes it to downstream modules. The pipeline must handle disconnections gracefully, detect stale data, and fill gaps from REST API fallbacks. For order book data, maintain a local copy that applies incremental updates from the WebSocket diff feed.
1import ccxt.pro as ccxtpro2import asyncio3import json4import redis.asyncio as aioredis5from datetime import datetime67class DataPipeline:8 def __init__(self, symbols: list[str], timeframe: str = '1m'):9 self.symbols = symbols10 self.timeframe = timeframe11 self.exchange = ccxtpro.binance({12 'enableRateLimit': True,13 'options': {'defaultType': 'future'},14 })15 self.redis = aioredis.from_url('redis://localhost:6379')1617 async def stream_candles(self, symbol: str):18 """Stream OHLCV candles and publish to Redis."""19 while True:20 try:21 candles = await self.exchange.watch_ohlcv(symbol, self.timeframe)22 latest = candles[-1]23 bar = {24 'symbol': symbol,25 'timestamp': latest[0],26 'open': latest[1],27 'high': latest[2],28 'low': latest[3],29 'close': latest[4],30 'volume': latest[5],31 'received_at': datetime.utcnow().isoformat(),32 }33 await self.redis.publish(f'candles:{symbol}', json.dumps(bar))34 await self.redis.set(f'latest:{symbol}', json.dumps(bar))35 except Exception as e:36 print(f"[DataPipeline] {symbol} error: {e}")37 await asyncio.sleep(2)3839 async def stream_orderbook(self, symbol: str):40 """Stream order book snapshots."""41 while True:42 try:43 book = await self.exchange.watch_order_book(symbol, limit=20)44 snapshot = {45 'symbol': symbol,46 'bids': book['bids'][:10],47 'asks': book['asks'][:10],48 'timestamp': book['timestamp'],49 }50 await self.redis.set(f'book:{symbol}', json.dumps(snapshot))51 except Exception as e:52 print(f"[DataPipeline] Book {symbol} error: {e}")53 await asyncio.sleep(2)5455 async def run(self):56 tasks = []57 for sym in self.symbols:58 tasks.append(self.stream_candles(sym))59 tasks.append(self.stream_orderbook(sym))60 await asyncio.gather(*tasks)Signal Generation Module
The signal generator subscribes to the data pipeline, maintains indicator state, and emits structured signals when entry or exit conditions are met. It should be purely functional given the same data: deterministic and side-effect-free. The signal itself is a data structure containing the symbol, direction, strength, timestamp, and the reason the signal triggered. This makes signals loggable, auditable, and backtestable.
1from dataclasses import dataclass2from enum import Enum3from collections import deque4import numpy as np56class SignalDirection(Enum):7 LONG = 'long'8 SHORT = 'short'9 FLAT = 'flat'1011@dataclass12class Signal:13 symbol: str14 direction: SignalDirection15 strength: float # 0.0 to 1.016 timestamp: int17 reason: str18 indicators: dict1920class SignalEngine:21 def __init__(self, fast_period=20, slow_period=50, rsi_period=14):22 self.fast_period = fast_period23 self.slow_period = slow_period24 self.rsi_period = rsi_period25 self.closes: dict[str, deque] = {}2627 def _compute_rsi(self, closes: list[float]) -> float:28 deltas = np.diff(closes[-self.rsi_period - 1:])29 gains = np.where(deltas > 0, deltas, 0)30 losses = np.where(deltas < 0, -deltas, 0)31 avg_gain = gains.mean()32 avg_loss = losses.mean()33 if avg_loss == 0:34 return 100.035 rs = avg_gain / avg_loss36 return 100 - (100 / (1 + rs))3738 def update(self, symbol: str, close: float, timestamp: int) -> Signal | None:39 if symbol not in self.closes:40 self.closes[symbol] = deque(maxlen=self.slow_period + 10)41 self.closes[symbol].append(close)4243 if len(self.closes[symbol]) < self.slow_period:44 return None4546 prices = list(self.closes[symbol])47 fast_ma = np.mean(prices[-self.fast_period:])48 slow_ma = np.mean(prices[-self.slow_period:])49 prev_fast = np.mean(prices[-self.fast_period - 1:-1])50 prev_slow = np.mean(prices[-self.slow_period - 1:-1])51 rsi = self._compute_rsi(prices)5253 indicators = {54 'fast_ma': fast_ma, 'slow_ma': slow_ma,55 'rsi': rsi, 'close': close,56 }5758 # Bullish crossover with RSI confirmation59 if prev_fast <= prev_slow and fast_ma > slow_ma and rsi < 70:60 return Signal(symbol, SignalDirection.LONG, 0.8, timestamp,61 'SMA bullish crossover + RSI confirmation', indicators)6263 # Bearish crossover64 if prev_fast >= prev_slow and fast_ma < slow_ma and rsi > 30:65 return Signal(symbol, SignalDirection.SHORT, 0.8, timestamp,66 'SMA bearish crossover + RSI confirmation', indicators)6768 return NoneExecution Engine
The execution engine translates signals into exchange orders and tracks their lifecycle. It must handle slippage by using limit orders with aggressive pricing (a few ticks through the spread) rather than market orders. It tracks open orders, matches fills to signals, and maintains an accurate position state. If a limit order does not fill within a timeout, the engine must decide whether to cancel, re-price, or escalate to a market order.
1import ccxt.pro as ccxtpro23class ExecutionEngine:4 def __init__(self, exchange):5 self.exchange = exchange6 self.positions: dict[str, dict] = {}7 self.open_orders: dict[str, dict] = {}89 async def execute_signal(self, signal: Signal, size_usd: float):10 """Convert a signal into an exchange order."""11 ticker = await self.exchange.fetch_ticker(signal.symbol)12 price = ticker['last']13 amount = size_usd / price1415 if signal.direction == SignalDirection.LONG:16 # Place limit buy slightly above best bid for fast fill17 limit_price = price * 1.000218 order = await self.exchange.create_order(19 signal.symbol, 'limit', 'buy', amount, limit_price,20 params={'timeInForce': 'GTC'}21 )22 elif signal.direction == SignalDirection.SHORT:23 limit_price = price * 0.999824 order = await self.exchange.create_order(25 signal.symbol, 'limit', 'sell', amount, limit_price,26 params={'timeInForce': 'GTC'}27 )28 else:29 return await self._close_position(signal.symbol)3031 self.open_orders[order['id']] = {32 'signal': signal,33 'order': order,34 'placed_at': signal.timestamp,35 }36 return order3738 async def monitor_fills(self):39 """Watch for order fills and update positions."""40 while True:41 try:42 orders = await self.exchange.watch_orders()43 for order in orders:44 if order['status'] == 'closed':45 self._update_position(order)46 self.open_orders.pop(order['id'], None)47 except Exception as e:48 print(f"[Execution] Fill monitor error: {e}")49 await asyncio.sleep(1)5051 def _update_position(self, order: dict):52 symbol = order['symbol']53 side = order['side']54 filled = float(order['filled'])55 avg_price = float(order['average'])5657 current = self.positions.get(symbol, {'size': 0, 'avg_price': 0})58 if side == 'buy':59 new_size = current['size'] + filled60 else:61 new_size = current['size'] - filled6263 self.positions[symbol] = {64 'size': new_size,65 'avg_price': avg_price,66 'updated_at': order['timestamp'],67 }6869 async def _close_position(self, symbol: str):70 pos = self.positions.get(symbol)71 if not pos or pos['size'] == 0:72 return None73 side = 'sell' if pos['size'] > 0 else 'buy'74 return await self.exchange.create_order(75 symbol, 'market', side, abs(pos['size'])76 )Risk Management Layer
The risk manager sits between the signal generator and the execution engine. Every signal must pass through risk checks before an order is placed. The risk manager enforces maximum drawdown circuit breakers, position limits, correlation exposure caps, and daily loss limits. When a circuit breaker triggers, the system halts all new entries and optionally flattens existing positions. This layer is the difference between a bad day and a blown account.
1from dataclasses import dataclass, field23@dataclass4class RiskConfig:5 max_position_size_usd: float = 50006 max_total_exposure_usd: float = 200007 max_daily_loss_pct: float = 0.03 # 3% daily loss limit8 max_drawdown_pct: float = 0.10 # 10% drawdown circuit breaker9 max_positions: int = 510 max_correlation_exposure: float = 0.71112class RiskManager:13 def __init__(self, config: RiskConfig, starting_capital: float):14 self.config = config15 self.starting_capital = starting_capital16 self.peak_equity = starting_capital17 self.current_equity = starting_capital18 self.daily_pnl = 0.019 self.halted = False2021 def check_signal(self, signal: Signal, size_usd: float,22 current_positions: dict) -> tuple[bool, str]:23 """Validate a signal against all risk constraints."""24 if self.halted:25 return False, 'SYSTEM HALTED: drawdown circuit breaker active'2627 # Daily loss limit28 if self.daily_pnl / self.starting_capital < -self.config.max_daily_loss_pct:29 self.halted = True30 return False, f'Daily loss limit exceeded: {self.daily_pnl:.2f}'3132 # Drawdown circuit breaker33 drawdown = (self.peak_equity - self.current_equity) / self.peak_equity34 if drawdown > self.config.max_drawdown_pct:35 self.halted = True36 return False, f'Drawdown circuit breaker: {drawdown:.2%}'3738 # Position count limit39 active = sum(1 for p in current_positions.values() if p['size'] != 0)40 if active >= self.config.max_positions:41 return False, f'Max positions ({self.config.max_positions}) reached'4243 # Position size limit44 if size_usd > self.config.max_position_size_usd:45 return False, f'Size {size_usd} exceeds max {self.config.max_position_size_usd}'4647 # Total exposure limit48 total_exposure = sum(49 abs(p['size'] * p['avg_price'])50 for p in current_positions.values()51 )52 if total_exposure + size_usd > self.config.max_total_exposure_usd:53 return False, f'Total exposure would exceed {self.config.max_total_exposure_usd}'5455 return True, 'APPROVED'5657 def update_equity(self, new_equity: float):58 self.current_equity = new_equity59 self.peak_equity = max(self.peak_equity, new_equity)60 self.daily_pnl = new_equity - self.starting_capital6162 def reset_daily(self):63 """Call at the start of each trading day."""64 self.daily_pnl = 0.065 if self.halted:66 drawdown = (self.peak_equity - self.current_equity) / self.peak_equity67 if drawdown < self.config.max_drawdown_pct * 0.5:68 self.halted = False69 print("[Risk] Circuit breaker lifted: drawdown recovered")Monitoring and Alerting
An automated system that you cannot observe is a ticking time bomb. Every module must log its actions, and critical events must push notifications to your phone via Telegram or Discord. Health checks verify that each component is alive and processing data. If the data pipeline stops receiving candles, if the execution engine has unfilled orders beyond a timeout, or if the risk manager triggers a circuit breaker. You must know immediately.
1import logging2import requests3from datetime import datetime, timedelta45logging.basicConfig(6 level=logging.INFO,7 format='%(asctime)s [%(name)s] %(levelname)s: %(message)s',8 handlers=[9 logging.FileHandler('trading_system.log'),10 logging.StreamHandler(),11 ]12)1314class TelegramNotifier:15 def __init__(self, token: str, chat_id: str):16 self.url = f"https://api.telegram.org/bot{token}/sendMessage"17 self.chat_id = chat_id18 self.logger = logging.getLogger('telegram')1920 def send(self, message: str, urgent: bool = False):21 prefix = '🚨 ' if urgent else '📊 '22 payload = {23 'chat_id': self.chat_id,24 'text': f"{prefix}{message}",25 'parse_mode': 'HTML',26 }27 try:28 requests.post(self.url, json=payload, timeout=10)29 except Exception as e:30 self.logger.error(f"Telegram send failed: {e}")3132class HealthMonitor:33 def __init__(self, notifier: TelegramNotifier):34 self.notifier = notifier35 self.last_heartbeat: dict[str, datetime] = {}36 self.logger = logging.getLogger('health')3738 def heartbeat(self, component: str):39 self.last_heartbeat[component] = datetime.utcnow()4041 def check_health(self, max_silence_seconds: int = 120):42 now = datetime.utcnow()43 for component, last in self.last_heartbeat.items():44 age = (now - last).total_seconds()45 if age > max_silence_seconds:46 msg = f"<b>HEALTH ALERT</b>\n{component} silent for {age:.0f}s"47 self.notifier.send(msg, urgent=True)48 self.logger.warning(f"{component} unresponsive for {age:.0f}s")4950class SystemMonitor:51 def __init__(self, notifier: TelegramNotifier, health: HealthMonitor):52 self.notifier = notifier53 self.health = health54 self.logger = logging.getLogger('monitor')5556 def on_signal(self, signal: Signal):57 self.logger.info(f"Signal: {signal.symbol} {signal.direction.value} ({signal.reason})")5859 def on_order(self, order: dict):60 msg = f"Order: {order['side']} {order['amount']} {order['symbol']} @ {order['price']}"61 self.logger.info(msg)62 self.notifier.send(msg)6364 def on_fill(self, order: dict):65 msg = f"<b>FILLED</b>: {order['side']} {order['filled']} {order['symbol']} @ {order['average']}"66 self.logger.info(msg)67 self.notifier.send(msg)6869 def on_risk_halt(self, reason: str):70 msg = f"<b>RISK HALT</b>\n{reason}"71 self.logger.critical(msg)72 self.notifier.send(msg, urgent=True)7374 def daily_report(self, equity: float, pnl: float, positions: dict):75 pos_str = '\n'.join(76 f" {sym}: {p['size']:.4f} @ {p['avg_price']:.2f}"77 for sym, p in positions.items() if p['size'] != 078 ) or ' No open positions'79 msg = (f"<b>Daily Report</b>\n"80 f"Equity: ${equity:,.2f}\n"81 f"Daily PnL: ${pnl:,.2f}\n"82 f"Positions:\n{pos_str}")83 self.notifier.send(msg)Deployment: Docker, systemd, and Failover
A trading system must run 24/7 in crypto markets. Deploy on a cloud VPS (AWS, Hetzner, DigitalOcean) with low latency to your exchange's API servers. Docker containers provide reproducible environments, and systemd ensures the process restarts automatically after crashes. For critical systems, run a standby instance that monitors the primary and takes over if it goes silent.
1FROM python:3.11-slim23WORKDIR /app4COPY requirements.txt .5RUN pip install --no-cache-dir -r requirements.txt67COPY src/ ./src/8COPY config/ ./config/910ENV PYTHONUNBUFFERED=111ENV TZ=UTC1213HEALTHCHECK --interval=30s --timeout=10s --retries=3 \14 CMD python -c "import requests; requests.get('http://localhost:8080/health')"1516CMD ["python", "-m", "src.main"]1# /etc/systemd/system/trading-bot.service2[Unit]3Description=Crypto Trading System4After=network.target redis.service56[Service]7Type=simple8User=trader9WorkingDirectory=/opt/trading-system10ExecStart=/usr/bin/docker compose up11ExecStop=/usr/bin/docker compose down12Restart=always13RestartSec=1014StandardOutput=journal15StandardError=journal1617[Install]18WantedBy=multi-user.target1920# Enable and start21# sudo systemctl enable trading-bot22# sudo systemctl start trading-bot23# sudo journalctl -u trading-bot -f # Follow logs1version: '3.8'2services:3 redis:4 image: redis:7-alpine5 restart: always6 volumes:7 - redis_data:/data89 trading-bot:10 build: .11 restart: always12 depends_on:13 - redis14 env_file: .env15 volumes:16 - ./logs:/app/logs17 - ./data:/app/data18 ports:19 - "8080:8080"2021volumes:22 redis_data:AWS (Tokyo/Singapore for Asian exchanges, Frankfurt for European). Hetzner offers excellent price/performance in Europe. Latency to Binance API is 1-5ms from Singapore.
systemd on Linux for automatic restart, log rotation, and dependency ordering. Docker Compose for multi-container setups (bot + Redis + monitoring).
Run a standby instance that monitors the primary via heartbeat. If the primary misses 3 consecutive heartbeats (90 seconds), the standby takes over and flattens any stale positions.
Write all signals, orders, fills, and position changes to a PostgreSQL database. If the system crashes and restarts, it must reconstruct its state from the database, not from memory.
Never hardcode API keys. Use environment variables via .env files (excluded from git), or a proper secrets manager like AWS Secrets Manager or HashiCorp Vault for production systems.
Paper trade for 30 days minimum
1.Why should the signal generator and execution engine be separate modules instead of a single script?
2.What is the purpose of a drawdown circuit breaker in the risk management layer?
3.Why should a trading system write all signals and orders to a database rather than keeping state in memory?
4.What is the recommended minimum paper trading period before deploying real capital?
5.Why should limit orders with aggressive pricing be preferred over market orders in the execution engine?
Put this lesson to work
Free on Thrive, no account needed.