Event-Driven Strategy Execution Framework for Quantitative Teams

Medium · Software Engineering Fundamentals · Software Engineer · Technical Screen

Prompt

You are given an open-ended engineering assignment: architect and prototype an event-driven trading platform that quantitative researchers and engineers will inherit, maintain, and expand over time. Researchers author individual trading algorithms, while the core engine feeds incoming events (such as market ticks, order status transitions, and scheduled callbacks) into those algorithms and routes any resulting trade instructions toward downstream brokers or simulators.

Present both the system design and concrete code sketches for the core abstractions. Walk through the end-to-end lifecycle of a market event—from feed ingestion through callback dispatch, risk validation, and order submission—and show how future contributors can plug in additional trading logic, market-data connectors, and execution adapters without modifying core engine internals.

Because the prompt leaves operational parameters unspecified (instrument types, programming language, throughput/latency budgets, concurrency scale, and whether historical simulation, paper trading, and production routing share one codebase), state your clarifying assumptions explicitly up front. Treat long-term code health—clean boundaries, automated verification, and onboarding documentation—as first-class requirements.

Scope & Expectations

  • Explicit operating assumptions: Pin down supported execution environments (historical replay, simulated live paper mode, and production), event schemas, multi-strategy isolation rules, and target latency vs. researcher usability trade-offs.
  • Deterministic event loop and clean plug-in contracts: Sketch minimal interfaces separating strategy callbacks, restricted runtime context, market-data readers, and venue routers around a unified clock and ordering model.
  • Order lifecycle and pre-trade safety gates: Trace state transitions from order creation through acknowledgement, partial/full fills, cancellations, and rejections, showing how automated limits guard against runaway strategy bugs.
  • Maintainable handoff structure: Outline module organization, unit/contract/regression testing layers, and concise contributor documentation so teammates can extend the codebase safely.

Step-by-step walkthrough

  1. Clarify the brief and state explicit assumptions

    When an engineering assignment asks for an extensible event-driven trading platform without pinning down asset classes or latency budgets, start by stating explicit assumptions in README.md and defining core domain terms so every contributor shares the same mental model:

    • Execution modes: The exact same strategy code must run unmodified in three modes:
      1. Backtest — replaying recorded historical data as fast as the CPU allows to test an idea.
      2. Paper trading — listening to a live market feed while simulating fills in software so no real money is risked.
      3. Live trading — listening to a live feed and routing real orders to a broker or exchange.
    • Events supported:
      • Quotes — updates showing the best bid (highest price a buyer is offering) and best ask (lowest price a seller is asking), plus available share sizes.
      • Trades — actual transactions printed on the market (price and size).
      • Order updates — lifecycle messages from a venue (ACKED, PARTIALLY_FILLED, FILLED, CANCELLED, REJECTED), where a fill means shares actually traded.
      • Timers — scheduled wake-ups (for example, "check risk or rebalance every 60 seconds").
    • Scale and latency target: Tens of strategies in one Python process reacting in milliseconds, where researcher productivity, safety, and clean interfaces matter more than microsecond speed.
    • Explicit non-goals for v1: Multi-machine distributed execution, portfolio-level convex optimization, and smart order routing across competing exchanges. Stating what v1 leaves out keeps a take-home focused and maintainable.
  2. Key idea: one event queue, one clock, and integer prices

    Suppose market data arrives on Thread A while broker fill notifications arrive on Thread B, and both invoke strategy methods directly. In live trading, operating-system scheduling makes Thread A and Thread B interleave differently every day, so bugs cannot be reproduced. Worse, in a backtest a strategy that calls time.time() reads today's wall-clock time instead of the historical date being replayed!

    We eliminate all of those bugs with three rules:

    1. Everything is an immutable event carrying an integer nanosecond timestamp ts.
    2. One priority queue (EventQueue) merges every event using a min-heap (a binary tree structure in heapq that always pops the smallest item in O(log N) time) ordered by (ts, arrival_number). Including arrival_number breaks timestamp ties in exact first-in, first-out order without ever comparing two event objects directly.
    3. One single-threaded loop pops events and advances a logical clock. While handling an event, "current time" (ctx.now()) is simply event.ts. Strategies never call time.time().

    We also represent all prices as integer cents (or integer minimum price ticks) rather than float. In binary floating-point arithmetic, 0.10 + 0.20 evaluates to 0.30000000000000004, which silently breaks quote.ask <= limit_price comparisons and causes cumulative profit-and-loss drift.

    import heapq
    from dataclasses import dataclass
    from typing import Optional
    
    
    @dataclass(frozen=True)
    class Quote:
        ts: int          # nanoseconds: recorded historical time in backtest, receive time in live
        symbol: str
        bid: int         # integer cents (e.g., $190.00 is 19000) to avoid float rounding bugs
        ask: int
        bid_size: int
        ask_size: int
    
    
    @dataclass(frozen=True)
    class Trade:
        ts: int
        symbol: str
        price: int       # integer cents
        size: int
    
    
    @dataclass(frozen=True)
    class OrderUpdate:
        ts: int
        order_id: int
        status: str      # "ACKED", "REJECTED", "PARTIALLY_FILLED", "FILLED", "CANCELLED"
        filled_qty: int = 0                # incremental shares filled on THIS event (not cumulative)
        fill_price: Optional[int] = None   # integer cents
        reason: str = ""
    
    
    @dataclass(frozen=True)
    class Timer:
        ts: int
        name: str
    
    
    class EventQueue:
        """Single timeline merging market data, order updates, and timers in (ts, arrival) order."""
    
        def __init__(self) -> None:
            # _heap entries are (timestamp_ns, arrival_seq, event_obj)
            self._heap = []
            self._arrivals = 0
    
        def push(self, event) -> None:
            # arrival_seq breaks ties deterministically so heapq never compares event dataclasses
            heapq.heappush(self._heap, (event.ts, self._arrivals, event))
            self._arrivals += 1
    
        def pop(self):
            ts, arrival_seq, event = heapq.heappop(self._heap)
            return event
    
        def __len__(self) -> int:
            return len(self._heap)
    

    Mini-trace of tie-breaking: if we push Quote(ts=5), then Trade(ts=3), then OrderUpdate(ts=5), pop() yields Trade(ts=3) first, then Quote(ts=5, arrival=0), and finally OrderUpdate(ts=5, arrival=2).

  3. Core interfaces: four small extension points

    To keep the framework easy to extend after handover, identify what teammates will add most often and isolate each behind a tiny adapter interface (a thin wrapper that translates an external feed or broker into the framework's standard calls):

    • Strategy (added weekly by researchers): overrides only the on_* callbacks it cares about; unused callbacks default to no-ops.
    • Context (the narrow capability object passed into every Strategy callback): lets a strategy read now(), inspect its position(symbol), submit or cancel a limit order (an order to buy at or below, or sell at or above, limit_price), and schedule a timer. Because a strategy only sees Context, it can never touch a network socket, read the wall clock, or bypass risk checks.
    • DataSource (added per market-data vendor or file format): reads CSV/Parquet files or a live WebSocket feed and pushes Quote / Trade objects into push(event).
    • ExecutionVenue (added per broker or simulator): accepts send(...) and cancel(...) calls and asynchronously pushes OrderUpdate events back through push(event).
    from abc import ABC, abstractmethod
    
    
    class Context(ABC):
        """Narrow sandbox exposed to strategies: no direct access to venues, sockets, or wall clock."""
    
        @abstractmethod
        def now(self) -> int: ...
    
        @abstractmethod
        def position(self, symbol: str) -> int: ...
    
        @abstractmethod
        def submit_order(self, symbol: str, side: str, qty: int, limit_price: int) -> int: ...
    
        @abstractmethod
        def cancel_order(self, order_id: int) -> None: ...
    
        @abstractmethod
        def schedule_timer(self, delay_ns: int, name: str) -> None: ...
    
    
    class Strategy(ABC):
        """Base class for user strategies; subclasses override only the events they need."""
    
        def on_start(self, ctx: Context) -> None:
            pass
    
        def on_quote(self, ctx: Context, quote: Quote) -> None:
            pass
    
        def on_trade(self, ctx: Context, trade: Trade) -> None:
            pass
    
        def on_order_update(self, ctx: Context, update: OrderUpdate) -> None:
            pass
    
        def on_timer(self, ctx: Context, timer: Timer) -> None:
            pass
    
    
    class DataSource(ABC):
        """Adapter for historical files, live feeds, or synthetic test streams."""
    
        @abstractmethod
        def start(self, symbols, push, clock) -> None:
            """Emit Quote and Trade events for `symbols` by calling `push(event)`."""
    
    
    class ExecutionVenue(ABC):
        """Adapter for a backtest simulator, paper-trading matcher, or live broker."""
    
        @abstractmethod
        def start(self, push, clock) -> None:
            """Deliver OrderUpdate events back into the engine via `push(event)`."""
    
        @abstractmethod
        def send(self, order_id: int, symbol: str, side: str, qty: int, limit_price: int) -> None: ...
    
        @abstractmethod
        def cancel(self, order_id: int) -> None: ...
    
        def on_market(self, quote: Quote) -> None:
            """Hook used only by simulated venues to check whether resting orders should fill."""
    

    Writing a new strategy now takes under twenty lines and zero plumbing:

    class BuyTheDip(Strategy):
        """Buy 100 shares when the ask drops to or below `threshold` while flat with no open order."""
    
        def __init__(self, symbol: str, threshold_cents: int) -> None:
            self.symbol = symbol
            self.threshold_cents = threshold_cents
            self.working_order = None
    
        def on_quote(self, ctx: Context, quote: Quote) -> None:
            if quote.symbol != self.symbol or self.working_order is not None:
                return
            if ctx.position(self.symbol) == 0 and quote.ask <= self.threshold_cents:
                self.working_order = ctx.submit_order(self.symbol, "BUY", 100, quote.ask)
    
        def on_order_update(self, ctx: Context, update: OrderUpdate) -> None:
            if update.status in ("FILLED", "REJECTED", "CANCELLED"):
                self.working_order = None
    
  4. Trace one event from market arrival to order execution

    Here is the complete path of an event through the engine:

                  push(Quote / Trade)                   pop earliest (ts, arrival)
     DataSource ----------------------> EventQueue --------------------------------> Engine._dispatch
                                            ^                                          |
                                            | push(OrderUpdate)                        | 1. update mid / fills / position
                                            |                                          | 2. invoke strategy callback
                                      ExecutionVenue                                   v
                                            ^                                    Strategy.on_quote(ctx, quote)
                                            | venue.send(...) if risk passes           |
                                            |                                          | ctx.submit_order(...)
                                       Risk checks <---------------------------- Record Order (status="SENT")
                                            |
                                            +--> if risk fails: push OrderUpdate(status="REJECTED") to EventQueue
    

    Pay close attention to two ordering invariants inside Engine._dispatch:

    1. Simulated venue sees a quote before the strategy does (self.venue.on_market(event) runs before self.strategy.on_quote(self, event)). That way, an existing resting order can fill on the incoming quote, whereas a brand-new order submitted by on_quote cannot magically fill on the very quote that triggered it.
    2. Positions update before on_order_update runs (self._apply_update(event) runs before self.strategy.on_order_update(self, event)), so ctx.position(symbol) inside on_order_update always reflects the fill that just happened.
    from collections import deque
    
    
    @dataclass
    class Order:
        order_id: int
        symbol: str
        side: str
        qty: int
        limit_price: int
        filled: int = 0
        status: str = "SENT"   # SENT -> ACKED -> PARTIALLY_FILLED -> FILLED (or CANCELLED / REJECTED)
    
    
    class Engine(Context):
        """Single-threaded event loop implementing Context and enforcing pre-trade risk checks."""
    
        def __init__(self, strategy: Strategy, source: DataSource, venue: ExecutionVenue, limits) -> None:
            self.strategy = strategy
            self.source = source
            self.venue = venue
            self.limits = limits
            self.queue = EventQueue()
            self.clock = 0
            self.positions = {}          # symbol -> signed integer shares (+long, -short)
            self.orders = {}             # order_id -> Order state record
            self.last_mid = {}           # symbol -> latest midpoint price in integer cents
            self.sent_times = deque()    # timestamps (ns) of orders sent within the trailing 1 second
            self.next_order_id = 1
    
        def run(self, symbols) -> None:
            self.source.start(symbols, self.queue.push, self.now)
            self.venue.start(self.queue.push, self.now)
            self.strategy.on_start(self)
            while len(self.queue) > 0:
                event = self.queue.pop()
                self.clock = event.ts
                self._dispatch(event)
    
        def _dispatch(self, event) -> None:
            if isinstance(event, Quote):
                self.last_mid[event.symbol] = (event.bid + event.ask) // 2
                self.venue.on_market(event)          # let resting simulated orders match first
                self.strategy.on_quote(self, event)
            elif isinstance(event, Trade):
                self.strategy.on_trade(self, event)  # forward market trade prints to the strategy
            elif isinstance(event, OrderUpdate):
                self._apply_update(event)            # update order & position state before callback
                self.strategy.on_order_update(self, event)
            elif isinstance(event, Timer):
                self.strategy.on_timer(self, event)
    
        def _apply_update(self, update: OrderUpdate) -> None:
            order = self.orders[update.order_id]
            order.status = update.status
            if update.status in ("PARTIALLY_FILLED", "FILLED"):
                order.filled += update.filled_qty
                sign = 1 if order.side == "BUY" else -1
                self.positions[order.symbol] = self.position(order.symbol) + sign * update.filled_qty
    
        def now(self) -> int:
            return self.clock
    
        def position(self, symbol: str) -> int:
            return self.positions.get(symbol, 0)
    
        def submit_order(self, symbol: str, side: str, qty: int, limit_price: int) -> int:
            order = Order(self.next_order_id, symbol, side, qty, limit_price)
            self.next_order_id += 1
            self.orders[order.order_id] = order
            reason = self._risk_reason(order)
            if reason:
                order.status = "REJECTED"
                # Emit rejection asynchronously on the event queue just like a broker reject
                self.queue.push(OrderUpdate(self.clock, order.order_id, "REJECTED", reason=reason))
            else:
                self.sent_times.append(self.clock)
                self.venue.send(order.order_id, symbol, side, qty, limit_price)
            return order.order_id
    
        def cancel_order(self, order_id: int) -> None:
            order = self.orders.get(order_id)
            # Only forward cancels for orders that are still live
            if order is not None and order.status in ("SENT", "ACKED", "PARTIALLY_FILLED"):
                self.venue.cancel(order_id)
    
        def schedule_timer(self, delay_ns: int, name: str) -> None:
            self.queue.push(Timer(self.clock + delay_ns, name))
    
        def _risk_reason(self, order: Order) -> str:
            if order.symbol not in self.last_mid:
                return "no market data"
            open_buy, open_sell = 0, 0
            for other in self.orders.values():
                if other is not order and other.symbol == order.symbol and (
                    other.status in ("SENT", "ACKED", "PARTIALLY_FILLED")
                ):
                    remaining = other.qty - other.filled
                    if other.side == "BUY":
                        open_buy += remaining
                    else:
                        open_sell += remaining
            # Evict timestamps older than 1 second (1_000_000_000 ns) from the rate-limit window
            while self.sent_times and self.clock - self.sent_times[0] >= 1_000_000_000:
                self.sent_times.popleft()
            return check_order(
                self.limits, order.side, order.qty, order.limit_price,
                self.position(order.symbol), open_buy, open_sell,
                self.last_mid[order.symbol], len(self.sent_times),
            )
    

    To scale this sketch from one strategy to twenty strategies in one process, the engine maps each order_id to its owning strategy, keeps positions and RiskLimits per strategy (plus a firm-wide aggregate limit), and fans each Quote or Trade out to the strategies subscribed to event.symbol.

    Worked numeric trace with BuyTheDip("AAPL", 19000) ($190.00) and a simulated 2 ms one-way venue latency:

    t (ms)  Popped event                  Engine & strategy actions
    ------  ----------------------------  ---------------------------------------------------------------
     0      Quote 19010 / 19014           ask 19014 > 19000 -> strategy does nothing
    10      Quote 18998 / 19000           ask 19000 <= 19000 and position == 0 -> submit BUY 100 @ 19000;
                                          risk passes; order reaches simulated venue at 10 + 2 = 12 ms
    11      Quote 19000 / 19004           order not at venue yet (arrival 12 > 11), and ask 19004 > 19000
    12      OrderUpdate(ACKED)            order #1 status SENT -> ACKED
    40      Quote 18994 / 18998           venue.on_market sees ask 18998 < 19000 -> pushes FILLED @ 19000
    40      OrderUpdate(FILLED, 100)      position 0 -> +100, then strategy clears working_order = None
    
  5. Pre-trade risk checks between the strategy and the venue

    A buggy loop or unit mistake inside one strategy must never bankrupt the account. Because strategies can only trade via ctx.submit_order(...), every order automatically passes through synchronous pre-trade risk checks before reaching venue.send(...):

    • Single-order quantity and notional caps: Notional value is qty × limit_price (total dollar value committed by the order).
    • Worst-case position limit including open orders: If the position limit is 500 shares and a strategy already holds 400 shares with an unfilled 100-share buy order working, another 100-share buy could take the position to 600 if both fill. Counting only filled shares is a classic bug that lets fast loops fire ten orders before the first acknowledgement returns.
    • Price collar in basis points (bps): A basis point is 0.01% (1 / 10,000). A price collar rejects any limit price too far from last_mid, catching cents-vs-dollars typos immediately. Notice how cross-multiplying by 10,000 (abs(limit_price - last_mid) * 10_000 > max_bps * last_mid) keeps the check in exact integer arithmetic!
    • Per-second order rate limit and a kill switch (an emergency flag that cancels all open orders and blocks new submissions on excessive loss or operator command).
    @dataclass
    class RiskLimits:
        max_order_qty: int = 500
        max_position: int = 500                # max abs shares per symbol, counting working orders
        max_notional_cents: int = 5_000_000    # $50,000.00 max value per single order
        max_price_move_bps: int = 100          # 100 bps = 1.00% collar around latest mid-price
        max_orders_per_second: int = 10
    
    
    def check_order(
        limits: RiskLimits, side: str, qty: int, limit_price: int,
        position: int, open_buy_qty: int, open_sell_qty: int,
        last_mid: int, orders_last_second: int,
    ) -> str:
        """Return '' when the order is safe to send, or a short rejection reason."""
        if side not in ("BUY", "SELL"):
            return "invalid side"
        if qty <= 0 or qty > limits.max_order_qty:
            return "order size"
        if limit_price <= 0:
            return "invalid price"
        # Worst-case position if every open order on the same side also fills
        if side == "BUY":
            worst_position = position + open_buy_qty + qty
        else:
            worst_position = position - open_sell_qty - qty
        if abs(worst_position) > limits.max_position:
            return "position limit"
        if qty * limit_price > limits.max_notional_cents:
            return "notional limit"
        # Integer basis-point check: |limit - mid| / mid > max_bps / 10_000
        if abs(limit_price - last_mid) * 10_000 > limits.max_price_move_bps * last_mid:
            return "price collar"
        if orders_last_second >= limits.max_orders_per_second:
            return "order rate"
        return ""
    

    Worked risk examples with default limits and last_mid = 19000 ($190.00):

    Candidate order        pos   open_buy  Arithmetic                                     Outcome
    ---------------------  ----  --------  ---------------------------------------------  ----------------
    BUY 100 @ 19000 ($190) 400   100       worst_pos = 400 + 100 + 100 = 600 > 500        REJECT: position limit
    BUY 100 @ 19000 ($190) 300   100       worst_pos = 300 + 100 + 100 = 500 <= 500       PASS
    BUY 100 @ 19300 ($193) 0     0         |19300 - 19000| / 19000 = 158 bps > 100 bps    REJECT: price collar
    BUY 300 @ 19000 ($190) 0     0         notional = 300 * $190 = $57,000 > $50,000      REJECT: notional limit
    
  6. Running identical strategy code across backtest, paper, and live

    Switching modes requires swapping only the DataSource, the ExecutionVenue, and how the outer loop waits for events — zero lines of Strategy or risk code change:

    Mode       DataSource                  ExecutionVenue                  Event timestamps
    ---------  --------------------------  ------------------------------  ---------------------------------
    Backtest   Historical file replay      SimulatedVenue (latency+fills)  Recorded timestamps from dataset
    Paper      Live market feed adapter    SimulatedVenue on live quotes   Wall-clock receive timestamp
    Live       Live market feed adapter    Live broker / exchange adapter  Wall-clock receive timestamp
    

    In paper and live modes, network reader threads push incoming events into a thread-safe queue, stamping ts and arrival_number under the same lock, while the dispatcher loop remains single-threaded so strategy authors never write locks. Unlike a backtest (which exits when the queue empties), the live loop waits when the queue is empty and holds any future-dated event (such as a scheduled Timer) until wall-clock time catches up to event.ts, preventing ctx.now() from ever jumping backward.

    In backtests and paper trading, SimulatedVenue avoids the two biggest sources of fake backtest profits:

    1. Order-entry latency (latency_ns): An order sent at 10 ms does not reach the book until 10 + 2 = 12 ms, so fleeting quotes in between cannot fill it.
    2. Conservative queue priority: A resting buy limit at 19000 fills only when quote.ask drops strictly below 19000 (trading through the price), because at ask == 19000 real orders ahead of ours in the exchange queue might take all available shares without filling us.
    class SimulatedVenue(ExecutionVenue):
        """Conservative simulator modeling one-way order latency and price-through fills."""
    
        def __init__(self, latency_ns: int) -> None:
            self.latency_ns = latency_ns
            # resting: order_id -> (arrival_ts, symbol, side, qty, limit_price)
            self.resting = {}
    
        def start(self, push, clock) -> None:
            self.push = push
            self.clock = clock
    
        def send(self, order_id: int, symbol: str, side: str, qty: int, limit_price: int) -> None:
            arrival_ts = self.clock() + self.latency_ns
            self.resting[order_id] = (arrival_ts, symbol, side, qty, limit_price)
            self.push(OrderUpdate(arrival_ts, order_id, "ACKED"))
    
        def cancel(self, order_id: int) -> None:
            if order_id in self.resting:
                del self.resting[order_id]
                self.push(OrderUpdate(self.clock() + self.latency_ns, order_id, "CANCELLED"))
    
        def on_market(self, quote: Quote) -> None:
            for order_id in list(self.resting):
                arrival_ts, symbol, side, qty, limit_price = self.resting[order_id]
                if arrival_ts > quote.ts or symbol != quote.symbol:
                    continue
                # Require the market to cross strictly through our limit price for a guaranteed fill
                crossed_buy = side == "BUY" and quote.ask < limit_price
                crossed_sell = side == "SELL" and quote.bid > limit_price
                if crossed_buy or crossed_sell:
                    del self.resting[order_id]
                    self.push(OrderUpdate(quote.ts, order_id, "FILLED", qty, limit_price))
    

    Finally, in live mode the engine appends every popped event to an on-disk event journal. Replaying that journal later through Engine reproduces every single state transition and decision deterministically, turning live post-mortems ("Why did Strategy B buy at 10:31:04?") into exact step-through debugging.

  7. Project layout, test pyramid, and team handover

    Because teammates will maintain and extend this codebase after handover, packaging, automated tests, and concise docs are first-class parts of the design:

    trading_framework/
      core/          events.py  queue.py  engine.py  risk.py  orders.py   # small, heavily reviewed core
      adapters/
        data/        csv_source.py  websocket_feed.py                     # plug-in DataSource classes
        venues/      simulated.py   broker_fix.py                         # plug-in ExecutionVenue classes
      strategies/    buy_the_dip.py  mean_reversion.py                    # researcher strategies
      config/        paper.yaml  live.yaml                                # declarative wiring + RiskLimits
      tests/         unit/  risk/  golden/  contracts/
    docs/            README.md  ARCHITECTURE.md  decisions/
    
    • Declarative registration instead of editing core files: Config files name the strategy class, symbol list, data adapter, venue adapter, and RiskLimits parameters, so adding a new strategy means creating one file in strategies/ plus one YAML entry.
    • Four-layer test suite:
      1. Strategy unit tests using a lightweight fake Context (feed three quotes, assert exact submit_order arguments in milliseconds).
      2. Risk and order-lifecycle tests covering boundary values on every limit and rejecting invalid transitions.
      3. Golden backtests that replay a small checked-in dataset and assert exact fills and ending positions in CI so accidental behavioral changes are caught immediately.
      4. Shared adapter contract tests run against SimulatedVenue and every broker mock (verifying ACKED precedes FILLED, rejects carry reasons, and cancels on filled orders do not corrupt state).
    • Runtime invariants and handover docs: Assert at runtime that position always equals the signed sum of fills; ship a 5-minute "Write and backtest your first strategy" README.md, an ARCHITECTURE.md with the event-flow diagram, and versioned Strategy / Context interfaces so older strategies keep working as new event fields are added.

Intuition & how it works

Think of the framework like a single-lane airport control tower: whether planes are arriving from the sky (market data), reporting takeoff from a runway (broker order updates), or ringing an alarm bell (timers), every radio message enters one numbered queue and is handled one at a time by a single controller reading the timestamp stamped on that message. Researchers writing trading strategies sit in a clean cockpit (Strategy) with a standardized control panel (Context): they see instruments and press "request buy", while the tower checks safety rules (RiskLimits) before clearing any instruction to the runway (ExecutionVenue).

The naive approach lets a market-data thread and a broker-callback thread call strategy methods directly, lets strategies read time.time(), uses floating-point prices, and hands strategies a raw broker client. That breaks down immediately: threads interleave differently on every run so bugs cannot be reproduced, time.time() breaks backtests (simulations over recorded historical data) because historical events are replayed in milliseconds rather than real hours, 0.1 + 0.2 != 0.3 in binary floats corrupts price comparisons, and a single buggy loop can send thousands of unchecked orders directly to an exchange.

Instead, every input becomes an immutable event ordered in one min-heap (a priority queue that always pops the earliest (timestamp, arrival_number) item in O(log N) time) and dispatched on one thread:

  • Suppose BuyTheDip("AAPL", 19000) watches integer-cent quotes (updates showing the highest buyer bid and lowest seller ask):
    1. At t = 10 ms, Quote(bid=18998, ask=19000) pops; Engine sets clock = 10 ms and calls strategy.on_quote, which calls ctx.submit_order("AAPL", "BUY", 100, 19000).
    2. Engine runs synchronous pre-trade risk checks (order size, notional value 100 × $190 = $19,000, worst-case position including working orders, price collar in basis points where 1 bps = 0.01%, and order rate) before calling venue.send(...).
    3. With 2 ms simulated latency, SimulatedVenue pushes OrderUpdate(ts=12 ms, status="ACKED"), and later when a quote at t = 40 ms drops to ask = 18998 (crossing strictly below 19000), pushes OrderUpdate(ts=40 ms, status="FILLED", filled_qty=100), updating position from 0 to +100 before notifying strategy.on_order_update.

Key points

  • Single timeline and logical clock. Merging market data, order updates, and timers into one (timestamp, arrival_number) priority queue dispatched by one thread makes strategies lock-free, keeps backtests and live runs aligned, and guarantees deterministic replay.
  • Four isolated extension points. Teammates extend the framework by implementing Strategy (trading logic), DataSource (historical files or live market adapters — thin wrappers around external feeds), and ExecutionVenue (simulator or broker adapters), while strategies interact exclusively through Context.
  • Mandatory pre-trade risk gate. Because strategies never hold a venue reference, every Context.submit_order call passes through size, notional, worst-case open-plus-filled position, integer basis-point price-collar, and rate-limit checks, backed by a per-strategy and global kill switch (an emergency stop that cancels open orders and blocks new ones).
  • Backtest, paper, and live parity via configuration. Paper trading (live market data with simulated fills), backtesting, and live trading run the exact same Engine, Strategy, and RiskLimits code, swapping only the DataSource and ExecutionVenue; SimulatedVenue models network latency and requires prices to cross strictly through resting limit orders (orders capped at a chosen price) to avoid unrealistic backtest fills.
  • Exact reproducibility. Integer tick/cent prices, banning wall-clock calls inside strategies, and recording an append-only live event journal let engineers replay any live trading incident step by step on a laptop.
  • Maintainable handover. Separating core/ from adapters/ and strategies/, wiring components via config files, and shipping unit tests (with a fake Context), risk state-machine tests, golden backtests, venue contract tests, and a 20-line quickstart README.md let the team extend the system safely.

Common mistakes

  • Multi-threaded callbacks directly into strategy objects. Separate market-data and order-update threads create data races, make live runs nondeterministic, and behave completely differently from single-threaded backtests.
  • Calling time.time() or time.sleep() inside strategies. Wall-clock calls silently ruin historical backtests where an entire trading day replays in under a second.
  • Zero-latency, touch-price backtest fills. Filling an order at the exact quote that triggered it (with zero network delay and assuming first place in the exchange queue) produces wildly optimistic backtest profits that evaporate live.
  • Checking risk against filled positions only. Ignoring working (SENT / ACKED / PARTIALLY_FILLED) orders lets a fast loop submit ten max-size orders before the first fill comes back.
  • Using IEEE-754 float for prices. Binary rounding artifacts break <= comparisons against limit prices and cause accounting drift; always use integer cents/ticks or fixed-point decimals.
  • Skipping tests and onboarding docs in a take-home. When the prompt explicitly states that a team will inherit and extend the framework, missing contract tests, golden tests, or clear interfaces is a major design gap.

Follow-up questions

  • Suppose one strategy raises an unhandled runtime error mid-day in production. How should the engine contain the failure and manage that strategy's resting orders and existing inventory? Wrap each per-strategy callback invocation inside Engine._dispatch in an isolated try/except block so one broken strategy never terminates the loop for healthy strategies. On an unhandled exception, record the full traceback alongside the triggering event (already persisted in the event journal for deterministic post-mortem replay), mark that strategy HALTED so future market updates skip it, automatically submit cancel requests for all of its live working orders, and alert an operator. Keep its existing filled inventory intact by default rather than dumping shares blindly into potentially bad market ticks, leaving automatic liquidation as an opt-in per-strategy setting. Because an infinite loop would still freeze a single-threaded dispatcher, monitor callback wall-clock duration, alert on budget overruns, and run untrusted strategies in separate OS processes when hard preemption is required.

  • What recording and timestamping rules ensure that a historical simulation replays events in the exact sequence observed during live trading? To replay a past production session identically, log every popped message at the EventQueue boundary together with its exact (receive_ts, arrival_number) assigned live; feeding that journal back into Engine reproduces every callback and order transition verbatim whenever strategy code is unchanged. When backtesting modified strategy logic on vendor history, merge streams by local gateway receive timestamp rather than remote exchange-matching timestamp (since live code only sees packets after wire transit; if historical files contain only exchange timestamps, add a calibrated per-venue feed offset first). Break timestamp ties deterministically by (source_priority, feed_sequence_number), schedule simulated order acknowledgements and fills at send_ts + venue_latency_ns, and apply identical timer tie-breaking rules across both modes.

  • If a new strategy requires single-digit microsecond tick-to-trade response times, which architectural layers must be redesigned and what developer conveniences disappear? Although popping a binary heap and invoking a method costs well under a microsecond, Python's garbage collector pauses, heap object allocations, kernel network stack traversal, and bytecode interpretation introduce tens to hundreds of microseconds of tail jitter. Isolate that latency-sensitive strategy in a dedicated C++ or Rust binary pinned to a dedicated CPU core, busy-polling a kernel-bypass NIC colocated at the exchange, backed by pre-allocated ring buffers (zero dynamic allocation on the hot path) and flat array-indexed risk checks. In return, you sacrifice rapid Python research iteration, dynamic plug-in loading, sharing one in-process loop with slower strategies, and zero-effort Python backtest reuse unless you also build a historical packet replayer for the compiled engine.

  • How can multiple strategies consume a single live market feed without a compute-heavy callback stalling faster strategies? Maintain one shared market-data adapter subscribed once per instrument to avoid duplicate sockets and exchange data fees, then fan each parsed immutable event out into bounded per-strategy queues drained by independent worker threads or processes. Never allow the feed reader to block on a lagging consumer: for Quote updates, use quote conflation (overwrite the lagging strategy's unread pending quote for that symbol in place so it skips stale intermediate ticks and processes the freshest market state), while never dropping or conflating OrderUpdate execution messages.

text Live Feed Adapter --> Quote(AAPL) --+--> Fast Strategy Queue : processes every tick immediately +--> Slow Strategy Queue : full? overwrite older unread AAPL Quote in place

Follow-up questions

Similar questions

More Cubist interview questions

All 3 Cubist questions →