Building Trading Bots
How to build a trading bot that is safe to run: the main components, an event loop, state and position tracking, risk checks, logging and a staged path to live.
A trading bot is a program that watches the market and places orders by itself according to rules. Writing a bot that places an order is easy; writing one that can run unattended without doing something expensive is the real work. Most of a robust bot's code has nothing to do with the strategy: it tracks state, checks risk, handles errors, logs everything and recovers from failures. This lesson walks through a sound architecture that works for stocks, futures or crypto and scales from a hobby script to a serious system.
The main components#
| Component | Responsibility | Lesson |
|---|---|---|
| Data handler | Receives live prices and builds bars | WebSocket Market Data Streams |
| Strategy | Turns data into target positions or signals | Developing, Testing and Monitoring Algorithms |
| Risk manager | Approves or blocks every order | Risk Controls and Kill Switches |
| Order manager | Sends, tracks and cancels orders; records fills | Working With Exchange and Broker APIs |
| Portfolio state | Knows current positions, cash and P&L | Trade Accounting and Reconciliation |
| Logger and alerts | Records events and notifies humans | Logging, Audit Trails and Incident Response, Monitoring Positions, P&L and Risk |
Keeping these separate means you can test each part alone and swap the strategy without touching the safety code.
A simple event loop#
while running:
event = queue.get() # a new bar, fill, or timer tick
if event.type == "bar":
target = strategy.on_bar(event) # desired position, e.g. +100 shares
order = portfolio.order_to_reach(target)
if order and risk.approve(order, portfolio):
broker.send(order)
elif event.type == "fill":
portfolio.apply_fill(event)
log.fill(event)
elif event.type == "timer":
portfolio.reconcile_with(broker) # compare with the broker every few minutes
Target positions instead of buy and sell signals#
A strategy that outputs "I want to hold +100 shares" is safer than one that outputs "buy 100 shares". If a fill is missed or the bot restarts, the order manager simply compares the target with the actual position and sends the difference. A signal based bot that restarts may buy again, doubling the position. See Automated vs Semi-Automated Trading.
Persisting state#
Store targets, open orders and recent fills somewhere that survives a crash, such as a small database. On startup, always reconcile with the broker before trading: the broker's records are the source of truth. See Database Design for Market Data.
Risk checks every bot needs#
- Maximum order size and position size.
- Daily loss limit that halts trading. See Maximum Trade Risk and Daily Loss Limits.
- Price collar against stale or wrong prices.
- Order rate limit to stop loops.
- Kill switch that cancels everything.
Where to run it#
| Option | Pros | Cons |
|---|---|---|
| Home computer | Free, easy to debug | Power and internet outages |
| Cloud server or VPS | Always on, cheap | Some setup and maintenance |
| Broker hosted platforms | Integrated | Less flexibility |
See VPS, Cloud and Bare-Metal Servers and Failover, Backups and Disaster Recovery.
A staged path to live#
- Backtest the logic. See Backtesting Methodology.
- Replay recorded market data through the full bot. See Market Data Replay.
- Paper trade with the broker's test environment. See Paper Trading.
- Go live small, compare fills with expectations. See From Backtest to Live: Paper, Shadow and Canary.
- Scale up gradually while monitoring.
Common mistakes#
- Strategy and order code tangled together, making bugs hard to find.
- No reconciliation with the broker.
- Signal based orders that duplicate after restarts.
- No logging, so failures cannot be explained.
- Running unattended without alerts.
Frequently asked questions#
How do I build a trading bot?#
Separate data, strategy, risk, order management, state and logging; have the strategy output target positions; reconcile with the broker; add risk limits; and test through replay and paper trading before going live.
What language is best for a trading bot?#
Python suits most retail bots. Faster languages matter only for latency sensitive strategies. See Python for Trading.
Are trading bots profitable?#
A bot only executes a strategy. It is profitable only if the strategy has a real edge after costs; automation alone does not create one.
Next, learn how alerts and webhooks connect tools together in Alerts and Webhooks.
3 quick questions on this lesson. Get them all right to finish it.
Turn on JavaScript to take the quiz.
Mentioned in
- Python for TradingProgramming and Data
- Backtesting Libraries ComparedProgramming and Data
- Pine Script BasicsProgramming and Data
- Market Data ReplayProgramming and Data
- Algorithmic Trading ExplainedAlgorithmic Trading
- Developing, Testing and Monitoring AlgorithmsAlgorithmic Trading