Enforcing Order-of-Operations Correctness Across Kalshi Place-Modify-Cancel Sequences

A stateful simulator catches invalid Kalshi order sequences that canned mocks wave through.

· 8 min read
Cover illustration for “Enforcing Order-of-Operations Correctness Across Kalshi Place-Modify-Cancel Sequences”
Kalshi API Integration · November 24, 2026 · 8 min read · 1,708 words

Integration testing against stateful APIs requires a simulator that preserves state between calls and rejects operations that are invalid from the current state. For Kalshi’s place-modify-cancel sequences, that means enforcing lifecycle transitions, terminal-state guards, and state-dependent deduplication. The simulator must also be continuously verified against the live API, or passing tests will validate an outdated contract.

What Kalshi's order lifecycle actually is as a state machine

Diagram: Kalshi Order Lifecycle State Machine. Visualizes: Show the finite-state machine for a Kalshi order.

Kalshi’s order lifecycle has a finite set of states, including resting, partially filled, fully filled, canceled, and expired. An operation’s validity depends on both the order’s current state and the request’s fields. A filled or canceled order cannot be amended. The API rejects that transition rather than treating it as a harmless no-op, so an otherwise well-formed request can still be invalid.

Kalshi’s quick-start guide shows placement through POST /trade-api/v2/portfolio/events/orders, with fields including ticker, side, count, price, time_in_force, self_trade_prevention_type, and an optional client_order_id. Amend uses POST /trade-api/v2/portfolio/events/orders/{order_id}/amend to change price and count on a resting order. Decrease uses POST /trade-api/v2/portfolio/events/orders/{order_id}/decrease only to lower the quantity of a resting order, while cancel uses DELETE /trade-api/v2/portfolio/events/orders/{order_id} to end a resting order.

Those operations are not interchangeable, and endpoint validity is a separate boundary around the lifecycle. The JBERRY2347 autopilot migration encountered HTTP 410 deprecated_v1_order_endpoint when its first placement reached the deprecated path. The request could not enter the order lifecycle at all. Once a request reaches a supported endpoint, its fields and the target order’s state decide whether the requested transition is allowed.

Why stateless mocks cannot model this lifecycle

A stateless mock has no memory of earlier requests. It can return a successful amend response without knowing whether the target order was ever placed, has remaining quantity, or has already filled. Consider a test that fills an order and then amends it. A canned 200 makes the test pass, but the live API rejects the same sequence because the fill made the order terminal.

A conditional mock can recognize a correctly shaped amend request, but it cannot infer the order’s current state from that shape. A static mock does even less: it returns the same success even when there is no order. Scripted logic can encode these distinctions, but once it retains order history and implements transition rules, it becomes a second implementation of the exchange that requires maintenance.

Deduplication makes the missing history especially consequential for retries. The client_order_id rejection is reliable only while the order is open, so a retry after a fill cannot be evaluated by matching the identifier alone. A mock that always rejects duplicates misrepresents one state, while one that always accepts them misrepresents another. That bug can reach production, where it can cause a double submission or waste write-token budget on rejected operations.

What a stateful simulator must track to enforce order-of-operations correctness

A simulator must retain each order’s lifecycle state, remaining count, price, side, and association with client_order_id. Remaining count governs whether a decrease is possible, while price and side preserve the meaning of a V2 order. State must change after each accepted transition so that the next request is judged against the resulting state.

For amend and decrease calls on filled or canceled orders, the simulator must replace generic 500 responses or silent 200 successes with the same error codes as the real API. Decrease must also reject a request to raise quantity or take it below zero. Deduplication must depend on state, rejecting resubmission while the order is open and allowing or treating it as a new order after termination according to the documented behavior.

Kalshi’s order groups allow an update to a contracts limit to trigger cancellation of all orders in the group. The simulator must propagate that change to the affected orders. It must also extend endpoint coverage beyond the legacy /portfolio/orders path to implement the V2 endpoint surface.

How the V2 migration exposed order-of-operations failures in real integrations

The JBERRY2347 migration exposed an integration failure at its first demo placement. The autopilot called the deprecated order path and received HTTP 410 deprecated_v1_order_endpoint. That was an endpoint failure. Its relevance to lifecycle testing is the boundary it exposed between code that can issue a request and code that can actually enter the supported state machine.

The repair required more than replacing a URL. The tool’s yes/no model had to map onto V2’s bid/ask representation, where buying YES at price p becomes a bid at p, and buying NO at price p becomes an ask at 1−p. An order with the wrong mapping can receive 200 even though it has the opposite position. That semantic error becomes visible when fills arrive, so response status alone cannot establish that placement was correct.

The migration also changed the application’s response to rejection. A rejected order is now journaled as order_rejected, and the pass continues to the next plan. Tests must cover both the exchange transition and the application’s next step. A simulator enforcing the V2 surface could have rejected the deprecated path during CI, before the first demo execution, while lifecycle assertions could have checked the resulting side and price. The case establishes where the defect should have surfaced without assuming that a particular mock implementation caused it.

Where Kalshi's current API surface adds new transition constraints to track

Kalshi’s November 2026 changelog makes side validation a concrete source of simulator drift. Create Order, Amend Order, and Batch Create Orders all need it on both Margin and Predictions. A missing value returns [400 missing](https://docs.kalshi.com/changelog)_parameters, while an invalid value returns 400 invalid_parameters. Margin previously treated an omitted side as an ask, so preserving that behavior in a simulator would now accept a request the API rejects.

Other guards depend on more than the order record. Margin exit-trigger writes reject a take_profit_price or stop_loss_price that the current mark has already passed, using 400 with take_profit_already_breached or stop_loss_already_breached. On-request market creation also has per-account limits within a rolling 24-hour window, returning 429 with stable endpoint-specific codes. These constraints require the simulator to account for current market conditions or account history where the operation depends on them.

Authentication creates another route to divergence before an order transition occurs. Ed25519 is the default for new keys as of October 1, 2026, while RSA remains offered. A simulator supporting only RSA cannot exercise new-key integrations correctly. Point-in-time fidelity becomes stale as request validation, guard conditions, authentication support, and rejection codes change, even if the familiar place-amend-cancel sequence still looks the same.

How do you write integration tests where Kalshi order operations must happen in the right order?

A lifecycle test must establish a prior state, attempt an operation, and assert both its response and its effect. For a filled order, an amend test must expect the correct rejection code. A decrease that raises quantity must be rejected. A second cancel on an already-canceled order must also return the correct error.

Deduplication tests need contrasting histories for the same identifier. A second placement with the same client_order_id must return 409 order_already_exists if the first order is still resting, but the terminal-state case must match what the API does in that state. The same suite must test field validation, including an amend with a missing or invalid side. Parallel tests need isolated order IDs and terminal-state cleanup between runs, or serial execution with isolated fixtures, so one test cannot supply another’s accidental precondition.

Seeding the tests with resting orders at several price levels, partially filled orders, and recently canceled orders cuts down on setup work. Simulated 429 write-token exhaustion and 503 exchange unavailability test retry and backoff handling, including whether a cancel retry accidentally resubmits a create. The demo environment has a narrower role in this workflow, checking RSA or Ed25519 signing, V2 routing, and error handling. Its fills do not reflect production liquidity, so it cannot fully establish order-execution correctness.

Why AI agents calling Kalshi's API need the same state-machine enforcement

An AI agent can choose the right tool and still perform the wrong operation. Selecting amend is not correct when the target order is already filled. The tool name and parameters are only part of the evaluation, because validity also depends on the accumulated effects of earlier calls. Agents face the same terminal-state risks as human-authored integrations, at higher frequency and with less ability to reason about rejection.

Tool correctness therefore requires a stateful execution environment. Deterministic evaluation checks whether the agent called the right tool with the right parameters in an order permitted by the current state. The AppWorld benchmark tests this distinction with state- and execution-based unit tests in several simulated apps. For Kalshi, these checks test what happened in the lifecycle, such as whether an amend was rejected after a fill or a retry created another order.

Reinforcement learning also needs reward signals that stay consistent. A deterministic, stateful simulator must produce consistent outcomes for equivalent states and actions across rollouts, rather than randomly rewarding an invalid amend because of mock behavior. Otherwise, training can reinforce the wrong policy. To run that training across thousands of parallel environments, each simulator instance must also have its own isolated state. One environment’s placements must not alter another’s fill state, or the reward no longer describes the agent’s own sequence.

The continuous verification requirement that keeps a simulator honest

A simulator can remember every order and still enforce the wrong contract. Keeping state lets responses take earlier calls into account, but validation and error semantics can still be outdated. The changelog shows how that mismatch grows as field requirements, stable rejection codes, guard conditions, and account limits are added. A test can then pass because it agrees with the simulator even if it would fail against Kalshi.

Provider sandboxes have an analogous drift risk. Production responses can gain fields before sandbox responses do, while rate limits and webhook payloads can differ between environments. For a stateful simulator, maintaining authority requires comparison of accepted and rejected transitions, including the errors returned, rather than checking only that requests still receive responses.

The release requirement is to run the simulator against the live API before every release and block release when its enforced transitions diverge. This gives continuous verification an operational meaning. Published fidelity scores show how closely simulator responses match the API, so developers can judge how much to trust a passing test.

Sources

  1. Quick Start: Create your first order - API Documentation
  2. API Changelog - API Documentation

More in Kalshi API Integration