Wiring the Kalshi Demo Environment as a Persistent Stateful Fixture in Your Test Suite
A local stateful simulator beats the demo for repeatable Kalshi order tests.

Integration testing against stateful APIs requires a persistent, resettable fixture whose responses reflect earlier calls. For Kalshi, that means testing creation, retrieval, partial fills, and cancellation as one connected workflow. A local stateful simulator provides that continuity without live credentials or hosted rate limits, while the demo remains useful for checking authentic API behavior.
What the Kalshi demo environment actually is and what it cannot do alone
The Kalshi demo environment has authentic API behavior but uses mock funds kept separate from production funds. It is not a production stand-in. Demo keys authenticate only against demo endpoints, while production keys authenticate only against production endpoints. A client configured with the wrong host therefore has an environment mismatch. The separation protects production funds, but it does not make test conditions reproducible.
The demo account guide says new accounts are not preloaded with funds and distinguishes submitting an order from proving a fill. Demo liquidity, fill rates, and book depth can also differ from production, so an accepted order does not establish how reconciliation will behave. Prices arrive as dollar strings and contract counts as fixed-point strings, making numeric parsing another source of errors that may surface only as arithmetic accumulates.
Why one-off smoke tests against the demo fail to validate real trading workflows
An order submission proves only the first transition. The client must then retrieve the resting order, observe a full or partial fill, and cancel the remainder or wait for settlement. Each step depends on the state left by the previous one. A test that checks only the creation response cannot establish whether the later retrieval refers to that order or whether the client reconciles its changing quantities.
Partial fills expose the gap most clearly. An order can be neither untouched nor complete, and the client must account for both the filled quantity and the remaining open quantity. Responses to separate calls can show those states without proving that the application links them correctly. Meanwhile, a manual smoke test leaves its orders behind, so the next run inherits conditions that may change its result.
What a persistent stateful fixture is and why the distinction matters
A persistent stateful fixture is a long-lived, resettable test double whose responses follow from accumulated state. Its memory spans the whole test workflow. For Kalshi, POST /portfolio/events/orders creates an order, retrieval by its ID returns that order, a fill changes its quantities, and cancellation changes its status. A subsequent retrieval must reflect the cancellation.
A hardcoded retrieval response can succeed even if the order was never created, while a one-off demo session has real behavior but no documented way to reset it to a clean slate. The fixture combines continuity within a case with isolation between cases. Its process starts once for the suite, its state resets before each case, and teardown ends the process after the suite finishes.
The 2026 Kalshi API surface a fixture must cover
The Predictions surface includes keyless market discovery through GET /series, GET /events, GET /markets, GET /markets/{ticker}/orderbook, and GET /markets/trades. These calls do not require authentication. A fixture that demands tokens for them models the wrong boundary. Authenticated order operations, WebSocket streaming, and token-cost rate limiting each need their own tests, while perpetual futures on margin are part of the separate Perps API family that this article does not cover.
The 2026 API guide specifies CreateOrder V2 at POST /portfolio/events/orders, with side set to bid or ask and prices supplied as dollar strings. It dates removal of the legacy /portfolio/orders mutation endpoints to June 2026. Cancellation must include market_ticker for exchange-shard routing. The guide recommends Ed25519 authentication with 64-byte signatures and requires SDK 3.31.0 or later for it, while also supporting RSA-PSS.
The April 2026 rate-limit model uses token buckets, and most requests have a fixed token cost. Exhaustion must produce an error. Basic has a lower per-second read/write allowance, while Advanced is a free self-upgrade through POST /account/api_usage_level/upgrade after a qualifying number of recent prediction-market orders were placed through the API. These rules define behavior a fixture must represent, even when no hosted quota constrains the test runner.
Why wiring against the live demo in CI is the wrong default
The demo remains useful for manual verification and first-pass authentication checks. CI needs a different kind of dependency. Parallel jobs sharing one demo account can see each other’s orders, and the demo has no documented endpoint that restores a clean slate after a failed run. Assertions about counts or order state can therefore depend on another job’s activity.
Hosted availability adds another source of ambiguity. A missing market ticker, an unreachable endpoint, or token-bucket exhaustion can fail a build without exposing an application defect. Unplanned 429 responses are especially different from deliberately injected rate-limit tests because their timing is uncontrolled. Direct demo access also blocks execution when network restrictions prevent reaching the endpoint, making it the wrong default for repeatable automated workflows.
Using the Rystic Kalshi simulator as the persistent stateful fixture
The locally hosted simulator keeps state, has named scenarios, and is checked against the live API on an ongoing basis. Pre-seeded scenarios have realistic market conditions, and POST /_rystic/scenario loads a named scenario and resets the simulator to that state. Production and demo keys are unnecessary, and local tests do not consume hosted rate limits.
The btc15m_tape scenario replays a captured market day through the matching engine on the exchange clock. That makes fills depend on recorded book conditions. Scripted events can schedule messages, seeds, and calls, and POST /_rystic/seed can change state during a run without a restart. The simulator also supports settlement resolution and correlated-market replay on one clock, extending the same fixture beyond isolated order submissions.
Access is a separate implementation consideration. Kalshi comes with the paid per-seat Pro plan, which has a free trial, and is outside the Free tier’s limited simulator catalog. Enterprise adds fully offline operation and RL environment resale.
Wiring the simulator as a fixture in practice — setup, isolation, and teardown
The implementation pattern is to launch the simulator container once from a Compose or stack file before the suite begins. The process outlives each individual test case. Before a case runs, its setup hook calls POST /_rystic/scenario to load an immutable scenario definition such as btc15m_tape. The application then sends CreateOrder V2 requests to that fixture, observes a partial fill, and cancels the remaining quantity within the same stateful run.
One simulator process holds one exchange, so every client on its port shares markets and order books. Each CI job therefore needs its own simulator process so that jobs do not compete to reset one global fixture. Within each process, immutable scenario definitions and runtime state kept for each test stop one case from changing where another starts.
Mid-test injection serves a different purpose from reset. POST /_rystic/seed can supply position state when a case needs to begin from a partially filled or partially settled condition without constructing every preceding action. Finally hooks should clean state after failures and stop the fixture at suite teardown. Reset controls belong only in the isolated test environment, never in a shared or production-adjacent deployment.
Testing the order lifecycle end to end — the four workflows that matter most

Creation begins from a known scenario with the market and balance state the case requires. The test posts to POST /portfolio/events/orders using bid or ask and a dollar-string price, then asserts that the response supplies an order ID. That ID becomes the next call’s input. A separate malformed-price case sends a float instead of a dollar string and checks the exchange-compatible error, including the query-binding behavior reproduced by the simulator.
Retrieval begins with the order created by that request. The test depends on the creation response to retrieve the order by its returned ID and assert that it is resting. The assertion establishes that the fixture retained the creation result and that the application can use the identifier across calls.
Partial-fill reconciliation begins with a resting limit order positioned against the recorded book in btc15m_tape. The order fills according to the tape’s recorded market activity. After a fill event, the test checks filled quantity, cost, remaining open quantity, and the WebSocket push’s sequence number against prior events. Submission alone cannot satisfy this case because the assertions require an observed change in both order state and the event stream.
Cancellation begins with an order that still has open quantity. The cancel request includes market_ticker, and a subsequent retrieval must show a cancelled state. Settlement provides a related terminal-state test. An order still resting at settlement should be cancelled, while the winning side is paid and settlement history and the account balance reflect the outcome.
Fault injection scenarios the live demo cannot provide
When a scripted token bucket exhausts mid-workflow, does retry logic respect Retry-After without duplicating the order. When acknowledgment is delayed, does the client distinguish a slow response from a failed placement. Injecting those conditions at known points makes the assertions repeatable instead of waiting for the demo to fail at a useful moment.
A WebSocket disconnect raises a different recovery question. The test must check whether the client reconnects and correctly replays missed sequence numbers during the fill stream. A cancellation without market_ticker checks whether the client handles the exchange’s shard-routing error. A scripted 503 on placement tests whether retrying duplicates the order, using persistent state to expose the side effect.
Fidelity drift and why a simulator that is not continuously verified against the live API silently misleads
The strongest objection is that the simulator can drift too. A fixture that accepts an obsolete order endpoint or omits a required cancellation parameter can keep tests green while the real integration breaks. Persistence can make the wrong contract internally consistent across an entire workflow. Statefulness alone is insufficient evidence of fidelity.
Continuous automated comparison against the live API addresses that separate risk. Manual periodic checks leave intervals in which divergence can go unnoticed, while automated verification makes agreement an ongoing test. The fidelity card and published agreement scores are the trust mechanism. They should be assessed as evidence of simulator-to-API agreement, while application workflows may still be incorrect and future interface changes may introduce a gap.
Extending the fixture for AI agents and RL environments that call Kalshi
An agent calling Kalshi needs the same state continuity as a trading client. Tool use does not remove order dependencies. The agent must create an order before retrieving it, distinguish submission from fill, and supply the routing information needed to cancel. Tests must also cover interface drift from argument-key changes, the move from legacy order mutations to CreateOrder V2, and the requirement to include market_ticker.
An up-to-date fixture lets tests check how those calls work together. Settable state makes constraint checks reproducible. Tests can check for forbidden field values, compare end-of-episode entity counts with setup baselines to detect spurious creation, and compare factual claims with API responses recorded in the tool trace. These checks connect the agent’s reported success to what actually changed in the simulated exchange.
RL evaluation also requires repeatable conditions across isolated episodes. The btc15m_tape replay gives each rollout the same market dynamics so that reward signals can be compared, while environments that run in parallel need separate simulator processes under the one-process-one-exchange rule. Enterprise supports resale inside RL environments. MCP tool-call semantics are still a possible extension, with support yet to be established here, because tests for that layer must cover more than the REST and WebSocket contract described above.


