Driving Kalshi Simulator State Forward With Scripted Market Event Sequences

Named, deterministic scripts let you test Kalshi bots without production risk.

· 8 min read
Cover illustration for “Driving Kalshi Simulator State Forward With Scripted Market Event Sequences”
Kalshi API Integration · November 23, 2026 · 8 min read · 1,768 words

Integration testing against stateful APIs needs a local simulator that remembers mutations and uses the state they leave behind to handle later calls. For Kalshi, scripted market event sequences drive that simulator through reproducible order-book changes, price movements, and settlement transitions without hitting production. The official demo checks that authentication and order flow work, while continuous fidelity verification keeps local tests tied to the real exchange.

What Kalshi's demo environment actually tests and what it cannot

Kalshi's demo environment supports checks of RSA-PSS and Ed25519 request signing, order creation, amendment, and cancellation. It also provides a setting for testing WebSocket subscriptions, reconnect logic, and exponential-backoff retry paths. Demo credentials are separate from production credentials, so the environment provides an isolated place to exercise that plumbing without trading against production.

That isolation does not make market conditions controllable. Kalshi's documentation warns that demo prices and market behaviour may differ from those in real markets. A strategy that fills cleanly there has not established how it handles realistic order-book depth, fill probability at a given price, or mid-price movement. Nor can a developer prescribe repeatable settlement transitions in a shared live sandbox. This boundary follows from the environment's purpose, rather than a defect in Kalshi's implementation, and applies to third-party staging environments generally.

Why stateless mocks cannot test APIs where order of operations matters

An order placed in one call must appear in a subsequent portfolio query, positions must update on fill, and balance must reflect the session history. A limit order placed at the next tick is at the market, behind it, or crossing it depending on order-book depth at the preceding tick. The sequence is part of the test input. A stateless HTTP mock returns a canned response to each call on its own, so its behaviour cannot show how these calls affect one another.

Kalshi's price-time-priority matching engine makes that distinction concrete. The exchange maintains a live order book and streams WebSocket events that reflect changes to it. A fixed snapshot can test whether the bot parses a book, but not whether its orders interact correctly with an evolving one. Manually arranging later responses does not resolve the underlying limitation. The test has supplied the expected outcome rather than exercised the state transition that should produce it.

Cassette replay offers determinism, but only along a recorded trajectory. It cannot branch on the bot's decisions or generate a fill when one of the bot's resting orders meets a crossing order. Replay therefore differs from both stateless mocks and stateful simulation. The required alternative maintains a live book, executes matching, emits events from evolving state, and remembers mutations across the session. Later responses then follow from what actually happened during the test.

How a local Kalshi simulator covers the full API surface the demo exposes

A credible local stand-in must serve the same REST Trade API v2, WebSocket, and FIX surface as the demo. Protocol breadth is a prerequisite for replacement. REST requests cannot be treated separately from the orderbook deltas, ticker updates, trades, and fills delivered over WebSocket. Kalshi's WebSocket documentation requires API-key authentication for every connection, including connections used only for public market data. A simulator that omits that requirement would test a different connection contract.

FIX adds another layer of shared behaviour. Kalshi's FIX gateway uses FIXT.1.1 transport with application version FIX50SP2 over TLS 1.2+, with separate hosts and ports for order entry and market data. It allows one connection per API key and draws from the same rate-limit token buckets as REST. The simulator must enforce the token-cost system, from Basic through Prestige tiers, for tests of 429 handling to be meaningful.

CreateOrder V2 uses POST /portfolio/events/orders, with fixed-point dollar-string prices and sizes, while the disabled legacy mutation endpoints return HTTP 410. Cancels must include market_ticker to reach the correct exchange shard. Together, they show why realistic simulation requires more than a matching engine and why API fidelity needs continuing verification.

What a scripted market event sequence is and how it drives the simulator's state machine

A scripted market event sequence is a named, deterministic program that advances a simulator through defined changes in order-book depth, prices, and market lifecycle. It supplies a known starting state and drives transitions from there. The scenario is the environment program. The bot is the agent running inside it, placing orders whose effects the simulator processes.

The script controls market conditions, while the matching engine handles the bot's actual orders and changes state to reflect them. Repeating the same script with the same bot behaviour produces the same progression, fills, and WebSocket event order. Changing the bot's decisions can change their consequences.

A scenario identifier in test output, CI logs, or an issue report connects a failure to the environment that produced it. For example, market_unopened seeds an initialized market where orders return 409 to test pre-open handling. The underwater scenario starts with a batch of YES contracts bought at 0.70 against a 0.25 book, exposing drawdown and kill-switch behaviour. Meanwhile, has_history combines a live book with a settled archive behind a real cutoff. Each name identifies a recognizable condition instead of an arbitrary accumulation of earlier test artifacts.

Fault scenarios as a first-class category of scripted sequences

Fault scenarios use the same mechanism to drive degraded conditions. This makes resilience testable within the strategy harness. The degrades_mid_run scenario alternates a clean period, a total 429 storm, and recovery, testing whether backoff logic resumes correctly after disruption. By contrast, rate_limited gives every request a meaningful chance of returning 429 without a Retry-After header. Kalshi's documented live behaviour omits that header, so a bot that waits for it before backing off will continue hammering the endpoint.

Response handling needs tests beyond rate limiting. The edge_5xx scenario returns 502 responses with HTML error pages for a portion of requests, revealing whether the error handler checks content type or assumes JSON. The flaky_500 scenario returns 500 for a fraction of requests, testing whether retries are idempotent or double-place orders. Successful JSON parsing on ordinary responses says little about either one.

Other faults distinguish temporary disruption from a reason to stop trading. In exchange_halted, orders return 409, testing whether the bot recognizes the halt and backs off. In forbidden_403, reads succeed while order writes return 403, testing whether trading stops without corrupting position tracking. The flash_crash scenario instead moves the mid-price sharply downward and partially recovers within seconds, exercising risk controls during rapid dislocation. Together, these named conditions make resilience reproducible rather than leaving its first assessment to production.

Seeding and advancing historical state for backtesting and the has_history scenario

Forward progression does not automatically create the historical fixture a backtest needs. Scenario scripts move state forward, while historical seeds supply the state from before the run. Both require explicit authorship. The has_history scenario supplies a live book and a settled archive behind a real cutoff, exercising /historical/* paths that return 404 or empty results in other scenarios. Its predefined archive limits those path tests to the history it supplies.

For strategy backtesting, developers must seed the historical registers by hand before the run. Subsequent /historical/* requests then return the seeded data. The fixture determines what history the test actually covers. Automated fidelity checks can only measure what was seeded, so a misconfigured archive can produce passing tests against the wrong conditions. The practical response is to author historical seeds with scenario scripts, keep them in version control, and review them as test data.

Structuring a CI pipeline around named Kalshi scenarios

Diagram: Three-Tier CI Pipeline for Kalshi Scenarios. Visualizes: Show a three-tier CI pipeline as a stepped flow or ranked layers.

The recommended pipeline starts with Tier 1 unit tests that check tool binding and output parsing against a known simulator state. These make no external calls, run in milliseconds, and gate every commit. Tier 2 runs the bot end-to-end through the market lifecycle and fault scenarios, gating every pull request. Each failure is attached to a defined condition rather than whatever market state a shared sandbox happened to expose.

Tier 3 retains the demo for its narrower role. It checks RSA/Ed25519 signing, the order lifecycle, and WebSocket reconnection on merge to main rather than on every pull request, because it is slower and requires real credentials. The pull-request gate therefore uses only the first two tiers. Every tool call goes to the local simulator, with no external API calls, demo credentials, or exposure to hosted rate limits. Tests can still use simulated rate limits to check how the bot handles them.

Schema-lock tests complement behavioural scenarios at the simulator boundary. They catch changes to required fields or moves to endpoints before those changes show up as hard-to-explain bot regressions. The changes to legacy mutation endpoints in June 2026 show why tests need to cover this boundary. A schema failure identifies a contract mismatch directly. Without that distinction, a changed request contract can cause a fill anomaly later in a run that seems unrelated.

The same architecture applies to AI agents that call Kalshi as a tool. Their tool calls go to the simulator, and its stateful responses inform the next decision. Assertions can cover the resulting trajectory, including which tools were called, in what order, and with what parameters. Order becomes an explicit part of correctness. The test can therefore examine a sequence of decisions against evolving state rather than only the shape of individual tool responses.

Fidelity verification as the mechanism that keeps scripted scenarios honest over time

Deterministic tests can remain green while their simulator drifts from the exchange. Reproducibility alone cannot detect a stale API model. The recommended verification architecture checks the simulator against the live Kalshi API before every release and publishes a fidelity score showing the fraction of the API surface handled correctly. A dated verification establishes only a point-in-time result. As the API keeps changing, it needs fresh comparisons even if the simulator was compatible at launch.

The check set determines what that score means. A high result across a narrow collection of happy-path endpoints can omit fault behaviour, historical endpoints, FIX-layer rate-limit enforcement, and WebSocket event ordering. Continuous verification still measures only what it checks. The response is to expand the check set progressively and publish its count with the score, treating fidelity as a coverage metric.

For teams depending on the simulator, the practical lesson is to track its fidelity score and check count as dependency metrics, much like test coverage. A score drop or a gap in the check set is a defect to address. Scripted sequences provide deterministic control over market state. Continuous fidelity verification establishes whether that controlled state still corresponds to the real exchange. Without both, integration tests face either an unpredictable environment or a perfectly controlled fictional one.

More in Kalshi API Integration