Constructing a Deterministic Backtest Runner for Kalshi Automated Strategies Using Recorded Tool Outputs
Record every tool call and model output, then replay them against a frozen simulator.

Testing a Kalshi bot reproducibly requires recording its tool calls and model outputs, then replaying them against a frozen, stateful environment. A deterministic backtest runner separates strategy changes from market changes and inference drift. It provides a regression test of recorded conditions, leaving profitability in live trading unproven.
Why Kalshi's market structure makes standard backtesting unreliable
Kalshi contracts resolve once, so repeated tests of the same contract do not create independent observations. Contracts tied to economic data releases, weather outcomes, or political milestones can also reprice together. Correlation reduces the effective sample further. A strategy that appears profitable across a handful of resolved contracts therefore has less evidence behind it than its trade count suggests, especially in thin markets with sparse resolution history.
Manual paper-trading shows how a strategy behaves live, while ad-hoc script replay can repeat a narrow calculation. Neither method alone establishes a repeatable, stateful test of an entire trading session. The gap appears between calls. A later position query depends on earlier execution, and borrowing assumptions of continuous, liquid pricing from equity or crypto backtests can conceal that dependency while overstating edge.
The second problem: LLM inference is non-deterministic even when you want it not to be
An LLM introduces another source of variation even when market inputs stay fixed. Identical prompts at temperature zero with a fixed seed can produce different token sequences across batch sizes and hardware. Model updates can also shift behavior between runs. A fixed prompt is not a frozen decision.
That variation builds up across an agent’s trajectory, which is its sequence of observations, tool calls, and decisions in order. A tool call is a request to a function available to the agent, such as fetching market data, placing an order, or querying positions. Its result becomes context for the next decision. One early divergence can redirect every later call, so rerunning inference against historical data cannot isolate a strategy improvement from model drift.
Record-and-replay as the architectural response to both problems at once
Record-and-replay freezes the boundaries where outside information enters the agent. During recording, immutable envelopes capture tool requests and responses, while model responses are saved for deterministic playback. During full replay, substituted clients replace calls to the exchange or model with those captured outputs. The strategy’s code path remains unchanged.
Chronicle implements this pattern by recording model and tool boundaries and turning captured incidents into regression tests without live inference. Structural assertions check which tool the agent selected, which arguments it supplied, and whether it refused a guarded action. Recording a bad decision is useful evidence. It preserves the failure so that a targeted change can be tested while unrelated inputs remain fixed.
Full replay reproduces the captured trajectory, whereas partial replay releases selected boundaries to exercise changed logic against the simulator. These release points are cut points. The architectural shift is from “re-run the agent” to “replay what the agent saw.”

What to record: the structure of a Kalshi tool-call envelope
The minimum envelope contains tool_name, tool_input, tool_output, sequence_index, timestamp_utc, and llm_output. The tool name identifies the registered function, such as get_market_orderbook, place_order, or get_positions. Inputs preserve the exact arguments supplied by the agent. The output holds the full response payload, while the sequence index fixes the call’s place in the session and the timestamp preserves its temporal context.
The llm_output field stores the model response immediately following the tool result so that replay can return it token-for-token. Prompt inputs need the same discipline. A generated UUID, temporary path, or setup timestamp must retain its captured value if it contributes to the prompt. Otherwise, the replay can diverge before any trading logic changes.
Newline-delimited JSON supports streaming ingestion and grep-based inspection, while SQLite supports sequence queries and cut-point selection. Either format must keep requests in order as well as match them. Each orderbook snapshot becomes a discrete envelope. Recorded WebSocket order-book updates belong in the same sequence so that their timing relative to decisions is not lost.
Recording infrastructure: intercepting live Kalshi calls without touching strategy logic
A recording decorator sits between the strategy and its Kalshi client, whether that client uses the kalshi-python SDK or direct HTTP requests. It intercepts a call, forwards it to the live API, captures the request and response, appends the envelope, and returns the response unchanged. Strategy code still calls tool_client.get_orderbook(ticker) as before.
Live authentication still requires RSA-PSS signed headers with request timestamps. Those authentication timestamps should be stripped or normalized in stored request metadata so that replay does not attempt to reuse stale signatures. The envelope’s temporal context must remain intact. Live rate limits also apply when recording, but they do not apply to local replay.
Session labels should identify the strategy version, market category, and date range, making relevant regressions selectable later. On replay, the substituted client must not forward side effects to the exchange. No real order should escape that boundary. This separation makes recorded sessions suitable for CI without exposing production capital to test execution.
Wiring a stateful Kalshi simulator into the replay loop
A stateless mock can check a single endpoint response, but it cannot model a trading session in which calls change shared state. An order placement followed by a position query exposes the gap. A fixed positions payload has no record of earlier execution. Position tracking, fill state, and P&L therefore require a backend that preserves execution history across calls.
The simulator maintains open orders, a position ledger updated by fills, and history for settled contracts. Every call reads or changes that shared state. Its starting state must match the recorded session. A plausible but unrelated starting portfolio would make subsequent comparisons misleading even if each endpoint returned a well-formed response.
Pure recorded-envelope replay returns captured responses directly, while simulator-backed replay executes recorded inputs and compares the resulting responses with the recording. The distinction is important for testing state transitions. The simulator must be frozen for reproducibility and checked against live API behavior for fidelity, because stable execution alone does not make its results accurate.
Isolating strategy logic so the replay produces the same agent decisions every time
The strategy needs separate modules for data ingestion, valuation or scoring, risk and position management, and execution. This separation makes failures attributable to a specific layer. Each module needs a controlled input boundary. Ingestion consumes recorded data, scoring receives recorded model outputs or frozen deterministic inputs, and portfolio decisions use simulator state.
Execution routes orders to the simulator and evaluates kill-switch conditions against that same environment. Consider an order-placement decision at step 5 that depends on a position query at step 3. Both must share the same state history. If the earlier query reads a live portfolio while the later order uses simulated state, the runner no longer tests a coherent session.
Fixtures must also replace wall-clock calls, UUID generation, and temporary paths that feed into decisions or prompts. A leaked datetime.now() can change the trajectory despite frozen API responses. Historical visibility needs equal care. At each decision point, sequence and timestamp controls must limit context to information that was already available and keep later outcomes from reaching it through the simulator.
The replay loop itself: how the runner sequences envelopes and advances simulator state
The runner loads envelopes in sequence-index order and initializes the simulator to the recorded starting state. Before serving each envelope, it checks the agent’s requested tool and arguments against the record. It then dispatches the input to the simulator. The response advances session state and is compared with the recorded output before the agent proceeds.
Comparison uses field-level differences with explicit tolerances because timestamps and cursor tokens may legitimately differ. Those exceptions must remain narrow. After the response check, the model client returns the captured llm_output, and the agent advances toward the next tool call. At session end, assertions compare P&L, the position ledger, and order history with the recorded terminal state.
Fill assumptions also belong in the runner. Because historical order-book snapshots are unavailable from the Kalshi API, order-placement replay needs snapshots captured during recording and an explicit fill model using their spread and depth. Platform fees must be included before P&L is worked out. The result log should show these assumptions along with decisions, fills, and divergences.
A cut point lets chosen parts of the changed logic, such as order sizing, run against the simulator while other boundaries use the recording. The result log for this changed-logic replay must show which decision changes were intended and which divergence was unexpected so that a successful fix is distinguished from an exact replay.
Fault injection during replay: testing the strategy's resilience, not just its happy path
An order-placement retry must not create a duplicate order. Injecting a 429 response tests whether the strategy backs off and recovers without double-ordering, so replay checks idempotency through an assertion. Clean recordings cannot establish that behavior alone. The fault must happen at a set boundary where the state is known.
Other variants can inject a 503 during a market-data fetch or latency during an orderbook call. The first tests graceful fallback or a controlled halt, while the second tests behavior when a delayed response crosses a time-decay threshold. Each variant should isolate one fault type. After clean responses resume, assertions should check both recovery behavior and the state from which trading continues.
These tests extend the same replay infrastructure rather than requiring an unrelated resilience harness. Their expected outcomes differ from the clean baseline because the injected condition deliberately changes the session. Recovery invariants replace exact trajectory matching where appropriate. A strategy can legitimately halt after a fault, but it should not silently resume with an incorrect position ledger.
The silent-corruption risk: when the simulator lies and the backtest looks fine
A simulator can return state that looks right but is wrong, without crashing. It might report zero positions after fills, accept orders without updating the stored order state, or use settlement rules that differ from how Kalshi behaves. A clean-looking backtest can therefore be false reassurance. End-of-session P&L alone is too coarse to detect every broken transition.
Checking each envelope for divergence catches errors closer to where they start, before later calculations hide them. Those checks still depend on the scope of the recorded evidence, so simulator limitations must appear in the result log. Exact matching priority for simultaneous fills is one such potential gap. A documented approximation is more useful than unexplained precision.
Rystic is one option for simulator-backed replay, offering locally runnable Kalshi stand-ins that preserve order and position state and are verified against the live API before each release, without requiring live credentials or risking real money during tests. Its role complements pure recorded-envelope playback by supplying the stateful environment for multi-step execution. Verification is the safeguard against drift. It must accompany deterministic replay rather than be inferred from passing regression tests.
How do you test a Kalshi bot from live recording to reproducible CI regression?
Initial instrumentation should use the demo environment with the recording decorator enabled and a session label configured. Recording can then collect sessions across strategy variants and market categories, using real markets or the demo environment. The corpus belongs in a versioned store. Keeping it with the strategy code preserves the relationship between each trajectory and the implementation that produced it.
The baseline stage runs the corpus through the stateful simulator, checks every divergence, and computes P&L under documented fill and fee assumptions. Its result log becomes the comparison artifact. The changed strategy then runs under those same frozen conditions, with cut points where the changed behavior needs to run. Differences in decisions, fills, or P&L can be examined without fresh market inputs or live inference obscuring their cause.
CI should run these tests on every pull request and keep recorded incidents as permanent regressions. With parameterized fault variants, the tests also cover order-placement 429s, market-data 503s, and duplicate settlement. The corpus also needs periodic renewal. Walk-forward sequencing validates against earlier sessions and adds later recordings as new markets resolve, without allowing future information into historical decisions.
The replay harness is a development and regression tool that complements live paper-trading in the demo environment before production capital is exposed to real order-book dynamics.


