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

Source: https://learn.tradelabsai.com/programming/building-trading-bots/  
Track: Programming and Data · Level: Intermediate · Updated: 2026-10-03  
Publisher: TradeLabs AI (https://tradelabsai.com). Education, not financial advice.  
Cite as: TradeLabs Learn, "Building Trading Bots", https://learn.tradelabsai.com/programming/building-trading-bots/

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](https://learn.tradelabsai.com/programming/websocket-market-data-streams/) |
| Strategy | Turns data into target positions or signals | [Developing, Testing and Monitoring Algorithms](https://learn.tradelabsai.com/algo-trading/algorithm-development/) |
| Risk manager | Approves or blocks every order | [Risk Controls and Kill Switches](https://learn.tradelabsai.com/algo-trading/risk-controls-and-kill-switches/) |
| Order manager | Sends, tracks and cancels orders; records fills | [Working With Exchange and Broker APIs](https://learn.tradelabsai.com/programming/trading-apis/) |
| Portfolio state | Knows current positions, cash and P&L | [Trade Accounting and Reconciliation](https://learn.tradelabsai.com/industry/trade-reconciliation/) |
| Logger and alerts | Records events and notifies humans | [Logging, Audit Trails and Incident Response](https://learn.tradelabsai.com/algo-trading/audit-trails/), [Monitoring Positions, P&L and Risk](https://learn.tradelabsai.com/algo-trading/live-monitoring/) |

Keeping these separate means you can test each part alone and swap the strategy without touching the safety code.

## A simple event loop

```python
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](https://learn.tradelabsai.com/algo-trading/automated-trading/).

**Example: A restart done right**
A bot targets +200 shares of a stock. It sends a buy for 200, receives a fill for 120 and then crashes. On restart, it loads its target of +200 from storage, asks the broker for the real position (+120) and open orders (a working order for the remaining 80), and does nothing, because the working order already covers the gap. A signal based bot might have sent a fresh order for 200, leaving it with up to 400 shares. See [Alerts, Error Handling and Reconnection](https://learn.tradelabsai.com/algo-trading/error-handling/).

## 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](https://learn.tradelabsai.com/programming/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](https://learn.tradelabsai.com/risk/daily-loss-limit/).
- **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](https://learn.tradelabsai.com/infrastructure/vps-cloud-and-bare-metal-servers/) and [Failover, Backups and Disaster Recovery](https://learn.tradelabsai.com/algo-trading/disaster-recovery/).

## A staged path to live

1. **Backtest** the logic. See [Backtesting Methodology](https://learn.tradelabsai.com/research/backtesting-methodology/).
2. **Replay** recorded market data through the full bot. See [Market Data Replay](https://learn.tradelabsai.com/programming/market-data-replay/).
3. **Paper trade** with the broker's test environment. See [Paper Trading](https://learn.tradelabsai.com/start-here/paper-trading/).
4. **Go live small,** compare fills with expectations. See [From Backtest to Live: Paper, Shadow and Canary](https://learn.tradelabsai.com/algo-trading/backtest-to-live/).
5. **Scale up gradually** while monitoring.

## Common mistakes

1. **Strategy and order code tangled together,** making bugs hard to find.
2. **No reconciliation** with the broker.
3. **Signal based orders** that duplicate after restarts.
4. **No logging,** so failures cannot be explained.
5. **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](https://learn.tradelabsai.com/programming/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](https://learn.tradelabsai.com/programming/alerts-and-webhooks/).

## Continue learning

- Next lesson: [Alerts and Webhooks](https://learn.tradelabsai.com/programming/alerts-and-webhooks/)
- Previous lesson: [Pine Script Basics](https://learn.tradelabsai.com/programming/pine-script-basics/)
- Related: [Pine Script Basics](https://learn.tradelabsai.com/programming/pine-script-basics/): Learn Pine Script, TradingView's language for custom indicators, strategies and alerts. Covers series, plots, inputs, a crossover strategy and common pitfalls.
- Related: [Automated vs Semi-Automated Trading](https://learn.tradelabsai.com/algo-trading/automated-trading/): Automated trading systems place and manage orders without manual input. Learn levels of automation, platforms, what to automate first and the safeguards.
- Related: [Working With Exchange and Broker APIs](https://learn.tradelabsai.com/programming/trading-apis/): How trading APIs let programs get prices, place orders and read positions. Learn REST, WebSocket and FIX, authentication, rate limits and safe API key handling.
- Related: [Risk Controls and Kill Switches](https://learn.tradelabsai.com/algo-trading/risk-controls-and-kill-switches/): Pre trade risk checks and kill switches stop a trading algorithm before a bug becomes a disaster. Learn the essential limits, how to layer them and how to test them.
- Related: [Alerts, Error Handling and Reconnection](https://learn.tradelabsai.com/algo-trading/error-handling/): Trading systems face rejected orders, disconnects, bad data and partial fills. Learn how to classify errors, retry safely, use idempotent orders and fail closed.
- Related: [From Backtest to Live: Paper, Shadow and Canary](https://learn.tradelabsai.com/algo-trading/backtest-to-live/): Why live results almost always trail backtests, how to measure the gap, and a staged plan for taking a strategy from backtest to paper trading to real money.
