betting_combat.store.orderbook
Kalshi order-book history in betting.betting_combat: what the card run’s recorder
(trading/book_recorder.py) saw on the orderbook_delta channel, kept so the book of
any recorded market can be rebuilt at any instant (Kalshi keeps no book history).
Three tables (sql/betting_combat_data.sql):
kalshi_orderbook_streams— one row per exchange subscription (“stream”). Kalshi numbers a subscription’s messages 1, 2, 3 … (seq) and starts again with every new subscription, sostream_id(ours, random 63-bit) scopes everyseq.complete_through: every message of the stream received up to this instant is recorded (no gap, nothing dropped); the stream’s books are known only up to it.kalshi_orderbook_snapshots— one row per snapshot message (a book reset), also when the book is empty (no level rows then).kalshi_orderbook— one row per snapshot level (kind = 'snapshot',size= the resting contracts) and per delta (kind = 'delta',size= the signed change). Key(ticker, stream_id, seq, side, price): a re-write is a no-op.
The book of ticker at t: the last snapshot received at or before t; its levels;
then that stream’s deltas with a higher seq received at or before t, in seq
order. It is known only when t <= complete_through of that stream (book_at).
Classes
BookReplayError
Bases: ValueError
The recorded deltas do not fit the snapshot (a level went negative).
DeltaRecord
One orderbook_delta message: one level of one market changed by delta.
OrderBookStore
book_at
book_at(ticker: str, at: dt.datetime) -> RecordedBook | Noneticker’s recorded book at at; None when the recording does not know it
(no snapshot yet, or at is past its stream’s complete_through).
ready
ready() -> boolTrue when the three tables exist (sql/betting_combat_data.sql was run).
write
write(records: Sequence[BookRecord], streams: Sequence[StreamRecord]) -> WriteCountEverything in ONE transaction: the levels and deltas, the snapshot headers and
the streams’ state (complete_through never claims rows that are not written).
Idempotent: rows already recorded are left as they are.
RecordedBook
A market’s resting bids at one instant, rebuilt from the recording.
SnapshotRecord
One orderbook_snapshot message: the whole book of one market.
StreamRecord
One exchange subscription as it stands (re-written whole on every change).
row
row() -> dict[str, Any]WriteCount
Functions
replay_book
replay_book(levels: Iterable[tuple[str, Decimal, Decimal]], deltas: Iterable[tuple[str, Decimal, Decimal]]) -> tuple[dict[Decimal, Decimal], dict[Decimal, Decimal]](yes, no) bids: the snapshot levels then deltas in seq order, each
(side, price, contracts or change). Empty levels are dropped; a negative one raises.
unnest_insert
unnest_insert(table: str, columns: Sequence[str], types: Sequence[str], key: Sequence[str]) -> sql.ComposedINSERT ... SELECT * FROM unnest(<one array per column>) ON CONFLICT (key) DO NOTHING: one statement, one round trip, for any number of rows.