Prediction Market API Trading Guide
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:
- 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.
- 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.
- 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:
- Connect a wallet. Generate or use an existing Ethereum wallet (MetaMask, private key, etc.). The wallet address serves as your identity on the platform.
- 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.
- 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 contractsyes_priceorno_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:
- 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.
- 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.
- 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.
- 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.
- 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.
- 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:
- Open a Kalshi account and generate your RSA key pair. Upload the public key and note your API key ID.
- Install the Kalshi Python SDK (
pip install kalshi-python) and authenticate with a simple test script. - 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.
- Build a monitoring bot (as described above) before attempting any order placement.
- 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.
- 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.
Affiliate link — we may earn a commission at no cost to you. CFTC-regulated. API access included with all accounts.