Replaying LOBSTER data¶
microbook.replay feeds order-by-order exchange data
through the matching engine. It does two things with a day of data:
- Reconstruction. Rebuild the book message by message and compare it with the exchange's own snapshots: a direct test of the engine's price-time priority against real exchange behaviour.
- Backtests. Trade any
Strategyagainst the historical order flow, with its latency, timers and analytics.
The data¶
The input is LOBSTER, the standard academic reconstruction of NASDAQ TotalView-ITCH. A day is two CSV files without headers:
- a message file (
*_message_N.csv): one row per book event, with the time in seconds after midnight, the event type, the order id, the size, the price in dollars × 10,000, and the direction (+1 buy, −1 sell); - an orderbook file (
*_orderbook_N.csv): the topNlevels on each side after each message.
LOBSTER provides academic sample days on request. Without licensed data,
synthetic_day() generates a day in the same
format, and write_lobster() saves it. The
generator keeps its own FIFO queues and does not use the engine, so it doubles
as an independent test oracle.
from microbook.replay import check_reconstruction, load_lobster, synthetic_day, write_lobster
write_lobster(synthetic_day(20_000, levels=5, seed=1), "SYN_message_5.csv", "SYN_orderbook_5.csv")
day = load_lobster("SYN_message_5.csv", "SYN_orderbook_5.csv")
print(len(day.messages), day.levels)
# 19999 5
print(day.messages[0])
# Message(time=34200.02429236, kind=1, order_id=10000001, size=400, price=99.98, direction=1)
load_lobster() uses the book after the first
message as the starting book and replays from the second message, because the
orders resting at the start of the file are not in it. Pass max_messages to
load only the start of a long day.
Rebuilding the book¶
check_reconstruction() replays every
message into a fresh book and compares it with the recorded snapshot after each
one:
report = check_reconstruction(day)
print(report.top_of_book_match, report.depth_match, report.first_mismatch)
# 1.0 1.0 None
On a synthetic day the reconstruction is exact at every level after every message. On real data, read the report's fields:
| Field | Meaning |
|---|---|
top_of_book_match |
share of messages after which the best bid and ask, price and size, match |
depth_match |
share of messages after which all levels levels match |
first_mismatch |
index of the first message whose snapshot differs |
rejected |
operations the engine refused |
unfilled_execution_qty |
shares of historical executions that found less liquidity than recorded |
The messages become book operations like this:
| LOBSTER event | Replayed as |
|---|---|
| 1 new limit order | a GTC limit order |
| 2 partial cancel | reduce (keeps queue priority) |
| 3 deletion | cancel |
| 4 visible execution | an IOC from the aggressor's side at the execution price, matched by the engine's own price-time priority |
| 5 hidden execution, 6 auction cross, 7 halt | nothing (not in the visible book) |
Orders resting before the first message are unknown one by one, so the book is seeded with one aggregate order per price level, and later messages about those orders act on the aggregate.
Backtesting a strategy¶
build_replay() returns a
Replay: a MarketSimulator
with a HistoricalFlow agent that replays the
messages, plus your strategies. Message times map onto the integer clock with
time_unit seconds per step (1 ms by default), so latencies, timers, snapshot
intervals and markout horizons are all in that unit.
from microbook.replay import build_replay
from microbook.sim import AdaptiveConfig, AdaptiveMarketMaker, format_table, strategy_report
cfg = AdaptiveConfig(size=50, tick_interval=100, latency=10, inv_limit=500, inv_k=0.004, max_skew_ticks=4)
mm = AdaptiveMarketMaker(cfg, name="mm")
replay = build_replay(day, [mm], time_unit=1e-3, snapshot_every=100) # 10 ms latency, requote every 100 ms
sim = replay.run()
report = strategy_report(sim, ["mm"], horizons=(100, 1_000))
print(format_table(report, ["volume", "spread_capture", "markout_100", "markout_1000"]))
# volume spread_capture markout_100 markout_1000
# -- ------ -------------- ----------- ------------
# mm 21100 0.0148 -0.0018 0.0029
The synthetic flow is random, so these numbers say nothing about real markets; on a real day the same code measures what a market maker would have earned and how much of it adverse selection took back.
What a replay backtest assumes¶
The historical flow does not react to the strategy: there is no market impact. Around the strategy's orders, the recorded book is kept intact:
- When a replayed execution fills the strategy's order because it was ahead in the queue, the historical order it would have hit is reduced by the same amount. The strategy is filled exactly when history reaches its place in the queue.
- When a new historical limit order crosses the strategy's quote (in history it rested), the strategy keeps the fill and the historical 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, and the test suite
checks that. The replay becomes counterfactual when the strategy takes
liquidity, or when its quote swallows a whole incoming order that then never
rests. replay.flow.stats counts both: unfilled_execution_qty and rejected
should stay small next to the day's volume.
Stylized facts of a real day¶
The stylized-facts toolkit works on any mid path and fill list, so it measures a replayed day with the same code as a simulation. Replay the day with no strategies, then choose horizons in the replay's time unit:
from microbook.stylized import stylized_facts
replay = build_replay(day)
sim = replay.run()
facts = stylized_facts(
sim.result.mid_path,
sim.result.fills,
end=replay.flow.horizon,
dt_short=1_000, # one-second returns
dt_long=60_000, # one-minute returns
vol_lags=(1, 10, 60),
sign_lags=(1, 10, 100),
)
print(facts.n_returns, facts.n_trades)
# 864 4268
On a real day¶
With a LOBSTER sample day, the same steps are:
day = load_lobster(
"AAPL_2012-06-21_34200000_57600000_message_10.csv", "AAPL_2012-06-21_34200000_57600000_orderbook_10.csv"
)
print(check_reconstruction(day))
examples/replay_lobster.py runs the whole pipeline (reconstruction, a market
maker at four latencies, the day's stylized facts) on a pair of LOBSTER files,
or on a synthetic day if you give it none: