State Trajectory Auditing as the Quant Standard for Kalshi Bot Correctness Verification
Tracing orders through fills, cancels, and restarts catches bugs that a profitable backtest hides.

Testing a Kalshi bot requires two separate checks. Backtesting measures strategy outcomes, while state trajectory auditing verifies execution by tracing orders through placement, fills, cancellation, restart, and their final recorded state. Before going live, a bot needs repeatable tests against a stateful simulator, because a profitable equity curve cannot establish that it executed correctly.
Why an equity curve is the wrong correctness test for a Kalshi bot
Profitability and correctness are independent properties of a trading system. A bot can make money while losing track of orders, just as a correctly executing bot can lose money on a poor strategy. Consider an order that fills and disappears from the resting-order set. If the bot treats that absence as evidence that the ticker is untouched, it can place another order. The resulting equity curve records the financial outcome.
Prediction-market fees and thin margins leave little room for duplicate positions or untracked limits when conditions change. A losing backtest can also be a reason to check the strategy without proving that execution went wrong. The correctness test needs evidence of what the bot believed, what the API state became, and whether those states remained consistent.
What the Kalshi order lifecycle actually looks like as a state machine
The Kalshi order lifecycle is a graph of states. An order can rest, fill fully or partially, become a recorded position, and reach market closure or resolution. Each transition changes what later calls should return. Cancellation adds another path, while a restart tests whether the bot keeps enough state to go on safely. The audit must track those paths from one request to the next.
Kalshi’s Create Order V2 uses POST /portfolio/events/orders. Its request includes ticker, side, count as a string, price as a fixed-point dollar string, time_in_force, and self_trade_prevention_type. Optional fields include client_order_id, post_only, reduce_only, cancel_order_on_pause, expiration_time, subaccount, order_group_id, and exchange_index. These fields define the submitted instruction. Kalshi’s API Changelog marked the legacy /portfolio/orders endpoints for deprecation no earlier than May 21, 2026, with deprecation subsequently occurring between June 18–25, 2026.
Other API mechanics also shape the state graph. Order groups, created through POST /portfolio/order_groups/create, cancel every resting order in a group when filled contracts exceed its configured limit within a rolling 15-second window. The bot must anticipate that collective transition. Kalshi’s order book returns YES bids and NO bids only, so the implied YES ask is 1.00 minus the best NO bid. With no NO bids, there is no ask, and a correctly implementing bot should not trade.
Request limits add a separate control boundary. Kalshi has separate Read and Write token buckets, so requests have no single fixed speed. Its documentation states that 429 responses omit Retry-After headers, so recovery requires exponential backoff without that server-provided timing hint. Correct execution depends on both the state of resources and the state of request controls.
The eight failure modes that stateless testing cannot catch
The eight bugs documented across two rebuilds of the same bot shared a state-transition failure. The bot’s internal account of execution diverged from the API state. Once a filled order stopped appearing as resting, the next loop treated its ticker as untouched and ordered again. The repair persisted ordered tickers in state.json and checked positions alongside resting orders.
The restart defect crossed a different boundary. An orders-per-minute count lived only in memory, so restarting the process erased the control’s history. A capped order went out nine seconds after reboot. Persisting order timestamps in state.json repaired that discontinuity. A mock that tests one session at a time cannot establish whether the cap survives the next session.
A deliberately wrong ticker produced the same data error on every loop, logged 126 times during the run. Returning an expected 404 would pass a single-call test. The failure was the absence of a retry limit across the trajectory. The remaining five bugs also came from state built up over time, so they call for more than checks of single responses.
A scripted test can assert counts or sequences around a stub, but canned responses alone do not model the resource’s evolution. The demo environment uses network calls, separate credentials, and real rate limits, and runs can be disrupted when the external service is unavailable. It also cannot inject a fill, partial fill, or kill-switch restart at an exact chosen transition on demand.
Why stateful simulation is the right foundation for trajectory auditing
A stateful simulator retains and updates resources across calls. Creating an order, fetching it, canceling it, and fetching it again should produce responses consistent with those actions. The second fetch must reflect the cancellation. A fixed response cannot establish that causal relationship, even when its fields match a valid API response.
The simulator must track resting orders, fills, positions, and closure and reject transitions that break the rules. Its state must also be controllable. Otherwise, a test cannot place a partial fill or restart precisely where the bot’s recovery logic needs examination. Repeatability makes a failed trajectory available for diagnosis and regression testing.
Fault injection extends that control to uncertain outcomes. Relevant faults include timeouts, 429s without Retry-After, malformed JSON, stuck retry loops, and partial-success-lost-response scenarios. In the last case, the POST side effect occurs but the bot never receives its response. Retrying can place a duplicate order. That makes POST recovery different from repeating a read.
Recorded cassettes keep responses but may leave out the rules behind them. If execution diverges from the recorded sequence, replay can supply a later state without the action required to reach it. A local HTTP stub has the same limitation unless it updates state. Trajectory auditing needs the causal model behind the response.
The trajectory audit methodology: tracing every order through its full state sequence
The methodology starts by setting out the valid paths for each order type. A limit order may move from placed to resting to filled and then to position recorded. It may instead move from resting to canceled, including cancellation by the order-group backstop. A partial-fill path can return to resting before reaching filled. Terminal states outside the defined graph fail the audit.
Instrumentation then makes each transition observable and attributable. The required event fields include a timestamp with nanosecond precision, event ID, actor ID, session and request ID, strategy ID, and an input snapshot containing the market-data snapshot hash and features used. BotCookery’s rebuild logs illustrate the event pattern through ts, ticker, event type, rule, and outcome. Those fields show which rule led to a recorded action. The fuller audit schema also needs enough identity and input context to reconstruct the path.
Fills, partial fills, cancellation, restarts, and injected faults must occur at defined points so that observed transitions can be compared with expected ones. A restart is part of the path. Treating it as a fresh test would hide the persistence failures the audit is intended to expose.
A pass requires every observed transition to match the graph, while a missing, duplicated, or out-of-order transition produces a fail. Insufficient evidence calls for quarantine. The ryanfrigo/kalshi-ai-trading-bot forward-only guard applies a related evidentiary discipline by refusing to claim edge with fewer than 10 forward-settled trades. That threshold concerns strategy evidence.
The log must also show how execution matches what the strategy intended. Every completed path needs a traceable authorization instruction. Even if a path is otherwise valid, execution without authorization is still unaccounted for. The EVOQUANT framework, published in July 2026, applies a related principle to strategy optimization by admitting a replacement candidate only after all verification stages pass and auditing the full optimization trajectory, including its terminal score.
Running trajectory audits in CI without live credentials or rate-limit exposure
A four-stage CI structure separates strategy evaluation, lifecycle verification, fault recovery, and connectivity. First, unit tests check strategy logic without API calls. Second, the trajectory suite runs against the stateful simulator and covers restart, fill, partial fill, cancellation, and order-group backstop transitions. Third, a fault-injection suite exercises the canonical failure cases. Fourth, a narrow authenticated demo smoke test uses separate keys to check connectivity and authentication.
The separation keeps the main audit independent of live credentials and demo rate limits. It also avoids external availability becoming a prerequisite for lifecycle tests. BotCookery’s October 2026 rebuild used edited mock state and a local fault-injecting relay to simulate fills and outages. That pattern places scripted failures behind a local HTTP interface. CI can then reproduce the same transition locally.
The simulation itself still needs to be checked before every release. A simulator that drifts from the live API can turn passing tests into false confidence. Verification of the simulator is therefore a separate requirement from verification of the bot. The isolated suite does not replace that work or the narrow demo smoke test. Its retrievable audit history also supports the emerging regulatory expectation that orders, model decisions, trade justification, and controls can be demonstrated.
Extending trajectory auditing to AI trading agents and LLM tool-use
An LLM-driven Kalshi bot needs the same execution audit, with additional attention to state interpretation. A model can misclassify an order or position without producing an explicit error. Text quality is not the relevant acceptance test. The audit must check which tools the bot chose, what context it kept, and how it recovered across the order’s full lifecycle, going beyond a single input-output pair.
The AgentChaos paper, published in August 2026, injected faults into LLM API responses without changing agent source code. Across five agent systems and four backbone models, pass@1 fell by up to 49.66 points. The most damaging failures were silent, providing evidence about agent resilience. Its relevance is the need to detect silent divergence through state evidence.
For a trading agent, the audit spans four distinct boundaries, namely observation, decision, execution, and confirmation. Reading market data must remain distinguishable from proposing a move, placing an order, and verifying its final state. A proposed action is not a confirmed fill. The authorization trace must connect these stages without allowing the agent’s interpretation to substitute for API state.
When an agent keeps a state misclassification between sessions, it can repeat the same control failure, so tests for long-lived agents must cover restarts. Missing evidence still calls for quarantine at the execution layer. For RL training or evaluation against the Kalshi API, the same simulator has deterministic behavior and state that tests can control, and it can scale horizontally across parallel evaluation containers without live calls.
What trajectory auditing tells you that an equity curve never will
A passing audit backs claims only about what it tested. Each fill can be traced to authorization and a recorded position, with checks against unintended re-ordering in the same session or after restart. The log can show that order timestamps survived reboot, the 60-second post-cancel wait was observed, and no POST was retried after a partial-success-lost-response.
Fault coverage supplies a different kind of evidence. The audit can demonstrate backoff after 429s, rejection of malformed JSON, and recognition of order-group cancellation as an expected transition. None of these claims follows from profit alone. Their credibility also depends on whether the simulator matches the API under its verification cadence. A passing static mock cannot establish that correspondence.
The practical next step is to instrument the bot’s state transitions with enough identity and input context to reconstruct each order. Then establish a verified stateful simulator for the Kalshi API. Write one trajectory test for each documented lifecycle transition, including restart and the order-group backstop. Add the fault cases, label incomplete evidence as quarantine, and connect every completed path to its authorization. Put that suite in CI before the next deployment.


