All postsAutomation & Coding

Building a Prediction Market Data Pipeline

PMA Research · · 7 min read · Updated

Building a Prediction Market Data Pipeline — article illustration

Capturing tick-level data from prediction markets is the foundation of any serious quantitative strategy. Relying on stale REST API pulls will leave you executing against phantom liquidity, while a robust WebSocket pipeline ensures you see the true state of the limit order book. This guide breaks down the architecture for streaming, validating, and storing market data for rigorous backtesting.

Key takeaways

  • Kalshi and Polymarket require distinct WebSocket handling, from authentication handshakes to sequence tracking.
  • Storing raw order book deltas in Parquet or DuckDB provides a highly compressed, query-optimized format for backtesting.
  • Sequence gaps in incremental updates mandate immediate snapshot requests to prevent corrupted local order book states.
  • Accurate timestamp synchronization is critical, as venues process the exact same real-world event at different latencies.

How do you connect to prediction market WebSockets?

Establishing a reliable connection is the first step in building your data pipeline. Different exchanges implement WebSocket protocols with varying authentication and subscription models.

For Kalshi, the production endpoint is located at wss://external-api-ws.kalshi.com/trade-api/ws/v2 as detailed in their API Environments and Endpoints documentation. Unlike some platforms that allow public access without credentials, Kalshi requires authentication headers directly within the initial HTTP handshake, even if you only intend to consume public market data. If the handshake fails, the server returns an HTTP error rather than upgrading the connection, as noted in the WebSocket Connection guide. For REST API pulls, the current example root is https://external-api.kalshi.com/trade-api/v2, which requires no authentication for public market data, though responses are cached and can lag by seconds.

Polymarket utilizes a different architecture. Their Central Limit Order Book (CLOB) market channel is accessible via wss://ws-subscriptions-clob.polymarket.com/ws/market, which streams public order book, price, and market lifecycle updates according to the Polymarket API documentation.

When building your connection handlers, write your own implementation rather than relying on unverified open-source wrappers. Malicious actors frequently target algorithmic traders; in fact, fake Polymarket arbitrage bot repos have stolen private keys. Always review our fake bot checklist before integrating third-party code.

What is the best schema for order book and trade data?

Normalizing data across multiple venues is mandatory for cross-market analysis. A standard binary YES contract typically pays $1.00 at resolution on both platforms, though rare Unknown/50-50 outcomes on Polymarket can redeem at $0.50. Furthermore, the raw data structures differ significantly. For instance, Kalshi's REST orderbook_fp arrays contain dollar strings, and the best YES ask is derived from the best opposite NO bid.

Your internal schema must standardize timestamps, price formats, and side indicators. Below is a recommended schema for storing normalized trade events:

| Column Name | Data Type | Description | | :--- | :--- | :--- | | exchange | VARCHAR | Venue identifier (e.g., 'kalshi', 'polymarket') | | market_ticker | VARCHAR | Standardized market ID | | timestamp_ms | BIGINT | Exchange timestamp in milliseconds | | local_ts_ms | BIGINT | Local machine timestamp upon receipt | | side | VARCHAR | 'yes' or 'no' | | price | DECIMAL | Execution price in USD | | size | DECIMAL | Number of contracts traded | | is_snapshot | BOOLEAN | True if part of an initial book build |

When calculating potential profitability in your backtests, you must account for exact fee structures. For example, the general Kalshi taker fee formula is round up(M * 0.07 * C * P * (1 - P)), where M is a multiplier (default taker M=1). For 100 contracts at $0.51, the unrounded fee is $1.7493, but precision must be read from live fee parameters as rounding rules apply (e.g., fee + position cost rounded up to a centicent). There is no universal blanket maker-free claim on Kalshi; certain series have exceptions.

Conversely, Polymarket charges taker fees across most categories (e.g., 0.07 for Crypto, 0.05 for Sports/Economics/Culture/Weather/Other, 0.04 for Finance/Politics/Mentions/Tech, and 0 for Geopolitics). Makers are never charged fees and may be eligible for rebates, though eligibility does not guarantee revenue. Polymarket fees are rounded to five decimal places in USDC, not cents. If you buy 100 shares at a 0.46 price with a 0.05 rate, the fee is 1.24200 USDC, not exactly 1.24. Your schema should ideally include a fee_estimate column to track these costs dynamically.

How do you handle sequence gaps and reconnects?

Maintaining an accurate local order book requires flawless processing of incremental updates. Dropping a single message will corrupt your book state, leading to disastrous trading decisions.

Kalshi manages this by sending an initial orderbook_snapshot followed by incremental orderbook_delta messages. Each message includes a seq integer. The Orderbook Updates documentation explicitly states that seq stays contiguous. If your system detects a gap in the sequence numbers, you must immediately halt trading on that market and request a get_snapshot action to rebuild the book. Applying deltas out of order will result in crossed books or phantom liquidity.

Polymarket handles state verification differently. Each order book response includes a unique hash representing the current state of the book. You must compare this hash with the previous response's hash to determine whether the book changed between reads, as explained in their Prices and Order Books documentation. If the hashes mismatch unexpectedly, a full refresh is required.

How should you store tick data for backtesting?

Writing raw JSON strings to a standard relational database like PostgreSQL will quickly exhaust your storage and result in abysmal query performance. For tick-level data, columnar storage is vastly superior.

We recommend writing incoming WebSocket messages to memory or a fast message broker like Redis, then flushing them to disk as Parquet files partitioned by date and exchange. DuckDB is an exceptional tool for querying these Parquet files directly. It allows you to run complex SQL aggregations over billions of rows on a standard laptop without the overhead of a dedicated database server.

For example, you can query the average spread of a specific market directly from a directory of Parquet files using DuckDB, filtering by the market_ticker defined in your normalized schema. This approach keeps your storage costs low while maximizing backtesting speed.

How do you validate data quality before backtesting?

Before running any historical simulations, you must rigorously validate your stored data. The most common silent failure in data pipelines is clock drift.

Always record both the exchange-provided timestamp and your local machine timestamp (local_ts_ms). By analyzing the delta between these two values, you can identify periods of high network latency or internal processing bottlenecks. If the delta spikes during volatile market events, your backtest fills will be overly optimistic.

Furthermore, when mapping markets across exchanges, remember that venues can resolve the "same" event differently. Polymarket uses the UMA optimistic oracle for prediction markets (where disputes can take days) and Chainlink TWAP for up-down markets. Rules define resolution, not the title. Cross-venue opposite labels alone do not guarantee a riskless payout. Always verify the exact resolution rules in the contract specifications.

Here is a short Python snippet demonstrating how to format a subscription request for Kalshi order book updates:

import json

def build_kalshi_subscription(message_id, tickers):
    return json.dumps({
        "id": message_id,
        "cmd": "subscribe",
        "params": {
            "channels": ["orderbook_delta"],
            "market_tickers": tickers
        }
    })

# Example usage
payload = build_kalshi_subscription(1, ["KXFUT24-LSV"])
print(payload)

This pipeline architecture provides the reliability required for professional quantitative research. Note that this is not financial advice; always test your systems thoroughly in a paper-trading environment before deploying capital.

Frequently asked questions

How much storage do I need for prediction market tick data?

It depends on the number of markets you track, but storing raw JSON can consume gigabytes per day. By converting the data to Parquet format, you can compress this by 80-90%, making it feasible to store years of tick data on a standard solid-state drive.

Can I use REST APIs instead of WebSockets for backtesting data?

REST APIs are insufficient for building accurate historical order books because they only provide snapshots at the exact moment of your request, and responses are often cached. WebSockets push every incremental change, ensuring you capture fleeting liquidity and transient price spikes that REST polling will miss.

What is the difference between a trade feed and an order book delta?

A trade feed only reports executed transactions, showing where buyers and sellers actually met. Order book deltas show changes in resting limit orders, including cancellations and new quotes that never resulted in a trade, which is crucial for understanding market depth and calculating slippage. Check our glossary for more definitions.

Sources

Information only, not financial advice. Trading prediction markets involves risk of loss.