# Trading bot development: architecture, process, pitfalls

URL: https://fincodelabs.com/en/blog/trading-bot-development · Publisher: Fincode (Fincode Yazılım ve Teknoloji A.Ş.), Istanbul, Turkey · Category: Trading bots · Published: 2026-10-24 · Updated: 2026-11-05

Trading bot development explained: the parts of a production bot, build vs buy, the spec-to-live process, common failure modes and what to ask a developer.

**Short answer:** **Trading bot development** is the work of turning written trading rules into software that runs unattended: a market data feed, a rule engine, an independent risk layer, an order manager, a state store, monitoring and a kill switch. A sound process moves from a written specification through backtesting and paper trading to a small, staged live rollout. A well-built bot executes rules reliably; it does not make a strategy profitable, and automated trading can lose money.

Most trading bot projects start with a strategy that looks good on a chart, yet the strategy code is usually the smallest part of the finished system. The larger part keeps the bot honest when the exchange is slow, a WebSocket drops, an order fills in three pieces or the server restarts at 3 a.m. with an open position.

This guide covers the components of a production bot, build vs buy, a development process that limits surprises, whether to create your own bot, common failure modes and the questions to ask a developer. Exchange details come from official documentation, dated as of October 2026. Related guides are collected under [trading bots](https://fincodelabs.com/en/blog/trading-bots).

## What does a production trading bot consist of?

A production trading bot is a set of seven cooperating components.

**Components of a production trading bot**

| Component | What it does | What goes wrong without it |
| --- | --- | --- |
| Market data feed | Streams trades and order book updates, with REST snapshots as fallback | Decisions based on stale or gapped data |
| Rule engine | Applies the strategy rules and emits order intents | Live logic quietly differs from the backtested logic |
| Risk layer | Checks every order against size, price, position and loss limits | One bug becomes an unbounded loss |
| Order manager | Places and cancels orders, tracks partial fills, retries safely | Duplicate or orphaned orders |
| State store | Persists orders, fills and positions so a restart resumes from known state | The bot forgets a position after a crash |
| Monitoring and alerting | Heartbeats, error rates and exposure, with alerts that reach a person | Problems are discovered hours later |
| Kill switch | Blocks new orders and cancels working orders on a trigger or command | No fast way to stop a misbehaving bot |

The key design decision is separation: the risk layer lives outside the strategy code, so a strategy bug cannot bypass a limit (see [trading bot risk management](https://fincodelabs.com/en/blog/trading-bot-risk-management)). Order handling can grow into a [crypto order management system](https://fincodelabs.com/en/blog/crypto-order-management-system). The exchange connection is its own module, covered in [crypto exchange API integration](https://fincodelabs.com/en/blog/crypto-exchange-api-integration), and depth-based strategies need a correctly synchronized [local order book](https://fincodelabs.com/en/blog/websocket-order-book).

## Custom trading bot or off-the-shelf software?

Adopt existing software when your strategy fits its model, and build a custom trading bot when the strategy, the venues or the controls you need do not.

Hosted bot platforms let you configure a strategy in a browser; you accept their execution model and usually hand them an API key. Open-source frameworks give you a running engine to extend, and libraries give you building blocks. As of October 2026, three widely used projects on GitHub illustrate the range:

- **Freqtrade**: a free, open source crypto trading bot, licensed under GPL-3.0.
- **Hummingbot**: software for creating and deploying high-frequency crypto trading bots, licensed under Apache-2.0.
- **CCXT**: a library rather than a bot, offering a unified trading API for more than 100 crypto exchanges, licensed under MIT.

GPL-3.0 is a copyleft license with source-sharing obligations when modified versions are distributed, so have licensing checked before building a commercial product on a framework.

A custom build tends to make sense when the strategy needs order types, data or multi-leg logic a framework does not model, when it trades through a broker API, when you need your own risk controls and audit trail, or when you want to own the code. For a standard indicator strategy on one exchange, a framework may be cheaper; see [how much a custom trading bot costs](https://fincodelabs.com/en/blog/trading-bot-cost).

## How to build a trading bot: the development process

A reliable process has five stages, and each one has an exit criterion that must be met before the next begins.

1. **Specification.** The rules are written precisely enough that two developers would code the same thing, including what happens on a partial fill, a price gap, exchange downtime or a restart.
2. **Backtest.** The rules run on historical data with fees, slippage and realistic fills, and are tested out of sample. The exit criterion is robustness to cost assumptions, not an attractive equity curve; see [backtesting pitfalls](https://fincodelabs.com/en/blog/backtesting-trading-strategy-pitfalls).
3. **Paper trading or testnet.** The complete system runs on live data without real money. On the Binance Spot Test Network balances are virtual and the network is reset approximately once a month without notice (as of October 2026). Testnet fills do not reflect real liquidity, so this stage tests the software, not the strategy.
4. **Staged live rollout.** Trading starts at the smallest practical size with hard limits, and size increases only after reconciliation shows the bot's records match the exchange's.
5. **Monitoring and change control.** Every change is retested and every deployment can be rolled back.

Regulated firms formalize this. Under Article 5 of the EU's RTS 6 (Delegated Regulation 2017/589), investment firms must establish methodologies to develop and test algorithms before deployment, a designated person must authorize deployment, and records must show when each material change was made, by whom, who approved it and what it was. Private traders are not bound by RTS 6, but it is a sound template.

> **Why deployment discipline matters:** According to the SEC, Knight Capital's router sent more than 4 million orders in the first 45 minutes after the open on August 1, 2012 while trying to fill 212 customer orders, and the firm lost more than $460 million. The SEC found inadequate controls and procedures for code deployment and testing; Knight agreed to pay $12 million to settle.

## Can you create your own trading bot?

Yes. Creating a crypto trading bot for one exchange and one rule set is a realistic project for someone who already programs. The first version is rarely the hard part: public market data needs no key, libraries such as CCXT handle much of the exchange connectivity, and a testnet costs nothing to try.

A bot you can leave running takes more:

- **Written rules.** Entries, exits, position size and what the bot does when it is unsure, in enough detail that a program can follow them.
- **Programming and debugging skill.** You read the exchange documentation and diagnose a failed request yourself, often while the market is moving.
- **Time to run it.** A server, logs, alerts and someone who responds when they fire, for as long as the bot trades.

Think twice if you cannot yet explain how your code handles a timeout, a partial fill or a restart, or if a wrong order would cost more than you can absorb. Adopt existing software when it already models your rules, and consider a [crypto trading bot developer](https://fincodelabs.com/en/blog/crypto-trading-bot-developer) when the rules need low latency, several venues or controls you cannot build. Doing it yourself removes the development bill, not the risk: your own bot can still lose money.

## Common failure modes in production

Most production incidents come not from the strategy but from a gap between what the bot believes and what the exchange has recorded.

### State drift

Local positions diverge from reality after a missed fill during a reconnect, a manual trade on the same account or a crash. The remedy is reconciliation: compare open orders, balances and positions with the exchange at startup and on a schedule, and stop trading on any unexplained mismatch.

### Partial fills

Limit orders often fill in pieces. In Binance's spot API such an order has the status PARTIALLY_FILLED, and IOC or market orders that fill only partly end as EXPIRED. Position and exit logic must use the filled quantity, never the requested one.

### Rate limits

As of October 2026, Binance's spot exchangeInfo endpoint lists a request weight limit of 6,000 per minute and order limits of 100 per 10 seconds and 200,000 per day. Breaking a limit returns HTTP 429; continuing afterward triggers an automatic IP ban (HTTP 418) that scales from 2 minutes to 3 days for repeat offenders. A bot needs a request budget, honors Retry-After and prefers WebSocket streams to polling.

### Clock skew

Signed requests carry a timestamp. Binance's recvWindow defaults to 5,000 ms (maximum 60,000 ms), timestamps more than one second ahead of server time are rejected, and failures return error -1021. Keep the host clock synchronized; raising recvWindow hides the problem.

### Reconnects

Binance documents that a market data connection lasts at most 24 hours and that the server pings every 20 seconds, disconnecting if no pong arrives within a minute. After a reconnect the bot must resubscribe, rebuild its order book from a fresh snapshot and query orders that may have changed. APIs also change underneath you: Binance deprecated listenKey user data streams on stream.binance.com in April 2025, removed their documentation in October 2025 and switched the listenKey endpoints off on February 20, 2026.

### Unknown order status

Binance states that after an HTTP 5XX response the execution status is unknown and the request could have succeeded; error -1007 says the same. Resending blindly is how duplicate orders are created.

## Handling an unknown order status: a tested sketch

When an order request times out, the bot must find out whether the order exists before doing anything else, and a client order ID chosen before the first attempt makes that possible.

The Python sketch below uses a synthetic exchange that accepts every order but loses the reply. Retrying with a fresh ID creates two orders; fixing the ID once and polling for it creates one, and if the order never appears the function stops for reconciliation instead of resending.

```python
import time
import uuid

class Timeout(Exception):
    pass

class FakeExchange:                 # accepts orders, loses the reply
    def __init__(self):
        self.orders = {}
    def place(self, cid, side, qty):
        self.orders[cid] = {"side": side, "qty": qty, "status": "NEW"}
        raise Timeout()
    def query(self, cid):
        return self.orders.get(cid)

def place_naive(ex, side, qty):
    for _ in range(2):              # retry with a fresh ID
        try:
            return ex.place(uuid.uuid4().hex, side, qty)
        except Timeout:
            pass

def place_safely(ex, side, qty, polls=5, delay=1.0):
    cid = "bot1-" + uuid.uuid4().hex[:16]   # fixed before 1st send
    try:
        return ex.place(cid, side, qty)
    except Timeout:
        for _ in range(polls):              # the order may still be on its way
            time.sleep(delay)
            if (known := ex.query(cid)) is not None:
                return known                # it exists: do not resend
    raise RuntimeError("status unknown: stop and reconcile")

a, b = FakeExchange(), FakeExchange()
place_naive(a, "BUY", 0.01)
print("naive:", len(a.orders), "orders")
print("safe: ", place_safely(b, "BUY", 0.01), len(b.orders), "order")
```

Output:

```
naive: 2 orders
safe:  {'side': 'BUY', 'qty': 0.01, 'status': 'NEW'} 1 order
```

The fake exchange lands the order at once. A real order can arrive after your first query, so a miss does not prove it failed, and [Binance accepts a reused client order ID once the first order has filled](https://github.com/binance/binance-spot-api-docs/blob/master/rest-api.md), so a blind resend can double a market order. Run against a synthetic exchange where the order lands after the first query and fills at once, this version made one fill; when the order never landed, it stopped with the status-unknown error after one send. The sample takes about a second because it waits before each query.

Real exchanges support the pattern. Binance's query-order endpoint accepts either orderId or origClientOrderId, and Coinbase's Advanced Trade API documents that if a client_order_id is not unique, no new order is created and the existing order is returned. Production code adds signing, backoff and logging, tested with testnet keys.

## What to ask a trading bot developer

Ask questions whose answers reveal how the developer handles failure, because a demo only shows the happy path.

- What happens if the bot restarts with an open position and working orders?
- How are partial fills, rejections, timeouts and rate-limit responses handled?
- Which limits are enforced outside the strategy code, and how is the kill switch triggered and reset?
- Which API permissions are needed? Trading and reading are enough; withdrawal permission never is. Binance, for example, requires IP restrictions before withdrawal permission can be enabled (as of October 2026). See [API key security for trading bots](https://fincodelabs.com/en/blog/api-key-security-trading-bots).
- How will the system be tested before real money is at risk, and what are the criteria for increasing size?
- Who owns the code, and who maintains it when the exchange changes its API? Binance's spot API changelog has 38 dated entries for 2025 alone.

Treat any promise of returns as a red flag: a developer can be accountable for executing your rules correctly, not for market outcomes. Which markets and platforms a bot may use depends on your jurisdiction and the exchange's terms; in Turkey, Article 99/A of Capital Markets Law No. 6362 treats activity by foreign crypto-asset platforms directed at Turkish residents as unauthorized. Put the answers into the written specification and contract so that they can be checked at acceptance; the stages and what you receive at each are on Fincode's [how we work](https://fincodelabs.com/en/how-we-work) page, and the build itself on the [custom trading bot development](https://fincodelabs.com/en/services/algorithmic-trading) page. If you are comparing firms rather than people, see [how to evaluate a development company](https://fincodelabs.com/en/blog/crypto-bot-development-company).

## Frequently asked questions

### Can I build a trading bot myself in Python?

A prototype, yes; libraries such as CCXT handle much of the exchange connectivity. The hard part is the production layer: state persistence, reconciliation, risk limits, monitoring and safe handling of timeouts.

### Will a trading bot make money?

Not by itself. A bot executes a strategy consistently, but if the strategy has no edge after costs, automation only loses money faster. Backtests do not guarantee future results.

### How long does trading bot development take?

It depends on the number of exchanges, the data the strategy needs, the risk features and the length of the paper trading period. In the hypothetical scoping in the trading bot cost guide, a one-exchange spot bot is about 22 person-days and a three-exchange system about 69, before several weeks of paper trading; those figures are illustrations, not a quote. A written specification is the only reliable basis for an estimate.

### Is it legal to use a trading bot?

Many exchanges offer APIs specifically for automated trading, but the rules depend on your jurisdiction and the platform's terms. Market abuse such as wash trading or spoofing is prohibited whether done by hand or by a bot.

## Sources

- [Binance Spot API: General API information (rate limits, 5XX responses, timing security)](https://developers.binance.com/en/docs/products/spot/rest-api#general-api-information)
- [Binance Spot API: Error codes (-1007 TIMEOUT, -1021 INVALID_TIMESTAMP)](https://developers.binance.com/en/docs/products/spot/errors)
- [Binance Spot API: Account endpoints (query order by origClientOrderId)](https://developers.binance.com/en/docs/catalog/core-trading-spot-trading/api/rest-api/account)
- [Binance Spot API: WebSocket market streams (connection lifetime, ping/pong)](https://github.com/binance/binance-spot-api-docs/blob/master/web-socket-streams.md)
- [Binance Spot API: Enum definitions (order status)](https://github.com/binance/binance-spot-api-docs/blob/master/enums.md)
- [Binance Spot API: CHANGELOG](https://github.com/binance/binance-spot-api-docs/blob/master/CHANGELOG.md)
- [Binance Spot Test Network: FAQ](https://testnet.binance.vision/)
- [Binance: How to create API keys on Binance (permissions and IP restrictions)](https://www.binance.com/en/support/faq/how-to-create-api-keys-on-binance-360002502072)
- [Coinbase Developer Platform: Advanced Trade API, Create Order (client_order_id)](https://docs.cdp.coinbase.com/api-reference/advanced-trade-api/rest-api/orders/create-order)
- [Commission Delegated Regulation (EU) 2017/589 (RTS 6), Article 5, as adopted](https://www.legislation.gov.uk/eur/2017/589/article/5/adopted)
- [SEC press release 2013-222: SEC Charges Knight Capital With Violations of Market Access Rule](https://www.sec.gov/newsroom/press-releases/2013-222)
- [Freqtrade on GitHub](https://github.com/freqtrade/freqtrade)
- [Hummingbot on GitHub](https://github.com/hummingbot/hummingbot)
- [CCXT on GitHub](https://github.com/ccxt/ccxt)
- [Capital Markets Law No. 6362, Article 99/A (Turkish)](https://www.mevzuat.gov.tr/mevzuatmetin/1.5.6362.pdf)

> This guide is general information about software and markets, not investment, legal or tax advice. Automated trading can lose money, past or backtested performance does not guarantee future results, and the rules that apply depend on your jurisdiction and your exchange's terms. Sources, checks and corrections: see the [editorial policy](https://fincodelabs.com/en/editorial-policy).

---

Published by Fincode (Fincode Yazılım ve Teknoloji A.Ş.), a software company in Istanbul, Turkey: https://fincodelabs.com/en/blog/trading-bot-development

Cite as: Fincode, "Trading bot development: architecture, process, pitfalls", updated November 5, 2026, https://fincodelabs.com/en/blog/trading-bot-development
