Skip to content

Architecture

The engine is a pipeline of components that never call each other. Each subscribes to the event types it needs on one bus and publishes events of its own. The engine is the clock: it feeds bars in, lets the cascade they cause settle, and moves on.

flowchart LR
    Feed[(Feed)] -->|MarketDataEvent| Strategy
    Strategy -->|SignalEvent| OM[Order manager]
    OM -->|OrderEvent| Risk[Risk manager]
    Exits[Exit manager] -->|OrderEvent| Risk
    Risk -->|ApprovedOrderEvent| Exec[Execution]
    Exec -->|FillEvent| Portfolio
    Portfolio -->|PortfolioUpdateEvent| Metrics

The bus

EventBus is synchronous and single-threaded. publish appends an event to a FIFO queue, and run dispatches until the queue is empty, including events that handlers publish along the way. It guarantees three things:

  • Breadth-first. Every handler of an event runs before any event those handlers published is delivered. A fill reaches the portfolio, the order manager, the risk manager and the metrics before any order the fill causes.
  • Deterministic. Handlers of one event type run in the order they subscribed, so the same inputs give the same run, event for event.
  • Fail-fast. A handler's exception propagates out of run. A backtest that skipped a broken component would report numbers that mean nothing.

Events are frozen, slotted, keyword-only dataclasses, so no handler can change what another sees.

The clock

Feeds are merged into time slices, one bar per symbol that traded at that time. For each slice the engine drains the bus twice:

for timestamp, bars in merge_feeds(feeds):
    for bar in bars:
        bus.publish(bar)
    bus.run()  # fills at the open, signals on the close, orders, risk decisions
    bus.publish(EndOfBarEvent(timestamp=timestamp))
    bus.run()  # the mark-to-market snapshot; cross-sectional strategies decide

Draining after every slice is what keeps time moving forward. An engine that queued every bar first and processed the events afterwards would run every strategy decision after the last bar had been seen, and price every order off it. A regression test pins this.

EndOfBarEvent exists because only the engine knows when a slice's cascade has settled. The portfolio's snapshot must include the fills that happened during the slice, and a PortfolioStrategy must see every symbol's bar before it decides.

The components

Components register in this order, which sets the order in which they handle each event:

# Component Handles Publishes
1 MarketState bars (nothing: it holds the latest bar of each symbol for the others)
2 Execution (ExecutionSimulator or BrokerExecution) bars, approved orders, cancel requests, snapshots fills, cancellations
3 PortfolioTracker bars, fills, end of bar snapshots, interest and fees
4 Strategy bars (and end of bar, for portfolio strategies) signals
5 OrderManager signals, fills, vetoes, cancellations, snapshots orders, cancel requests, targets
6 ExitManager (with exits configured) fills, vetoes, cancellations stop and take-profit orders
7 RiskManager orders, fills, cancellations, snapshots approved orders, vetoes
8 PerformanceMetrics bars, fills, cash flows, snapshots, vetoes, cancellations (nothing: it builds the report)
9 EventLogger, then SQLiteWriter everything (nothing)

The order is what makes a bar causal. Execution handles a bar before the strategy does, so orders placed on earlier bars fill at this bar's open. Only then does the strategy see the bar, and decide on its close. Orders it causes are approved now but wait in the simulator for the next bar. The portfolio is marked at this bar's close only at the end of the slice.

The rules that keep it causal

Rule Enforced by
A decision on bar t fills on bar t + 1 or later The simulator queues approved orders until the next bar; tests check fill timestamps
Fills are never better than the bar allowed Market orders fill at the open with adverse slippage; a stop the open gapped through fills at the open, past its price; a limit never fills worse than its limit
When a bar touches a stop and a take-profit, the stop fills The simulator checks stops first
Sizing uses equity known before the decision The order manager sizes from the last snapshot, the previous slice's close
Warm-up bars never trade They run on a separate bus with only the market state and the strategy
Reducing risk is never blocked Risk limits apply to orders that add exposure only

A property-based test (Hypothesis) checks the position accounting on random sequences of fills, long and short: realised plus unrealised P&L always equals the cash flows of the fills.

Warm-up

BacktestEngine(..., warmup_until=t) runs the bars before t on a separate bus that holds only the market state, the strategy and a recorder of its last signal per symbol. When trading starts, the components register on the real bus and the recorded signals are replayed, so the strategy takes its position at once instead of waiting for its next crossover. The paper trader warms up the same way on recent history, and walk-forward test windows warm up on the bars before them, so their indicators start warm.

One pipeline, two executions

build_components builds the same list for a backtest and a paper session. Paper trading swaps the simulator for BrokerExecution, which sends approved orders to Alpaca and turns the broker's fills into FillEvents, and swaps the feed for bars polled as they complete. Everything else, from the strategy to the metrics, runs unchanged. That is what makes trading compare, a backtest of the session's own bars set against its paper fills, meaningful.

Research

Sweeps and walk-forward runs load the data once and pass it to worker processes when they start, then send each worker only the parameter overrides of the runs it does. A run cannot change the data, the store or the charts: the simulation, persistence and visualization sections are the same for every run of a sweep. Each run is an ordinary backtest, so it is exactly as causal as one.

Storage

Each run writes to SQLite: one row in runs (its config, status and metrics) and one row per event in market_data, signals, orders, approved_orders, risk_vetos, cancellations, fills, cash_flows, portfolio_updates, positions and targets. Sweeps add sweeps and sweep_results. The schema is versioned and migrated in place, so older databases stay readable. Paper sessions resume from these tables.

Package layout

src/trading/
├── backtest/engine.py         # pipeline wiring and the slice-by-slice event loop
├── bus/event_bus.py           # FIFO, breadth-first pub/sub
├── events/types.py            # every event type
├── market_data/               # feeds, download cache, calendars, slice merging, state
├── signal/                    # strategy bases, indicators, built-in strategies, registry
├── order_manager/             # target-position sizing, protective exits
├── risk/manager.py            # pre-trade limits
├── execution/simulator.py     # fills from OHLCV bars: order types, slippage, volume caps
├── portfolio/                 # position accounting, PortfolioTracker
├── metrics/                   # pure stats, bootstrap, round-trip trades, report
├── research/                  # parameter grids, sweeps, walk-forward, studies
├── live/                      # Alpaca client, broker execution, paper trader, alerts
├── persistence/               # SQLite schema, run and sweep storage
├── visualization/chart.py
├── logger/                    # event log lines, JSON log format
├── config.py                  # typed, validated configuration
└── cli.py                     # the trading command