Skip to main content

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

Watch the series
Daily and Weekly Loss Limits: Building Circuit Breakers Into Your Trading

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 → Signal Generator → Execution Engine → Risk Manager → Monitor. Each module runs independently, communicates via message queues or shared state, and can be restarted without taking down the entire system. Think microservices, not monolith.

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.

python-Data pipeline with Redis message bus
1import ccxt.pro as ccxtpro
2import asyncio
3import json
4import redis.asyncio as aioredis
5from datetime import datetime
6
7class DataPipeline:
8 def __init__(self, symbols: list[str], timeframe: str = '1m'):
9 self.symbols = symbols
10 self.timeframe = timeframe
11 self.exchange = ccxtpro.binance({
12 'enableRateLimit': True,
13 'options': {'defaultType': 'future'},
14 })
15 self.redis = aioredis.from_url('redis://localhost:6379')
16
17 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)
38
39 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)
54
55 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.

python-Signal generation engine
1from dataclasses import dataclass
2from enum import Enum
3from collections import deque
4import numpy as np
5
6class SignalDirection(Enum):
7 LONG = 'long'
8 SHORT = 'short'
9 FLAT = 'flat'
10
11@dataclass
12class Signal:
13 symbol: str
14 direction: SignalDirection
15 strength: float # 0.0 to 1.0
16 timestamp: int
17 reason: str
18 indicators: dict
19
20class SignalEngine:
21 def __init__(self, fast_period=20, slow_period=50, rsi_period=14):
22 self.fast_period = fast_period
23 self.slow_period = slow_period
24 self.rsi_period = rsi_period
25 self.closes: dict[str, deque] = {}
26
27 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.0
35 rs = avg_gain / avg_loss
36 return 100 - (100 / (1 + rs))
37
38 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)
42
43 if len(self.closes[symbol]) < self.slow_period:
44 return None
45
46 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)
52
53 indicators = {
54 'fast_ma': fast_ma, 'slow_ma': slow_ma,
55 'rsi': rsi, 'close': close,
56 }
57
58 # Bullish crossover with RSI confirmation
59 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)
62
63 # Bearish crossover
64 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)
67
68 return None

Execution 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.

python-Order execution with position tracking
1import ccxt.pro as ccxtpro
2
3class ExecutionEngine:
4 def __init__(self, exchange):
5 self.exchange = exchange
6 self.positions: dict[str, dict] = {}
7 self.open_orders: dict[str, dict] = {}
8
9 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 / price
14
15 if signal.direction == SignalDirection.LONG:
16 # Place limit buy slightly above best bid for fast fill
17 limit_price = price * 1.0002
18 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.9998
24 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)
30
31 self.open_orders[order['id']] = {
32 'signal': signal,
33 'order': order,
34 'placed_at': signal.timestamp,
35 }
36 return order
37
38 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)
50
51 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'])
56
57 current = self.positions.get(symbol, {'size': 0, 'avg_price': 0})
58 if side == 'buy':
59 new_size = current['size'] + filled
60 else:
61 new_size = current['size'] - filled
62
63 self.positions[symbol] = {
64 'size': new_size,
65 'avg_price': avg_price,
66 'updated_at': order['timestamp'],
67 }
68
69 async def _close_position(self, symbol: str):
70 pos = self.positions.get(symbol)
71 if not pos or pos['size'] == 0:
72 return None
73 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.

python-Risk management with circuit breakers
1from dataclasses import dataclass, field
2
3@dataclass
4class RiskConfig:
5 max_position_size_usd: float = 5000
6 max_total_exposure_usd: float = 20000
7 max_daily_loss_pct: float = 0.03 # 3% daily loss limit
8 max_drawdown_pct: float = 0.10 # 10% drawdown circuit breaker
9 max_positions: int = 5
10 max_correlation_exposure: float = 0.7
11
12class RiskManager:
13 def __init__(self, config: RiskConfig, starting_capital: float):
14 self.config = config
15 self.starting_capital = starting_capital
16 self.peak_equity = starting_capital
17 self.current_equity = starting_capital
18 self.daily_pnl = 0.0
19 self.halted = False
20
21 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'
26
27 # Daily loss limit
28 if self.daily_pnl / self.starting_capital < -self.config.max_daily_loss_pct:
29 self.halted = True
30 return False, f'Daily loss limit exceeded: {self.daily_pnl:.2f}'
31
32 # Drawdown circuit breaker
33 drawdown = (self.peak_equity - self.current_equity) / self.peak_equity
34 if drawdown > self.config.max_drawdown_pct:
35 self.halted = True
36 return False, f'Drawdown circuit breaker: {drawdown:.2%}'
37
38 # Position count limit
39 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'
42
43 # Position size limit
44 if size_usd > self.config.max_position_size_usd:
45 return False, f'Size {size_usd} exceeds max {self.config.max_position_size_usd}'
46
47 # Total exposure limit
48 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}'
54
55 return True, 'APPROVED'
56
57 def update_equity(self, new_equity: float):
58 self.current_equity = new_equity
59 self.peak_equity = max(self.peak_equity, new_equity)
60 self.daily_pnl = new_equity - self.starting_capital
61
62 def reset_daily(self):
63 """Call at the start of each trading day."""
64 self.daily_pnl = 0.0
65 if self.halted:
66 drawdown = (self.peak_equity - self.current_equity) / self.peak_equity
67 if drawdown < self.config.max_drawdown_pct * 0.5:
68 self.halted = False
69 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.

python-Monitoring with Telegram and health checks
1import logging
2import requests
3from datetime import datetime, timedelta
4
5logging.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)
13
14class 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_id
18 self.logger = logging.getLogger('telegram')
19
20 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}")
31
32class HealthMonitor:
33 def __init__(self, notifier: TelegramNotifier):
34 self.notifier = notifier
35 self.last_heartbeat: dict[str, datetime] = {}
36 self.logger = logging.getLogger('health')
37
38 def heartbeat(self, component: str):
39 self.last_heartbeat[component] = datetime.utcnow()
40
41 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")
49
50class SystemMonitor:
51 def __init__(self, notifier: TelegramNotifier, health: HealthMonitor):
52 self.notifier = notifier
53 self.health = health
54 self.logger = logging.getLogger('monitor')
55
56 def on_signal(self, signal: Signal):
57 self.logger.info(f"Signal: {signal.symbol} {signal.direction.value} ({signal.reason})")
58
59 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)
63
64 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)
68
69 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)
73
74 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'] != 0
78 ) 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.

dockerfile-Dockerfile for trading system
1FROM python:3.11-slim
2
3WORKDIR /app
4COPY requirements.txt .
5RUN pip install --no-cache-dir -r requirements.txt
6
7COPY src/ ./src/
8COPY config/ ./config/
9
10ENV PYTHONUNBUFFERED=1
11ENV TZ=UTC
12
13HEALTHCHECK --interval=30s --timeout=10s --retries=3 \
14 CMD python -c "import requests; requests.get('http://localhost:8080/health')"
15
16CMD ["python", "-m", "src.main"]
bash-systemd service and Docker Compose
1# /etc/systemd/system/trading-bot.service
2[Unit]
3Description=Crypto Trading System
4After=network.target redis.service
5
6[Service]
7Type=simple
8User=trader
9WorkingDirectory=/opt/trading-system
10ExecStart=/usr/bin/docker compose up
11ExecStop=/usr/bin/docker compose down
12Restart=always
13RestartSec=10
14StandardOutput=journal
15StandardError=journal
16
17[Install]
18WantedBy=multi-user.target
19
20# Enable and start
21# sudo systemctl enable trading-bot
22# sudo systemctl start trading-bot
23# sudo journalctl -u trading-bot -f # Follow logs
yaml-docker-compose.yml
1version: '3.8'
2services:
3 redis:
4 image: redis:7-alpine
5 restart: always
6 volumes:
7 - redis_data:/data
8
9 trading-bot:
10 build: .
11 restart: always
12 depends_on:
13 - redis
14 env_file: .env
15 volumes:
16 - ./logs:/app/logs
17 - ./data:/app/data
18 ports:
19 - "8080:8080"
20
21volumes:
22 redis_data:
Cloud hosting

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.

Process management

systemd on Linux for automatic restart, log rotation, and dependency ordering. Docker Compose for multi-container setups (bot + Redis + monitoring).

Failover strategy

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.

Data persistence

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.

Secret management

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

Before deploying real capital, run your system in paper-trade mode for at least 30 days. Log every signal, order, and fill as if it were real money. Compare paper results against your backtest expectations. Debug every discrepancy: the gap between backtest and paper trade reveals execution bugs, data issues, and flawed assumptions. If paper trading shows a significant performance drop from backtest, do not go live. Fix the system first.
Module Quiz

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?

0/5 answered

Put this lesson to work

Free on Thrive, no account needed.