Skip to content
LeetQuant
QD08 Trading Systems Architecture

QD08 · Trading Systems Architecture · Lesson 5 of 5

Order Management and Risk Checks

The order state machine and its races, acks, fills and cancels, pre-trade risk checks (size, worst-case position, price collars, rate limits) and kill switches.

17 min

Objective

Model an order's life correctly, including the races between your messages and the exchange's, and design the checks that stop a bug or a bad input from sending orders the firm cannot afford. Interviewers use this topic to see whether you think about failure as carefully as about speed.

The order state machine

The states below follow the FIX protocol's order status values, which most venues and brokers map to:

StateMeaningLeaves by
Pending newsent, not yet acknowledgedack → New; reject → Rejected
Newlive at the exchange, nothing filledfill → Partially filled or Filled; cancel request → Pending cancel
Partially filledlive, some quantity filledmore fills; cancel request
Pending cancelcancel sent, not yet confirmedcancel ack → Cancelled; fill → Filled
Filled, Cancelled, Rejectedterminalnothing

(A cancel/replace adds a symmetric Pending replace state.) The key facts:

  • Fills race cancels. Between sending a cancel and the exchange receiving it, the order can fill. So Pending cancel must accept fills, and a cancel can be rejected with "too late to cancel". Position must be updated from fills whatever state the order is in.
  • Messages can arrive out of the expected order (a fill before the ack on some venues), and the exchange can cancel unilaterally (end of day, a price band, cancel-on-disconnect). Robust code applies the fill quantity first and reconciles state second.
  • Each order has a unique client order id that you generate, so retries are idempotent and every response maps back to one order.
  • Reconcile your view against the exchange's (a drop copy feed of executions) and alert on any difference.

Pre-trade risk checks

Every order passes these before it leaves the process. In the US, SEC Rule 15c3-5 (the Market Access Rule) requires broker-dealers with market access to have such controls; every serious firm has them regardless.

CheckCatchesHow
Max order size / notionalfat fingers, unit bugs (shares versus lots)compare quantity and quantity × price with limits
Price collara price far from the market (bad reference, sign error)reject if more than xx% from a reference (last trade, mid)
Position limitrunaway accumulationworst case: current position plus every open order on that side, plus this one
Rate limita loop sending orders foreverat most kk orders per sliding window
Duplicate detectionretry bugsthe same order repeated within a short window
Loss limita strategy losing more than expectedrealised plus unrealised PnL against a threshold

The position check must assume open orders fill. Checking only the current position lets a strategy rest 10 orders that are each acceptable alone but together breach the limit.

Kill switches

A kill switch stops a strategy (or the firm) immediately: block all new orders, cancel every open order, and alert a human. Triggers are automatic (a loss limit, a rate-limit storm, a position breach, lost connection to the risk server) or manual (a big red button). Exchanges add cancel-on-disconnect, which pulls your resting orders if your session drops. Flattening the resulting position is usually a separate, human-supervised decision, because sending more orders from a malfunctioning system can make things worse. The standard cautionary tale is Knight Capital in 2012, which lost about $440 million in under an hour after a faulty deployment sent unintended orders.

An order manager with risk checks

Limits: max order 1,000 shares, worst-case position ±2,000, a 5% price collar around a reference of 100.00 (prices in cents), and at most 3 orders per 1,000 ms.

from collections import deque
from dataclasses import dataclass

# Allowed transitions of the order state machine.
NEXT = {
    "PENDING_NEW": {"NEW", "REJECTED"},
    "NEW": {"PARTIALLY_FILLED", "FILLED", "PENDING_CANCEL"},
    "PARTIALLY_FILLED": {"PARTIALLY_FILLED", "FILLED", "PENDING_CANCEL"},
    "PENDING_CANCEL": {"PENDING_CANCEL", "CANCELLED", "FILLED"},  # fills can race the cancel
}


@dataclass
class Order:
    id: str
    side: int  # +1 buy, -1 sell
    qty: int
    px: int  # price in cents
    filled: int = 0
    state: str = "PENDING_NEW"

    @property
    def open_qty(self) -> int:
        return 0 if self.state in ("FILLED", "CANCELLED", "REJECTED") else self.qty - self.filled

    def move(self, new: str) -> None:
        if new not in NEXT.get(self.state, set()):
            raise ValueError(f"{self.id}: illegal {self.state} -> {new}")
        self.state = new


class Oms:
    MAX_QTY, MAX_POS, COLLAR, RATE, WINDOW_MS = 1000, 2000, 0.05, 3, 1000

    def __init__(self, ref_px: int) -> None:
        self.ref_px, self.position, self.killed = ref_px, 0, False
        self.orders: dict[str, Order] = {}
        self.sent: deque[int] = deque()  # send times inside the rate window

    def check(self, o: Order, now: int) -> str | None:
        if self.killed:
            return "kill switch active"
        if o.qty > self.MAX_QTY:
            return f"qty {o.qty} > max {self.MAX_QTY}"
        if abs(o.px - self.ref_px) > self.COLLAR * self.ref_px:
            return f"price {o.px} outside collar {self.ref_px} +/- 5%"
        # Worst case: every open order on this side fills, plus this one.
        same_side = sum(x.open_qty for x in self.orders.values() if x.side == o.side)
        worst = self.position + o.side * (same_side + o.qty)
        if abs(worst) > self.MAX_POS:
            return f"worst-case position {worst} breaches +/-{self.MAX_POS}"
        while self.sent and self.sent[0] <= now - self.WINDOW_MS:
            self.sent.popleft()
        if len(self.sent) >= self.RATE:
            return f"rate limit {self.RATE}/{self.WINDOW_MS}ms"
        return None

    def submit(self, o: Order, now: int) -> None:
        reason = self.check(o, now)
        self.orders[o.id] = o
        if reason:
            o.move("REJECTED")
            print(f"t={now:4} {o.id} REJECTED: {reason}")
        else:
            self.sent.append(now)
            print(f"t={now:4} {o.id} sent {'BUY' if o.side > 0 else 'SELL'} {o.qty} @ {o.px}")

    def on_ack(self, oid: str) -> None:
        self.orders[oid].move("NEW")

    def on_fill(self, oid: str, qty: int) -> None:
        o = self.orders[oid]
        o.filled += qty
        self.position += o.side * qty
        if o.filled == o.qty:
            o.move("FILLED")
        elif o.state != "PENDING_CANCEL":
            o.move("PARTIALLY_FILLED")
        print(f"       fill {oid} {qty}: {o.state}, position {self.position}")

    def kill(self, now: int) -> None:
        self.killed = True
        for o in self.orders.values():
            if o.open_qty and o.state != "PENDING_CANCEL":
                o.move("PENDING_CANCEL")
                print(f"t={now:4} KILL: cancel sent for {o.id} (open {o.open_qty})")


oms = Oms(ref_px=10000)
oms.submit(Order("o1", +1, 800, 10010), now=0)
oms.submit(Order("o2", +1, 1500, 10000), now=100)
oms.submit(Order("o3", +1, 900, 10600), now=200)
oms.submit(Order("o4", +1, 900, 10020), now=300)
oms.on_ack("o1")
oms.on_fill("o1", 800)
oms.on_ack("o4")
oms.submit(Order("o5", +1, 400, 10000), now=400)
oms.submit(Order("o6", -1, 300, 9990), now=500)
oms.submit(Order("o7", -1, 100, 9995), now=600)
oms.on_ack("o6")
oms.kill(now=700)
oms.on_fill("o4", 200)  # this fill was already in flight when the cancel went out
oms.orders["o4"].move("CANCELLED")
oms.orders["o6"].move("CANCELLED")
oms.submit(Order("o8", -1, 100, 10000), now=1500)
print({o.id: o.state for o in oms.orders.values()}, "position", oms.position)
try:
    oms.on_fill("o6", 50)
except ValueError as e:
    print("error:", e)

Output:

t=   0 o1 sent BUY 800 @ 10010
t= 100 o2 REJECTED: qty 1500 > max 1000
t= 200 o3 REJECTED: price 10600 outside collar 10000 +/- 5%
t= 300 o4 sent BUY 900 @ 10020
       fill o1 800: FILLED, position 800
t= 400 o5 REJECTED: worst-case position 2100 breaches +/-2000
t= 500 o6 sent SELL 300 @ 9990
t= 600 o7 REJECTED: rate limit 3/1000ms
t= 700 KILL: cancel sent for o4 (open 900)
t= 700 KILL: cancel sent for o6 (open 300)
       fill o4 200: PENDING_CANCEL, position 1000
t=1500 o8 REJECTED: kill switch active
{'o1': 'FILLED', 'o2': 'REJECTED', 'o3': 'REJECTED', 'o4': 'CANCELLED', 'o5': 'REJECTED', 'o6': 'CANCELLED', 'o7': 'REJECTED', 'o8': 'REJECTED'} position 1000
error: o6: illegal CANCELLED -> PARTIALLY_FILLED

Worked example

why each order was accepted or rejected

Walk through the run above: which check fired for each rejection, and how did o4 end up cancelled with 200 filled?

Show solution
  • o1 buy 800 at 100.10: within size, collar (∣10010−10000∣=10≤500|10010 - 10000| = 10 \le 500), worst case 800, first in the window. Sent.
  • o2 buy 1,500: size check, 1,500>1,0001{,}500 > 1{,}000.
  • o3 buy at 106.00: collar, ∣10600−10000∣=600>500|10600 - 10000| = 600 > 500 (5% of 10,000 cents).
  • o4 buy 900: worst case 0+800+900=1,7000 + 800 + 900 = 1{,}700, since o1 was still open. Sent. Then o1 fills: position 800, o1 filled.
  • o5 buy 400: worst case 800+900+400=2,100>2,000800 + 900 + 400 = 2{,}100 > 2{,}000 (current position, open o4, and o5). Rejected.
  • o6 sell 300: worst-case short side 800−300=500800 - 300 = 500. Rate window holds sends at 0, 300 and 500 ms: this is the third. Sent.
  • o7 at 600 ms: three sends already in the last 1,000 ms. Rate limit. (Rejected orders do not count, because they never reached the exchange.)
  • Kill at 700 ms: cancels go out for o4 (900 open) and o6 (300 open). Before the exchange processes o4's cancel, 200 of it fills: the order is in Pending cancel, accepts the fill, and position becomes 1,000. The cancel acks then close both orders, and o8 is blocked by the kill switch.

The last line shows the state machine guarding against a logic error: a fill for an order already Cancelled is illegal and raises, rather than silently corrupting the position. In production that error would trigger reconciliation with the exchange.

Worked example

worst case versus net open orders

Position +500, open buys 1,200, open sells 800, limit ±2,000. A new buy for 400 arrives. A colleague's check nets open orders: 500+(1,200−800)+400500 + (1{,}200 - 800) + 400. Compare with the worst-case check and say which is right.

Show solution

Netted: 500+400+400=1,300500 + 400 + 400 = 1{,}300, which passes.

Worst case on the long side: 500+1,200+400=2,100500 + 1{,}200 + 400 = 2{,}100, which breaches 2,000.

The worst case is right. Nothing forces the sells to fill: they can be cancelled, or the market can rally, filling every buy and none of the sells. A risk check must hold in the scenario where every order on the dangerous side fills and every order on the other side does not. Netting is only valid for orders that have already filled.

Knowledge check

You sent a cancel for an order and its state is Pending cancel. A fill for 200 arrives. What should the order manager do?

Knowledge check

Position +300, open buys 900, open sells 1,500, worst-case position limit ±2,000. Is a new sell for 900 accepted?

Knowledge check

What should an automated kill switch do first when a strategy breaches its loss limit?

Key takeaways

  • Model orders as a state machine with explicit legal transitions; Pending cancel must accept fills, and position is driven by fills, not states.
  • Use unique client order ids and reconcile against the exchange's drop copy.
  • Pre-trade checks: size and notional, price collar, worst-case position (current plus all open orders on the side, plus the new one), rate limits, duplicates, loss limits.
  • Never net open orders on opposite sides in a position check.
  • A kill switch blocks new orders and cancels open ones; flattening is a separate, supervised step.

Finished reading?

Answer the 3 knowledge checks to complete this lesson (0 done).