How to Pull Live Polymarket Odds With the API and WebSocket
Use the Gamma API to identify the market and outcome ID, fetch an initial CLOB order-book snapshot, then subscribe to the official market WebSocket for book, price_change and last_trade_price events. Display the midpoint as an indicative probability and the best ask as the immediate YES buy price. Mark the feed stale when updates or heartbeats stop.
A reliable odds widget is a small market-data system, not a timer that scrapes the webpage.
Decide what “live odds” means
Four prices can all be correct at the same moment:
| Field | Meaning | Best use |
|---|---|---|
| Last trade | Price of the most recent matched trade | Activity history |
| Best bid | Highest resting buy order | Immediate sell reference |
| Best ask | Lowest resting sell order | Immediate buy reference |
| Midpoint | Average of best bid and ask | Indicative probability when both sides exist |
Do not label the last trade as “the price you can buy now.” If the last trade was 45¢ but the best ask is 49¢, an immediate YES purchase starts at 49¢ and may move higher for a large order.
For a transparent interface, show:
- implied midpoint probability;
- best bid and best ask;
- spread;
- last trade;
- data timestamp;
- a stale or disconnected badge.
The data flow
Event URL or slug
↓
Gamma event metadata
↓
Market + YES/NO asset IDs
↓
REST order-book snapshot
↓
WebSocket book and price updates
↓
Validated odds state + freshness indicator
The REST snapshot gives a known starting state. The WebSocket keeps it current. After reconnecting, fetch a new snapshot rather than assuming no messages were missed.
Step 1: resolve the event and outcome ID
Fetch a known event by slug:
curl "https://gamma-api.polymarket.com/events/slug/<event-slug>"
Choose the exact nested market. Extract its protocol version and outcome identifiers. A CTF market uses token IDs; a V2 market uses position IDs. The official SDK presents either as an asset ID.
Store both the identifier and human label:
{
"market_id": "<market_id>",
"condition_id": "<condition_id>",
"outcome": "Yes",
"asset_id": "<yes_token_or_position_id>",
"version": "v1-or-v2"
}
Never map a number to YES merely because it appears first. Verify the outcome array.
Step 2: fetch the initial order book
curl "https://clob.polymarket.com/book?token_id=<asset_id>"
The response includes bids, asks, timestamp, minimum order size, tick size, negative-risk status, last trade and a hash of the book state.
Current documentation says bids are ascending and asks descending. The best bid and ask are therefore the final array elements:
from decimal import Decimal
def top_of_book(book):
bid = Decimal(book["bids"][-1]["price"]) if book["bids"] else None
ask = Decimal(book["asks"][-1]["price"]) if book["asks"] else None
return bid, ask
def quote(bid, ask):
if bid is None or ask is None:
return {"mid": None, "spread": None}
return {
"mid": (bid + ask) / Decimal("2"),
"spread": ask - bid,
}
Use Decimal, not binary floating point, for prices and tick-size validation.
Step 3: subscribe to market updates
The official raw market WebSocket is:
wss://ws-subscriptions-clob.polymarket.com/ws/market
After connecting, send a market subscription containing one or more asset IDs:
{
"assets_ids": ["<asset_id>"],
"type": "market",
"custom_feature_enabled": true
}
The documentation instructs clients to send the text frame PING every ten seconds; the server responds with PONG. A network library’s protocol-level ping is not necessarily the same as this application heartbeat.
A Python monitoring example
This example starts from a known asset ID, requests a snapshot and prints public updates. It does not place orders or require credentials.
import asyncio
import json
import time
from decimal import Decimal
import requests
import websockets
ASSET_ID = "replace_with_yes_asset_id"
BOOK_URL = "https://clob.polymarket.com/book"
WS_URL = "wss://ws-subscriptions-clob.polymarket.com/ws/market"
def snapshot():
r = requests.get(BOOK_URL, params={"token_id": ASSET_ID}, timeout=15)
r.raise_for_status()
return r.json()
async def heartbeat(ws):
while True:
await asyncio.sleep(10)
await ws.send("PING")
async def stream():
book = snapshot()
print("snapshot", book.get("timestamp"), book.get("hash"))
async with websockets.connect(WS_URL, ping_interval=None) as ws:
await ws.send(json.dumps({
"assets_ids": [ASSET_ID],
"type": "market",
"custom_feature_enabled": True,
}))
ping_task = asyncio.create_task(heartbeat(ws))
last_message = time.monotonic()
try:
async for raw in ws:
last_message = time.monotonic()
if raw == "PONG":
continue
message = json.loads(raw)
print(message.get("event_type"), message)
finally:
ping_task.cancel()
asyncio.run(stream())
Production code needs reconnect backoff, schema validation, logging and state reconciliation. The example prints raw events intentionally; applying deltas incorrectly is worse than not applying them.
Handle each event type correctly
book
A book event contains bids and asks for an asset. Replace the local book state with the snapshot supplied by the event and recompute top-of-book values.
price_change
This event contains one or more changes with asset ID, price, size and side. With the custom feature enabled, messages can include best bid and best ask. Use those fields for top-of-book display when present; maintain full depth only if you have implemented and tested the documented update semantics.
last_trade_price
This is the most recent matched trade, including price, side, optional size, fee rate and timestamp. Update the “last trade” field, not the best ask or midpoint automatically.
tick_size_change
Update price validation when the permitted tick size changes. An order rounded under an old tick can become invalid.
YES and NO prices do not always add to exactly one on screen
At theoretical settlement, opposite binary outcomes are complementary. Executable quotes contain spreads.
If:
- YES best ask = 0.58;
- NO best ask = 0.45;
buying both immediately costs 1.03 before fees. That three-cent excess reflects crossing two books, not a 103% probability.
For a probability display, choose one method and label it:
- YES midpoint;
- normalized YES and NO midpoints;
- last trade;
- executable YES ask.
Do not silently switch methods when one side is empty. Show “insufficient quote” instead of inventing 50%.
Calculate depth-aware buy odds
The best ask applies only to the size resting at that level. For a target share quantity, walk asks from lowest price upward:
from decimal import Decimal
def average_buy_price(asks, target_shares):
remaining = Decimal(str(target_shares))
cost = Decimal("0")
filled = Decimal("0")
for level in reversed(asks): # documented array is descending
price = Decimal(level["price"])
size = min(remaining, Decimal(level["size"]))
cost += price * size
filled += size
remaining -= size
if remaining == 0:
break
return None if filled == 0 else {
"filled": filled,
"average_price": cost / filled,
"complete": remaining == 0,
}
Add the current taker fee separately. Never report a complete quote if book depth fills only part of the requested size.
Freshness and reconnection rules
A live widget must fail visibly.
- Store the receive time of every valid update.
- Mark data stale after a defined interval appropriate to the market.
- Treat a missed heartbeat or closed socket as disconnected.
- Reconnect with exponential backoff and jitter.
- Fetch a fresh REST snapshot after reconnecting.
- Compare book hashes when available.
- Do not carry the old “live” label across a disconnect.
Clock synchronization matters. Record both exchange timestamp and local receive timestamp in UTC so latency can be estimated.
Cache without creating stale odds
Event titles, icons and rule summaries can be cached longer than order books. A practical split is:
- event metadata: minutes;
- market status and rules: shorter near deadlines;
- books: live stream plus periodic reconciliation;
- price history: cache by completed time bucket;
- settled outcomes: long cache after dispute risk ends.
Use one backend connection to serve many front-end viewers. Opening a WebSocket per browser tab wastes resources and makes reconnection behavior inconsistent.
Security and data-use boundaries
Public market data does not require a private key. If a live-odds page asks for one, the architecture is wrong.
Keep order credentials and wallet signers on a protected server. Use separate services and permissions for read-only data and trading. Never log authentication headers.
Review the current Terms of Use before commercial redistribution or professional capital-markets use. Public visibility does not automatically grant unlimited redistribution, indexing or resale rights.
Frequently asked questions
Which Polymarket price should my widget display?
Use the midpoint as a clearly labeled indicative probability when both sides exist. Also show best bid and ask so users can see executable references.
Do I need an API key for live market data?
The public market WebSocket and REST books are documented for public data. Trading and private account operations require authentication.
Why is my WebSocket disconnecting?
One common cause is missing the application-level PING heartbeat every ten seconds. Also implement network timeouts and backoff.
Can I use last trade as the current odds?
You can display it as “last trade,” but it may be stale and is not necessarily the current buy or sell price.
How do I recover after a dropped message?
Reconnect, fetch a new REST snapshot and resume streaming. Do not assume the local book stayed synchronized while disconnected.
Why do YES and NO asks total more than $1?
Each ask includes its own spread. Buying both sides crosses both books. That total is an execution cost, not a probability sum.
Official sources
- Polymarket Documentation — Discover Markets
- Polymarket Documentation — Prices and Order Books
- Polymarket Documentation — Real-Time Data
- Polymarket Documentation — Market Data Overview
- Polymarket Help Center — How Prices Are Calculated
- Polymarket — Terms of Use
Developer notice: Market data can be delayed, incomplete or disconnected. Examples are educational and require production hardening. Never use a displayed probability as a guarantee of execution or outcome.
Related guides
- Polymarket API Beginner Guide
- How to Backtest Historical Data
- How to Read Spreads, Liquidity and Slippage
Update log
- November 17, 2026: Verified current REST book schema, market WebSocket URL, subscription frame, heartbeat and event types.