Python Trading Bot Architecture Review: Coupling Flaws to Fix

A Python trading bot stays testable, reviewable and portable to another broker when five parts are kept apart: strategy logic that knows nothing about the broker, a risk engine that can veto every order, a broker adapter for ib_async or IBKR’s TWS API behind a narrow interface, state that survives a restart and configuration outside the code. An architecture review checks whether these boundaries hold and where they leak: a strategy that calls placeOrder() itself, risk checks scattered across modules, broker objects deep inside the domain logic, positions that exist only in memory. This article describes each part, the coupling flaws a review typically flags, a tested script that enforces the most important boundary, and the limits of a review, as of November 2026.

What does a trading bot architecture review check?

A code review reads lines; an architecture review looks at boundaries. It answers four questions: which components exist, which one may call which, where state lives and what happens when a part fails. The result is a map of the current structure, a ranked list of coupling flaws, a target picture and the effort to get there.

The table shows the components most Python trading bots need, whatever the strategy. Names vary; the responsibilities should not.

ComponentResponsibilityMust not
Market data adapterTurns broker ticks and bars into plain data with timestampsMake trading decisions
StrategyTurns data into intents, such as “target position 100”Import a broker library or send orders
Risk engineApproves or rejects every intent and order, with a reasonBe skipped or switched off by the strategy
Order managerTurns approved intents into orders and tracks their statesResend after a timeout without a status query
Broker adapterSpeaks ib_async or the TWS API, maps callbacks to own eventsLeak broker objects into other modules
State storeKeeps what must survive a restartReplace the broker as the record of positions
ConfigurationOne validated object, loaded at startupBe scattered across constants and modules
MonitoringHeartbeats, alerts, a log of every decisionRely on someone happening to read an email

Strategy logic that does not know the broker

The strategy changes most often, so it should be the easiest part to test. It receives bars, ticks or account values as plain data and returns an intent: a target position, an entry with its stop, or a request to flatten. It never imports ib_async, ib_insync or IBKR’s ibapi, and it never calls placeOrder().

This is the ports-and-adapters idea that Alistair Cockburn described in 2005: an application that can be driven by users, programs or automated tests and is developed and tested “in isolation from its eventual run-time devices and databases”. For a trading bot it pays off three times: the backtest runs the same strategy code as the live bot, unit tests need no TWS session, and a change of broker or library touches only the adapter.

A review checks this boundary mechanically first. The script below fails as soon as a module in the strategy or risk package imports a broker library. It parses the files without executing them and uses only the standard library. Tested with Python 3.9 and 3.12 on a sample project, it reported both broker imports in the strategy package, ignored the adapter package and returned exit code 1; on a clean project it returned 0.

"""Fails if strategy or risk code imports a broker library. Python 3 standard library only;
it parses source files and executes none of them."""
import ast
import pathlib
import sys

BROKER_LIBS = {"ib_async", "ib_insync", "ibapi"}
PROTECTED = ("strategy", "risk")   # packages that must stay broker-independent


def broker_imports(path):
    tree = ast.parse(path.read_text(encoding="utf-8"), filename=str(path))
    for node in ast.walk(tree):
        if isinstance(node, ast.Import):
            names = [alias.name for alias in node.names]
        elif isinstance(node, ast.ImportFrom) and node.level == 0 and node.module:
            names = [node.module]
        else:
            continue
        for name in names:
            if name.split(".")[0] in BROKER_LIBS:
                yield node.lineno, name


def main(root):
    found = 0
    for package in PROTECTED:
        for path in sorted(pathlib.Path(root, package).rglob("*.py")):
            for line, name in broker_imports(path):
                print(f"{path}:{line}: imports {name}")
                found += 1
    print(f"{found} boundary violation(s)")
    return 1 if found else 0


if __name__ == "__main__":
    sys.exit(main(sys.argv[1] if len(sys.argv) > 1 else "."))

Run it with python3 boundary_check.py path/to/project in the test suite or the build pipeline. It does not catch imports hidden in strings or loaded through importlib, and it says nothing about coupling through shared objects; that still needs a reader.

A risk engine with veto power

The risk engine is a separate component on the only path from strategy to adapter. It has its own configuration, its own state and one job: approve or reject, with a reason that goes into the log. The strategy can ask it in advance, but cannot skip it or change its limits at run time.

This matters because the broker does not know your limits. IBKR states that the TWS API contains no logic beyond ensuring the integrity of the exchanged messages; requests are validated in TWS and on IBKR’s servers. The API does not know your daily loss limit or your maximum position. A review looks for these flaws in the risk path:

  • Checks inside the strategy, so a second strategy forgets them.
  • Limits that count filled positions but not working orders.
  • An exception in the risk code that ends in “allow”; the default must be “reject”.
  • A kill switch held only in memory, which a restart clears.
  • Decisions based on account values without a check of their age.

The pre-live checklist for AI-built trading bots shows a reconciliation and kill-switch example in Python.

A swappable broker adapter for ib_async or the TWS API

The adapter is the only module that imports a broker library. It translates intents into IBKR orders, resolves contracts, rounds prices and quantities, and turns callbacks or events into a small set of own events such as accepted, filled, rejected, connection lost and connection restored. Everything IBKR-specific stays inside:

  • Readiness: after the handshake, TWS sends the accounts accessible in the session, the next valid order ID and the connection time. IBKR describes the nextValidId callback as the usual signal that the connection is complete; requests sent earlier may be dropped.
  • Order IDs: IBKR rejects an order whose ID is lower than or equal to a previous one from the same client as a duplicate (error 103). The adapter takes the next ID from nextValidId on every connection instead of counting on from memory.
  • Client IDs: according to IBKR, orders submitted through the API stay bound to the client ID that sent them, and only that client can modify them. A fixed client ID per bot belongs in the configuration.
  • Startup sync: the ib_async 2.1.0 documentation states that connect() returns a fully synchronized client and by default loads positions, open and completed orders, account updates and executions. The same documentation advises against placing new requests inside an event handler, as it may lead to too much recursion.

With this boundary, the choice between ib_async and IBKR’s own API becomes a decision about one module; see ib_async vs ib_insync for the library side. A fake adapter with the same interface makes the rest of the bot testable: it records orders, replays fills and raises errors on demand.

State and persistence: what must survive a restart

A bot that keeps everything in memory starts every restart with a guess. A review asks which state belongs to the broker and which state only the bot knows.

StateSource of truthAfter a restart
PositionsBrokerLoad from the broker and compare with the local record
Open ordersBrokerLoad, then map back to the intents that created them
Next order IDBrokerTake it from nextValidId
Kill switch and its reasonBotLoad from disk; only a person clears it
Daily loss baselineBotLoad the start-of-day value; never reset it on restart
Intent-to-order mappingBotLoad, so fills are attributed to the right intent
Last processed barBotLoad, so no signal is acted on twice

The bot’s own state belongs in durable storage, for example an SQLite file or an append-only log, in a directory that only this bot instance uses. Until positions and open orders match the broker, the risk engine blocks every order that increases risk. A mismatch is not something to repair automatically: it is an alert and a reason to stop.

Configuration: one validated source, separate from the code

The Twelve-Factor App calls config stored as constants in the code a violation and requires a strict separation of config from code. Its litmus test fits trading bots well: could the codebase be made open source at any moment without compromising any credentials? Twelve-Factor recommends environment variables. For a trading bot, a practical split is credentials in environment variables or a secret store, and limits, symbols, ports and client IDs in a reviewed configuration file per deployment.

A review checks how that configuration enters the bot. Good practice is one typed object, loaded and validated once at startup, with explicit units such as shares, contracts or account currency, no silent defaults for limits and a refusal to start when a value is missing. Paper and live get separate files, not one boolean that changes port, account and limits at once.

Flags deserve special care: in the SEC’s 2013 order against Knight Capital, a repurposed flag reactivated a function that had been unused for years on the one server still running old code, as the trading system audit guide describes. The architectural lesson: delete dead code instead of leaving it switched off, and never give an old flag a new meaning.

Typical coupling flaws a review flags

FlawSymptomFix
Strategy calls the broker directlyNo test without TWS; risk checks can be skippedStrategy returns intents; only the adapter sends orders
Broker objects in the domain logicA library update breaks strategy codeOwn data types, mapping inside the adapter
Risk checks spread across modulesLimits differ between strategiesOne risk engine on the only path to the broker
Work and new requests inside event handlersSlow reactions; ib_async warns of recursionHandlers only queue events; one worker processes them
Positions only in memoryAfter a restart the bot assumes it is flatBroker as source of truth, reconciliation before trading
Global objects for connection and configTests influence each other; paper and live mixPass dependencies explicitly at startup
Timestamps without time zonesSession filters fail around clock changesTime-zone-aware timestamps, UTC inside
Dead code and reused flagsOld behavior can returnDelete unused paths; new meanings get new flags

Most of these flaws are not bugs in the narrow sense: the bot works on a normal day. They show up on the day something fails, and they make every later change more expensive, because nothing can be tested in isolation.

Limits of an architecture review, and what to do next

An architecture review shows where a bot is fragile; it does not prove that it is correct, and it says nothing about whether the strategy will make money. Refactoring also carries risk: moving risk checks or replacing the adapter changes the code that trades. Make the changes in small steps behind tests, and before switching, run the new version next to the old one on the same market data with order sending disabled and compare their decisions. Automated trading can lose money quickly, and with leveraged products the losses can exceed the capital deployed.

A practical order of work:

  1. Draw the current components and arrows on one page: who imports whom, who sends orders.
  2. Run the boundary check and list every broker import outside the adapter.
  3. Write a fake adapter and get one strategy test running without TWS.
  4. Move all limits into one risk engine that rejects by default.
  5. Persist the kill switch, the daily baseline and the intent-to-order map, and reconcile on every start.
  6. Move the configuration into one validated object per deployment.

If the bot grew quickly, possibly with the help of AI coding tools, an independent architecture review before these steps shows which of them matter most for your code.

Frequently asked questions

What is a good architecture for a Python trading bot?

There is no single best architecture, but a reviewable one keeps strategy logic, risk engine, order management, broker adapter, state and configuration apart. The strategy returns intents and imports no broker library, the risk engine approves or rejects every order, and only the adapter talks to ib_async or the TWS API. The same strategy code can then run in backtests and live, and be tested without a broker connection.

Should the risk engine be separate from the strategy?

Yes. A separate risk engine on the only path to the broker applies the same limits to every strategy and cannot be skipped by a strategy bug. It returns approve or reject with a reason, counts working orders as well as positions and rejects when data is missing. Interactive Brokers states that its TWS API contains no logic beyond message integrity, so the API does not enforce these limits; your own code has to.

How do you make a trading bot broker-independent?

Put everything broker-specific into one adapter module: connection handling, contract lookup, order IDs, price rounding and the mapping of callbacks to your own events. Strategy and risk engine use only your own data types. A fake adapter with the same interface lets you test the bot without TWS or IB Gateway, and a switch from ib_async to IBKR’s own API, or to another broker, touches one module.

What state should a trading bot persist across restarts?

Persist what only the bot knows: the kill switch and its reason, the start-of-day value for the daily loss limit, the mapping from intents to order IDs and the last processed bar. Positions and open orders belong to the broker. Load them after every restart, compare them with the local record and block new risk-increasing orders until both match.

Sources and status

As of November 2026. Third-party rules, prices and APIs may have changed since; the providers' current documentation and the official texts are authoritative.

This article is also available in German: Python-Trading-Bots prüfen: Strategie, Risiko, Broker trennen.

Want an architecture review of your Python trading bot? Get in touch — a free intro call clarifies the code base, the question and what the review should deliver. More: Trading system code review and audit.