Tool Call Bench

Sandboxed Exchange API Testing Frameworks for Prediction Market Bots

Static mocks miss the stateful failures that sink prediction market bots.

· 8 min read
Cover illustration for “Sandboxed Exchange API Testing Frameworks for Prediction Market Bots”
Trading Bot Test Environments · December 1, 2026 · 8 min read · 1,800 words

Testing a Kalshi bot needs a stateful exchange simulator first, then checks against hosted and live environments. Static mocks cannot establish whether orders, fills, positions, and balances remain consistent across sequential API calls.

Why prediction market bots break in ways that static mocks cannot catch

A market-making bot can place valid quotes and still have no meaningful test of its strategy. If nobody can hit its resting orders, the simulation cannot measure fill rate or adverse selection, and the strategy’s profitability depends on both. Order acceptance is not evidence of execution quality. Even a liquidity-taking bot depends on a linked sequence of decisions, order placement, fill confirmation, and position updates, where each result constrains the next call.

Static fixtures sever those links. A status endpoint that always returns the same response can leave a polling loop running forever or make it terminate immediately. Its order ID may not match the order just created, and a cancel-after-fill conflict cannot occur if cancellation does not consult the filled order’s state. When balance changes, book updates, and fill events are independent fixtures, the environment cannot expose failures in the causal relationships between them.

What the order book state machine actually requires from a simulator

A credible simulator needs an order book with price-time priority matching, a fill engine that updates positions, and a balance ledger that records deposits, withdrawals, and settlement. Those subsystems must share a consistent state. Resting orders must stay in the book between requests, and each new order must meet the depth already there. Cancellation must remove that depth at once, and the change must show up in later order book queries.

Matching must also produce linked changes before the next read. When a taker order crosses the spread, the fill engine must generate a fill event, reduce or remove the maker’s resting quantity, credit the taker’s position, and debit the maker’s. The ledger has corresponding obligations. A deposit or margin call must appear on the next balance query, a withdrawal must fail if it would make the balance negative, and settlement must transfer funds from the losing side to the winning side atomically. A bot that observes an order as filled and then cancels it must receive a 409 conflict, with a 200 response constituting an error.

Rate limiting belongs in this state machine too. Kalshi switched to a token-bucket model as of 2026-04-23, with independent buckets and no Retry-After header. The simulator must therefore represent consumption and replenishment and vary its 429 responses accordingly. Elapsed time changes what the client may do next. Without that behavior, a retry test that passes says little about whether the bot will recover correctly when its live request budget runs out.

The options developers actually use and what each one can and cannot hold

Kalshi’s demo environment provides mock funds, the same endpoints as production, separate API keys, and REST, WebSocket, and FIX interfaces. Its full central limit order book, or CLOB, uses a real matching engine, with other developers testing as counterparties. However, Kalshi warns that demo markets “may not be reflective” of real ones. Correct matching in the demo therefore does not show what production fill rates or adverse selection will be.

SKALE Network introduced AgentPit on August 12, 2026, as a Polymarket-compatible sandbox that synchronizes real market questions, prices, and resolution states. It uses price-time priority matching, simulated USDC and outcome tokens, and a shared book for autonomous agents and human participants. A house market maker mirrors Polymarket’s real depth so that a counterparty is always present. Counterparty availability is built into the environment. AgentPit also reproduces Polymarket’s REST structure and data schemas, manages wallet operations through a streamlined API key system, and integrates with OpenClaw for execution, memory, and orchestration.

Manifold provides play-money trading with other users as counterparties and a matching system combining limit orders with an automated market maker. It is not a Kalshi or Polymarket API replica, so production integration code must be rewritten. Simmer serves a different purpose. Its AI-agent harness uses virtual $SIM and an automated market maker as counterparty, rather than a CLOB, so it cannot test order book depth or price-time priority mechanics. Polymarket itself has no official sandbox or testnet, leaving small real orders on the live network as the direct testing path there.

Two CI jobs from the same team can interleave writes, producing flakes that resemble race conditions in the bot. The matching engine may behave correctly throughout. The test nevertheless loses control over the state on which its assertions depend. Per-job isolation requires either separate environments or tenant-keyed reset endpoints and cleanup infrastructure, which the team must then maintain.

Official environments do not expose a fault-injection surface for deliberately dropping a WebSocket connection, returning a malformed order book payload, or introducing latency that produces a stale fill. Nor can a team reliably arrange a 429 response without a Retry-After header at the precise point a test requires. Access itself adds dependencies. Kalshi demo calls require demo credentials, consume token-bucket budget, and need network access, making that environment unsuitable for offline or air-gapped CI.

A simulator can become internally consistent while drifting away from the exchange it represents. Kalshi’s rate-limit model change illustrates the risk, because obsolete bucket behavior could leave retry tests passing against the wrong rules. Drift can remain silent until deployment. Local simulation therefore needs continuing comparison with live API behavior even if its implementation matched the API when it was first written.

What stateful simulation looks like in a local CI-safe environment for exchange APIs

A local stateful environment keeps the book, fill engine, and ledger in an instance that belongs to one CI job. State belongs to that instance alone. Destroying the process tears down the environment, so there is no need for shared cleanup jobs or tenant-key management. This gives each run control over its initial conditions and the sequence of changes it exercises. Pre-seeded markets, realistic depth, and plausible price histories also give decision logic something to act on, instead of leaving every team to construct an exchange from empty fixtures.

The simulator needs controls for latency, dropped connections, malformed payloads, and 429 responses both with and without Retry-After headers. Its Kalshi behavior must follow the token-bucket rules introduced in April 2026, so retry tests check replenishment. These tests require no live API access. Running locally without an API key removes exchange credential exposure and lets the CI environment work offline.

For a Kalshi bot, the required surface includes REST, WebSocket, and FIX, together with endpoints such as GET /markets/{ticker}/orderbook, POST /portfolio/events/orders, and their perps variants. The responses must also track the same exchange state as it changes, which protocol coverage alone cannot show. Fidelity requires a separate release check. Running the simulator’s test suite against the real API before each release is intended to expose behavioral divergence before the simulator ships, while ordinary CI runs remain local. AgentPit’s production-style CLOB establishes a relevant architectural target, but the local implementation must make that behavior deterministic and resettable without a network dependency.

Testing an AI prediction market agent requires the same infrastructure, applied to tool calls

An AI prediction market agent inherits the bot’s state requirements and adds a semantic failure mode. Its tool calls can each look right but be wrong when taken in sequence. An order can be placed successfully without its fill being confirmed correctly, and a valid cancellation request may still conflict with a fill already seen. The environment must retain those dependencies. Testing only tool names, arguments, or response formats cannot establish whether the agent’s decisions remain consistent with the exchange state it has created.

IIT’s Agent Error Simulator, presented at eScience 2026, introduced declarative fault injection through a transparent proxy in hierarchical planner-worker-aggregator workflows. AES reported “universal catastrophic failure under aggregator-level logic injection.” That finding is limited to the tested agent workflows. The architectural connection is nevertheless direct. A prediction market planner can delegate order placement to a worker and fill confirmation to an aggregator, making the integrity of the combined result essential to subsequent trading decisions.

AgentPit lets agents test against one another in its multi-agent arena. Agents meet each other’s resting orders and fills, so competing strategies can interact in a controlled setting before they go live. Local simulation serves the repeatability requirement instead. Reinforcement learning needs thousands of sequential market interactions per training run, with each action updating state correctly and each environment remaining deterministic, resettable, and horizontally scalable. CI regressions and reinforcement learning thus share an infrastructure requirement, even though one checks behavior and the other trains it.

How do you test a prediction market trading bot before going live?

Diagram: Four-Layer Testing Sequence: From Local Simulator to Live Trading. Visualizes: Show a stepped, sequential flow of four testing layers a prediction market bot must pass through before going live.

The practical sequence starts with Layer 1, a local stateful simulator for unit and integration testing on every commit. This is where teams should exercise the bot’s code paths under isolated state and inject 429 responses, latency, dropped connections, and Kalshi’s token-bucket behavior. No exchange credentials or rate-limit budget are needed. The objective is to establish sequential correctness, including whether a fill changes later reads and whether a conflicting action receives the appropriate failure. Strategy evaluation needs those checks, but correct execution alone does not show that a strategy will make money.

Layer 2 is Kalshi’s official demo environment as a pre-deployment gate. After local tests pass, the demo should validate real authentication, WebSocket streams, and FIX protocol handling against exchange infrastructure. This tests a different boundary. Shared state and credential requirements make the demo unsuitable as a substitute for isolated CI, but those same real interfaces make it useful before production access. Keeping this stage separate also distinguishes an infrastructure integration failure from a failure already reproducible locally.

Layer 3 is a live paper venue with a real matching engine, such as Rizon or Kalshi demo, for market-making behavior under real or bot-generated flow. This stage checks fills and what happens when quotes go stale, including whether a quote gets hit and loses money. Flow is the distinguishing input here. Kalshi’s warning about demo representativeness still applies, so results cannot establish production adverse selection merely because the venue uses a real matching engine. Layer 4 is small real size with hard limits in code, where real flow can reveal behavior that paper trading cannot.

For AI agents, the sequence also needs a regression gate after any prompt, model, or orchestration change. The full tool-call sequence should rerun against the local simulator before promotion to the sandbox. That keeps changes to the decision-maker subject to the same state requirements as changes to trading code. It also reserves hosted testing for questions that require hosted infrastructure. At reinforcement-learning scale, with thousands of interactions per run, only Layer 1 is economically viable, making deterministic local stateful simulation the foundation.

More in Trading Bot Test Environments