PredictorHQ
Menu
Advanced Guide for Programmatic Traders

Prediction Market API Trading Guide

SK
Written by · LinkedIn · Last updated:
Affiliate disclosure: Some links on this page are affiliate links. We may earn a commission at no cost to you. Editorially independent.

Overview of Prediction Market APIs

Two Primary APIs

Kalshi offers a centralized REST + WebSocket API with standard authentication (API keys). Polymarket offers a decentralized CLOB API built on Polygon smart contracts. Both support market data, order management, and portfolio queries. Your choice depends on regulatory jurisdiction, settlement currency, and available markets.

Prediction market APIs enable programmatic access to market data and order management — the same capabilities available through each platform's web interface, but accessible to automated trading systems, custom dashboards, data pipelines, and quantitative models.

The two major APIs serve different ecosystems:

Feature Kalshi API Polymarket CLOB API
Protocol REST + WebSocket REST + WebSocket + on-chain
Authentication API key (RSA-signed) Ethereum wallet signature
Settlement USD (ACH/wire) USDC on Polygon
Regulation CFTC DCM Unregulated (non-US)
Rate limits ~10 req/sec (REST) Varies by endpoint
Market types Economics, politics, sports, weather Politics, crypto, global events
SDK Python (official) TypeScript (official)
US access Yes (KYC required) Restricted for most contracts

Authentication and Getting API Keys

Kalshi API Authentication

Kalshi uses RSA key-pair authentication. The process:

  1. Generate an RSA key pair. Use OpenSSL or any standard cryptographic library to generate a 4096-bit RSA key pair. Keep the private key secure — it controls your trading account.
  2. Upload your public key to Kalshi. In your Kalshi account settings, navigate to the API section and upload your public key. Kalshi will assign an API key ID associated with this key pair.
  3. Sign requests with your private key. Each API request must include a signature generated using your private key. The signature covers the timestamp and request path, preventing replay attacks. Kalshi's official Python SDK handles signing automatically.

The authentication flow is similar to AWS Signature V4 or other enterprise API authentication schemes. If you have experience with AWS, GCP, or financial exchange APIs, the pattern will be familiar.

Polymarket API Authentication

Polymarket's CLOB API uses Ethereum wallet-based authentication:

  1. Connect a wallet. Generate or use an existing Ethereum wallet (MetaMask, private key, etc.). The wallet address serves as your identity on the platform.
  2. Create API credentials. Use Polymarket's API to derive API credentials from your wallet signature. This produces an API key, secret, and passphrase for authenticating subsequent requests.
  3. Sign orders on-chain. Order placement requires cryptographic signatures that authorize the smart contract to execute trades on your behalf. This is fundamentally different from Kalshi's centralized model — orders are executed by on-chain matching rather than a centralized matching engine.

Market Data Endpoints

Both APIs provide comprehensive market data access. The core endpoints:

  • Markets list. Enumerate all available markets with their contract specifications, status (open/closed/settled), and metadata. Filterable by category, status, and event type.
  • Orderbook. The current state of the order book for a specific market — all outstanding bid and ask orders, organized by price level. This shows the current best bid, best ask, spread, and depth at each price level.
  • Trades. Historical trade data — every executed trade with timestamp, price, quantity, and side (buy/sell). Essential for backtesting, volume analysis, and detecting market microstructure patterns.
  • Market summary / ticker. Aggregated market statistics: last trade price, 24-hour volume, open interest, high/low prices. Useful for dashboard and screening applications.

For real-time data, both platforms offer WebSocket feeds that push orderbook updates and trades as they occur, without the latency and rate-limit overhead of polling REST endpoints. Any serious automated trading system should use WebSocket feeds for market data.

Kalshi-specific data endpoints include market event details (resolution source, settlement date), historical candlestick data, and series metadata for multi-contract markets (e.g., CPI outcome ranges). These are especially useful for economic market analysis.

Polymarket-specific data endpoints include on-chain settlement data, token contract addresses, and condition IDs that map to the underlying smart contract positions. These are necessary for interacting with positions on-chain.

Order Placement

Both APIs support standard order types:

  • Limit orders. Specify a price and quantity. The order rests on the book until it is filled by a matching order, you cancel it, or the market closes. Limit orders are maker orders and typically incur lower fees.
  • Market orders. Execute immediately at the best available price. Market orders are taker orders and incur higher fees. On thin markets, large market orders may experience slippage — executing at progressively worse prices as they consume liquidity at each price level.

Key parameters for order placement on Kalshi:

  • ticker — the market identifier (e.g., "FED-26JUN-T4.50")
  • side — "yes" or "no"
  • action — "buy" or "sell"
  • type — "limit" or "market"
  • count — number of contracts
  • yes_price or no_price — price in cents (1–99 for limit orders)

Important constraints: orders cannot exceed your available balance (no margin trading on prediction markets). Kalshi enforces a maximum position size per market, which varies by contract. Orders are validated server-side and rejected if they violate any constraint.

On Polymarket, order placement involves creating a signed order object and submitting it to the CLOB API. The order is matched off-chain by Polymarket's operator, but settlement occurs on-chain. This hybrid model provides centralized matching speed with on-chain settlement guarantees.

Position Management and Portfolio Queries

Managing open positions programmatically is essential for automated trading:

  • Open positions. Query all your current positions across all markets — contract, side, quantity, average entry price, current market price, and unrealized P&L.
  • Order status. Check the status of submitted orders — pending, partially filled, fully filled, or canceled. Implement polling or WebSocket listeners to track order lifecycle events.
  • Balance and settlement. Query account balance, pending settlements, and withdrawal availability. On Kalshi, settled contracts are credited to your USD balance immediately. On Polymarket, settlement involves on-chain transactions with associated gas fees.
  • Trade history. Download your complete trade history for backtesting, performance analysis, and tax reporting. Kalshi provides CSV export; the API also supports paginated trade history queries.

For portfolio-level risk management, you will typically build your own position tracking system on top of the API. Track exposure by market category, total capital at risk, maximum drawdown limits, and correlation between positions. No prediction market API provides built-in portfolio analytics at the level that professional traders require.

Building a Simple Bot: Monitoring CPI Market Probabilities

A practical starting point for API trading is a monitoring bot — a system that reads market data and alerts you to significant changes, without placing trades automatically. Here is the architecture for a CPI probability monitor:

  1. Connect to Kalshi's market data API. Authenticate using your RSA key pair. Query the markets endpoint with a filter for CPI-related markets to get the list of active CPI contracts.
  2. Poll orderbook data at regular intervals. For each CPI outcome range contract, fetch the current best bid and best ask. The midpoint price is your market-implied probability for that range.
  3. Build a probability distribution. Aggregate the midpoint prices across all CPI contracts into a single probability distribution. Store each snapshot with a timestamp for historical tracking.
  4. Compare to Bloomberg consensus. Manually input the latest Bloomberg consensus estimate. Calculate the divergence between the Kalshi distribution and the consensus. This is the informational signal per the Federal Reserve research.
  5. Alert on significant moves. Set thresholds — for example, alert if the probability of an above-consensus CPI print changes by more than 5 percentage points in 24 hours. Send alerts via email, Slack, or SMS.
  6. Log and visualize. Store all data in a local database or CSV file. Build simple charts showing how the probability distribution evolves over time as the CPI release date approaches.

This monitoring bot requires no order placement API access — only market data reads. It is a low-risk way to build familiarity with the API, validate the signal quality with your own data, and develop the infrastructure for more sophisticated automated strategies later.

Python is the recommended language for this type of project. The standard stack is: Kalshi's Python SDK for API access, pandas for data manipulation, matplotlib or plotly for visualization, and a simple scheduler (cron or APScheduler) for periodic data collection.

Rate Limits and Best Practices

Both APIs enforce rate limits to prevent abuse and ensure platform stability. Practical guidelines:

  • Kalshi REST API: Approximately 10 requests per second for market data endpoints. Order placement endpoints may have stricter limits. Exceeding limits returns a 429 status code. Implement exponential backoff with jitter on retries.
  • Kalshi WebSocket: Supports multiple market subscriptions per connection. Heartbeat messages maintain the connection. Reconnect logic is essential — WebSocket connections will drop periodically and your system must handle reconnection gracefully.
  • Polymarket REST API: Rate limits vary by endpoint and are subject to change. The API returns rate limit headers in responses — parse these to implement adaptive throttling.
  • General best practices:
    • Cache market metadata locally and refresh infrequently (once per hour or less).
    • Use WebSocket feeds for real-time data instead of polling REST endpoints.
    • Batch operations where possible — e.g., cancel all orders in a single request rather than individually.
    • Implement circuit breakers that halt trading if error rates exceed a threshold.
    • Log all API requests and responses for debugging and audit purposes.

Risk Management for Automated Trading

Automated trading systems require rigorous risk management. Prediction markets have unique risk characteristics:

  • Binary outcome risk. Every prediction market position resolves to either $1 or $0. There is no partial loss — you either win or lose the full amount at risk. Position sizing must account for this binary payoff structure.
  • Event risk concentration. Many prediction markets resolve on the same date (e.g., multiple CPI contracts resolve simultaneously). If you hold positions across multiple contracts in the same event, your risk is concentrated in a single moment. Calculate correlated exposure across related markets.
  • Maximum loss limits. Define a maximum daily and weekly loss limit before starting automated trading. Implement hard stops in your code that halt all trading activity if the limit is breached. Do not rely on manual intervention — automated systems can lose money faster than a human can react.
  • Position size limits. Never risk more than a small percentage of your total capital on any single contract. A common rule: no more than 2-5% of trading capital on any single binary outcome.
  • API failure handling. Your system must handle API outages, network failures, and unexpected responses gracefully. An open order that you cannot cancel due to an API outage is a risk. Consider using time-in-force parameters (good-til-canceled vs. good-til-date) to limit stale order risk.
  • Backtesting vs. live performance. Historical backtesting on prediction market data often overstates real-world performance due to slippage, fees, and the bid-ask spread. Always account for realistic execution costs in backtests. Paper trade for at least 2-4 weeks before deploying capital.

Tax Implications of High-Frequency Prediction Market Trading

Automated trading generates a high volume of taxable events. Key considerations:

  • Kalshi 1099 reporting. Kalshi issues 1099 forms for US taxpayers. Each contract settlement is a taxable event. High-frequency traders may have hundreds or thousands of taxable events per year. Maintain detailed trade logs from the API for tax preparation.
  • Section 1256 potential. CFTC-regulated contracts (Kalshi) may qualify for Section 1256 treatment — 60% long-term capital gains / 40% short-term, regardless of holding period. This is potentially favorable for short-term traders. However, the IRS has not issued definitive guidance on all prediction market contract types. Consult a tax professional who is familiar with CFTC-regulated instruments.
  • Wash sale considerations. If you trade the same contract frequently (buying and selling within 30-day windows), wash sale rules may apply, disallowing certain losses. The interaction between prediction market contracts and wash sale rules is not fully settled in tax law.
  • Polymarket tax complexity. Trading on Polymarket involves USDC (a cryptocurrency), which may trigger separate capital gains events on the underlying crypto asset in addition to gains or losses on the prediction market contracts themselves. This double taxation layer adds complexity.
  • Record-keeping. Automated trading systems should log every order, fill, and settlement with timestamps, prices, and quantities. Export this data regularly. API-sourced trade logs are generally more reliable than exchange-provided reports for tax purposes, because they capture your complete order history including canceled and partially filled orders.

Getting Started

To begin building with prediction market APIs:

  1. Open a Kalshi account and generate your RSA key pair. Upload the public key and note your API key ID.
  2. Install the Kalshi Python SDK (pip install kalshi-python) and authenticate with a simple test script.
  3. Query market data — list active CPI markets, fetch an orderbook, and retrieve recent trades. Verify that data matches what you see on the Kalshi web interface.
  4. Build a monitoring bot (as described above) before attempting any order placement.
  5. Paper trade by logging theoretical orders without submitting them to the API. Compare your theoretical P&L to actual market outcomes over 2-4 weeks.
  6. Start small. When you begin live trading, use the minimum position size ($1 contracts) until you have verified that your order placement, position tracking, and risk management systems work correctly in production.
Open Kalshi Account ↗

Affiliate link — we may earn a commission at no cost to you. CFTC-regulated. API access included with all accounts.

Prediction Market API Trading: FAQ

Does Kalshi have a public API?
Yes. Kalshi provides a public REST API and a WebSocket API for real-time data. The REST API supports market data queries (markets, orderbook, trades, portfolio), order placement (limit and market orders), and account management. The WebSocket API provides real-time orderbook updates, trade feeds, and ticker data. API access is available to all verified Kalshi accounts at no additional cost. Full documentation is available at trading-api.readme.kalshi.com.
Does Polymarket have an API?
Yes. Polymarket provides a CLOB (Central Limit Order Book) API built on the Polygon blockchain. The API supports market queries, order placement via signed transactions, and position management. Unlike Kalshi's centralized API, Polymarket's API interacts with on-chain smart contracts, requiring a crypto wallet and USDC on Polygon. API documentation is available at docs.polymarket.com. Note: US residents face access restrictions on Polymarket.
What programming languages can I use with prediction market APIs?
Both Kalshi and Polymarket APIs are standard REST/WebSocket APIs accessible from any programming language with HTTP support. Python is the most popular choice due to its data analysis ecosystem (pandas, numpy) and available SDKs. Kalshi provides an official Python SDK. JavaScript/TypeScript, Go, and Rust are also commonly used. Polymarket's SDK is available in TypeScript. For backtesting and quantitative analysis, Python with Jupyter notebooks is the standard workflow.
What are the rate limits on prediction market APIs?
Kalshi's REST API enforces rate limits of approximately 10 requests per second for market data endpoints and stricter limits for order placement endpoints. WebSocket connections have their own limits on subscription counts and message rates. Polymarket's API rate limits vary by endpoint. Both platforms may temporarily restrict API access during periods of extreme market activity. Best practice: implement exponential backoff retry logic, cache market data locally, and use WebSocket feeds for real-time data instead of polling REST endpoints.
Is automated prediction market trading profitable?
Profitability depends on strategy quality and execution costs. Fee structures (~$0.07 per contract on Kalshi for takers) create meaningful drag on high-frequency strategies. Market making strategies can earn the spread but require sophisticated risk management and compete against professional firms. Signal-based strategies (e.g., trading CPI markets based on proprietary macro models) can be profitable if the signal is consistently more accurate than the market consensus. Most retail API traders should start with paper trading and backtesting before committing capital.
What are the tax implications of automated prediction market trading?
Automated trading on Kalshi generates the same tax obligations as manual trading — profits are reportable income, and Kalshi issues 1099 forms for US taxpayers. High-frequency trading may generate a large number of transactions, making record-keeping critical. CFTC-regulated contracts (Kalshi) may qualify for Section 1256 treatment (60/40 long-term/short-term split), but consult a tax professional — the IRS has not issued definitive guidance on all prediction market contract types. Polymarket trading in USDC may trigger capital gains on the underlying crypto as well as on the prediction market positions.