Algorithmic trading bot reacting to a real-time price chart

Blog ·

Build a Trading Bot With Real-Time Prices: Architecture and Code

An algorithmic trading bot is only as good as its data. This guide outlines a robust architecture for a bot that uses real-time prices to generate signals, with safeguards most tutorials skip.

The architecture

  1. Market data: a WebSocket stream of quotes for the symbols you trade.
  2. State: the latest price per symbol plus a rolling window of history.
  3. Strategy: turns prices into signals.
  4. Risk: position limits, maximum loss per day, kill switch.
  5. Execution: sends orders to your broker.
  6. Logging: every price, signal and order, for later review.

Seed history, then stream

# 1) warm up indicators with recent candles
r = requests.get(API + "/bars", params={"symbol": "EURUSD", "timeframe": "M1",
                 "from": start_iso, "to": now_iso}, headers=H, timeout=30)
closes = [float(b["close"]) for b in r.json()["data"]]
# 2) then subscribe to live quotes over WebSocket and update `closes` on every tick

Never trade on stale prices

def usable(q, max_age_s=5):
    age = time.time() - datetime.fromisoformat(q["time"].replace("Z", "+00:00")).timestamp()
    return q["status"] == "LIVE" and age <= max_age_s

Every quote carries its source time and status. Skip signals when the market is closed or a price is older than your tolerance.

Risk first

  • Hard limits on position size and daily loss, enforced outside the strategy code.
  • A kill switch that flattens positions when data stops arriving.
  • Paper-trade before going live.

Testing before going live

  1. Backtest on historical candles, then on ticks for the critical periods.
  2. Paper trade with live data for at least a few weeks.
  3. Go live small, with conservative limits, and scale only after results match expectations.

Operational checklist

  • Run the bot on a server close to your broker, with monitoring and alerts.
  • Log every decision with the price and timestamp that triggered it.
  • Handle reconnections and restarts without duplicating orders.
  • Review performance daily: drift between backtest and live results is an early warning.

Which timeframe should a bot use?

It depends on the strategy: scalpers react to ticks, intraday systems to M1-M15 candles, swing systems to H1-D1. Data costs grow with frequency, so use the slowest timeframe that captures your edge.

Market data is indicative: orders are filled at your broker's prices. Start with the streaming guide and free credits.

Try the market price API

1000 free credits after sign-up.

Get a free API key

More articles