BilgeStore
BilgeStore
crypto2026-02-12

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.

cryptotradingbotBinancearchitecture

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

  • Moving Average Crossover (SMA, EMA)
  • RSI Oversold/Overbought
  • Bollinger Band Breakout
  • MACD Signal Line Cross
  • Grid Trading (range-bound markets)
  • 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

  • Fixed: 2% stop loss, 4% take profit (2:1 R:R)
  • ATR-based: Dynamic stops based on market volatility
  • Trailing: Lock in profits as price moves in your favor
  • Portfolio Limits

  • Max 5 concurrent positions
  • Max 20% exposure to single asset
  • Daily loss limit: 5% of portfolio
  • 4. Backtesting

    Test strategies against historical data before going live:

    `python

    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(),

    }

    ``

    5. Production Deployment

    Infrastructure

  • VPS: Hetzner or DigitalOcean (low latency to Binance)
  • Monitoring: Grafana dashboards for PnL, positions, strategy performance
  • Alerts: Telegram notifications for trades, errors, and daily PnL reports
  • Failsafe: Auto-close all positions if bot crashes or loses connection
  • Exchange Support

  • Binance (spot + futures)
  • Bybit
  • OKX
  • Kraken
  • 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.