Prediction Market Arbitrage via API: A Beginner's Tutorial (2025)
9 minPredictEngine TeamTutorial
Prediction market arbitrage via API is the practice of automatically exploiting price differences for the same event outcome across multiple prediction market platforms, generating near-risk-free profits by buying low and selling high simultaneously. Beginners can start with simple Python scripts that compare **Polymarket** and **Kalshi** prices via their public APIs, executing trades when implied probabilities diverge by more than 2-3%. This tutorial walks you through the complete setup—from API credentials to your first automated arbitrage trade.
## What Is Prediction Market Arbitrage?
**Arbitrage** in prediction markets works similarly to traditional financial markets: you profit when identical or nearly identical assets trade at different prices. On **Polymarket**, a "Yes" share on "Will Trump win 2024?" might trade at $0.62 (62% implied probability), while **Kalshi** lists the same outcome at $0.58 (58%). Buy the cheaper share, sell the expensive one, and lock in a 4-cent profit per share—regardless of who actually wins.
The key difference from manual trading? **API automation** lets you scan hundreds of markets in milliseconds, catching opportunities that disappear within seconds. Human traders simply cannot compete.
| Arbitrage Type | Description | Profit Margin | Difficulty |
|--------------|-------------|-------------|------------|
| Cross-Platform (Polymarket ↔ Kalshi) | Same event, different platforms | 2-5% | Beginner |
| Cross-Event (Related Markets) | Correlated outcomes, same platform | 1-3% | Intermediate |
| Temporal (Time-Based) | Same market, price swings | 0.5-2% | Advanced |
| Synthetic Arbitrage | Combining multiple outcomes | 3-8% | Expert |
## Why Use APIs Instead of Manual Trading?
Manual arbitrage faces three insurmountable problems. First, **price discrepancies last 15-60 seconds** on average during volatile periods—barely enough time to log into two platforms. Second, **simultaneous execution** is impossible by hand; you buy on one platform, prices move, and your "risk-free" trade becomes speculative. Third, **scale**: profitable arbitrage requires monitoring 50+ markets continuously, a task no human can sustain.
APIs solve all three. They enable **sub-second price scanning**, **atomic execution** (both legs nearly simultaneously), and **24/7 operation** without fatigue. For beginners, this means starting with $500-$2,000 and compounding small edges into meaningful returns.
The [AI-Powered Polymarket Trading via API: The 2025 Guide](/blog/ai-powered-polymarket-trading-via-api-the-2025-guide) covers advanced automation strategies, but this tutorial focuses on your foundational setup.
## Getting Your API Credentials: Step-by-Step
Before writing code, you need access. Here's the exact process for major platforms:
### Polymarket API Access
1. **Create a Polymarket account** and complete **KYC verification** (required for API access)
2. Navigate to **Settings → API Keys** in your dashboard
3. Generate a **read-only key** first for testing; upgrade to **trading permissions** after verification
4. Store your **API key** and **secret** in environment variables—never hardcode them
Polymarket uses **REST APIs** for market data and **WebSocket feeds** for real-time prices. Their **Gamma API** provides market metadata, while **CLOB (Central Limit Order Book)** handles execution.
### Kalshi API Access
1. Register at **Kalshi.com** and complete their **accredited investor verification** (stricter than Polymarket)
2. Request API access via **[email protected]** with your use case description
3. Receive **API key** and **download their OpenAPI specification**
4. Test in **paper trading mode** before live deployment
Kalshi's API is more **institutionally oriented**, with stricter rate limits (100 requests/minute for standard accounts vs. Polymarket's 300).
### Alternative Platforms
- **PredictIt**: No public API; requires web scraping (legally gray, technically fragile)
- **Smarkets**: REST API available for UK/EU users
- **[PredictEngine](/)**: Unified API layer abstracting multiple platforms—ideal for beginners wanting one integration point
## Building Your First Arbitrage Scanner
Your scanner needs three components: **price fetcher**, **opportunity detector**, and **logger**. Here's a simplified Python framework:
```python
import requests
import os
from dotenv import load_dotenv
load_dotenv()
POLY_API_KEY = os.getenv('POLY_API_KEY')
KALSHI_API_KEY = os.getenv('KALSHI_API_KEY')
def get_polymarket_price(market_id):
"""Fetch best bid/ask for a Polymarket outcome"""
url = f"https://clob.polymarket.com/markets/{market_id}"
headers = {"POLY_API_KEY": POLY_API_KEY}
response = requests.get(url, headers=headers)
data = response.json()
return {
'bid': float(data['bids'][0]['price']),
'ask': float(data['asks'][0]['price'])
}
def get_kalshi_price(ticker):
"""Fetch best bid/ask for Kalshi event"""
url = f"https://api.elections.kalshi.com/trade/v2/markets/{ticker}/orderbook"
headers = {"Authorization": f"Bearer {KALSHI_API_KEY}"}
response = requests.get(url, headers=headers)
data = response.json()
return {
'bid': float(data['orderbook']['yes'][0]['price']),
'ask': float(data['orderbook']['no'][0]['price'])
}
def detect_arbitrage(poly_price, kalshi_price, threshold=0.02):
"""Returns arbitrage opportunity if spread exceeds threshold"""
# Buy YES on cheaper, sell YES on more expensive
if poly_price['ask'] < kalshi_price['bid'] - threshold:
return {
'action': 'BUY_POLY_SELL_KALSHI',
'buy_price': poly_price['ask'],
'sell_price': kalshi_price['bid'],
'profit': kalshi_price['bid'] - poly_price['ask']
}
elif kalshi_price['ask'] < poly_price['bid'] - threshold:
return {
'action': 'BUY_KALSHI_SELL_POLY',
'buy_price': kalshi_price['ask'],
'sell_price': poly_price['bid'],
'profit': poly_price['bid'] - kalshi_price['ask']
}
return None
```
This skeleton illustrates core logic. Production systems need **error handling**, **retry logic**, and **WebSocket subscriptions** for real-time feeds.
## Executing Your First Automated Trade
Detection without execution is academic. Here's how to complete the loop:
### Step 1: Validate the Opportunity
Before committing capital, verify:
- **Market expiration alignment**: Both markets resolve at identical times?
- **Outcome definition match**: "Trump wins" means the same thing on both platforms?
- **Liquidity check**: Can you execute your desired size without moving the price?
### Step 2: Size Your Position
Begin with **$50-$100 per leg** ($100-$200 total exposure). Calculate:
- **Maximum position**: 5% of your bankroll per trade
- **Minimum profit threshold**: $2-$5 gross profit after fees
- **Fee impact**: Polymarket charges ~0% (gas fees only); Kalshi charges **0.5% per trade**
### Step 3: Execute Simultaneously
Use **asyncio** for near-parallel execution:
```python
import asyncio
import aiohttp
async def execute_arbitrage(opportunity, size):
async with aiohttp.ClientSession() as session:
# Fire both orders simultaneously
poly_task = place_poly_order(session, 'buy', size, opportunity['buy_price'])
kalshi_task = place_kalshi_order(session, 'sell', size, opportunity['sell_price'])
results = await asyncio.gather(poly_task, kalshi_task, return_exceptions=True)
# Handle partial fills or failures
if any(isinstance(r, Exception) for r in results):
await emergency_hedge(results) # Close open leg
```
### Step 4: Log and Reconcile
Every trade needs **post-execution verification**:
- Confirm both legs filled
- Calculate actual vs. expected profit
- Update running **P&L spreadsheet**
The [AI Agent Cross-Platform Arbitrage: Risk Analysis Guide](/blog/ai-agent-cross-platform-arbitrage-risk-analysis-guide) details failure modes and hedging strategies for when one leg fails to execute.
## Managing Risk: What Can Go Wrong
"Risk-free" arbitrage has risks. Beginners underestimate these:
| Risk | Probability | Mitigation |
|------|-------------|------------|
| Execution lag (one leg fills, other doesn't) | 5-15% | Start with small size; use limit orders |
| Market resolution discrepancy | 2-5% | Verify outcome definitions character-by-character |
| Platform downtime during trade | 1-3% | Maintain emergency manual hedging capability |
| Smart contract failure (Polymarket) | <1% | Diversify across platforms |
| Regulatory freeze (Kalshi) | <1% | Keep 50% funds in stablecoins |
**Settlement risk** is particularly insidious. In November 2024, a **Senate race market** on Polymarket resolved differently than Kalshi's equivalent due to **recount timing disputes**—arbitrageurs who hadn't verified resolution criteria lost 8-12% on "winning" trades.
The [Senate Race Predictions With Limit Orders: A Beginner's Tutorial](/blog/senate-race-predictions-with-limit-orders-a-beginners-tutorial) demonstrates how limit order discipline prevents adverse selection in volatile political markets.
## Scaling Your Operation: From $1K to $10K
Once you've executed 20+ profitable trades manually via API, consider scaling:
### Infrastructure Upgrades
- **Colocate your server**: AWS **us-east-1** (Virginia) reduces latency to Polymarket's servers by 20-40ms versus West Coast
- **WebSocket feeds**: Replace REST polling with streaming price updates
- **Database logging**: PostgreSQL for trade history, Redis for opportunity caching
### Strategy Evolution
- **Multi-leg arbitrage**: Combine [Prediction Market Liquidity Sourcing: $10K Portfolio Quick Reference](/blog/prediction-market-liquidity-sourcing-10k-portfolio-quick-reference) techniques to access deeper pools
- **Cross-asset hedging**: Offset prediction market exposure with **options** or **perpetual futures** on crypto exchanges
- **Machine learning filtering**: Train models to predict which opportunities will persist long enough to execute
For mobile monitoring, the [Algorithmic Science & Tech Prediction Markets on Mobile: A 2024 Guide](/blog/algorithmic-science-tech-prediction-markets-on-mobile-a-2024-guide) shows how to manage positions without being desk-bound.
## Frequently Asked Questions
### What programming language is best for prediction market arbitrage APIs?
**Python** dominates for beginners due to excellent **asyncio** support, abundant **HTTP client libraries**, and the **pandas** ecosystem for analysis. **JavaScript/TypeScript** works well for WebSocket-heavy implementations. **Rust** offers 10-20% latency improvements for high-frequency operations but has steeper learning curves.
### How much capital do I need to start prediction market arbitrage?
**$500-$1,000** is sufficient for learning and small profits. **$5,000-$10,000** enables meaningful returns after fees—expect **$50-$200 monthly** at $1K scale, scaling to **$500-$2,000** at $10K with mature systems. The [Algorithmic NFL Season Predictions: How to Deploy a $10K Portfolio](/blog/algorithmic-nfl-season-predictions-how-to-deploy-a-10k-portfolio) illustrates capital deployment across multiple strategies.
### Are prediction market arbitrage profits taxable?
In the **United States**, arbitrage profits are typically **ordinary income**, not capital gains, because holding periods are minutes not years. **Section 1256 contracts** (futures-style) receive 60/40 treatment, but prediction markets generally don't qualify. Consult a **crypto-specialized CPA**; platforms issue **1099s** inconsistently.
### What happens if one platform suspends trading mid-arbitrage?
This is **leg risk**—your primary exposure. If you've bought on Platform A and Platform B freezes before you sell, you're **directionally exposed**. Mitigation: use **smaller position sizes**, maintain **stop-loss orders** where supported, and diversify across **3+ platforms** so no single suspension devastates your book.
### How do fees impact arbitrage profitability?
**Fee math is unforgiving**. Kalshi's **0.5% per leg** means **1% round-trip**. Polymarket has **zero trading fees** but **gas costs** (typically **$0.50-$3** per transaction on Polygon). An opportunity showing **2% gross spread** becomes **0.5-1% net**—barely worth the operational complexity. Target **>3% gross spreads** for sustainable operations.
### Can I arbitrage prediction markets without coding?
**Semi-automated tools** exist. **[PredictEngine](/)** offers **no-code arbitrage alerts** that ping you when spreads exceed your threshold—you execute manually. **Zapier + Google Sheets** integrations can scrape prices without custom code. However, **pure manual execution** captures <10% of available opportunities due to speed constraints.
## Tools and Resources for Continued Learning
| Resource | Purpose | Cost |
|----------|---------|------|
| Polymarket CLOB API Docs | Order execution | Free |
| Kalshi API Reference | Market data & trading | Free |
| PredictEngine | Unified multi-platform API | Freemium |
| [Reinforcement Learning Prediction Trading via API: 5 Approaches Compared](/blog/reinforcement-learning-prediction-trading-via-api-5-approaches-compared) | Strategy evolution | Free (blog) |
| [Advanced Market Making on Prediction Markets: An Institutional Guide](/blog/advanced-market-making-on-prediction-markets-an-institutional-guide) | Professional techniques | Free (blog) |
## Your Next Steps: From Tutorial to Trading
You've now built the mental model and technical foundation for **prediction market arbitrage via API**. The path forward is deliberate practice:
1. **Open accounts** on **Polymarket** and **Kalshi** this week
2. **Request API access** and test with **read-only endpoints**
3. **Deploy the scanner code** above on a **$5/month DigitalOcean droplet**
4. **Paper trade** for 2 weeks, logging every detected opportunity
5. **Go live with $100** when your paper tracking shows consistent 2%+ spreads
Arbitrage is a **volume game with thin margins**—patience and precision beat aggression. The traders who compound $1,000 into $10,000 in 12 months aren't finding home runs; they're executing **200+ small, high-probability trades** with mechanical discipline.
Ready to eliminate platform complexity? **[PredictEngine](/)** provides a **unified API** connecting Polymarket, Kalshi, and emerging platforms—with **pre-built arbitrage detection**, **risk management guardrails**, and **institutional-grade execution infrastructure**. Start your free tier today and execute your first cross-platform arbitrage before the week ends.
---
*Last updated: January 2025. Prediction markets involve risk of loss; this tutorial is educational not financial advice. Verify all API documentation against current platform specifications before deploying capital.*
Ready to Start Trading?
PredictEngine lets you create automated trading bots for Polymarket in seconds. No coding required.
Get Started Free