Pre-Trade Risk Checks for Trading Bots: How to Test Them

Pre-trade risk checks, also called risk gates, decide whether an order may leave a trading bot at all: order size, price, position including working orders, daily loss, a stop attached from entry, and whether the bot’s positions have been reconciled with the broker. Testing them means proving four things: each gate blocks exactly at its limit, counts working orders as well as fills, fails closed when data is missing or a check throws an error, and keeps blocking new risk after a disconnect until positions and open orders match the broker again. This article lists the gates, a test matrix and a tested Python example with fault injection and a simulated disconnect, based on FIA’s 2024 best practices and IBKR’s documentation, as of November 2026.

What pre-trade risk checks are and where they sit

A pre-trade risk check is a rule that every new or modified order must pass before it is sent. In a trading bot the checks sit in one place, between the strategy and the broker adapter, and return a decision with a reason that goes into the log. The strategy cannot skip them, and no other code path may send orders.

Industry guidance is clear on why they matter. FIA, the global trade organization for the futures, options and centrally cleared derivatives markets, calls localized pre-trade risk controls the primary tools against inadvertent market activity caused by unauthorized access, system failures and errors. Its July 2024 paper lists pre-trade controls such as maximum order size, maximum intraday position, price tolerance, cancel-on-disconnect and kill switches. Two rules set the standard for regulated firms. For investment firms that trade algorithmically in the EU, Article 15 of Commission Delegated Regulation (EU) 2017/589, known as RTS 6, requires price collars, maximum order values and volumes and maximum message limits, and requires all orders sent to a trading venue to be included in the limit calculation immediately. In the US, SEC Rule 15c3-5, the Market Access Rule, requires broker-dealers with market access to have controls reasonably designed to prevent erroneous orders and orders that exceed pre-set credit and capital thresholds. A private bot is normally bound by neither rule, but both are useful benchmarks.

The broker’s own checks do not replace yours. They apply the broker’s rules; your position limit, your daily loss limit and your stop rule hold only if your own code enforces them. Daily loss rules for prop firm accounts in MQL5 are covered in prop firm EA rules in code.

Which risk gates a trading bot needs

GateBlocks whenMust countIf data is missing
Maximum order sizeQuantity above the limit for the instrumentNew and modified ordersNo limit configured: block
Price toleranceLimit price too far from a reference priceThe age of the reference priceStale or missing price: block
Maximum positionWorst-case position above the limitPosition plus working orders on the same sidePosition unknown: block
Daily loss limitLoss since the session start has reached the limitRealized and unrealized P&L, feesP&L stale: block new risk
Mandatory stopRisk-increasing order without a protective stopStop side and quantityStop missing: block
Order and execution rateToo many orders or repeated fills in a time windowAll orders of the strategyCounter lost: block
Reconciliation statePositions not confirmed by the brokerPositions and open ordersUnknown: block new risk
Kill switchSet by a person or a severe eventPersisted across restartsUnreadable: treat as set

Two definitions decide how the table works in code. A risk-increasing order moves the position away from zero or flips it; a risk-reducing order moves it toward zero without crossing it. And working orders are open entry orders: a buy limit that has not filled still counts toward the long limit, because the limit must hold if it fills. FIA puts it directly: when an order is submitted or modified, both current positions and working orders should be evaluated. The SEC’s order on Knight Capital shows the gap this closes: Knight had position limits for some trading groups, but they did not account for the firm’s exposure from outstanding orders.

FIA also recommends that systems prevent orders where no size limit has been set for an instrument, and that a strategy be disabled after a configurable number of repeated executions until an authorized person re-enables it. Both follow the same principle: when in doubt, block.

How to enforce a stop from the moment of entry

“Every position has a stop” is easy to state and easy to break: the entry fills, the bot crashes before it sends the stop, and the position sits unprotected. The robust version sends entry and stop as one unit, so the stop exists at the broker before the entry can fill.

With Interactive Brokers this is a bracket order: a parent entry with a take-profit and a stop-loss attached as children. IBKR’s documentation names the risk of sending the three orders separately, since one could fill before the whole bracket has arrived, and the remedy: set the transmit flag to false on the parent and the take-profit, so TWS holds them without transmitting, and to true on the last child, the stop-loss. TWS then transmits the parent and its siblings together with the stop.

The gate checks the stop before anything is sent: present, on the protective side (below the entry for a long, above it for a short), within a maximum distance and for the full quantity. One more case belongs in the order manager’s tests: an entry reported as filled while the stop is not confirmed as working. That state is an incident. The bot blocks new risk, raises an alert and follows the path the specification defines, either placing the stop again or closing the position.

Blocking new risk while reconciliation is open

After a disconnect, the bot’s picture of its positions is a guess, because orders may have filled or been canceled in the meantime. IBKR reports the connection state through system codes: 1100 means connectivity between IB and TWS has been lost; 1101 means it has been restored, but market data requests were lost and must be re-submitted; 1102 means it has been restored with data maintained. A gate that treats 1102 as “all good” can miss fills that happened during the outage, so each of the three codes sets the state to “reconciliation open”.

Reconciliation then compares the bot’s records with the broker’s. With IBKR’s API, reqPositions returns all positions and ends with positionEnd; reqAllOpenOrders returns the current open orders once and ends with openOrderEnd. Only after both ends have arrived and the data match does the gate return to normal. Until then it blocks every risk-increasing order. Risk-reducing orders may pass, but only measured against the positions the broker has just reported: if the bot believes it is long 100 while the broker reports 30 after a fill during the outage, a sell of 100 would open a short of 70.

A mismatch is not something to repair automatically. It trips the kill switch, which keeps blocking new risk until a person has looked at it. FIA describes kill switches that may allow risk-reducing orders while preventing risk-increasing ones; the example below does the same, using the broker’s numbers. A lost socket connection between the bot and TWS or IB Gateway needs the same treatment: after any reconnect, reconcile first and trade second.

A test matrix for pre-trade risk checks

#CaseSetupExpected result
1Size boundaryOrder at the limit, then one unit aboveFirst passes, second blocked
2Unknown instrumentNo limits configuredBlocked
3Working ordersPosition and open buys close to the limitA buy beyond the worst case is blocked
4Price toleranceLimit price outside the bandBlocked
5Stale priceReference price older than allowedBlocked
6Missing or wrong stopNo stop, or a stop on the wrong sideBlocked
7Daily loss reachedP&L exactly at the limitNew risk blocked, closing allowed, a flip blocked
8Error in a data sourceThe price source raises an exceptionBlocked, with the error as the reason
9DisconnectCodes 1100, then 1102Blocked until reconciled
10Mismatch after reconnectThe broker reports a different positionKill switch; only reductions based on the broker’s numbers
11RestartKill switch set, process restartedStill set
12Repeated executionsThe same order fills again and againStrategy disabled until a person re-enables it

Cases 1 to 10 run in milliseconds as unit tests. Cases 11 and 12 need the persistence and the execution counter of the real bot, and a real disconnect belongs in the paper account as well: stop IB Gateway or interrupt the network during a session, then check the log for the block and the reconciliation.

Fault injection and a disconnect simulation in Python

The example implements the gates that do not need a broker and tests them with Python’s unittest. Fault injection uses unittest.mock: according to the Python documentation, a mock whose side_effect is an exception class or instance raises it when called, so the price source can fail on demand. The disconnect simulation feeds IBKR’s codes 1100, 1101 and 1102 to the gate. All eight tests pass with Python 3.9 and 3.12; the code uses only the standard library, connects to nothing and sends no orders. Every order in the example is a limit order; an emergency flatten would follow its own, separately tested path.

"""Pre-trade risk gate with fault-injection tests. Python 3 standard library only.
The gate only decides: it connects to nothing and sends no orders."""
import unittest
from dataclasses import dataclass
from typing import Optional
from unittest import mock

LOST, RESTORED_DATA_LOST, RESTORED_DATA_KEPT = 1100, 1101, 1102  # IBKR system codes


@dataclass
class Order:
    symbol: str
    qty: int                      # signed: positive buys, negative sells
    limit: float
    stop: Optional[float] = None  # stop-loss sent together with the entry


class RiskGate:
    def __init__(self, limits, prices, max_age=5.0):
        self.limits, self.prices, self.max_age = limits, prices, max_age
        self.positions = {}       # symbol -> signed position, trusted once reconciled
        self.working = {}         # symbol -> (open buy qty, open sell qty) of entry orders
        self.broker = None        # positions the broker reported since the last reconnect
        self.reconciled = False
        self.kill_reason = None   # persist this in production; only a person clears it
        self.pnl_today = 0.0

    def check(self, o, now):
        try:
            return self._check(o, now)
        except Exception as exc:  # fail closed: an error is never an approval
            return False, f"check failed: {type(exc).__name__}"

    def _check(self, o, now):
        lim = self.limits.get(o.symbol)
        if lim is None:
            return False, "no limits configured"
        if abs(o.qty) > lim["max_qty"]:
            return False, "order size"
        price, stamp = self.prices(o.symbol)
        if now - stamp > self.max_age:
            return False, "stale price"
        if abs(o.limit - price) > lim["tolerance"] * price:
            return False, "limit price outside tolerance"
        known = self.positions if self.reconciled and not self.kill_reason else self.broker
        if known is None:
            return False, "position unknown: reconciliation open"
        pos = known.get(o.symbol, 0)
        if pos and (pos > 0) != (o.qty > 0) and abs(o.qty) <= abs(pos):
            return True, "reduces exposure"
        if self.kill_reason or not self.reconciled:
            return False, self.kill_reason or "reconciliation open"
        if self.pnl_today <= -lim["daily_loss"]:
            return False, "daily loss limit"
        buys, sells = self.working.get(o.symbol, (0, 0))
        worst = pos + buys + o.qty if o.qty > 0 else pos - sells + o.qty
        if abs(worst) > lim["max_pos"]:
            return False, "position limit incl. working orders"
        if o.stop is None or (o.stop < o.limit) != (o.qty > 0):
            return False, "no stop on the protective side"
        return True, "ok"

    def on_system_code(self, code):
        if code in (LOST, RESTORED_DATA_LOST, RESTORED_DATA_KEPT):
            self.reconciled, self.broker = False, None  # fills may have happened meanwhile

    def on_position(self, symbol, qty):
        """reqPositions keeps sending changes after positionEnd."""
        if self.broker is not None:
            self.broker[symbol] = qty

    def reconcile(self, broker_positions, broker_working):
        """Positions up to positionEnd, open orders up to openOrderEnd."""
        self.broker = {s: q for s, q in broker_positions.items() if q}
        local = {s: q for s, q in self.positions.items() if q}
        if self.broker == local and broker_working == self.working:
            self.reconciled = True
        else:
            self.kill_reason = "mismatch with broker after reconnect"
        return self.reconciled


class RiskGateTest(unittest.TestCase):
    LIMITS = {"XYZ": {"max_qty": 100, "max_pos": 200, "tolerance": 0.02, "daily_loss": 500.0}}
    NOW = 1000.0

    def gate(self, positions=None, working=None, prices=None):
        g = RiskGate(self.LIMITS, prices or mock.Mock(return_value=(50.0, self.NOW)))
        g.positions, g.working = dict(positions or {}), dict(working or {})
        g.reconcile(g.positions, g.working)        # broker agrees with the bot
        return g

    def reason(self, g, qty, stop=None, limit=50.0):
        return g.check(Order("XYZ", qty, limit, stop), self.NOW)[1]

    def test_size_boundary_and_unknown_symbol(self):
        g = self.gate()
        self.assertEqual(self.reason(g, 100, 49.0), "ok")
        self.assertEqual(self.reason(g, 101, 49.0), "order size")
        self.assertEqual(self.reason(g, 10, 49.0, limit=51.5), "limit price outside tolerance")
        self.assertEqual(g.check(Order("ABC", 1, 50.0, 49.0), self.NOW)[1], "no limits configured")

    def test_working_orders_count_toward_position_limit(self):
        g = self.gate({"XYZ": 150}, {"XYZ": (40, 0)})
        self.assertEqual(self.reason(g, 10, 49.0), "ok")            # 150 + 40 + 10 = 200
        self.assertEqual(self.reason(g, 11, 49.0), "position limit incl. working orders")

    def test_stop_required_on_protective_side(self):
        g = self.gate()
        self.assertEqual(self.reason(g, 10), "no stop on the protective side")
        self.assertEqual(self.reason(g, 10, 51.0), "no stop on the protective side")
        self.assertEqual(self.reason(g, -10, 51.0), "ok")

    def test_daily_loss_blocks_new_risk_but_not_reduction(self):
        g = self.gate({"XYZ": 50})
        g.pnl_today = -500.0
        self.assertEqual(self.reason(g, 10, 49.0), "daily loss limit")
        self.assertEqual(self.reason(g, -50), "reduces exposure")
        self.assertEqual(self.reason(g, -60, 51.0), "daily loss limit")  # would flip to short

    def test_fault_injection_fails_closed(self):
        g = self.gate(prices=mock.Mock(side_effect=TimeoutError))
        self.assertEqual(self.reason(g, 10, 49.0), "check failed: TimeoutError")
        g = self.gate(prices=mock.Mock(return_value=(50.0, self.NOW - 6)))
        self.assertEqual(self.reason(g, 10, 49.0), "stale price")

    def test_disconnect_blocks_until_reconciled(self):
        g = self.gate({"XYZ": 100})
        for code in (LOST, RESTORED_DATA_KEPT):
            g.on_system_code(code)
            self.assertEqual(self.reason(g, -10), "position unknown: reconciliation open")
        self.assertTrue(g.reconcile({"XYZ": 100}, {}))
        self.assertEqual(self.reason(g, 10, 49.0), "ok")

    def test_mismatch_trips_kill_switch_and_trusts_broker(self):
        g = self.gate({"XYZ": 100})
        g.on_system_code(RESTORED_DATA_LOST)
        self.assertFalse(g.reconcile({"XYZ": 30}, {}))              # e.g. a fill during the outage
        self.assertEqual(self.reason(g, -100), "mismatch with broker after reconnect")
        self.assertEqual(self.reason(g, -30), "reduces exposure")   # based on the broker's 30
        self.assertEqual(self.reason(g, 10, 49.0), "mismatch with broker after reconnect")

    def test_kill_switch_uses_latest_broker_position(self):
        g = self.gate({"XYZ": 100})
        g.kill_reason = "set by a person"
        g.on_position("XYZ", 0)                     # e.g. the stop filled meanwhile
        self.assertEqual(self.reason(g, -100), "set by a person")   # would open a short
        g.on_position("XYZ", 40)
        self.assertEqual(self.reason(g, -40), "reduces exposure")


if __name__ == "__main__":
    unittest.main()

Run it with python3 risk_gate.py -v. Two details matter more than the rest. The check method catches every exception and turns it into a rejection, so an exception inside a check can never become an approval; a wrong comparison still can, which is what the tests are for. And after a reconnect or with the kill switch set, the decision whether an order reduces exposure uses self.broker, the positions the broker reports, not the bot’s memory; on_position keeps it current, because reqPositions keeps sending updates after positionEnd. In production, the kill switch and its reason are written to disk before the gate returns, and the daily P&L comes from a source with its own staleness check. The example also leaves out the stop’s distance and quantity, and exit orders that are already working: a real gate measures a reduction against the position minus the exits working on the same side, such as the stop of a bracket, or a manual close and that stop could both fill and open a new position.

Limits and risks of pre-trade checks

  • Checks limit damage; they do not create profits. A bot with flawless gates can still trade a losing strategy. With leveraged products, losses can exceed the capital deployed.
  • A stop is not a price guarantee. In a gap or a fast market, a stop can fill far beyond its price.
  • Limits are only as good as their values. A wrong number in the configuration is enforced as faithfully as a right one, so limit changes need a review like code changes.
  • Unit tests use a model of the broker. Real behavior, such as partial fills or order states during an outage, has to be checked in the paper account and again with small size live.
  • Blocking has a cost. A gate that fails closed can keep a bot out of the market. That is intended, but the alerts must reach a person who can act.
  • The check itself can be wrong. Keep it simple, test it like the strategy and log every decision with its reason.

Next steps: put your risk gates under test

  1. Write every gate and its limit into one configuration, with units, and make missing values block.
  2. Route every order through one check function, and search the code for any other path to the broker adapter.
  3. Write one test per row of the matrix, starting with working orders, fail-closed behavior and the reconciliation block.
  4. Persist the kill switch and the daily loss baseline; restart the bot in a test and check that both survive.
  5. Run the disconnect drill in the paper account and keep the log as evidence.
  6. Have the gates reviewed by someone who did not write them; a fresh reader is more likely to find the path that skips them.

The pre-live checklist for AI-built trading bots adds the wider picture, from secrets to the exit criteria of the paper phase.

Frequently asked questions

What are pre-trade risk checks in a trading bot?

They are rules every new or modified order must pass before it is sent: a maximum order size, a price tolerance against a reference price, a maximum position including working orders, a daily loss limit, a mandatory stop for risk-increasing orders, rate limits, a reconciliation check after reconnects and a kill switch. They sit in one place between the strategy and the broker connection, and the strategy cannot skip them.

Should a position limit include open orders?

Yes. A limit that counts only filled positions can be exceeded by several working orders that fill together. FIA’s 2024 best practices say both current positions and working orders should be evaluated when an order is submitted or modified. Count every working order on the same side as if it were already filled.

How do you test a daily loss limit in a trading bot?

Set the loss in a test to exactly the limit and check three cases: a new risk-increasing order is blocked, an order that reduces the position is allowed, and an order that would flip the position is blocked. Add a test in which the P&L source is stale or raises an error; the gate must block. Then repeat the drill in a paper account with a deliberately low limit.

Does the broker enforce my own risk limits?

No. A broker checks orders against its own rules. In the US, broker-dealers with market access must have pre-trade controls under SEC Rule 15c3-5, designed to stop erroneous orders and orders above pre-set credit and capital thresholds. Those controls protect the broker and the market; they know nothing about your strategy’s limits. Your maximum position, daily loss limit and mandatory stop hold only if your bot checks them before every order.

What is fault injection in trading bot testing?

Fault injection means provoking failures on purpose to see how the bot reacts: a price feed that raises an error, stale data, a rejected order, a lost connection. In Python, unittest.mock can make any dependency raise a chosen exception when it is called. For a risk gate the expected result is always the same: block, log the reason and alert, never approve by default.

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: Risiko-Gates testen: greifen Stop, Limits und Sperren wirklich?.

Want the risk checks of your trading bot reviewed and tested before go-live? Get in touch — a free intro call clarifies the gates, the test scope and what the review should deliver. More: Trading system code review and audit.