Constructing a Kalshi Strategy Backtest From Raw API Event Logs

A Kalshi backtest must route data tiers, gate leakage, and fill at quotes.

· 8 min read
Cover illustration for “Constructing a Kalshi Strategy Backtest From Raw API Event Logs”
Kalshi API Integration · November 21, 2026 · 8 min read · 1,854 words

Testing a Kalshi bot requires a backtest that reconstructs both what the strategy could know and what it could execute at each timestamp. That means routing raw API records across the live and historical tiers, keeping their observation times, and simulating fills at executable quotes. The order is essential because execution logic cannot repair an incomplete universe or contaminated features.

Why Kalshi's API is split into two tiers and what that means before you write a single line of backtest code

Kalshi’s historical data tier is a separate endpoint surface. Markets and candlesticks for contracts settled before the moving cutoff belong to the historical tier. Trades have a separate boundary, trades_created_ts. Consequently, a pipeline cannot assume that one endpoint, queried with an earlier start date, returns the entire record. It also cannot safely use the market cutoff as the boundary for every record type.

A contract universe enumerated through GET /markets can stop at the cutoff while every request returns HTTP 200. Subsequent candle requests can also succeed because they fetch only the tickers already discovered. A backtest can therefore train on two months of data while appearing to cover a year. Nothing in those successful responses exposes the omitted contracts.

The boundary also advances as markets pass into the historical tier. A hardcoded cutoff can become stale even when the collection code has not changed. Completeness therefore depends on routing as well as successful requests and correctly parsed timestamps. The first engineering decision in a Kalshi backtest is therefore not strategy logic. It is data routing.

Routing raw event logs across the live/historical cutoff without losing records or duplicating them

To address that discovery gap, the collector must query the historical tier for markets settled before the documented market_settled_ts cutoff and the live tier for everything else. It must implement both candlestick routes. The live path is /series/{series_ticker}/markets/{ticker}/candlesticks, while the historical path is /historical/markets/{ticker}/candlesticks. Their response schemas are the same, but their routing requirements differ. Normalization belongs after that distinction.

Collection requires pagination because list responses return up to 100 records per call and a cursor token for the next page. Stopping after the first page produces another silent gap, even when the collector selects the correct tier. After collecting the pages, the pipeline should merge and deduplicate records using stable identifiers, including series ticker, market ticker, and timestamp. Strategy logic should get that merged dataset rather than separate outputs from each tier that may overlap.

Raw responses should be kept with the normalized rows. This preserves the evidence needed to reproduce a parsing fix or schema correction without fetching the data again. Before strategy evaluation, the pipeline should also build a manifest with one row per market containing its series ticker, market ticker, open time, close time, settlement time, final result, rule text, and settlement source. Each field needs an observation time. A final result may belong in the archive without yet belonging in the feature table.

Similar headlines can describe contracts with different thresholds, operators, time zones, or settlement sources. A title-only join can therefore combine contracts that were never equivalent. Stable identifiers preserve record identity, while the manifest preserves the contract definition and the timing of what became known.

What the candlestick schema actually exposes, and what it cannot reconstruct

A Kalshi candlestick contains three separate OHLC blocks. The price block shows executed trades, yes_bid shows the resting buy side, and yes_ask shows the resting sell side. Each has its own open, high, low, and close for the interval. These are distinct inputs to execution modeling. A traded price does not substitute for the quote at which a new order could execute.

The orderbook response uses a different representation. It exposes yes_dollars and no_dollars bid ladders. The best YES ask is one dollar minus the best NO bid, while the best NO ask is one dollar minus the best YES bid. That crossed-sides arithmetic must be explicit when interpreting book snapshots. Reading both ladders as independent bid-and-ask sides would misstate the available prices.

Candles summarize intervals. They do not show every queue position, cancellation, or depth change. The /markets/{t}/orderbook endpoint supplies a live-only snapshot, and there is no Kalshi-native historical orderbook API. A depth-sensitive study therefore requires timestamped snapshots or WebSocket messages collected while the market was live. Predexon’s tick history offers another route, covering Kalshi and Polymarket order book event streams in a common schema for cross-venue microstructure work.

Candle labels including source, sourceType, quality, and isTrueCandle identify intervals that cannot be traded against and must be dropped. Crossed candle data, where bid exceeds ask within an interval, must also be excluded. The manifest should record the drop counts. Those exclusions define the usable evidence before any fill assumptions are applied.

The three look-ahead contamination paths that survive a surface-level bias check

Resolution leakage starts in the market object itself. The response includes result, settlement_value_dollars, and settlement_ts together with open-market fields, so ground truth can arrive during universe construction. Joining the complete object into features can expose an outcome before the decision timestamp. Settlement data needs a temporal gate. A field belongs in a decision only when its observation time permits it, and a result must not enter features before settlement.

Unsettled-but-closed leakage enters through sample selection. A closed market that has not settled returns an empty result. Treating that blank as grounds for removal from scoring admits only markets with clean outcomes and biases the reported win rate upward. The blank means no outcome is known. It does not mean that the contract was absent from the tradable population or that its exposure can disappear from the report.

Macro revision leakage substitutes later knowledge for the original signal. CPI, NFP, and GDP figures can be revised, so a strategy using economic releases needs the vintage available at decision time. The timestamp of the market candle does not solve that problem. The external input must also be point-in-time correct.

Universe survivorship is a fourth, structural contamination path. A universe built from currently listed contracts can omit markets that were delisted, voided, or never resolved. Getting the timing right for every feature in the surviving sample does not bring back those missing contracts. The population must represent what was tradable at entry. Together, these checks constrain both the information available to the strategy and the contracts on which its results are judged.

Simulating fills against candle spread data without inventing liquidity

A marketable buy executes against the ask, and a marketable sale executes against the bid. Neither the midpoint nor the last trade can stand in for the ask or bid. The midpoint is not an executable market price. Candle-based simulation can use the separate quote blocks to model spread costs, but it cannot use their presence to claim knowledge of queue priority or depth throughout the interval.

Timing must follow the signal’s information boundary. A signal based on a closed candle cannot get a fill inside that same candle. Its earliest possible execution is the next observable quote, represented in a candle-based model by the following interval’s opening ask for a marketable buy. Missing quotes must remain missing. Forward-filling a display price and executing against it invents liquidity that may never have existed.

Size requires a separate constraint from price. Where recorded depth is available, fills must be capped against it. With candles alone, a conservative proxy is a fraction of the interval’s traded volume, and no fill should exceed what that volume can support. In particular, the interval’s completed volume cannot become information used to generate a signal at its opening.

After a close-based buy signal, the simulator checks the next interval’s opening ask, leaves the order unfilled if that quote is missing, and limits the requested quantity using the volume cap. A supported quantity smaller than the request produces a partial fill. If it supports a quantity of zero, the order gets no fill. Always granting the full requested size overstates access to liquidity, especially in thin markets near expiration.

Binary payoffs make these assumptions economically decisive. Buying YES at 74¢ when fair value is 85¢ means a win pays 26¢ and a loss costs 74¢. A systematic fill error near the profitability boundary can reverse the sign of expected value. Fees must also use the schedule effective on the simulated date, with approximations labeled in the manifest. Trading stops at the documented contract close, and remaining positions settle at the actual result, with full payout for YES and zero for NO.

Rate budget management as a backtest infrastructure constraint, not an afterthought

Execution realism depends on a collection process that remains intact. Kalshi’s rate limits use a token bucket that keeps refilling. Public market-data calls, including order books and trade history, use a Read bucket that is separate from the Write bucket for trading endpoints. Both buckets nevertheless remain governed by the account’s tier limits, so separating their roles does not remove the need to budget requests.

Collection should degrade deliberately while preserving state. The practical architecture uses defined thresholds to move first to minimum-frequency polling, then to disabling scanning while processing only order confirmations, and finally to a complete halt near the limit. These transitions belong in the operating design of a collector that also supports live execution. A pipeline used only for analysis avoids signed trading calls but still has to budget its reads. Scanning many markets at short intervals can exhaust that budget.

Every API request should be logged, with the daily total tracked in real time. Discovering exhaustion afterward leaves a gap in the historical record. Such a gap affects later backtests as well as the collection run that produced it.

Assembling the layers in the right sequence to produce an auditable backtest

The integrated pipeline begins with routed collection and deduplication. The manifest then attaches contract definitions and field observation times before any strategy features are built. Candle validation follows, removing unusable and crossed intervals and recording the exclusions. Only then can temporal checks determine which surviving fields were available at each decision timestamp.

Execution consumes those validated, time-constrained inputs. It applies ask-side buys, bid-side sales, size limits, partial and zero fills, and the dated fee schedule. No execution precedes the next observable quote after its signal. Settlement then applies actual contract results at settlement time, and reporting computes P&L net of fees. Drop counts and approximation flags belong beside that result, including labels for positions evaluated with approximated data.

The pipeline itself also needs testing before its performance output is trusted. A stateful simulator that keeps market, candle, and orderbook state between calls can return responses that agree with each other as the client uses both tiers. That allows tests to expose wrong endpoints, missed pagination cursors, and stale cutoff handling before strategy logic consumes corrupted inputs.

The final artifact must preserve that chain of evidence. It should show which tier supplied each candle, which intervals were excluded, which information was available to each decision, and which fills were size-capped. A positive result without this lineage hides the errors that could have produced it. A credible Kalshi backtest is therefore a documented path from raw API response to P&L line.

More in Kalshi API Integration