Seeding Kalshi Backtest Runs With Recorded API Fixtures for Deterministic Strategy Validation
Recorded fixtures and a stateful simulator make Kalshi backtests reproducible.

Testing a Kalshi bot before going live requires recorded API fixtures and a stateful simulator. Fixtures lock market data, order book depth, and settlement values into replayable artifacts, while the simulator tracks orders, fills, fees, and positions. Together, they make strategy results reproducible and comparable, provided replay enforces point-in-time access and fresh captures expose drift.
Why Kalshi backtests are structurally harder to make deterministic than traditional financial backtests
Kalshi splits its API data between live and historical namespaces, with a boundary that moves independently for different records. The cutoff endpoint returns four timestamp fields, which are market_settled_ts, trades_created_ts, orders_updated_ts, and market_positions_last_updated_ts. They do not advance together. A backtest therefore cannot use one fixed historical date to route every request, even when all the requests are for the same trading period.
On 8 October 2026, the orders cutoff sat roughly two weeks back, while the market and trades cutoffs sat roughly two months back. A query crossing those boundaries on different days can silently return different result sets. The strategy code need not change at all. Its apparent performance can change simply because the same request no longer reaches the same records.
The namespaces also disagree about field names. The live endpoint uses price.close_dollars, while the historical endpoint uses price.close for the same number. A merge that expects only one field can introduce gaps without an obvious request failure. These are data-routing and schema problems before they are modelling problems, and they distinguish Kalshi validation from a backtest built around a fixed historical price series.
What does testing a Kalshi bot deterministically actually require?
A deterministic Kalshi backtest must reconstruct the market state available at each decision moment without consulting an endpoint whose contents may have shifted. Its access rule is context = data_available_strictly_before(t). Decisions must have no access to settlement information from the future. The same rule holds for candle fields, book observations, and other inputs used to choose an order or set its size.
Three core artifacts must be locked. Market metadata includes the ticker, title, question, strike, open and close timestamps, and resolution source. Price time series include candlestick OHLC and yes_bid/yes_ask per interval. The final yes/no settlement outcome supplies the ground truth for scoring, but not an input the strategy may inspect before resolution.
Execution requires more than the last printed price. A strategy cannot assume a full fill when the available book contains only a fraction of its required size. DepthFeed captures every level on both sides at every change, while Kalshi BackTest provides L2 snapshots at 100ms resolution with 100 depth levels per side.
Fee inputs must be fixed as well. The kalshi_backtest taker fee model uses ceil_cent(M·0.07·C·P·(1−P)) per leg/order, with a series-specific multiplier M that defaults to 1. Omitting fees tests a different strategy. Finally, the recorded universe must include markets that resolved against the thesis, because reproducibly excluding losing markets is still survivorship bias.
How recording API fixtures solves the moving-boundary problem
The VCR-style pattern records real API responses once, then replays them in later runs without network access. Each fixture contains the raw response and metadata identifying the conditions under which it was generated. The response becomes a stable test input. A later cutoff movement cannot relocate data inside that artifact or change the field names it contains.
This stability preserves evidence as captured. Capture must query the live and historical paths in one sweep, merge their results, and deduplicate candles on ticker plus candle-end timestamp. A market closing just before the cutoff can appear in both paths. When duplicate records overlap, capture must fail if their raw payloads are not byte-identical after canonicalization, so that it cannot quietly choose one version.
The same distinction applies to dataset completeness. Recording must cover the full market universe before strategy filtering, because replay cannot recover markets that were excluded at capture time. A fixture containing only survivors embeds lookahead bias permanently. Likewise, a recorded final settlement value prevents later scoring from accidentally substituting a newly fetched pre-settlement state.
Fixtures therefore move the uncertainty into a controlled capture step. They preserve the received schema, the selected universe, and the available settlement evidence even after a ticker crosses the historical cutoff or is delisted. Correct capture remains a prerequisite.
Structuring fixture capture for Kalshi: what to record, at what granularity, and how to scrub it
The capture procedure should begin with GET /historical/cutoff and store all four timestamp fields in the fixture manifest. No cutoff date should be hardcoded. Each query should use the field appropriate to its record type, with the live path above the cutoff and the historical path below it. Windows that straddle the boundary require merging and candle deduplication before commit.
For each market, capture should retain the metadata needed to interpret the contract, including its underlying question, strike or threshold, trading timestamps, and resolution source. Candles should have OHLC plus the open, high, low, and close for yes_bid/yes_ask in each interval. Trade prints add execution price, size, and timestamp for slippage and liquidity analysis. The settlement record completes the scoring data.
Book capture needs a separate availability decision. The /markets/{t}/orderbook endpoint is a live-only snapshot, with no historical equivalent. Full bid/ask ladders therefore need to be recorded as they are observed, with the size at every level and timestamps at 100ms resolution where available. Kalshi BackTest provides that L2 depth across BTC, ETH, SOL, DOGE and XRP markets.
Before commit, API keys and authentication tokens must be masked. CI should scan committed fixtures with a secrets-masker regex and fail on secret-shaped strings. Fetch timestamps and pagination cursors that legitimately vary should become documented stable-substitutions in the manifest. A max_age_days threshold should also set when entries need a refresh, which must happen through explicit capture and without an unexpected network call during CI replay.
Why a stateful simulator is required to replay Kalshi fixtures correctly
A recorded book snapshot is sufficient for testing a pricing formula in isolation. It is not sufficient for validating an order lifecycle. A Kalshi strategy may place an order, receive a partial fill, cancel the remainder, and then query its position. Those calls depend on changes made by earlier calls, so replay needs a persistent world.
The simulator must distinguish orders from filled positions. Cancelling an unfilled remainder does not erase the position created by the fill. Open positions and their fill histories must remain retrievable, resting orders must reflect their partial-fill status, and account balances must include fee adjustments. Settlement events must then close the positions in the markets that have settled. Returning the same response on every GET /orders/42 cannot express that sequence.
Statefulness alone does not establish instrument fidelity. A 2026 preprint on agentic compliance reported silently incorrect sandbox results involving ignored query syntax, misspelled fields, uniform portfolio figures, and generation-order record storage. The figures looked right and hid the errors. That finding concerns instrument validity and illustrates why credible-looking responses are an inadequate test of simulator correctness.
Most checks should be stateless. Pricing formulas, fee calculations, and single-candle signal logic do not require a persistent account world. Complex order and position workflows do. Those stateful scenarios should use isolated data and run serially so one scenario cannot alter the starting conditions of another.
Running seeded backtests in CI: the record-once, replay-always pattern for Kalshi pipelines
The pipeline begins with an infrequent local recording run using --record-fixtures. That run calls the real API, stores scrubbed responses, and updates the manifest with the cutoff timestamps used. Network access belongs in this explicit capture mode. The local auto setting must not bypass that gate, while CI selects replay through mode = "replay" if os.environ.get("CI") else "auto".
Every commit then runs the strategy against the simulator serving committed fixtures. Results are compared with a committed baseline, and divergence fails the build. CI makes no live API calls. This removes dependence on trading endpoint limits, which vary by key and tier, and avoids placing live API credentials in runners.
Point-in-time access must be enforced by the replay layer. The simulator should serve only data whose timestamp precedes the current decision moment. An early request for a settlement value must return a miss. Without that rule, even a fixture that never changes can give the strategy knowledge of the future and bias the results on every run.
A scheduled capture supplies fresh fixtures for a separate schema comparison against the committed baseline. Field renames or type changes can fail a plain pytest check without Docker or a live connection during that comparison. Fault-injection scenarios should also test what happens with latency, rate-limit responses, and service-unavailable errors. These tests examine whether order management degrades gracefully instead of relying on clean fills throughout the run.
The drift and fidelity problem: what happens when fixtures go stale or the simulator diverges from the real API
Fixed inputs make results repeatable, but repeatability does not establish continued fidelity to the exchange. With schema drift, fixtures can keep serving an old field name or type even as every test passes. Kalshi's live and historical naming asymmetry demonstrates why schema assumptions deserve explicit checks.
Handwritten responses introduce a related risk because their accuracy depends on the person who wrote them. Stripe documentation describes stripe-mock as spec-derived and stateless, suitable for basic sanity checks, with regression suites outside its scope. Even a stateful simulator can drift behaviorally through differences in edge-case 4xx responses or partial-fill rounding that a schema check does not detect.
Under the prescribed verification rule, new payloads must match committed payloads byte-for-byte after canonicalization, or capture fails with a diff. Legitimately variable bytes require documented stable-substitutions. Changed market observations or API behavior require review.
Fixture expiry adds a freshness constraint to this process. Entries beyond max_age_days become misses that require explicit recapture, while offline CI remains unable to refresh them silently. This prevents an ageing dataset from masquerading as current market structure. The strongest basis for trusting the simulator is continued comparison with real API behavior.
Putting it together: a complete fixture-seeded Kalshi backtest workflow
The capture phase establishes the evidence set. It reads the four cutoffs, routes requests across both namespaces, records the full market universe and available depth, merges overlapping candles, and commits scrubbed fixtures with their manifest so boundary gaps and survivorship are addressed before testing.
The seeding phase establishes the simulated world. It loads the recorded market observations into an isolated stateful environment that tracks resting orders, fills, positions, fees, and settlement, preventing a sequence of strategy actions from collapsing into unrelated HTTP responses.
The backtest phase executes the strategy in mode = "replay". Timestamp-gated access prevents settlement lookahead, while recorded liquidity and fill prices support execution and fee modelling.
The CI phase makes that run repeatable for every commit. It compares results with the baseline, checks fixture schema, and runs fault scenarios without API keys or live network calls, so changes in the external data service stay separate from strategy changes.
The drift-detection phase governs when the evidence changes. Scheduled capture, canonicalized diffs, and fixture expiry send divergence for review before refreshed artifacts replace the baseline, preserving a clear distinction between performance changes caused by strategy code and those caused by new data or exchange behavior.


