CI Pipeline Testing for Kalshi Bot Order Logic
A stateful simulator lets CI test trading bot order logic without touching production or demo.

Integration testing against stateful APIs requires a locally hosted simulator that remembers prior calls, updates shared state, and exposes failures without touching production. For Kalshi bot order logic, that simulator must enforce request signing and reproduce order transitions, position updates, and retry conditions. A CI pipeline built around those behaviors tests mechanical correctness on every commit without placing real trades or depending on the demo environment.
Why testing Kalshi bot order logic in CI is structurally different from testing ordinary API integrations
A Kalshi bot executes a chain of financially consequential operations, including authentication, market retrieval, order placement, fill tracking, and position updates. Each operation changes what the next operation should do. A regression that goes unnoticed can then lose money even when each request succeeds. The bot also combines two distinct test surfaces, namely a transport-and-protocol layer and an agent decision layer. RSA-PSS signing, rate-limit handling, and WebSocket reconnection belong to the first, while LLM tool selection, order parameterization, and risk governor behavior belong to the second.
Authentication alone has a precise failure surface. Kalshi requires three headers on every authenticated call, including a key ID, a timestamp in milliseconds, and a base64-encoded signature. The signature is built from the concatenation of timestamp, HTTP method, and request path, signed with a private key using RSA-PSS and SHA-256. A wrong concatenation order returns a generic 401 without diagnostic detail. The bot can fail at this step before it reaches its order logic, with little to show what caused the failure.
The payload contract can shift just as sharply. Since March 12, 2026, Kalshi has used fixed-point dollar strings with the *_dollars suffix for prices, such as "0.6500", and fixed-point strings with the *_fp suffix for quantities, such as "10.00", replacing older integer formats. The Kalshi Developer Agreement v1.1, Section 2.2, commits to best-effort advance notice of major changes only for endpoints marked “stable”, while beta endpoints can change without notice. Production bot logic must therefore distinguish which endpoints it can depend on. AI agents add non-determinism to this already complex protocol because the same input can lead to different tool selections, order parameters, and reasoning chains from one run to the next, without regressions causing clear test failures.
Why Kalshi's two official environments — production and demo — cannot anchor a CI workflow
Production places real orders with real funds, making every-commit execution financially and operationally untenable. Demo removes that financial exposure, but not the uncertainty needed for repeatable assertions. Kalshi warns that demo prices and market behavior “may not be reflective of those in real markets”. Demo has a legitimate role in initial plumbing checks. It can validate the signing handshake and connectivity, but it cannot anchor correctness assertions about order lifecycle, partial fills, or retries under realistic state conditions.
Basic production accounts face documented token-based limits of roughly 20 reads and proportionally fewer writes per second, while demo rate-limit parity is not explicitly confirmed. A full CI suite can encounter rate-limit errors that interrupt the run rather than deliberately exercise the bot’s response to them. The ryanfrigo/kalshi-ai-trading-bot project separates that exposure by skipping tests marked live unless RUN_LIVE_TESTS=1 pytest -m live explicitly enables them against an account whose losses the developer accepts. That is a manual escape hatch.
How to test APIs where order of operations matters with stateful simulation, not stateless mocks
A fill created through POST /orders must be visible on a subsequent GET /portfolio/positions. A stateless mock can confirm that the order request is well formed, but its position response remains the same regardless of what was posted. The causal link is missing from the test. As a result, the test cannot establish whether the bot reads and acts on the position created by its own order.
A stateful simulator preserves that link by tracking prior calls and updating its internal records. Creating a record, listing it, and deleting it changes what later requests can see. Kalshi order testing needs the same property across placement, partial fill, and cancellation. Without it, duplicate client_order_id retries, partial-fill handling, and position reconciliation remain untested as connected behaviors. For an LLM-driven bot, state must also persist across turns so that later tool calls encounter the consequences of earlier ones.
Stateful tests are slower and complicate parallel execution, so the appropriate architecture is hybrid. Early checks for signing, request-shape, and parameter-validation can use stateless stubs and run in parallel. Order-lifecycle integration tests should use isolated data and run serially. This confines sequencing costs to tests whose assertions actually depend on prior operations.
What a stateful Kalshi simulator must faithfully reproduce to be useful in CI
The simulator must enforce the key ID, millisecond timestamp, and base64-encoded RSA-PSS signature contract, returning meaningful errors for the wrong concatenation order or algorithm. Payload validation needs comparable strictness. It must enforce fixed-point dollar prices and count_fp quantities rather than accepting legacy integer-cent formats as interchangeable. Otherwise, a serialization regression can pass locally while failing against Kalshi.
Order transitions are the next fidelity requirement. The simulator must model resting, partially filled, executed, and canceled states, with subsequent reads to /portfolio/positions and /portfolio/fills reflecting the transitions. Kalshi uses client_order_id as an idempotency key, so reusing one returns the original order without placing another. The simulator must detect that reuse and test the bot’s duplicate-retry guard against the state that follows.
Faults need to be controllable. Configurable rate-limit thresholds must produce errors that exercise exponential backoff, which the agreement’s API best-practices clause requires. The simulator must also support dropping and re-establishing a WebSocket connection during a sequence. That lets tests make assertions about reconnection logic, sequence-number tracking, and local order-book patching without waiting for a network event that may or may not happen.
These contracts need an external check over time. A simulator that is not continuously compared against the live API can drift as Kalshi changes, even while its own test suite remains green. Published fidelity scores against the real API provide a mechanism for judging whether that comparison is being maintained. Local repeatability and API fidelity serve different purposes. The former makes failures reproducible, while the latter establishes whether the reproduced behavior still represents the service.
Structuring the CI pipeline: stages, data isolation, and the gate that blocks a bad image from shipping
The practical workflow should separate four stages and finish with one image-promotion gate. Stage 1, signing and request-shape validation, should verify the three-header signing structure, fixed-point prices, and count_fp serialization. It should also check that each new order submission receives a unique client_order_id, distinct from a retry of the same order. These checks are stateless and can run in parallel. They establish that requests meet the contract without claiming to test the consequences of those requests.
Stage 2, order lifecycle integration, should start the stateful simulator with market data already seeded. Each scenario should authenticate, fetch markets, place an order, observe a partial fill, cancel the remainder, and confirm the position update. Isolated seed data keeps one scenario’s orders from contaminating another. These tests should run serially and verify that submitting the same client_order_id twice triggers the duplicate-submission guard. The project’s live-test marker pattern keeps this routine suite that uses the simulator separate from the live smoke tests run by hand from time to time.
Stage 3, agent tool-invocation testing, should replace the LLM call with a deterministic mock returning fixed JSON tool selections. The model is an external dependency here. The stateful simulator then handles downstream API calls, making routing, order parameterization, fill parsing, and position-model updates repeatable. Assertions should target endpoint selection and parameters rather than the coherence of the agent’s text, because fluent output can accompany malformed trading JSON. Tool-invocation patterns should also be tracked across runs, while recognizing that fixed mocked selections do not measure changes in a live model’s behavior.
Stage 4, fault injection and resilience, should add failures to the same order sequence. Configured 429 responses test exponential backoff, while simulated latency and 503s at execution test timeout handling and circuit-breaker behavior. WebSocket drops test reconnection, sequence-number tracking, and order-book patching. Partial-fill scenarios must also establish that the bot does not submit an already filled portion as a new order. Fill data for edge cases should test the hard risk checks for maximum price, maximum contract count per order and per day, and daily loss limits.
Define the workflow in .github/workflows/ci-cd.yml, build the image once, and run all four stages against that image. The exact image that passes, including the fault-injection suite, should be promoted and deployed. A separate deploy build would break that connection. Live-API smoke tests, if used, belong after promotion on a dedicated staging runner, outside the main CI gate.
Extending the same simulator substrate to the bot's downstream dependencies — Slack alerts, payment rails, and position telemetry
An order can trigger effects beyond the Kalshi integration, including a Slack alert, a ledger write, and potentially a payment or withdrawal event. Those dependencies extend the correctness boundary beyond trading requests. A bot may place the right order while failing to tell its operator what happened or record the resulting position. Testing each dependency on its own cannot show whether its output matches the fill from the same run.
A stateful Slack simulator should check which channel gets the alert, what the message says, and when it arrives in the order lifecycle. A successful webhook POST is not enough evidence. The alert must reflect the actual fill data returned by the Kalshi simulator. The same pattern applies to PayPal or Stripe funding and withdrawal integrations, where payment-trigger logic needs to be tested under the correct position conditions. Ledger writes and position telemetry should also be tested as part of the downstream chain, beyond separate request-shape checks.
Running the dependency graph locally also changes where CI can operate. Kalshi, Slack, and payment simulators enable offline and air-gapped execution for teams that cannot expose API credentials in CI. By contrast, giving each dependency a different mock strategy leaves the chain represented at inconsistent levels of fidelity. That inconsistency prevents a coherent end-to-end correctness claim even when individual integration tests pass.
What a well-verified CI setup for a Kalshi bot actually tells you — and what it deliberately does not
Passing this pipeline provides confidence in mechanical behavior under the tested scenarios. It establishes that signing, lifecycle handling, deterministic agent routing, and recovery paths satisfy their assertions. It does not establish positive expected value. Determining whether entry and exit rules produce an edge against the Kalshi book requires historical data replay and out-of-sample measurement.
The project illustrates that separation through its cli edge command. It reads locally persisted settlements pulled by the separate cli settle command, computes Brier score and edge vs. book, and refuses to claim edge below a threshold of forward-settled trades. That measurement harness is separate from the integration suite. Risk controls, however, remain within CI’s scope because maximum price, contract limits, daily loss limits, and the order-group backstop constrain execution regardless of strategy quality.
Confidence also depends on which contract the tests represent. When Kalshi introduces a field-format, endpoint, or rate-limit change, the next live-API fidelity check should expose the discrepancy before code is committed against outdated behavior. A green local run cannot substitute for that check. Within a single sprint, a team can wire a stateful Kalshi simulator into an existing pytest suite, separate signing, lifecycle, and agent tests, add 429 and WebSocket-drop scenarios, and gate promotion on all four stages passing.


