Payments PendingDry-Run Order Execution for Kalshi Bots Inside a Payment Flow Test Harness

Dry-Run Order Execution for Kalshi Bots Inside a Payment Flow Test Harness

A DRY_RUN flag blocks orders but misses the state failures that cost money.

· 8 min read

Testing a Kalshi bot before going live requires a locally hosted, stateful simulator, followed by Kalshi’s demo environment. A DRY_RUN flag can block real orders, but it cannot test balance checks, position tracking or fill reconciliation. A complete payment flow test harness must link those operations through state that lasts and catch failures before production credentials enter the system.

Why a DRY_RUN flag is not a test harness

Setting DRY_RUN=True at the top of a file creates a false sense of safety when the developer assumes every downstream function will respect it. In a documented SDK incident, trade(dry_run=True, venue="kalshi") fetched a quote, signed a transaction and submitted a real order. The underlying _execute_kalshi_byow_trade function had no dry_run parameter, so the flag disappeared at that boundary.

Every layer in the call chain had to pass along the dry-run flag, and execution had to short-circuit before any quote, sign or submit call and return a clear failure result. That closes the submission path, but it does not create a simulated payment flow. A bot that never submits an order can still fail to track exposure, reconcile fills or preserve limits across restarts. Preventing a transaction and testing its consequences are separate responsibilities.

What the Kalshi API actually does across a full order cycle

A Kalshi order cycle spans authentication, market discovery, placement, position tracking and balance reads. Each authenticated request requires KALSHI-ACCESS-KEY, KALSHI-ACCESS-TIMESTAMP and KALSHI-ACCESS-SIGNATURE. The signature is the Base64 encoding of the signed concatenation of timestamp, HTTP method and path. Kalshi supports Ed25519 by default and RSA-PSS with SHA-256. These are distinct signing paths to exercise in tests, while demo credentials are separate from production credentials and work only against demo endpoints.

Kalshi accepts only limit orders because it removed the market order type in April 2026. When filled contracts in a rolling 15-second window pass the group limit, every resting order in that group is canceled. The resulting order state therefore depends on both activity across the group and the response to an individual placement request.

The payment-layer reads expose different parts of that state. GET /portfolio/balance returns current balance and portfolio value, while GET /portfolio/orders retrieves resting orders. Each resting order contributes yes_price_dollars * remaining_count_fp to open exposure. GET /portfolio/positions?settlement_status=settled provides settled positions’ market_exposure_dollars. These reads are related but not interchangeable. The bot’s view of available funds and exposure depends on the results remaining consistent with the orders and fills that preceded them.

Kalshi’s demo WebSocket endpoint, wss://external-api-ws.demo.kalshi.co/trade-api/ws/v2, streams order book deltas, tickers, trades and fills. Those events extend the cycle beyond request-and-response HTTP interactions. A fill can change what a later position check must return. Kalshi publishes openapi.yaml for REST and asyncapi.yaml for WebSocket integration as machine-readable contracts. Those specifications provide the authoritative target for contract tests across both surfaces.

How the duplicate-order bug exposes what a flag-only approach cannot catch

The October 25, 2026 dry run showed how proposals that each follow the rules can still lead to a trading loop that breaks them. While the ask stayed low on ticker KXNFLTD-26OCT25KCSEA-KCAARMSTRONG85-1, the bot proposed a new 1-contract bid on every iteration. The Basic tier’s token-bucket rate limit slowed the loop, and the exposure cap eventually stopped it. Every proposal obeyed the “1 contract per order” rule. That rule did not constrain the accumulated position.

The restart exposed a second boundary failure. Exposure existed only as an in-memory count, so restarting the process returned that count to zero. The run produced 38 orders in one session and 38 more after restart. No check asked whether the ticker already had a resting order or an existing position before another proposal. Because the bot counted exposure rather than computing it from durable state, the restart also undermined daily-loss tracking.

Order timing had the same persistence gap. Timestamps were not saved to disk, so the per-minute limit reset with the process. In dry-run mode, that check must read a paper ledger at state/paper.json. The design rule follows from the sequence itself. Order limits must operate on persistent trading state, rather than on counters that vanish when execution stops.

Why stateless mocking cannot model this failure class

A stateless mock can validate a response without validating what the response changes. An order response can show success with the expected fields and status code even when every later position query is empty. The bot then treats itself as flat and proposes another order. Nothing in an isolated response assertion establishes that placement changed the state consulted by the next iteration.

In the canonical payment-flow failure, CI mocked POST /v1/payment_intents and asserted a 200 response, but the handler never stored the PaymentIntent ID. Production failed when the next step of the webhook path read undefined. The first request had passed its test. What remained untested was the dependency between that request and the later handler, just as the Kalshi loop failed to connect an order proposal with subsequent exposure checks.

Stateful mocking makes those dependencies part of the test. Chained scenarios can represent changes among resting, filled and expired order states, so a later query reflects earlier activity and a filled order is not proposed again. The paper ledger approximates that mechanism manually. Fidelity remains essential, however, because a simulator that accepts invalid tickers or ignores position checks can conceal the same defects. In one 2026 Kalshi bot run, a deliberately wrong ticker produced identical data errors 126 times, with the error presenting as a legitimate response.

What a complete dry-run harness must wire together

Connect execution to a locally hosted simulator that tracks the full trading and payment sequence. Intercepting outbound HTTP requests alone is insufficient. The paper ledger at state/paper.json must record every proposed order’s ticker, side, price, count and timestamp, then preserve those records across process restarts. Its queries must answer whether a ticker has a resting order, what current open exposure is and what balance began the day.

Daily-loss tracking also needs a durable starting point. state/day_start.json must save today’s first balance plus portfolio value from GET /portfolio/balance. That baseline is stored by the bot. It is not a separate daily-loss field returned by the endpoint. Saving it keeps a restart from replacing the day’s starting point with a new in-memory value. Together with the ledger’s timestamps, it lets loss tracking and per-minute order counting span process lifetimes.

Every function that could reach a quote, sign or submit operation must receive the flag as a parameter rather than depend on a global or module-level variable. Submission paths must stop before the quote fetch. When no Kalshi preview path exists, the harness must return an explicit failure TradeResult. This keeps an unsupported operation distinguishable from a successfully simulated one.

Retry behavior belongs in the same implementation. Only GET requests should retry automatically. POST order creation and DELETE cancellation must not retry, to avoid duplicate orders or duplicate cancels. The code that handles rate limits should follow Retry-After up to a reasonable cap and use short connect and read timeouts. Signing tests should exercise RSA-PSS and Ed25519 against the public key with a fake HTTP session. These tests need no real credentials and can expose signature errors before the first keyed request returns a 401.

Fault injection as a first-class concern in the payment flow

Once the simulator keeps state, fault injection can test what happens to that state when delivery breaks. Happy-path placement does not cover concurrent webhooks, missing fills, delayed events or mid-cycle network failures. Each requires an explicit test. The purpose is not simply to produce an error response, but to observe whether the next position query and order decision remain consistent with what happened before the fault.

Concurrent delivery of the same fill webhook tests idempotency in reconciliation. A fill webhook that never arrives tests whether position tracking stalls or recovers. A delayed fill that arrives after the client has already retried tests whether reconciliation updates the state twice. 429 or 503 responses and network timeouts in the middle of a cycle test whether the bot blocks more orders or proposes the failed operation again. These scenarios exercise different breaks in continuity, so passing one does not establish recovery from the others.

For an LLM-driven Kalshi agent, a tool-call failure introduces another ambiguity. A network error mid-call does not tell the agent whether the order was placed before communication failed. Blind retry recreates the duplicate-order risk at the tool boundary. The recovery pattern is verify-before-retry, using the paper ledger or simulator to check for a resting order on the ticker before re-proposing. Future frameworks and tool APIs with idempotency keys or explicit status endpoints can make recovery deterministic, but the harness must model the ambiguous case until those facilities exist.

How to test a Kalshi bot against the demo environment before using real credentials

Diagram: Three-Stage Testing Progression Before Live Credentials. Visualizes: Visualize the mandatory three-stage operational progression for testing a Kalshi bot: (1) Local Simulator — all API calls resolve inside a stateful simulator, no…

The operational progression is local simulation, then Kalshi demo, then production only after both pass. Each stage tests a different boundary. Locally, every API call resolves inside the simulator without credentials, allowing position checks, exposure accumulation, daily-loss tracking and per-minute counting to be exercised against persistent state. This is also where 429s, 503s, delayed fills and duplicate webhook delivery can be injected deliberately.

A locally hosted, stateful Kalshi API simulator can do this job if it is tested against the real API on an ongoing basis and before every release. It lets the bot trade and make payments in the simulation without live credentials or service rate limits. The ledger supplies the continuity that a flag cannot. Its responses to /portfolio/orders, /portfolio/balance and position queries must change with the simulated activity that came before them.

Kalshi demo then tests how the bot works with the service over real HTTP, using mock funds and separate demo API keys. Its WebSocket endpoint is wss://external-api-ws.demo.kalshi.co/trade-api/ws/v2. This stage exercises the chosen RSA-PSS or Ed25519 signing path against the service, where a signing error appears as a 401. Demo rate limits also apply. The bot’s 3-per-minute order limit is a separate application control, and persisted ledger timestamps prevent a restart from resetting that control and permitting another burst.

Contract tests keep the two stages connected over time. Hard-fail tests on every commit should compare the simulator’s fields, types and status codes with Kalshi’s openapi.yaml and asyncapi.yaml. Behavioral tests cannot substitute for that comparison, because a consistent local state machine can still expose an outdated API contract. Restart and fault tests are still needed when contract tests pass.

More in Payment Flow Testing