Skip to content

Historical replay

Replay historical order-book data through the matching engine.

The input is order-by-order (L3) data in the LOBSTER format (lobsterdata.com), the standard academic reconstruction of NASDAQ TotalView-ITCH: a message file with one row per book event and an orderbook file with the top N price levels after each message.

Replaying a day does two things:

  • Reconstruction. check_reconstruction() rebuilds the book message by message and compares it with the exchange's own snapshots. It is a direct test of the engine's price-time priority against real exchange behaviour.
  • Strategy backtests. build_replay() puts a HistoricalFlow agent into a MarketSimulator, so any Strategy (with its latency, timers and analytics) can trade against the historical order flow.
How messages become book operations

==================== ========================================================= LOBSTER event Replayed as ==================== ========================================================= 1 new limit order a GTC limit order 2 partial cancel reduce (cancel-by-size, keeps priority) 3 deletion cancel 4 visible execution an IOC from the aggressor's side at the execution price, so it matches by price-time priority and can hit a strategy's order that is ahead in the queue 5 hidden execution nothing (hidden liquidity is not in the visible book) 6 auction cross nothing 7 trading halt nothing ==================== =========================================================

Orders resting before the first message are unknown individually: the book is seeded with one aggregate order per price level from the first snapshot, and later messages about such orders act on that level's aggregate.

Backtest assumptions

The historical flow does not react to the strategy (no market impact feedback), and the recorded book is kept intact around the strategy's orders:

  • when a replayed execution fills a strategy's order ahead of the historical order it hit, that historical order is reduced by the same amount, so the strategy is filled exactly when history reaches its place in the queue;
  • when a new historical limit order crosses a strategy's quote on arrival (in history it rested), the strategy keeps the fill and the order's resting size is restored.

With these rules a passive strategy whose orders are small next to the historical ones leaves the recorded book exactly as it was (tested). The replay becomes counterfactual when a strategy takes liquidity, or when its quote swallows a whole incoming order, which then never rests; the stats of HistoricalFlow count both (unfilled_execution_qty, rejected).

load_lobster

load_lobster(message_path: PathLike, orderbook_path: PathLike, *, price_scale: float = PRICE_SCALE, max_messages: int | None = None) -> LobsterDay

Load a LOBSTER message/orderbook pair as a LobsterDay.

The book after the first message seeds the replay, which then starts at the second message (the orders resting at the open are not in the file).

LobsterDay dataclass

LobsterDay(messages: list[Message], initial_book: BookSnapshot, snapshots: list[BookSnapshot])

A replayable day: the book before messages[0] and the book after each message.

messages instance-attribute

messages: list[Message]

The day's messages, in order.

initial_book instance-attribute

initial_book: BookSnapshot

The book before the first message.

snapshots instance-attribute

snapshots: list[BookSnapshot]

The book after each message: snapshots[i] follows messages[i].

levels property

levels: int

Number of price levels per side the snapshots carry.

read_lobster_messages

read_lobster_messages(path: PathLike, *, price_scale: float = PRICE_SCALE) -> list[Message]

Parse a LOBSTER message file (*_message_N.csv; no header).

read_lobster_orderbook

read_lobster_orderbook(path: PathLike, *, price_scale: float = PRICE_SCALE) -> list[BookSnapshot]

Parse a LOBSTER orderbook file (*_orderbook_N.csv; no header).

Each row holds ask price, ask size, bid price, bid size for levels 1..N. Empty levels (LOBSTER's dummy prices, or size 0) are dropped.

write_lobster

write_lobster(day: LobsterDay, message_path: PathLike, orderbook_path: PathLike, *, levels: int | None = None, price_scale: float = PRICE_SCALE) -> None

Write day.messages and day.snapshots in the LOBSTER file format.

Message

Bases: NamedTuple

One row of a LOBSTER message file.

time instance-attribute

time: float

Seconds after midnight.

kind instance-attribute

kind: int

Event type, a MessageType value.

order_id instance-attribute

order_id: int

Exchange order id.

size instance-attribute

size: int

Shares.

price instance-attribute

price: float

Price, in dollars.

direction instance-attribute

direction: int

+1 for a buy limit order, -1 for a sell; for an execution, the side of the resting order.

MessageType

Bases: IntEnum

LOBSTER event types.

BookSnapshot

Bases: NamedTuple

Visible price levels, best first, as (price, size).

bids instance-attribute

bids: tuple[tuple[float, int], ...]

Bid levels, best first, as (price, size).

asks instance-attribute

asks: tuple[tuple[float, int], ...]

Ask levels, best first, as (price, size).

PRICE_SCALE module-attribute

PRICE_SCALE = 10000.0

check_reconstruction

check_reconstruction(day: LobsterDay, *, tick_size: float = 0.01, levels: int | None = None) -> ReconstructionReport

Rebuild the book from day.messages and compare it with day.snapshots.

ReconstructionReport dataclass

ReconstructionReport(messages: int, levels: int, top_of_book_match: float, depth_match: float, first_mismatch: int | None, rejected: int, unfilled_execution_qty: int)

How closely the replayed book tracks the recorded snapshots.

messages instance-attribute

messages: int

Number of messages replayed.

levels instance-attribute

levels: int

Price levels per side compared.

top_of_book_match instance-attribute

top_of_book_match: float

Fraction of messages after which the best bid and ask (price and size) match.

depth_match instance-attribute

depth_match: float

Fraction of messages after which all levels levels on both sides match.

first_mismatch instance-attribute

first_mismatch: int | None

Index of the first message whose snapshot differs; None if all match.

rejected instance-attribute

rejected: int

Messages the engine rejected.

unfilled_execution_qty instance-attribute

unfilled_execution_qty: int

Shares of historical executions that found less resting quantity than recorded.

build_replay

build_replay(day: LobsterDay, strategies: Sequence[Strategy] = (), *, tick_size: float = 0.01, time_unit: float = 0.001, snapshot_every: int = 100, record_snapshots: bool = False, name: str = 'hist') -> Replay

A simulator that replays day with strategies trading alongside.

snapshot_every (in time_units; default 100 ms) sets how often SNAPSHOT events fire, which drives on_tick and the PnL series.

Replay dataclass

Replay(sim: MarketSimulator, flow: HistoricalFlow)

A simulator wired to replay one day (see build_replay()).

sim instance-attribute

The simulator, holding the historical flow and your strategies.

flow instance-attribute

The agent that replays the historical messages.

run

run(until: int | None = None) -> MarketSimulator

Run to until (default: the last message).

HistoricalFlow

HistoricalFlow(messages: Sequence[Message], *, initial_book: BookSnapshot | None = None, tick_size: float = 0.01, time_unit: float = 0.001, name: str = 'hist')

Bases: Strategy

Replays historical messages into a MarketSimulator.

Message times map onto the integer clock as 1 + round((time - first_time) / time_unit) (time_unit in seconds, default 1 ms), so strategy latencies, timers and snapshot intervals are in the same unit. Messages that share a clock tick are applied in file order.

stats counts replayed message types plus rejected (operations the book refused, e.g. a cancel for an order a strategy already consumed) and unfilled_execution_qty (historical executions that found less liquidity than recorded). Both are zero for an exact reconstruction.

horizon property

horizon: int

Simulation time of the last message.

to_sim_time

to_sim_time(seconds: float) -> int

Simulator time step of a LOBSTER timestamp (seconds after midnight).

is_historical

is_historical(order_id: str) -> bool

Whether order_id belongs to the replayed history rather than to a strategy.

seed_actions

seed_actions(now: int) -> list[Action]

One aggregate order per visible level of initial_book.

translate

translate(m: Message, now: int) -> list[Action]

Book operations for one message (see the module docstring).

on_start

on_start(now: int, lob: LimitOrderBook) -> list[Action]

Seed the book with the initial snapshot and schedule the first message.

on_timer

on_timer(now: int, lob: LimitOrderBook) -> list[Action]

Apply the next historical message and schedule a wake-up for the one after.

on_fill

on_fill(now: int, fill: Fill, side: Side, is_maker: bool, lob: LimitOrderBook) -> list[Action]

When a replayed execution fills a strategy's order, shrink the historical order it was meant for.

on_report

on_report(now: int, report: ExecutionReport) -> list[Action]

Track execution outcomes and restore historical orders that crossed a strategy's quote.

synthetic_day

synthetic_day(n_messages: int = 10000, *, levels: int = 5, seed: int = 0, start_price: float = 100.0, tick_size: float = 0.01, start_time: float = 34200.0) -> LobsterDay

A LOBSTER-format day generated by a small FIFO reference model.

Useful for trying the replay pipeline without licensed data, and as a test oracle: the generator keeps its own order queues (it does not use LimitOrderBook), so check_reconstruction() on its output must match exactly. Orders rest at the open on the first levels levels and are not in the message stream, like a real file that starts mid-session.