Polymarket is the largest prediction market, with billions of dollars in volume across politics, sports, crypto, and macro events. If you are building a dashboard, a trading bot, an aggregator, or a research pipeline, you need programmatic access to that data: current odds, volume, liquidity, trade flow, and how probabilities have moved over time.
Polymarket has its own API, and it is good at what it was built for: trading on Polymarket. What it was not built for is powering data products. Rate limits are tight, historical data is limited, there are no sub-day rankings or trending signals, and the data stops at Polymarket's walls.
This guide covers both approaches: Polymarket's native API and the Codex prediction markets API, which indexes Polymarket and Kalshi into one enriched schema. By the end you will know which to use for what, with working Python and TypeScript code you can copy into a project.
What Polymarket Data Is Available via API?
Whichever route you take, this is the data on the table:
- Events and markets: questions, outcomes, categories, open/close/resolution dates, status
- Current odds: last trade price per outcome, which doubles as implied probability (a YES priced at $0.62 implies 62%)
- Bid, ask, and spread: top-of-book quotes per outcome
- Volume and liquidity: how much money is actually behind each market
- Open interest: total value of outstanding positions
- Trade flow: individual buys and sells with size, price, side, and wallet
- Historical odds: how probabilities moved over time, the raw material for charts and backtests
- Trader data: positions, PnL, and per-market performance for individual wallets
The native API covers some of this. The gaps, mostly around history, rankings, time-windowed stats, and trader analytics, are where a dedicated data API earns its keep.
Option 1: Polymarket's Native API
Polymarket exposes two main APIs:
- The Gamma Markets API (docs.polymarket.com) serves market metadata: events, markets, outcomes, volume, and liquidity over REST. No API key required for public reads.
- The CLOB API powers trading: order books, order placement, and fills. This is the API you need if you want to place trades, and the
py-clob-clientPython library wraps it well.
For getting your first look at the data, Gamma is simple:
import requests
resp = requests.get(
"https://gamma-api.polymarket.com/events",
params={"closed": "false", "order": "volume24hr", "ascending": "false", "limit": 5},
)
for event in resp.json():
print(event["title"])
Where the native API falls short for data products
If you are building anything beyond a casual integration, you will hit these walls quickly:
- Rate limits. The public endpoints allow roughly 30 requests per second. Fine for a script, painful for a product polling hundreds of markets.
- Limited ranking signals. Gamma's
orderparameter accepts a handful of attributes likevolume24hrandliquidity. There are no trending scores, no momentum signals, and no sub-day windows. - Volume-only stats. You get volume at 24h/1w/1mo/1yr. No trade counts, no unique-trader counts, no time-windowed liquidity or open interest changes.
- Limited historical odds. Building a probability chart over arbitrary time ranges and resolutions means collecting and storing the data yourself.
- Polymarket only. The moment you want Kalshi data next to Polymarket data, you are integrating a second vendor with a second schema and second auth.
None of this is a knock on Polymarket. Their API exists to support trading on their venue, and it does that well. It just is not a data platform.
Option 2: The Codex Prediction Markets API
Codex indexes Polymarket and Kalshi into a single GraphQL schema with the enrichment layered on top: trending scores, time-windowed stats at 5m/1h/4h/12h/24h/1w, OHLC odds history at resolutions from 1 minute to 1 week, live trade streams, and trader analytics. One query, one auth, both venues. Note that prediction market endpoints require a Growth plan.
Everything below runs against https://graph.codex.io/graphql with your API key in the Authorization header. Here is a minimal Python helper used by every example in this guide:
import requests
CODEX_API_KEY = "YOUR_API_KEY"
CODEX_URL = "https://graph.codex.io/graphql"
def codex(query, variables=None):
resp = requests.post(
CODEX_URL,
headers={"Authorization": CODEX_API_KEY, "Content-Type": "application/json"},
json={"query": query, "variables": variables or {}},
)
resp.raise_for_status()
return resp.json()["data"]
Get trending Polymarket events (Python)
The filterPredictionEvents query returns events ranked by any signal you want: 24h volume, trending score, open interest, liquidity, unique traders, or the percent change of any of those over windows from 5 minutes to 1 week.
TRENDING = """
query TrendingPolymarketEvents {
filterPredictionEvents(
filters: { protocol: [POLYMARKET], status: [OPEN] }
rankings: [{ attribute: volumeUsd24h, direction: DESC }]
limit: 10
) {
results {
event { question venueUrl closesAt }
marketCount
categories
volumeUsd24h
trades24h
uniqueTraders24h
liquidityUsd
openInterestUsd
}
}
}
"""
data = codex(TRENDING)
for row in data["filterPredictionEvents"]["results"]:
vol = float(row["volumeUsd24h"] or 0)
print(f'{row["event"]["question"]} | ${vol:,.0f} 24h volume | {row["trades24h"]} trades')
Each event row comes with rolled-up stats across all of its child markets, something you would otherwise compute yourself by paging through every market.
Get current odds for the top markets (Python)
filterPredictionMarkets returns markets with outcome prices inline. The last trade price per outcome is the implied probability:
TOP_MARKETS = """
query TopPolymarketMarkets {
filterPredictionMarkets(
filters: { protocol: [POLYMARKET], status: [OPEN] }
rankings: [{ attribute: volumeUsd24h, direction: DESC }]
limit: 5
) {
results {
id
eventLabel
market { question }
outcome0 { label lastPriceUsd }
outcome1 { label lastPriceUsd }
volumeUsd24h
liquidityUsd
}
}
}
"""
data = codex(TOP_MARKETS)
for m in data["filterPredictionMarkets"]["results"]:
yes = float(m["outcome0"]["lastPriceUsd"] or 0)
print(f'{m["eventLabel"]}: {m["outcome0"]["label"]} = {yes:.0%} implied probability')
For a single-market drill-down with the full quote (best bid, best ask, and spread per outcome), use predictionMarketPrice instead. It even accepts an optional timestamp to fetch the quote as of any moment in the past.
Get historical odds (Python)
This is the data that is genuinely hard to get from the native API. predictionMarketBars returns OHLC bars per outcome at resolutions from min1 to week1, so you can chart how a probability moved or feed a backtest:
import time
ODDS_HISTORY = """
query OddsHistory($marketId: String!, $from: Int!, $to: Int!) {
predictionMarketBars(input: {
marketId: $marketId
from: $from
to: $to
resolution: hour1
}) {
bars {
t
trades
volumeUsd
outcome0 { priceUsd { o h l c } }
}
}
}
"""
now = int(time.time())
data = codex(ODDS_HISTORY, {
"marketId": "POLYMARKET_MARKET_ID", # the id field from filterPredictionMarkets
"from": now - 7 * 86400,
"to": now,
})
for bar in data["predictionMarketBars"]["bars"]:
close = float(bar["outcome0"]["priceUsd"]["c"] or 0)
print(f'{bar["t"]}: YES closed at {close:.0%} on ${float(bar["volumeUsd"] or 0):,.0f} volume')
Each bar also carries bid/ask OHLC, order book depth, open interest, trade counts, and unique traders, so one query powers a full TradingView-style chart.
The same query in TypeScript
If you are in a TypeScript stack, the Codex SDK wraps the same GraphQL API:
import { Codex } from "@codex-data/sdk";
import { gql } from "graphql-tag";
const sdk = new Codex(process.env.CODEX_API_KEY!);
const { filterPredictionEvents } = await sdk.query(gql`
query {
filterPredictionEvents(
filters: { protocol: [POLYMARKET], status: [OPEN] }
rankings: [{ attribute: trendingScore24h, direction: DESC }]
limit: 10
) {
results {
event { question venueUrl }
volumeUsd24h
trendingScore24h
}
}
}
`);
Stream trades in real time (WebSocket)
For live tickers and bots, the onPredictionTradesCreated subscription pushes every Polymarket trade as it is ingested. With the TypeScript SDK:
sdk.subscribe(gql`
subscription {
onPredictionTradesCreated(input: { marketId: "POLYMARKET_MARKET_ID" }) {
trades {
outcomeLabel
tradeType
priceUsd
amountUsd
maker
timestamp
}
}
}
`, {
next: (data) => {
for (const trade of data.data.onPredictionTradesCreated.trades) {
console.log(`${trade.tradeType} ${trade.outcomeLabel} @ ${trade.priceUsd} ($${trade.amountUsd})`);
}
}
});
You can subscribe by market, by event, or by trader. Subscribing by trader is the building block for copy-trading and whale-watching tools.
Polymarket API vs Codex API: When to Use Which
| Use case | Polymarket API | Codex API |
|---|---|---|
| Place trades on Polymarket | Yes (CLOB API) | No |
| Current odds | Yes | Yes |
| Historical odds (OHLC, any resolution) | Limited | Yes (1-minute to weekly bars) |
| Trending and momentum rankings | No | Yes (5m to 1w windows) |
| Time-windowed stats (trades, traders, OI, liquidity) | Volume only (24h/1w/1mo/1yr) | All, at 5m/1h/4h/12h/24h/1w with % change |
| Trader analytics (positions, PnL, leaderboards) | No | Yes |
| Cross-venue data (Kalshi too) | No | Yes, one schema |
| Real-time trade stream | Limited | Yes (WebSocket) |
| Rate limits | ~30 req/s | 1,000+ req/s |
The rule of thumb: use Polymarket's CLOB API to place trades. Use Codex for everything else. They are complementary, and most serious Polymarket tools end up using exactly that combination: Codex as the data and signal layer, the CLOB API as the execution layer.
Building a Simple Prediction Market Dashboard
Here is a complete script that pulls the most active Polymarket markets and prints a live-updating terminal dashboard. Roughly 40 lines, and it is the skeleton of any odds tracker:
import time
import requests
CODEX_API_KEY = "YOUR_API_KEY"
CODEX_URL = "https://graph.codex.io/graphql"
QUERY = """
query Dashboard {
filterPredictionMarkets(
filters: { protocol: [POLYMARKET], status: [OPEN] }
rankings: [{ attribute: volumeUsd24h, direction: DESC }]
limit: 15
) {
results {
eventLabel
market { question }
outcome0 { label lastPriceUsd }
volumeUsd24h
trades24h
uniqueTraders24h
}
}
}
"""
def fetch():
resp = requests.post(
CODEX_URL,
headers={"Authorization": CODEX_API_KEY, "Content-Type": "application/json"},
json={"query": QUERY},
)
resp.raise_for_status()
return resp.json()["data"]["filterPredictionMarkets"]["results"]
while True:
print("\n" + "=" * 80)
print(f"{'MARKET':<48} {'YES':>6} {'24H VOL':>12} {'TRADES':>8}")
print("-" * 80)
for m in fetch():
label = (m["market"]["question"] or m["eventLabel"] or "")[:46]
yes = float(m["outcome0"]["lastPriceUsd"] or 0)
vol = float(m["volumeUsd24h"] or 0)
print(f"{label:<48} {yes:>5.0%} {vol:>11,.0f} {m['trades24h'] or 0:>8}")
time.sleep(30)
From here, the natural next steps are charting odds history with predictionMarketBars, adding alerts when a probability moves more than a few points in an hour, or comparing the same event across venues. If you want to take it all the way to automation, our guide to building a Polymarket trading bot picks up where this script ends.
Getting Started
- Get a Codex API key at dashboard.codex.io/signup. Prediction market endpoints are available on the Growth plan, which includes 1M requests per month plus the WebSocket subscriptions used above.
- Explore the prediction market queries in the API reference:
filterPredictionEvents,filterPredictionMarkets,predictionMarketPrice,predictionMarketBars,predictionTrades, and the trader analytics queries. - If you also want Kalshi data through the same schema, see our Kalshi API guide. The queries in this article work for Kalshi by changing one enum value.
FAQ
Does Polymarket have an API?
Yes. Polymarket offers the Gamma Markets API for market metadata (events, markets, volume, liquidity) and the CLOB API for trading (order books, order placement). Both are documented at docs.polymarket.com. For enriched data such as historical odds, trending rankings, time-windowed stats, and trader analytics, third-party APIs like Codex index Polymarket data into a richer schema.
How do I get Polymarket data via API?
For basic metadata, call Polymarket's Gamma API directly over REST. For production data needs, query the Codex GraphQL API: filterPredictionEvents for ranked event lists, filterPredictionMarkets for markets with current odds inline, predictionMarketBars for historical odds, and onPredictionTradesCreated for a real-time trade stream. All of it works in any language that can send an HTTP POST.
Is the Polymarket API free?
Polymarket's public Gamma endpoints are free with rate limits of roughly 30 requests per second. Codex's prediction market endpoints require a Growth plan (from $350/month for 1M requests with 1,000+ req/s limits and WebSocket access), which is built for production workloads rather than casual scripts.
How do I use the Polymarket API in Python?
No SDK is required. POST GraphQL queries to https://graph.codex.io/graphql with the requests library and your API key in the Authorization header, as shown in the examples in this guide. For trading on Polymarket from Python, use the official py-clob-client library against the CLOB API.
Can you build a bot for Polymarket?
Yes. Bots are widely used on Polymarket for market making, arbitrage, momentum strategies, and copy trading. The standard architecture is a data layer (Codex for odds, trade streams, and signals) feeding an execution layer (Polymarket's CLOB API for placing orders). See our Polymarket trading bot guide for a working starter bot.
What is the difference between Polymarket's API and Codex?
Polymarket's API is built for trading on Polymarket: order books, order placement, and basic market metadata. Codex is built for data products: historical OHLC odds, trending and momentum rankings, stats windowed from 5 minutes to 1 week, trader analytics, real-time WebSocket streams, and the same schema across both Polymarket and Kalshi. Most production tools use Polymarket's API to execute and Codex to decide.
Start building with prediction market data. Get your Codex API key and run the examples in this guide.

