PnL ProfitEncyclopedia
🌐 English

Building Trading Bots

7 min read · Updated Nov 23, 2026
More in Algorithmic & Quant Trading

A trading bot is a program that connects to a broker or exchange, reads market data, decides when to trade and sends orders automatically. Building one that places an order is easy; building one that behaves safely when data is late, the connection drops or the strategy misfires is the real work. It is the engineering side of algorithmic trading: the standard architecture, how exchange APIs work, and the safety controls every bot needs before it touches real money.

Key takeaways

  • Separate a bot into layers: data feed, signal, risk, execution and monitoring.
  • Use WebSocket streams for market data and keep REST calls for orders and account checks, staying within rate limits.
  • API keys should have the minimum permissions needed, with withdrawals disabled and IP restrictions where available.
  • Hard risk limits and an automatic kill switch are not optional; software failures can lose money faster than any bad trade.
  • Run in dry-run or paper mode first, log everything, and compare live behavior with your backtest.
On this page
  1. Bot architecture
  2. Exchange and broker APIs
  3. Rate limits
  4. API key security
  5. Kill switches and risk limits
  6. Dry run, paper trading and logging
  7. Deployment
  8. Open-source tooling
  9. Worked example: rate limit and risk budget
  10. Common mistakes

Bot architecture

Most robust bots, from simple scripts to professional systems, share the same building blocks.

Layer Job Key concerns
Data feed Receive prices, order books, trades and account updates Reconnection, gaps, stale data, timestamps
Signal (strategy) Turn data into desired positions or orders Same logic as the backtest; no look-ahead
Risk Check every order against limits before it leaves Position size, exposure, daily loss, price sanity checks
Execution Place, amend and cancel orders; track fills Idempotency, partial fills, retries, rate limits
State and storage Keep positions, orders and balances consistent Reconcile with the exchange regularly
Monitoring Alerts, dashboards, logs Know within minutes when something is wrong

Keeping the layers separate means you can reuse the same signal code in backtesting and live trading, and you can test the risk layer on its own. The risk layer should be able to block any order, regardless of what the strategy wants. The execution layer can be as simple as sending limit orders or as involved as the slicing logic described in execution algorithms.

Exchange and broker APIs

REST

REST APIs use standard web requests. You send a request (place an order, get balances) and receive a response. They are simple but slow for streaming data, and each request counts against a rate limit.

WebSocket

WebSocket connections stay open and push updates to you as they happen: trades, order book changes, order fills. They are the standard way to receive market data in real time. Bots must handle disconnects, resubscribe, and rebuild the local order book from a fresh snapshot if any update is missed, usually detected through sequence numbers.

FIX

The FIX protocol is the long-established messaging standard in institutional trading, used by many brokers, futures firms and some crypto venues for order entry and market data. It is more complex to implement but offers stable sessions and lower overhead for high message rates.

Authentication

Private endpoints usually require an API key and a signature computed with a secret, often HMAC-based, plus a timestamp. If your server clock drifts, requests can be rejected, so keep the system clock synchronized. Crypto venues built on blockchains may instead require signing orders with a wallet's private key.

Rate limits

Exchanges limit how many requests you can send per second or minute, often as a "weight" budget where heavy requests cost more. Exceeding the limit returns errors and, on repeated violations, temporary bans. Good practice:

  • Get market data from WebSocket streams instead of polling REST endpoints.
  • Track your own usage, often with a token-bucket counter, and slow down before hitting the limit.
  • On a rate-limit error, back off with increasing delays instead of retrying immediately.
  • Batch operations where the API supports it, such as cancelling all orders in one call.

API key security

A leaked API key can empty an account. Treat keys like passwords to your bank:

  • Disable withdrawals on trading keys. A bot rarely needs to withdraw funds.
  • Restrict by IP address so the key only works from your server.
  • Use least privilege: read-only keys for monitoring, trade keys only where needed.
  • Never put keys in code or public repositories. Load them from environment variables or a secrets manager.
  • Use a sub-account with limited funds for each bot, where the venue supports it.
  • Be wary of third-party bot services that ask for keys with withdrawal rights, and of any tool that asks for a wallet seed phrase. See crypto wallet security and, for Telegram-style swap bots, meme coin trading bots.

Kill switches and risk limits

Software failures can be spectacular. On August 1, 2012, the US market maker Knight Capital deployed faulty code that sent a flood of unintended orders, losing about 440 million dollars in under an hour and pushing the firm into a rescue. Smaller versions of the same thing, such as a loop that resends orders or a unit error that trades ten times the intended size, happen to retail bots all the time.

Every bot should have:

  • Maximum position size per instrument and overall.
  • Maximum order size and a price collar that rejects orders far from the current market.
  • Daily loss limit that cancels orders, optionally flattens positions, and stops the bot until a human restarts it.
  • Order-rate limit that stops the bot if it sends far more orders than expected.
  • Stale-data check that stops trading if market data has not updated for a set time.
  • A manual kill switch you can trigger from your phone.

Dry run, paper trading and logging

Run the full system in dry-run mode first, where it computes orders and logs them without sending, then in paper trading or on an exchange testnet where available. Testnets often behave differently from live markets, with thinner books and different fills, so treat them as a software test, not a performance test.

Log every input and decision: received data, signals, orders sent, exchange responses, fills and errors, all with UTC timestamps. When something goes wrong, logs are the only way to reconstruct what happened. Use unique client order IDs so that a retried request cannot accidentally create a duplicate order, and regularly reconcile your bot's view of positions with the exchange's.

A minimal main loop shows how the pieces fit together. The feed, strategy and broker objects are placeholders for your own data, signal and execution layers.

import logging

MAX_DAILY_LOSS = 300.0      # account currency
MAX_POSITION = 2_000.0      # absolute notional per symbol

def run(feed, strategy, broker, dry_run=True):
    start_equity = broker.equity()
    for tick in feed:                                   # e.g. messages from a WebSocket queue
        pnl = broker.equity() - start_equity
        if pnl <= -MAX_DAILY_LOSS:
            logging.critical("Daily loss limit hit (%.2f). Stopping.", pnl)
            broker.cancel_all()
            broker.flatten()
            return                                      # kill switch: wait for a human
        order = strategy.on_tick(tick)
        if order is None:
            continue
        new_pos = broker.position(order.symbol) + order.signed_notional
        if abs(new_pos) > MAX_POSITION:
            logging.warning("Order blocked by position limit: %s", order)
        elif dry_run:
            logging.info("DRY RUN, would send: %s", order)
        else:
            broker.send(order, client_order_id=order.uid)  # unique ID prevents duplicates

Deployment

Bots usually run on a cloud server or virtual private server close to the exchange's servers, with automatic restart on crash. On restart, a bot must first load its state from the exchange (open orders, positions) rather than assuming it starts flat. Keep the clock synchronized, monitor memory and disk use, and plan for exchange maintenance windows.

Open-source tooling

Many traders build on existing libraries instead of starting from scratch. Well-known open-source examples include CCXT (a unified library for many crypto exchange APIs), Freqtrade and Hummingbot (crypto bot frameworks), Backtrader and NautilusTrader (backtesting and trading frameworks) and QuantConnect's LEAN engine. These are mentioned as examples, not recommendations; review any code you run with real money. For a platform-specific walkthrough, see the Polymarket trading bot guide.

Worked example: rate limit and risk budget

An exchange allows a request weight of 1,200 per minute (an illustrative figure; check your venue's documentation). A bot tracks 10 markets.

  • Polling the order book for each market every second at a weight of 5 costs 10 × 5 × 60 = 3,000 per minute, 2.5 times the limit. The bot would be banned.
  • Switching market data to WebSocket streams removes those requests. If the bot then places or cancels about 40 orders per minute at a weight of 1 each, plus one balance check per minute at a weight of 10, it uses about 50 per minute, around 4% of the budget.

For risk, the account holds 10,000 dollars. The bot caps exposure at 20% per market (2,000 dollars) and stops trading at a daily loss of 3% (300 dollars). Even if every open position moved sharply against it before the kill switch fired, the worst case is bounded by those limits and by the stop logic, rather than by luck.

Common mistakes

  • No reconnection logic. WebSocket feeds drop; a bot that silently stops updating trades on stale prices.
  • Assuming orders fill. Handle partial fills, rejections and cancellations explicitly.
  • Retrying without idempotency. A timed-out order may still have been accepted; resending can double the position.
  • Keys with withdrawal permission. This turns any server compromise into a total loss.
  • Going live without a kill switch. Bugs are certain; unlimited bugs are optional.
  • Testing only in calm markets. Volatile periods expose race conditions and rate-limit problems.

FAQ

What programming language is best for a trading bot?

Python is the most common choice for retail bots because of its libraries and ease of use. Faster languages such as C++, Rust or Java are used when latency or very high message rates matter.

Are trading bots profitable?

A bot only automates a strategy; it does not create an edge. Many bots lose money because the underlying strategy has no edge after costs, or because of software and risk-control failures.

Is it safe to give a trading bot my API key?

It can be reasonably safe if the key cannot withdraw funds, is restricted to known IP addresses, and is limited to a sub-account with capped funds. Never share keys with withdrawal rights or wallet seed phrases with third-party services.

What is a kill switch in algorithmic trading?

A kill switch is a control that automatically or manually stops a trading system, cancels its orders and, if configured, closes positions when limits such as a daily loss or order rate are breached.

Educational content only. Nothing here is financial, investment, legal or tax advice. Trading carries a high risk of loss, and leveraged products can lose more than you deposit. Rules, fees and platform details change: check current terms with your broker, exchange or regulator before you trade.