Historical data (phase 5, part 1)

crates/data turns vendor files into a normalised, checked stream. It rebuilds the order book and checks it against the vendor’s own snapshots, records where every dataset came from, and replays hypothetical orders under an explicit queue model. The hftsim binary exposes it.

Status.

Results on historical data are a separate stage from simulation results. Every result built on this crate carries its provenance and states the data level it rests on (ARCHITECTURE §10).

1. LOBSTER files, as implemented

LOBSTER (lobsterdata.com) sells reconstructed NASDAQ order books as two CSV files per stock-day. Source tags as in RESEARCH_SURVEY.md:

LOBSTER’s own documentation page could not be loaded, so nothing here is [V].

Detail As implemented Source
File names TICKER_DATE_STARTms_ENDms_message_N.csv and ..._orderbook_N.csv, for example AAPL_2012-06-21_34200000_57600000_message_10.csv [S] a university course page on LOBSTER data
Message fields time, type, order id, size, price, direction [S] documentation of a LOBSTER reconstructor library
Time seconds after midnight, decimal; parsed exactly to nanoseconds, never through floating point [S] same
Types 1 submission, 2 partial cancellation, 3 deletion, 4 execution of a visible order, 5 execution of a hidden order, 6 cross trade, 7 trading halt [S] same
Price dollars × 10,000 [S] same, and a LOBSTER loader script
Direction 1 buy order, −1 sell order: the side of the order the message is about, so an executed sell order is a buyer-initiated trade side of the book [S]; the ±1 coding [M]
Order-book rows one per message, the book after it; per level: ask price, ask size, bid price, bid size [S] loader script; one row per message [M]
Empty levels size 0 with a dummy price (±9,999,999,999). The reader treats any level with size 0 as empty, so it does not depend on the dummy value [M]
Halt rows (type 7) price −1 halt, 0 quote-only, 1 resume; counted, not otherwise interpreted [M]

The reader rejects any field it cannot interpret and names the line, instead of guessing. hftsim lobster-check on a real file will confirm or correct every [M] row above.

2. Rebuilding the book and checking it against the vendor

A LOBSTER message file starts at its start time (9:30 for a full day). The book at that moment already holds orders placed earlier, and they appear only through later cancellations and executions of order ids the file never submitted. lobster::Rebuilder therefore keeps, per price level:

lobster::validate applies each message, then compares the best N levels with the vendor’s snapshot row. When they disagree it reconciles: it changes only seed quantities, never known orders, so the book agrees again before the next message. Its report separates a perfect reconstruction from a reconciled one:

Field Meaning
matched, matched_share rows that agreed before any reconciliation
first_mismatch first row (1-based) that did not
reconciled_rows, seed_added, seed_removed how often, and by how many shares, the seeds were changed
unexplained_rows contradictions seeds cannot absorb: known orders exceed the vendor’s size, or a known level is missing from it. Should be 0
unknown_order_events, unknown_order_volume cancellations, deletions and executions of orders never submitted in the file
size_mismatches, duplicate_submissions internal inconsistencies of the message file

Levels deeper than N are never compared: the vendor file does not show them.

Checked on simulated days (crates/runner/tests/lobster.rs):

3. Provenance

provenance::Provenance records:

hftsim lobster-check prints it beside every validation, and hftsim lobster-export writes it next to the files. FNV-1a detects accidental change, not tampering.

LOBSTER message files are order-level (MBO) data for the visible book. They carry no hidden orders’ resting state and no participant identities, and nothing before the start time.

4. Pure replay: a queue model, checked against the exchange

replay::replay_passive answers the question every passive backtest has to answer: when would a hypothetical resting order have filled? The historical market cannot react to it (ARCHITECTURE §10 mode a), so a FIFO queue model with conservative rules decides (RISKS K3):

With MBO data the order ids alone place unknown orders ahead, so the fills do not depend on snapshots. Snapshots only make the reported queue ahead complete (tested).

The check against ground truth

The simulator knows what really happened. hftsim replay-check (and runner::replay_check) works in four steps:

  1. It runs a market with probe agents (agents::ProbeTrader) that rest small orders at the touch and cancel them after a fixed life.
  2. It writes the market’s event log as LOBSTER messages without the probes’ own book events and executions: what a vendor file would show if the probes had been someone’s hypothetical orders.
  3. It replays each probe through that stream (entry at its acceptance, expiry at its cancellation).
  4. It compares the modelled fills with the exchange’s.

Settings: seed 2026, 120 s, one market maker (step 7), 10 informed traders, and 6 co-located probes that place an order every 300 ms on average with a 3 s life.

Background Probe size Probes Filled by both Exchange only Model only Neither Same nanosecond Model later: median / p90 Fills visible without the probe
default 1 share 986 924 1 0 61 518 10 ms / 104 ms 518
default 5 shares 863 795 6 0 62 0 30 ms / 194 ms 0
zero intelligence 1 share 979 917 0 0 62 502 10 ms / 78 ms 502
zero intelligence 5 shares 888 813 11 0 64 0 20 ms / 155 ms 0

Rerun on 2026-11-19 and 2026-11-20 after each rule that the ITCH days led to (leaving, executions away from an order’s own price, auctions, receipt order): every number is unchanged.

In every configuration the model filled no probe that the exchange left unfilled, and none earlier than the exchange. It found every fill that a stream without the probe can show at the same nanosecond: 518 of 518 and 502 of 502. Those are the fills where the aggressor that hit the probe went on to trade behind it or through its level in the same command.

The blind spot. The other fills came from aggressors whose last shares went to the probe. Without the probe, history shows no trade for that volume, so the model can only fill the probe when a later aggressor shows up: 10–30 ms later at the median. With 5-share probes every fill was of this kind. The event log explains why: aggressive orders in this market execute a median of 2 shares (90th percentile 3, none 6 or more), so a 5-share probe absorbs any aggressor that reaches it. The blind spot comes from building “history” from a world that contained the probe. A genuinely probe-free history would show that last volume trading against the order behind.

What this establishes. The replay model implements the same FIFO logic as the matching engine. Given exact order-level data, it is never optimistic.

What it does not.

5. Simulated sessions as LOBSTER files

hftsim lobster-export DIR [--levels N] [run flags] runs one market and writes its public feed as LOBSTER files:

Mapping:

Orders that never rest do not appear, as in exchange order-level feeds. Auction trades have no equivalent here and are refused.

No simulated agent cuts an order in place, so simulated files have no partial cancellations (type 2). Real LOBSTER files have many. The writer’s type-2 path is tested directly through the matching engine (TESTING.md, phase 5, mutant D04).

Uses:

6. Bitstamp: real order-level data, checked against the exchange’s snapshots

LOBSTER’s sample now needs an academic e-mail, proof of purchase and staff approval (§8). Bitstamp publishes order-level data without an account. Its WebSocket API v2 documentation was read ([V]):

That is order-level data and order-level vendor snapshots, so the rebuild can be checked order by order. LOBSTER’s check (§2) compares only aggregate price levels.

Recording

python -m hftsim.bitstamp record subscribes to the three channels. It writes every order and trade message exactly as received, prefixed by the local receive time, plus the first snapshot of each second, and stops at a time limit or a size cap. It uses the standard library only: a small RFC 6455 WebSocket client over ssl, tested on synthetic frames.

Recording data/bitstamp/btcusd-20261118T011941Z/
Window 2026-11-18 01:19:42 – 01:38:38 UTC: 18 min 56 s, stopped by the 200 MB cap
Messages 365,180 order events, 348 trades, 1,136 snapshots
Integrity no reconnects, no event-id gaps, events already in time order
Order events 182,404 created, 182,448 deleted, 328 changed; no stop orders
Orders created, by subtype MOC 173,155 (95%), IOC 6,448, limit 2,770, FOK 29, market 2

The recorder checked the cap after writing each message, so this run ended 422 bytes past 200,000,000. It now stops before the message that would pass the cap.

Conversion

python -m hftsim.bitstamp convert writes derived/events.csv and derived/snapshots.csv (formats in crates/data/src/l3.rs):

derived/convert.json records the counts above, the event stamps’ unit and whether ids rise with time.

The check

hftsim l3-check (data::l3) rebuilds the book from the events and compares it with every snapshot: the same ids, prices, amounts and priority order (price, then lower id) for the 100 listed orders per side. Three features of a real feed are handled explicitly:

  1. The opening book is unknown. When recording starts, the book is already full of orders, and the event stream mentions such an order only when it changes or leaves. Before each comparison a snapshot may therefore reveal orders the stream has not mentioned: listed ones are added, and revealed ones it no longer shows inside its listed range are retired. A snapshot never changes an order the stream has created, changed or deleted.
  2. Event stamps are coarse. Every order event’s “microsecond” timestamp is a whole millisecond (all 365,180 are multiples of 1,000), while snapshots carry true microseconds. An event stamped t happened in [t, t + 1 ms), so events stamped less than 1 ms before a snapshot cannot be ordered against it. The snapshot matches at its own time if the book equals it before, part-way through or after those events. This assumes stamps are truncated, not rounded. It is consistent with the data: no snapshot needed an event stamped after it.
  3. Snapshots can lag the order channel. A snapshot that matches no state at its own time is searched for among the book states within ±500 ms.
Class Meaning Snapshots
exact equals the rebuilt book at its own time, nothing revealed 976, 120 of them only within the 1 ms stamp
explained equals it after revealing orders placed before the recording 9
matched with offset equals the book at an earlier event boundary 151
unexplained none of these 0

Other counts:

Would it catch errors? A break test

python -m hftsim.bitstamp power breaks the converted events in one known way at a time and reruns the check against the unchanged snapshots. The target is the best-ranked order in the middle snapshot (#569) that the stream created, never changed and deleted more than 2 s later.

Break Unexplained snapshots Caught
none (control) 0 clean
the order’s deletion dropped 565, from #572 on yes
its amount +1 satoshi 4 yes
its price +1 cent 4 yes
its creation 1 s late 3 yes
its creation dropped 0, but it is revealed with an id above the first created id yes, by the id check
every event +600 ms 1,132 of 1,136 yes
every event −600 ms 1,114 of 1,136 yes

A dropped creation looks exactly like an order placed before the recording. Only the id check catches it, which is why that check exists.

What the data says about the feed

The replay fill model against real fills

python -m hftsim.bitstamp replay first writes the recording as a LOBSTER message file (to_lobster). As in LOBSTER, an order appears only for what of it rests:

The conversion reconciles exactly. Maker executions equal the trades channel to the satoshi (348 trades, 18.08 BTC). No resting order was cut, moved or enlarged, and every deletion’s remaining amount agrees with the fills before it.

Each trade is its own execution row. Two more files describe the takers LOBSTER leaves out:

Of the 235 takers, 156 filled completely, 77 were cancelled with a remainder (IOC) and 2 rested one (limit). That is 28.65 BTC left unfilled in all.

Leave-one-out. hftsim replay-truth replays each order submitted during the recording as a copy, with the same entry time, side, price and size, and compares the copy’s modelled fills with the order’s real ones:

This is the real-data counterpart of the probe check in §4: there the simulator knew the truth, here the exchange’s own fills are the truth. Left out: the 288 opening-book orders, and 9,309 orders gone within their entry millisecond (a copy joins after that millisecond, so it could never rest beside its original). 172,862 orders are compared; 298 of them really traded.

Two corrections came out of this check.

The taker-remainder rule (replay_passive_with) uses what Bitstamp publishes and LOBSTER does not: the taker’s own order. A taker that ends with volume unfilled at its limit had exhausted every resting order it could reach. A copy resting at a price within that limit, entered before the taker’s stamp and not cancelled within it, would therefore have received up to that volume.

The premise is checked per taker, on the book once the taker is done, and a taker that fails it gives the rule nothing. It must have no resting order left within its limit, and it must not be a fill-or-kill order (killed whole while liquidity rests). All 79 takers with a remainder passed.

Stream Rule Never filled → filled Earlier Overfilled Same ms Later Never Volume found
history minus the order queue + trade-through 0 0 0 97 102 99 22%
history minus the order + taker remainder 0 0 0 169 35 94 26%
history without the order queue + trade-through 0 0 0 196 87 15 32%
history without the order + taker remainder 0 0 0 292 1 5 99.6%

“Never filled → filled” counts the 172,564 orders that never traded. “Same ms / Later / Never” counts the 298 that did; “Earlier” and “Overfilled” are among them. “Volume found” is the model’s share of the 18.08 BTC really traded.

What this establishes, and what it does not

It establishes:

It does not establish:

7. Nasdaq ITCH 5.0: two real equity days

Nasdaq publishes sample days of its TotalView-ITCH feeds without an account. Its archive holds 11 days for BX, 11 for PSX and 7 for its main market, from 2019–2020. LOBSTER sells books rebuilt from the main market’s feed; this section reads that feed directly. Two venues were downloaded for the same date, 2019-12-30:

Both sizes matched the listing, and both files passed gzip’s CRC check. Nasdaq’s checksum files beside them could not be fetched (the server answers 404).

ITCH is the exchange’s own order-level feed: every add, execution, cancellation, deletion and replacement, with nanosecond timestamps. A day starts with an empty book, so no order is unknown. It names no taker: an execution names only the resting order.

Reading it

crates/data/src/itch.rs reads the binary file, in which each message is preceded by its length. The field layouts were written from memory of the ITCH 5.0 specification [M], because Nasdaq’s specification page could not be loaded. The data checks them in two ways:

Check BX Main market
Messages 29,156,757, of 15 types 268,744,780, of 18 types
Each type’s length against the layout all match all match
Unknown types; malformed messages 0; 0 0; 0
Order references never added; added twice 0; 0 0; 0
Messages whose stock differs from their order’s 0 0
Executions or cancellations larger than the order 0 0
Timestamps out of order 0 0
Crossed or locked books 0 33, each while the stock was halted, paused or quoting only
Orders left at the end of the day 0 0
Stocks in the directory; stocks traded 8,906; 5,533 8,906; 7,411
Orders added, replacements included 13,996,869 140,270,523

Cross-check. For each day’s 8 most-traded stocks, the day is also written in LOBSTER form and rebuilt by LOBSTER’s own rebuilder (§2), an independent implementation. Their best 10 levels agree after every book-changing message, with 0 mismatches: 1,608,422 messages on BX (GDX, SQQQ, EWZ, AMD, SPY, UVXY, INTC, NIO) and 8,461,699 on the main market (NIO, AAPL, SPY, AMD, TSLA, MSFT, SVRA, FB).

Auctions and non-printable executions

The main market opens and closes each stock with an auction (a cross); BX ran none that day.

What the code does with them:

Queue priority

Replay assumes price-time priority: at one price, orders fill in the order they arrived. The feed lets that be checked directly. For every execution at a displayed price, was the executed order the first in its level’s queue? Here a replacement counts as a new order.

BX.

The check now counts executions at a non-displayed price apart. An independent Python pass over the raw file reproduced the earlier counts exactly (581,525 executions, 1,244 apparent jumps) and produced the breakdown above. The exact order type is inferred: ITCH does not carry it, but the data matches the rule in every execution and contradicts it in none.

Main market.

So on both venues, priority followed price, then receipt. What first looked like queue jumps were two ways the order of display differs from the venue’s own: a better, hidden price, and an earlier receipt.

The replay fill model on equity orders

hftsim itch-check runs the leave-one-out check of §6 on each day’s 8 most-traded stocks. Because ITCH names no taker:

On the main market the check uses every 10th order (--every 10). Copies never interact, so a sample measures the same rates at a tenth of the cost.

Real outcome Model BX: all 801,154 orders Main market: every 10th, 439,219 orders
never filled not filled 710,970 412,189
never filled filled 0 0
filled first fill earlier 0 0
filled first fill in the same nanosecond 6,181 11,709
filled first fill later 82,041 (median 2.4 ms, p90 15 s) 13,434 (median 0.54 s, p90 19 s)
filled never filled 1,962 1,887

On neither day was a copy filled for more than its original traded. The model eventually filled 93% of the volume really traded on BX (5.64 of 6.04 million shares) and 94% on the main market (5.80 of 6.14 million).

What this establishes, and what it does not

It establishes:

It does not establish:

8. Not done yet

9. Commands

Write a simulated session as LOBSTER files:

hftsim lobster-export out/sim --levels 10 --seed 1 --secs 60 --mm 7 --informed 10

Rebuild a LOBSTER day and check it against its snapshots (the level count comes from the file name):

hftsim lobster-check AAPL_2012-06-21_34200000_57600000_message_10.csv AAPL_2012-06-21_34200000_57600000_orderbook_10.csv

Or every stock-day under a folder: message and order-book files are paired by name. A pair that fails does not stop the others. Files without a partner are listed.

hftsim lobster-check path/to/lobster-files

Check the replay fill model against the exchange in the simulator:

hftsim replay-check --probes 6 --probe-interval-ms 300 --probe-life-ms 3000 --seed 2026 --secs 120 --mm 7 --informed 10

The same three commands from Python, as hftsim.lobster.export, check and replay_check (standard library only; they call the binary and return the JSON as dicts).

Record Bitstamp data and check it (§6). Run Python with -I, as for any downloaded data. Each command writes its report under the run’s derived/ folder:

python -I -m hftsim.bitstamp record --minutes 30 --cap-mb 200 --out ../data/bitstamp/btcusd-run
python -I -m hftsim.bitstamp check ../data/bitstamp/btcusd-run      # converts first; check.json
python -I -m hftsim.bitstamp power ../data/bitstamp/btcusd-run      # break test; power.json
python -I -m hftsim.bitstamp crossings ../data/bitstamp/btcusd-run  # crossings.json
python -I -m hftsim.bitstamp replay ../data/bitstamp/btcusd-run     # fills vs model; replay.json

replay writes lobster_message.csv. Any LOBSTER message file can be checked the same way, with orders submitted before --from-seconds treated as its opening book:

hftsim replay-truth derived/lobster_message.csv --from-seconds 4783.581000

Check an ITCH day (§7): decompress it, read every stock’s book, cross-check the most-traded stocks against LOBSTER’s rebuild and run the replay check on them. About 3 minutes for the BX day; the report lands in derived/itch_check.json beside the file:

python -I -m hftsim.itch check ../data/itch/20191230-bx/20191230.BX_ITCH_50.gz --replay 8

The main-market day, with every 10th order in the all-orders replay check (about 17 minutes; progress goes to stderr):

python -I -m hftsim.itch check ../data/itch/20191230-nasdaq/12302019.NASDAQ_ITCH50.gz --replay 8 --every 10

Only the checks, without the replay (--replay 0 skips the second pass):

hftsim itch-check 12302019.NASDAQ_ITCH50 --replay 0

Or chosen stocks, on the decompressed file:

hftsim itch-check 20191230.BX_ITCH_50 --symbols SPY,AMD --sample 200

check converts again whenever the raw files are newer than the converted ones or the converter has changed. The binary also runs directly on converted files:

hftsim l3-check derived/events.csv derived/snapshots.csv --depth 100 --tolerance-us 500000 --event-stamp-us 1000