End-to-End Harness Design for Testing a Kalshi Prediction Market Bot Against Live-Schema Contracts
A stateful simulator plus schema contracts turns API drift into CI failures.

Testing a Kalshi prediction market bot before going live needs a stateful simulator that follows contracts for the current API schema. The harness must test order lifecycles, inject trading-specific failures, and reject removed or mistyped fields in CI. Its purpose is to make schema drift a build failure before it becomes an unhedged position or a missed fill.
Why Kalshi's API breaks bots silently and what that demands of a test harness
Kalshi’s API has repeatedly deleted fields after deprecation periods as short as seven days. The March 12, 2026 removal deleted yes_bid, yes_ask, last_price, volume, and open_interest simultaneously. Price fields changed to *_dollars fixed-point dollar strings, and count fields changed from integers to *_fp fixed-point strings. Consuming code could fail with a KeyError without a warning or a usable fallback. The change reached directly into trading logic.
The removal of tick_size reinforced the pattern. Originally scheduled for May 7, 2026, it took effect on April 2, 2026. Other changes reached fills, settlements, validation errors, and fractional RFQs, so compatibility was not just a market-data parsing problem. A bot could still have correct strategy logic but no longer be able to read the exchange’s responses. In live trading, that asymmetry is consequential because a runtime crash can leave a position unhedged or a fill unnoticed. A test suite that still supplies deleted fields conceals precisely the failure it needs to expose.
The Kalshi data model a simulator must reproduce faithfully
The simulator needs the API’s three-level market hierarchy. A series groups related events, such as KXFEDDECISION, while an event identifies one instance, such as KXFEDDECISION-26DEC for the December 9, 2026 meeting. A market is a single binary contract within that event, such as KXFEDDECISION-26DEC-H25, “Hike 25bps”. Kalshi’s documentation explicitly warns against inferring relationships by parsing tickers. Fixtures must therefore use the API’s relational fields.
Field types are part of the specification. Prices arrive as fixed-point dollar strings such as "0.1200", and counts arrive as *_fp strings such as "10.00". Fills use fee_cost, available since January 28, 2026, plus yes_price_dollars and no_price_dollars rather than the removed yes_price_fixed and no_price_fixed. Settlements use yes_total_cost_dollars and no_total_cost_dollars, while order validation now returns granular codes in place of invalid_order. As of June 2026, RFQs support contracts_fp in 0.01-contract increments.
The order book requires equally exact treatment. GET /markets/{ticker}/orderbook returns an orderbook_fp wrapper containing yes_dollars and no_dollars arrays. Each entry is a [price-string, count-string] pair, ordered worst to best by ascending price, so the best bid is last. There is no asks array because the best YES ask is derived as 1 - best_no_bid. Either side may be empty without constituting an error. Beyond response shapes, the simulator must reproduce separate read and write token buckets whose state persists across calls.
How do you test a Kalshi bot before going live? Start with stateful simulation
A stateless mock can return a successful submission, a plausible poll response, and a successful cancellation as independent responses disconnected from a shared order lifecycle. Kalshi’s lifecycle spans POST /portfolio/events/orders, GET /portfolio/orders/:id, and DELETE /portfolio/events/orders/:id. Each mutation must change the state that later calls see. Otherwise, passing tests establish only that the bot accepts canned responses.
WebSocket events must share that order state. A synthetic fill event needs to refer to the order submitted through REST, and a later REST poll must reflect the same lifecycle. Rate limits impose a similar requirement because the next request succeeds if the write bucket has sufficient depth after a burst and receives a 429 if it does not. An independent response fixture cannot represent that dependency.
WireMock can use scenario state machines to get close to this behavior. That is a valid approach, but hand-wiring transitions for the full order lifecycle requires substantial custom work. A purpose-built stateful simulator is built to keep session history, so the harness only needs to set the conditions and assertions. For this harness, the decisive criterion is whether REST mutations, WebSocket events, and token-budget changes remain consistent across requests.
Seeding the simulator with realistic Kalshi market data
An empty sandbox leaves important bot behavior untested. Sparse books, one-sided markets, and stale prices are normal Kalshi conditions, so fixtures must represent them rather than only liquid, two-sided markets. The seed set needs at least one complete series/event/market hierarchy with the tickers and relational structure described above. It also needs books with realistic depth, including a case where no_dollars is empty. That case tests whether the bot can handle a missing implied YES ask while still treating the response itself as valid.
Price freshness needs a separate fixture. A market with an hours-old last_price_dollars tests whether the bot mistakes an old trade for a current signal. A market with fractional_trading_enabled set and contracts_fp values needs a parallel market without that flag, so the harness exercises both branches. Fill records must use current fields, including yes_price_dollars and fee_cost, and leave out removed fields even if keeping them would be easier. An early-close fixture must place close_time before the bot’s expected expiry.
Whenever the live schema changes, their field names, types, and supported conditions must change with it. Configurable initial state lets a test establish the required market conditions before its first request, independently of another test’s mutations. The later CI contract gate enforces this upkeep. Without that link, realistic seed data can slowly come to look like an API that no longer exists.
Fault injection scenarios specific to a prediction market trading bot
Happy-path success does not establish safe failure behavior. A bot on a regulated venue can produce double orders or unhedged positions when exchange or network anomalies leave execution state ambiguous. Configurable latency profiles, exponential lag tails, connection drops, and token-bucket simulation with standard Retry-After headers allow the harness to create those conditions deliberately. The assertion must concern the bot’s trading response. A handled error can still leave the bot with an incorrect view of its position.
Write-budget exhaustion must be tested separately from read-budget exhaustion. When a 429 reflects a depleted write bucket, the bot needs to back off the affected operation type while allowing other calls to continue. A WebSocket disconnect during a fill creates a different ambiguity. The bot must reconcile through a REST poll rather than trust an incomplete event, because a missed fill can distort its view of exposure. These tests depend on the shared state established by the simulator.
An hours-old last_price_dollars must not become a current trading signal, and an early close_time must prevent submissions after close. Validation failures must test granular error codes in place of the removed invalid_order branch. Each scenario targets a distinct decision boundary.
Writing schema contract assertions that fail loudly on field removal
Realistic simulation alone cannot prevent simulator drift. The structural contract layer should keep one OpenAPI specification as the source of truth and use oasdiff to compare the PR’s specification against main. The check must fail if fields are removed, types change, or new required fields are added. That comparison detects changes in the maintained specification, but it cannot establish freshness by itself. The specification and simulator still need continuous comparison with the live API.
Consumer-driven contracts provide the second layer. The bot defines the interactions it relies on in a Pact artifact, and the simulator proves that it satisfies those expectations on every run. The contract’s scope is limited to the fields the bot actually reads. This focuses failures on dependencies that can break the consumer. It also makes a removed field visible before the bot reaches the corresponding production code path.
For fills, assertions must check that yes_price_dollars and no_price_dollars are strings. Market-response checks must also reject removed yes_bid, yes_ask, last_price, volume, and open_interest fields, so stale fixtures cannot preserve obsolete parser behavior. Order-book checks must require orderbook_fp, arrays of [string, string] pairs, and no asks key. Validation checks must fail if they find the old generic error code. Presence alone is not a sufficient contract.
Pact’s May 2026 release introduced Drift, a spec-driven CLI for comparing provider implementations with API specifications and reporting discrepancies. It complements consumer contracts by checking the simulator against the specification. Structural checks still have a boundary because a payload can retain its shape while its behavioral meaning changes. Stateful integration tests remain necessary for that gap. Field deletion, however, is exactly the kind of failure explicit structural assertions can expose.
Testing the bot's LLM or agent layer against the Kalshi tool schema
An LLM decision layer adds another contract boundary. Coherent reasoning does not establish that the resulting tool call uses valid fields or preserves fixed-point values. The harness must check whether order submissions emit yes_price_dollars as a decimal string, the replacement for the removed integer yes_price. It must also check whether the bot consults fractional_trading_enabled before choosing count_fp or count. These request-side checks complement validation of the simulator’s responses.
Parsing and derived prices need their own assertions. The bot must parse yes_bid_dollars as Decimal because rounding errors from float can compound across a session. It must reconstruct the best YES ask from the best NO bid because an ask field does not exist. Empty-book fixtures are especially useful here because they exercise the limits of that calculation. Fluent model output cannot substitute for correct arithmetic and schema handling.
Deterministic tests isolate these responsibilities from model variability. When a mock returns fixed JSON in place of the LLM call, the harness can test routing, parsing, and tool-call validation as it would other application logic. Multi-turn tests then run a series of tool calls with simulator state that stays in sync across calls. Session replay and open-source observability tools can make it easier to see how the agent behaves during those tests, but assertions are still needed.
Wiring the full harness into a CI gate that surfaces schema drift before it ships

The CI pipeline must order these checks by dependency. When a PR opens, oasdiff first compares its OpenAPI specification with main and fails on breaking changes. If that passes, Pact verifies the bot’s consumer contract against the simulator. Only then does the full integration suite run with 429 exhaustion, WebSocket reconnects, stale prices, and early closes enabled. Deterministic agent-layer tests run next and check the shapes of requests and responses as they pass through the bot’s tool-call path.
The simulator choice determines how much lifecycle machinery the team maintains. Next to hand-wired mock-server scenarios, Rystic offers a purpose-built Kalshi simulator that remembers prior calls within a session, preserving order-lifecycle and token-bucket state across requests. It also provides pre-seeded realistic market data so the harness does not begin from an empty sandbox. A platform choice does not remove the obligation to test fidelity.
Live alignment is a separate, continuous responsibility. Kalshi’s changelog publishes an RSS feed at /changelog/rss.xml, and subscribing to it can trigger a schema-diff job on each entry. Ongoing checks against the live API keep the simulator from falling out of date even when its own responses agree with one another. The simulated PR suite can then run without live credentials, external rate limits, or network variability. That separation preserves fast feedback without confusing deterministic tests with evidence of current API fidelity.
Kalshi has shown that fields can disappear with very little warning, including an effective removal date earlier than the date originally scheduled. The engineering response is to connect live-schema changes to specification checks, simulator verification, consumer contracts, and bot-level tests. Drift caught in a PR is a ten-minute fix rather than a potential trading halt after deployment.


