TradeLabs AILearn

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.

Intermediate3 min readUpdated 3 Oct 2026
Markdown
Lesson 10 of 27

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#

ComponentResponsibilityLesson
Data handlerReceives live prices and builds barsWebSocket Market Data Streams
StrategyTurns data into target positions or signalsDeveloping, Testing and Monitoring Algorithms
Risk managerApproves or blocks every orderRisk Controls and Kill Switches
Order managerSends, tracks and cancels orders; records fillsWorking With Exchange and Broker APIs
Portfolio stateKnows current positions, cash and P&LTrade Accounting and Reconciliation
Logger and alertsRecords events and notifies humansLogging, 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#

OptionProsCons
Home computerFree, easy to debugPower and internet outages
Cloud server or VPSAlways on, cheapSome setup and maintenance
Broker hosted platformsIntegratedLess flexibility

See VPS, Cloud and Bare-Metal Servers and Failover, Backups and Disaster Recovery.

A staged path to live#

  1. Backtest the logic. See Backtesting Methodology.
  2. Replay recorded market data through the full bot. See Market Data Replay.
  3. Paper trade with the broker's test environment. See Paper Trading.
  4. Go live small, compare fills with expectations. See From Backtest to Live: Paper, Shadow and Canary.
  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.

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.

Check your understanding

3 quick questions on this lesson. Get them all right to finish it.

Turn on JavaScript to take the quiz.

Finished this lesson?Sign in to save your progress across devices.
Next lessonAlerts and WebhooksHow price alerts and webhooks work, how to send TradingView alerts to your own server or a chat channel, and how to secure webhook endpoints against fake signals.

Mentioned in