Build an Extensible Event-Driven Trading Strategy Framework
System DesignModel answerLast updated
Design a maintainable framework that routes market events to trading strategies, manages order lifecycle, and runs identically in backtests and live trading.
The Problem
Your team is building an internal platform where multiple quantitative strategies run side by side. You have been asked to design and sketch the core framework they will all share — one that the team can keep extending long after the initial version ships.
The framework has two jobs: deliver events (new market data, fills, timer ticks, etc.) to each strategy in a well-defined order, and carry out whatever orders a strategy decides to send. Individual developers should be able to write a new strategy without touching framework internals.
Describe the architecture you would build, the core interfaces a strategy author would implement, and the path an event takes from arrival through to an order being sent.
What is expected
- A clear architecture diagram or description of the major components and how they connect
- The core interfaces: what a strategy must implement, what the framework provides to it
- How the event loop works: ordering guarantees, time handling, and dispatch
- How the same strategy code runs in a historical backtest, a paper-trading simulation, and live
- How the framework handles order lifecycle, position tracking, and pre-trade risk checks
- What makes the framework safe to extend: strategy isolation, logging, tests, and documentation
Constraints and clarifications
- Asset class, language, data sources, venues, and latency targets are not specified — state your assumptions or ask
- This is a deliverable other people will maintain; interfaces, tests, and documentation are part of the answer
- Worth addressing: what happens when one strategy crashes or misbehaves, and how a new venue or data source is added without changing existing code
Good clarifying questions to raise
- Should the same strategy instance run unmodified across backtest, paper, and live modes?
- Which event types must be supported at launch: top-of-book quotes, trade prints, OHLCV bars, order acknowledgements, partial and full fills, rejections, and/or timer events?
- Do strategies share market data subscriptions, a common position ledger, or per-strategy risk limits?
- Is there an existing order-routing or market-data infrastructure to integrate with, or is everything greenfield?
- Is microsecond latency a hard requirement, or is developer ergonomics the priority?
Hints
Hint 1
Start with the event model before anything else. Define a sealed Event type hierarchy so every component in the system speaks the same language. A poorly typed event model causes subtle bugs that are expensive to fix once strategies are written on top of it.
Hint 2
The key to backtest/live parity is a Clock abstraction. If every component that needs to know the current time calls `clock.now()` rather than the system clock, you can replay history at any speed and the strategy code never changes.
Hint 3
Put a risk and order manager between the strategy and the venue — strategies call `submit_order()` on the framework, never on the venue directly. This is where you enforce position limits, rate limits, and size checks without asking strategy authors to remember to do it themselves.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Assumptions
Python, latency target in the tens of milliseconds (algorithmic, not HFT), equities or crypto, single process, multiple strategies running concurrently on shared market data. The framework is greenfield.
Architecture Overview
Five layers, each with a narrow interface to its neighbors:
Data Sources → Event Bus → Strategy Runner → Order Manager → Execution Venues
↑ ↑
Clock / Time Risk Engine
Data Sources normalize external feeds (WebSocket, CSV file, database) into framework events and push them onto the bus.
Event Bus is a prioritized, ordered queue. It is the only shared mutable state between the layers.
Strategy Runner pops events from the bus and dispatches them to registered strategies one at a time. It gives each strategy a read-only view of market state and a handle to submit orders.
Order Manager tracks the lifecycle of every order, maintains per-strategy positions, and runs pre-trade risk checks before forwarding to an execution venue.
Execution Venues are adapters — a backtest simulator, a paper-trading layer, or a live broker — all implementing the same interface.
The Event Model
from dataclasses import dataclass
from enum import Enum, auto
from datetime import datetime
class EventType(Enum):
BAR = auto()
QUOTE = auto()
TRADE = auto()
ORDER_ACK = auto()
FILL = auto()
REJECTION = auto()
TIMER = auto()
@dataclass(frozen=True)
class Event:
type: EventType
timestamp: datetime # always from Clock, never datetime.now()
payload: object
Using a frozen dataclass prevents strategies from mutating events mid-dispatch, which is a subtle source of bugs in shared-bus designs.
The Clock Abstraction — Key to Backtest/Live Parity
class Clock:
def now(self) -> datetime: ...
class WallClock(Clock):
def now(self): return datetime.utcnow()
class SimulatedClock(Clock):
def __init__(self, start): self._time = start
def advance(self, ts): self._time = ts
def now(self): return self._time
Every component that needs the current time receives a Clock at construction. Swapping WallClock for SimulatedClock is the only change needed to run in backtest mode. This is the single most important design decision for parity.
The Strategy Interface
Keep it small. A strategy author implements exactly two methods:
class Strategy:
def on_event(self, event: Event, ctx: StrategyContext) -> None:
"""Called for every event the strategy is subscribed to."""
...
def subscriptions(self) -> list[EventType]:
"""Declare which event types this strategy wants."""
...
StrategyContext is what the framework hands the strategy at dispatch time:
class StrategyContext:
def get_bar(self, symbol: str, lookback: int) -> list[Bar]: ...
def position(self, symbol: str) -> float: ...
def submit_order(self, order: Order) -> str: ... # returns order_id
def cancel_order(self, order_id: str) -> None: ...
@property
def clock(self) -> Clock: ...
Strategies never import from the order manager or execution layer directly. This enforces the dependency boundary and makes testing trivial — inject a mock context.
Event Dispatch Loop
class StrategyRunner:
def run(self):
while True:
event = self.bus.pop() # blocks or returns None at EOD
for strategy in self.registry:
if event.type in strategy.subscriptions():
try:
strategy.on_event(event, self._ctx_for(strategy))
except Exception as e:
self.logger.error(f"{strategy} raised {e}, skipping")
# isolate: continue to next strategy, don't crash the loop
The loop is single-threaded by default. Strategies are dispatched sequentially, so they never observe a half-updated market state. If a strategy throws, it is logged and skipped; the bus continues draining. This is the isolation contract the team can rely on.
Order Lifecycle and Risk
Orders flow: strategy → OrderManager → RiskEngine → VenueAdapter.
class OrderManager:
def submit(self, order: Order, strategy_id: str) -> str:
self.risk.check(order, strategy_id) # raises RiskViolation if breached
order_id = self._assign_id(order)
self._pending[order_id] = order
self.venue.send(order)
return order_id
def on_fill(self, fill: Fill):
self._positions[fill.strategy_id][fill.symbol] += fill.qty
self.bus.push(Event(EventType.FILL, self.clock.now(), fill))
Risk checks include max order size, max position per symbol, and a daily loss limit. These live in one place; strategy authors never touch them.
Adding a New Venue or Data Source
Both extend a single-method interface:
class VenueAdapter:
def send(self, order: Order) -> None: ...
class DataAdapter:
def stream(self, bus: EventBus) -> None: ...
A new venue is a class that implements send. A new data source implements stream and pushes events onto the bus. No existing code changes — this is the open/closed principle applied directly.
Testing Strategy
- Unit test each strategy by constructing a
MockContextand callingon_eventdirectly - Integration test the runner with a
CSVDataAdapter+SimulatedClock+PaperVenue - Test risk checks in isolation by calling
OrderManager.submitwith boundary values - Snapshot test: run a known strategy over a fixed dataset and assert the fill log matches a golden file — catches regressions across refactors
Common Mistakes to Avoid
- Letting strategies call
datetime.now()ortime.sleep()— breaks backtest determinism - Putting order routing logic inside strategy code — makes risk controls inconsistent
- A mutable shared position dict without clear ownership — causes race conditions if you ever add threads
- Over-engineering the bus with async/await before you have a latency requirement — adds complexity with no benefit at this scale