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 aHistoricalFlowagent into aMarketSimulator, so anyStrategy(with its latency, timers and analytics) can trade against the historical order flow.
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.
snapshots
instance-attribute
¶
snapshots: list[BookSnapshot]
The book after each message: snapshots[i] follows messages[i].
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
¶
BookSnapshot
¶
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.
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.
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
¶
sim: MarketSimulator
The simulator, holding the historical flow and your strategies.
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.
to_sim_time
¶
Simulator time step of a LOBSTER timestamp (seconds after midnight).
is_historical
¶
Whether order_id belongs to the replayed history rather than to a strategy.
seed_actions
¶
One aggregate order per visible level of initial_book.
translate
¶
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
¶
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.