Constructing a Zero-Capital Paper Trading Loop Against the Kalshi Demo Environment

A Kalshi demo run proves your plumbing works, not your strategy.

· 8 min read
Cover illustration for “Constructing a Zero-Capital Paper Trading Loop Against the Kalshi Demo Environment”
Kalshi API Integration · December 4, 2026 · 8 min read · 1,908 words

Testing a Kalshi bot before it goes live means checking the infrastructure first, with strategy testing to follow. A zero-capital paper trading loop should pass local stateful tests, a demo smoke test that runs for a full trading-day, and real-book paper trading before it uses real money. The demo validates authentication, order handling, WebSocket recovery, and retries, while real-book paper trading tests strategy against live liquidity.

What the Kalshi demo environment actually is and what it is not

Building the strategy first postpones the failures that can prevent it from trading at all. A loop may express the intended trading decision correctly yet fail when it signs a request, amends an order, or restores a subscription. Those are separate engineering problems from choosing a position. The demo isolates them from financial exposure. It uses separate credentials and hosts, with demo keys working only on demo hosts and production keys working only on production hosts.

That separation makes the demo an infrastructure test harness. It supports testing RSA-PSS or Ed25519 signing, order creation and rejection, amendments and cancellations, and WebSocket recovery. It also provides a place to exercise the required retry behavior against an actual service. Its order books, however, are separate from live books and do not reflect real liquidity.

The distinction determines what a passing test means. Demo results can support a claim that the trading integration works, but not that its decisions have economic value. Testing the strategy calls for paper trading against the real order book with modeled fees. Neither test substitutes for the other.

RSA-PSS request signing: the first layer that must work before anything else

Authentication is the first genuine failure surface because a locally valid signing implementation can still produce requests the API rejects. Ed25519 is the default key type, while RSA-PSS with SHA-256 is the alternative. The recommended choice is RSA-PSS only when the codebase cannot support Ed25519. Both work across demo and production environments. The algorithm choice does not remove the need to test the complete authenticated request against the demo service.

Key handling comes before that test. Private key material is shown once at generation and cannot be retrieved again, so secure storage is a precondition for using the integration. The private key must never be put in version control or client-side code. These are deployment constraints. A working signature does not compensate for exposing the key that creates it.

The first demo smoke test should generate the key pair, sign a balance read, and sign an order placement before strategy logic is added to the loop. A successful balance read establishes only part of that path, because order placement must also succeed through the trading endpoint. Clock synchronization belongs in the same test. A timestamp too far from the server’s clock causes rejection even when the signing code otherwise works, so system time must be synchronized before authentication is considered complete.

The order lifecycle the demo is built to exercise

Once authentication works, the test unit becomes an order’s lifetime. CreateOrder V2 uses POST /portfolio/events/orders. The legacy /portfolio/orders mutation endpoints were removed in June 2026, so examples that still use them are not a valid foundation for deployment. A successful create returns a 201 and an order ID. The loop must then poll status, amend, cancel, and handle rejection paths.

Retries make this lifecycle more demanding because the intended order and the attempted request are not the same thing. Idempotency keys preserve that distinction. One key belongs to each intended order, and retries resend that key so the API returns the stored order, preventing duplicates. This behavior must be verified in the demo.

Terminal states also need explicit coverage. A cancel on an already-filled order can return 404 not_found, which the loop must handle without crashing. The 409 conflict path belongs in the test suite as well, rather than being omitted because ordinary create-and-fill tests never encounter it. These cases expose assumptions about which transitions remain possible after the order changes state. An exhaustive lifecycle test checks how the loop responds when its requested action no longer matches the order’s state.

WebSocket subscriptions and the reconnection logic the Developer Agreement requires

Real-time delivery adds state to track because a connection can work even when the subscriptions it needs have been lost during recovery. Kalshi’s WebSocket documentation requires authentication during the handshake, even for channels containing public market data. The channels for public data include ticker, trade, and market_lifecycle_v2, while the private channels include orderbook_delta and fill. Authorization remains a separate boundary within that session. A market-data-only key receives error code 9 on activity channels including fill, market_positions, order_group_updates, and user_orders.

The demo test should exercise that boundary with a scoped key, then verify recovery with the permissions the trading loop requires. The concrete recovery test subscribes to orderbook_delta and fill, deliberately closes the connection, and checks that reconnection restores both subscriptions. Timing is part of correctness here. A reconnect during order submission must not cause the bot to submit duplicate orders while its real-time view is interrupted.

Kalshi’s documentation gives two reasons for WebSocket Too Many Requests responses: the tier’s concurrent connection limit has been reached, or connections are being opened too quickly. Both produce the same HTTP status and error code, so a tight retry loop cannot safely distinguish them. The Developer Agreement requires exponential backoff for reconnection, and unused connections should be closed.

Connection-health checks need equal care. By default, heartbeat handling does not need to be manual, though some WebSocket libraries need manual ping/pong handling. A missing Ping is not sufficient evidence that a connection receiving data is dead. Likewise, a Pong sent in response to a self-initiated Ping does not establish liveness.

Rate limits and retry logic under the token-cost system

The April 2026 shift to token-cost rate limits changes how the loop budgets requests and recovers from exhaustion. Creation, amendment, and cancellation all use the same write pool, so they share write capacity throughout the order lifecycle. Retry traffic competes with intended trading actions. A loop that treats each endpoint on its own can thus use up the capacity it needs to finish the sequence it has already started.

GET /account/api-limits is the authoritative source for the account’s current tier and limits. Fixed token figures in examples are not a substitute because tier allowances can change. The demo should validate how polling, order mutations, and recovery behave under the applicable limits. A loop is still incomplete if it cannot recover from rate exhaustion, even when it normally sends few requests.

The Developer Agreement requires exponential backoff with jitter for retries. An immediate retry after rate exhaustion puts more pressure on an already-exhausted pool and can extend the interruption. The recommended implementation is shared retry infrastructure that keeps REST and WebSocket recovery policies aligned over time. Its tests must cover exhaustion during an order sequence, when the loop still has state to resolve.

Why the demo alone is insufficient and what a stateful local simulator adds

The demo provides real-service validation, but it is a poor primary harness for repeated development and CI runs. Each run requires network access and consumes rate-limit budget, while the demo’s order books do not reset between tests. State can outlive the test that created it. A later run may then act on an earlier order, so results depend on the order in which tests run and need a manual reset or cleanup.

A stateless fixture mock removes the network dependency but not the need to model transitions. A status endpoint that always returns the same response cannot express the changing state required by a create-poll-amend-cancel sequence. The polling loop may never stop, or it may stop when it should keep going. Nor can an unchanging fixture reproduce a state-dependent 409 conflict.

A stateful simulator preserves state within a test and resets it to a known baseline before the next run. That makes the lifecycle repeatable without consuming demo tokens or depending on network conditions. Rystic offers one such option, a stateful Kalshi simulator that runs locally or in CI and can repeat the create-poll-amend-cancel sequence, including the 409 conflict path, on demand. It is verified against the real API daily and before every release to reduce drift. That supports its role as a development harness, but does not replace the actual demo smoke test.

Fault injection as a first-class concern in a trading loop, not an afterthought

Repeatable state is most useful when tests can deliberately make that state disagree with the loop’s expectations. Server errors and connection drops are visible failures, but an HTTP 200 can still contain semantically wrong state. A fill notification might claim the wrong quantity, a status response might never transition to filled, or a cancel acknowledgment might describe an order already filled. Successful transport is not successful execution.

Controlled fault injection makes the timing of failure reproducible. A 429 during order submission tests recovery while the intended order is still unresolved, and a 429 during amendment tests exhaustion later in the lifecycle. A 503 mid-reconnect tests recovery when the real-time channel is already down. A malformed fill payload tests a different boundary. These cases cannot be reproduced deterministically by waiting for the demo to produce them.

Each error path needs a known response and an expected loop behavior, including malformed parameters producing a 400, a signing regression producing a 401, conflict producing a 409, rate exhaustion producing a 429, and downtime producing a 503. Synthetic tests can also deliver an already-filled cancel conflict or a cancel confirmation that contradicts filled state. Those injected cases should be kept separate from the demo’s 404 not_found cancel response. Otherwise, the suite may treat its own fixtures as proof of how the exchange behaves.

How do you test a Kalshi bot before going live with a two-layer architecture?

Diagram: Three Gates to Live Trading. Visualizes: Show a linear three-stage progression representing the deployment sequence a Kalshi bot must pass before going live.

The complete architecture separates infrastructure validation from strategy validation, with three gates across those two layers. The first gate is local simulation in CI on every commit. Signing, order transitions, subscription recovery, and retry behavior run against resettable state, while injected faults cover conflicts, exhaustion, downtime, and silent wrong-state responses. This is the repeatable regression gate. It establishes whether a code change preserves the behavior the loop is expected to have.

The second gate is a full trading-day smoke test against the actual demo before production deployment. This checks authentication against the real service, lifecycle endpoint behavior, subscription restoration after a deliberate disconnect, and the retry path on a real 429. Clock skew and library incompatibilities need to be tested here because local tests may miss them. Simulator fidelity has limits. New fields, rate-limit behavior, and webhook payload shapes can drift, so the simulator needs to be checked against the real API on an ongoing basis, even if it was accurate before.

The third gate is real-book paper trading, where paper orders walk the actual order books and include modeled fees. Rivo’s paper trading works at this layer with one bearer key and no signing code. That makes it a strategy-testing option. Real-book paper results show how well the modeled orders fill and what they cost against live liquidity. They answer a different question from either the local simulator or the demo.

The deployment sequence should preserve that separation. Code changes begin with deterministic local tests, pass CI on every commit, and then complete the full trading-day demo smoke test before deployment. Build and verify the plumbing first, then test the strategy against live books without committing capital.

Sources

  1. Quick Start: WebSockets - API Documentation

More in Kalshi API Integration