Tool Call Bench

Implementing a Paper Trading Mode Directly in Kalshi Bot Logic With State-Intercepting Middleware

Local order simulation tests a Kalshi strategy where the demo exchange can't.

· 8 min read
Cover illustration for “Implementing a Paper Trading Mode Directly in Kalshi Bot Logic With State-Intercepting Middleware”
Trading Bot Test Environments · November 18, 2026 · 8 min read · 1,820 words

Testing a Kalshi bot before going live requires more than redirecting it to the demo exchange. State-intercepting middleware lets the bot read live Kalshi prices while keeping orders, simulated fills, balances, and positions local. This tests how the strategy behaves without submitting real trades, but results can be trusted only with durable state, clear fill assumptions, and repeatable integration tests.

Why Kalshi's demo environment cannot test a trading strategy

Kalshi’s demo environment is suited to testing authentication and order flow. It runs at demo.kalshi.co, with REST at external-api.demo.kalshi.co and WebSockets at wss://external-api-ws.demo.kalshi.co/trade-api/ws/v2. It has separate credentials and a separate exchange. That separation provides a place to exercise Ed25519/RSA-PSS request signing, key handling, clock issues, and the full create, amend, and cancel lifecycle. WebSocket subscriptions and reconnect logic also belong within that scope.

The demo does not expose a strategy to real bid/ask spreads, real liquidity depth, or real fill behavior. A strategy that fills cleanly there has not encountered Kalshi’s production order book. Testing strategy behavior therefore requires a different boundary between the bot and the exchange. The architectural choice is whether to redirect requests to the demo host or intercept orders inside the bot’s own logic.

The architectural split between demo-redirect and in-process interception

Demo-redirect changes the host and key while leaving the exchange responsible for order state. It answers whether signing, retries, and order-lifecycle code work against the demo environment. In-process interception instead reads production market data and simulates order execution locally. The interception layer is the middleware. Its purpose is to test strategy returns against real prices under stated execution assumptions.

The Kalshi v5 bot makes this distinction explicit through separate paper-trading and live-trading scripts. Its guide recommends starting with paper mode and confirming that settings and behavior match the trading plan before using real funds. The kalshi-paper-trading-bot, published October 29, 2026, formalizes the boundary in its HTTP client. That client permits only market, series, event, order-book, and Kalshi-hosted reference-feed reads, while a separate live-account implementation has real-order submission disabled by default.

This separation preserves the bot’s market-data reading logic. Moving to paper mode changes where orders go, without requiring a rewrite of the data-read paths. Production reads still supply the prices on which the strategy acts. The middleware replaces the exchange’s role in maintaining simulated account state, while the strategy retains its role in deciding when to trade.

Where the middleware layer sits in the bot's call stack

The interception boundary sits at the HTTP transport layer, before an order-submission call can reach Kalshi. Market-data calls still go to the live production API. Order calls remain inside the process instead. For each simulated submission, the middleware records the order, computes a fill against the observed bid/ask, and updates the local balance and position state. The exchange never receives that order.

The v5 paper configuration illustrates the state and settings involved without requiring a separate strategy implementation. initialBalance establishes the starting cash, while orderSize determines the requested size. EntryRange, Exit, and TakeProfitPts define conditions whose effects must appear correctly in simulated fills and positions. Daily_Profit_Target and Daily_Loss_Target depend on accumulated results. The middleware must keep the accounting that those decisions use, while the strategy still sets the trading rules.

The v5 bot polls the order book through pollIntervalMs, with pollJitterMaxMs also present in its paper configuration. It refreshes market and session metadata through marketRefreshMs and throttles underlying-price calls separately through priceRefreshMs. Those reads continue to supply observations while the middleware intercepts the write path.

Why stateful fill simulation is harder than it looks

A static “filled” response does not implement paper trading. A position opened during one polling cycle must still exist when the next cycle queries it, with the corresponding cash change intact. Otherwise, later decisions operate on phantom positions or incorrect buying power. This can go wrong within a single session. Returning a plausible response is insufficient when the next request depends on what the previous request changed.

The state transition must also be indivisible. Recording a position without its matching cash update leaves an account that never could have existed, even if each stored value looks reasonable alone. The kalshi-paper-trading-bot makes this requirement explicit in rule ownership tests covering atomic writes and durable remote state through state_store.save and persistence.persist. Without atomic writes, a crash mid-cycle can leave phantom positions.

This is the same limitation that makes stateless mocks inadequate for broader integration testing. They return canned responses for configured paths but remember nothing about earlier requests. A trading bot depends on that memory to distinguish an available balance from committed capital and an open position from a completed trade. Stateful simulation therefore has to preserve a coherent account history.

Atomic state, durable persistence, and the settlement loop

Atomic writes protect a transition within a cycle. Persistence preserves completed transitions across process restarts, while settlement determines when an unresolved position can become a final outcome. None substitutes for the others. A durable record of inconsistent state remains inconsistent, and an intact position cannot be settled from an unofficial observation.

The kalshi-paper-trading-bot uses state_store.save for atomic paper state and blocks new entries when state is invalid, executions are uncertain, or durability checks fail. Its GitHub Actions persistence mode, --paper --persist-to-github, runs for a configured session length. A STOPPED paper run exits before it creates a live client. That makes the persistence boundary a safety boundary as well. Pending positions settle only from Kalshi’s official final YES/NO result, while unknown, missing, or provisional results remain pending across runs.

The gambles project uses SQLite at data/gambles.db for durable state, with deletion of that database deliberately resetting the simulation. Its simulator charges Kalshi’s taker fee on every entry and early exit using ceil_to_cent(M × 0.07 × contracts × P × (1 − P)). Fees belong in the account state from the start. A fresh scenario starts slightly negative because crossing the bid/ask spread and paying fees cost money from the start.

Fill fidelity and what the middleware can honestly simulate

Live prices remove one source of unreality without removing all of them. A simulator that always fills at the observed price assumes away market impact and queue position. Those assumptions become especially consequential in thin markets. The book may show a price without establishing that the bot could transact its intended size there. Even with correct accounting, an execution model can be too optimistic.

Paper mode can establish whether the order-state machine behaves correctly under tested conditions. It can also test cash accounting, entry and exit conditions against real prices, and responses to stale books, settlement voids, and low-cash states. These are substantial claims, but they are bounded. They do not establish that live orders will receive the same fills. Simulated profitability remains conditional on the fill rules.

The practical implication is to account for book depth, order age, and fees rather than treating every observed price as an unconditional execution opportunity. Even then, paper results are evidence about behavior under a model. Reading current production prices also serves a different purpose from replaying a historical strategy test. Repeatable validation needs control over the sequence of market observations as well as control over order state.

Connecting paper mode to a broader integration testing pipeline

A pure paper-mode run still gets its markets, order books, and reference feeds from Kalshi’s production API. In CI, those reads introduce rate limits, credential exposure, and non-deterministic results. The order interceptor alone cannot remove those dependencies. Automated testing therefore needs a second separation, with a stateful, locally hosted simulator serving the data-read path while the same paper fill logic intercepts writes. This provides deterministic tests without live credentials and supports horizontal scaling.

The simulator also needs realistic starting data. Pre-seeded order books, populated markets, and realistic price series give the strategy conditions in which its decisions can actually execute. Continuous verification against the real Kalshi API addresses a different risk, which is drift between simulated and production behavior. New response fields, rate-limiting differences, and webhook inconsistencies can otherwise leave tests passing against an inaccurate boundary.

Fault injection turns that boundary into a test instrument. Malformed order-book responses, stale reference feeds, and rate-limit errors during an entry window exercise failures that happy-path runs cannot expose. The simulator controls the inputs, while the middleware preserves the resulting account transitions. Together, they make it possible to test whether an adverse response leaves the bot’s trading state coherent.

Testing LLM-driven Kalshi bots where the agent is the trading logic

An LLM-driven bot can treat a malformed or stale tool response as ground truth. That differs from a rule that gets valid data wrong. When the agent trusts whatever the tool returns, the test must challenge the tool boundary itself. Injecting malformed order books or stale settlement data exposes whether the decision layer accepts unreliable observations. Paper execution contains the financial consequence while the test examines the agent’s response.

The ryanfrigo/kalshi-ai-trading-bot offers a place to start, with separate paper/live modes and SQLite logging for every signal. Its Streamlit dashboard displays real-time P&L, with a secondary static HTML paper-trading report at docs/paper_dashboard.html. Those records make the decision layer observable during a paper run. They do not, by themselves, establish that tool results were valid. Boundary testing is still necessary to distinguish flawed input handling from flawed trading judgment.

Schema drift makes that distinction particularly important. If an external API shifts a required field, detecting the change at the boundary prevents it from being mistaken for an LLM quality regression. Reinforcement-learning environments extend the same statefulness requirement to thousands of parallel agent rollouts. At that scale, deterministic, horizontally scalable simulators must reset state on demand. The infrastructure supports both repeatable CI checks and isolated training runs, though the amount of work it runs differs.

What a complete paper trading middleware implementation covers

A complete implementation is a small, tested subsystem. Its HTTP client enforces the separation between permitted reads and intercepted orders, so a simulated submission never reaches the exchange. Live paper runs use production market data. CI runs use a stateful simulator for those reads and keep the same write-path interceptor.

Within that boundary, atomic state and durable storage keep balances and positions in sync across cycles and restarts. The fill engine accounts for depth, order age, and fees, while official settlement resolves pending positions only when a final YES/NO result exists. Provisional or missing results remain pending instead. Test coverage exercises stale books, malformed responses, and 429s during the entry window, as well as normal execution. These checks establish whether the subsystem preserves its guarantees when its inputs fail.

Observability completes the record of each simulated trade. Every order is logged with timestamp, ticker, price, size, fees, and P&L, and a dashboard, including a static HTML file, can render cumulative performance after settlement. That record connects strategy decisions to their simulated financial consequences. CI then provides the repeatable acceptance test, running against a stateful local simulator without live credentials or rate limits and failing loudly on any state inconsistency.

More in Trading Bot Test Environments