Composing a Kalshi Bot Simulation Stack From Recorded Orderbook Snapshots and Deterministic Fill Models
Replaying validated orderbook sequences makes Kalshi backtests trustworthy.

Testing a Kalshi bot requires a locally hosted, stateful simulation stack that replays validated orderbook sequences through a deterministic fill model. Recorded snapshots are not isolated price samples, because simulated execution depends on the book’s cumulative integrity. Backtesting that can be trusted therefore needs sequence validation, clear assumptions about execution, and an API layer that tests the bot without live credentials or rate limits.
Why Kalshi's orderbook data model resists naive replay
Kalshi returns only bids, with no conventional bid/ask pair. The yes_dollars and no_dollars arrays are sorted low to high, placing the best bid last. A no-bid implies a yes-offer at its complement because yes and no prices sum to a dollar by construction, although displayed quotes can differ because of the spread. Replay must reconstruct those implied offers before calculating spread, available depth, or fills.
Price precision is a separate recording constraint. Integer-cent fields have been removed, and sub-cent markets require the native _dollars strings. Tapered markets use finer ticks outside their outer price thresholds and coarser ticks between them, while combo markets can tick in hundredths of a cent near the edges. Quantities also require exact representation. Fills can be fractional even when whole contracts were ordered, so quantities belong in hundredths or Decimal.
Kalshi organizes contracts as series, events, and markets, but a market within a multivariate combo collection needs creation through its own endpoint before lookup or trading. The recording implication is direct.
Recording a snapshot sequence that is worth replaying
A replayable sequence preserves complete book state in temporal order, including decision moments between trades. KalshiBackTest documents a reference design that streams full snapshots at sub-second intervals from market open through settlement across five deployments, namely btc, eth, sol, doge, and xrp. Its REST API provides L2 depth, queries by ticker and timestamp, a /snapshots/at/{timestamp} endpoint, and paginated bulk pulls with ?limit=500. Availability is a separate question from design quality. The service has closed new signups, purchases, and plan changes, while existing paid access lasts until the current billing period ends and subscriptions will not renew.
For a new recorder, REST polling would use up the token budget to capture data at similar sub-second intervals. The appropriate division is REST for bootstrap snapshots and WebSocket for the delta stream. Recording should keep native yes/no price and size fields without lossy conversion, and keep raw _dollars strings alongside any form derived from them. Each snapshot also needs an independent observation timestamp. Settlement and resolution fields must remain separate from what was knowable at that observation time.
Capture interruptions belong in the recorded sequence’s validity metadata. A 429 during capture leaves a hole that invalidates fills in the affected window, while Thursday maintenance from 3:00 to 5:00 a.m. creates a forced interruption. Neither can be silently swallowed. Before the sequence reaches the fill model, a validity pass must check timestamp monotonicity, find gaps longer than the expected capture interval, and flag rows that have resolution data at pre-settlement timestamps. That last check protects the simulation from learning an outcome before the bot could have known it.
Handling delta gaps and the reconnection problem
A skipped delta sequence number invalidates the accumulated local book. Kalshi does not expose a delta replay endpoint, so the missing mutations cannot be recovered by requesting them again. The correct response is to discard the invalid local state and obtain a fresh authoritative snapshot before allowing fills to resume. Recorded gaps also cannot be filled through interpolation, so fills during those gaps must be skipped or flagged.
The initial orderbook_snapshot establishes mutable state, and each subsequent delta changes that state in sequence order. A delta is not a replacement snapshot. Sam Marriott’s SSRN paper, Reconstructing Full Limit Order Books for Kalshi from WebSocket Streams, documents implementation challenges in KDB+/q that required non-standard reconstruction patterns.
This protocol requirement becomes a contract between reconstruction and execution. The fill model must stop using a book when its sequence continuity fails, even if the last prices it showed still look plausible. Recovery is therefore a testable trading behavior. A synthetic gap should make the bot halt fills, reconnect, and wait for a fresh snapshot before resuming.

Choosing a fill model that respects book depth and the queue position limit
Mid-fill is the most optimistic execution model. Filling at the snapshot midpoint can bound best-case strategy performance, but it does not establish that the bot could have executed there. Maker/taker simulation is more demanding because it respects available size at each price level and applies the relevant fees. PredictionMarketBench uses deterministic replay of orderbooks, trades, and settlement with maker/taker semantics and fee modeling.
Trade-tape execution is a third way to test strategies that have no need for depth or queue position. PredictionMarketBench and AlphaOpsBench, identified as arXiv 2609.31390, approach each order by scanning only its causal interval in historical trade prints indexed by market and token. The choice depends on the strategy’s information requirements. A strategy concerned only with whether a price printed does not require a depth model, while one that sizes into the book does. Greater complexity is useful only when it represents a constraint the strategy encounters.
Snapshots show displayed size, leaving the simulated order’s queue position and any depletion by an unrecorded intervening fill unknown. “Would have filled if queue position was favorable” is a valid conditional result, whereas a claimed full fill exceeding recorded available size is not. Capacity beyond visibly depleted liquidity is modeled liquidity and must never be reported as an observed fill.
Point-in-time discipline also governs every signal consumed by the model. The model must keep future book states, later trade prints, and resolution labels out of an earlier decision step. For PredictionMarketBench, reproducibility means using the same episode files, simulator configuration, and agent code with fixed seeds. Reproducibility alone, however, does not establish causal validity. A leaked resolution label can make a result repeatable while still making it an invalid backtest. Recorder validation therefore precedes execution modeling.
Wiring the layers into a locally hosted, stateful simulation stack
The runtime architecture needs a snapshot replayer, a fill model, and a stateful API layer. The replayer advances a cursor through the validated sequence and emits book states at their simulated timestamps. Gaps interrupt execution, leaving intermediate states unmodeled. The fill model receives intended orders and evaluates them against the current valid state, returning fills or rejections under the selected assumptions. The API layer exposes that accumulated simulation state through the endpoint surface the bot already calls.
That surface includes GET /markets/{ticker}/orderbook, order placement, fill retrieval, and portfolio queries. Writes must change subsequent reads. An order placed at step N must be reflected in balance and position queries at step N+1, while partial fills must update the depth exposed by the model at the next snapshot. A fixed-response stub cannot represent depleted liquidity, partial execution, or the margin checks following a large position. Its limitations become especially consequential when one order changes the conditions for the next.
Contract counts use strings with up to two decimals in _fp fields, including "10.00", while prices use _dollars strings and orderbooks return two ascending bid arrays without asks. Simplifying those conventions removes precisely the parsing and arithmetic behavior the test needs to exercise. The API layer makes the architecture an integration test. Its value lies in exercising order placement, portfolio reconciliation, and rate-limit handling as well as fills, because testing execution logic alone does not test the bot’s full call graph.
Fault injection scenarios specific to a Kalshi bot simulation stack
Fault injection belongs in the simulation design from the start. The worst failures happen when a connection drops and leaves the trading state unclear, especially when the bot cannot tell whether an order landed before the connection dropped. Correct prices do not resolve that ambiguity. The simulator therefore needs configurable failures at specific sequence steps, with assertions about the bot’s response. This is what separates an adversarial simulation stack from a recording playback tool.
A skipped sequence number should make the bot halt fills, reconnect with a fresh get_snapshot request, and avoid acting on stale local state for the whole gap. A separate write-bucket test should return HTTP 429 when the bot places an order. The expected response is exponential backoff without double-submission, followed by correct resumption when the budget refills. Deduplication through client_order_id belongs in the order-submission behavior under test, rather than relying on a successful retry alone as evidence of correctness.
The maintenance test should advance the simulated clock through Thursday from 3:00 to 5:00 a.m. and return appropriate errors. The bot should queue or skip requests while the endpoint is unavailable. A tapered-market test addresses a different boundary. It should inject a snapshot whose best bid crosses below the threshold for the sub-cent tick regime, then assert that price rounding and order sizing retain the full precision of the _dollars value.
Running the simulation stack in CI without live credentials
A CI pipeline that depends on live exchange calls cannot provide a controlled regression test. Thursday maintenance, token-budget exhaustion from parallel jobs, and changing live conditions introduce failures unrelated to the bot’s logic. The demo environment is a sandboxed live environment. The recommended separation is a local simulation stage with no external network calls and a less frequent integration stage that validates authentication and order placement against the live demo environment.
The local stage should run the bot’s full call graph with fixed inputs. The same recorded sequence, fill configuration, and fixed seeds in decision logic should produce the same fills, portfolio state, and fault responses. Differences then become useful evidence of changed behavior. Across bot versions, a fill difference on a known sequence can reveal how a strategy change altered its interaction with the book, rather than reflecting unrelated movement on the exchange.
The simulator itself still needs ongoing verification. Kalshi’s API changes described in the brief include replacement of integer-cent fields with _dollars strings, a token-bucket rate-limit model across seven tiers, Ed25519 becoming the default key type as of October 1, 2026, and the get_snapshot reconnection action added in April 2026. Tests against an out-of-date simulator could keep passing through these changes because both sides of the test still expect the old contract. A check each night or with each release should therefore compare the simulator’s response shapes with the live API’s current contract. Recorded-sequence integrity and API fidelity are continuing commitments, and without both, a reproducible simulation can become a reproducible source of false confidence.
Sources
- Reconstructing Full Limit Order Books for Kalshi from WebSocket Streams by Sam Marriott :: SSRN
- PredictionMarketBench: A SWE-bench-Style Framework for ...
- Kalshi BackTest - Historical Order Book Data & Backtesting API for Kalshi Crypto Markets
- Introduction - KalshiBackTest
- PredictionMarketBench: A SWE-bench-Style Framework for Backtesting Trading Agents on Prediction Markets


