get_order_book() is the py_clob_client method that fetches the full order book for a Polymarket outcome token. It returns an OrderBookSummary containing all resting bids and asks with their prices and sizes. This page covers the method signature, return type, batch retrieval with get_order_books(), spread calculation, and common errors.
For the complete py_clob_client method reference covering all methods, see the py_clob_client Reference. For a side-by-side comparison with Kalshi’s order book API, see the Prediction Market API Reference.
Try it live: Test get_order_book in the API Playground — no setup required.
Method Signature
client.get_order_book(token_id: str) -> OrderBookSummary
Parameters
| Parameter | Type | Required | Description |
|---|---|---|---|
token_id | str | Yes | The outcome token ID. Each Polymarket market has two tokens: one for YES, one for NO |
Return Type: OrderBookSummary
OrderBookSummary is a Pydantic model with the following structure:
| Field | Type | Description |
|---|---|---|
market | str | The market/condition ID |
asset_id | str | The token ID queried |
bids | list | Buy orders, sorted highest price first. Each entry has price (str) and size (str) |
asks | list | Sell orders, sorted lowest price first. Each entry has price (str) and size (str) |
Authentication required: No. get_order_book() is a public endpoint.
Basic Example
Fetch the order book for a single token and print the top bids and asks:
from py_clob_client.client import ClobClient
client = ClobClient("https://clob.polymarket.com")
book = client.get_order_book("TOKEN_ID")
print("Top 5 bids (buy orders):")
for bid in book.bids[:5]:
print(f" ${bid['price']} — {bid['size']} shares")
print("\nTop 5 asks (sell orders):")
for ask in book.asks[:5]:
print(f" ${ask['price']} — {ask['size']} shares")
Convert to Dictionary
If you prefer working with plain Python dicts instead of the Pydantic model:
book = client.get_order_book("TOKEN_ID")
book_dict = book.model_dump() # Pydantic v2
# or book.dict() for Pydantic v1
print(book_dict["bids"][0])
# {'price': '0.55', 'size': '1200.0'}
Batch Retrieval: get_order_books()
Fetch order books for multiple tokens in a single API call. This is significantly more efficient than calling get_order_book() in a loop.
Signature
client.get_order_books(params: list[BookParams]) -> list[OrderBookSummary]
Parameters
| Parameter | Type | Required | Description |
|---|---|---|---|
params | list[BookParams] | Yes | List of BookParams, each specifying a token_id |
Example
from py_clob_client.client import ClobClient
from py_clob_client.clob_types import BookParams
client = ClobClient("https://clob.polymarket.com")
books = client.get_order_books([
BookParams(token_id="YES_TOKEN_ID"),
BookParams(token_id="NO_TOKEN_ID"),
])
for book in books:
best_bid = book.bids[0]["price"] if book.bids else "none"
best_ask = book.asks[0]["price"] if book.asks else "none"
print(f"Token {book.asset_id[:16]}... | Best bid: {best_bid} | Best ask: {best_ask}")
Spread Calculation
The bid-ask spread is the difference between the lowest ask and the highest bid. A narrow spread indicates high liquidity.
from py_clob_client.client import ClobClient
client = ClobClient("https://clob.polymarket.com")
book = client.get_order_book("TOKEN_ID")
if book.bids and book.asks:
best_bid = float(book.bids[0]["price"])
best_ask = float(book.asks[0]["price"])
spread = best_ask - best_bid
midpoint = (best_bid + best_ask) / 2
print(f"Best bid: ${best_bid:.4f}")
print(f"Best ask: ${best_ask:.4f}")
print(f"Spread: ${spread:.4f}")
print(f"Midpoint: ${midpoint:.4f}")
print(f"Spread %: {spread / midpoint * 100:.2f}%")
else:
print("Order book is empty on one or both sides")
You can also use the built-in helper methods:
# Quick price check (no order book parsing needed)
mid = client.get_midpoint(token_id="TOKEN_ID")
buy_price = client.get_price(token_id="TOKEN_ID", side="BUY")
sell_price = client.get_price(token_id="TOKEN_ID", side="SELL")
spread = client.get_spread(token_id="TOKEN_ID")
Order Book Depth Analysis
Calculating available liquidity at different price levels is essential for sizing orders:
from py_clob_client.client import ClobClient
client = ClobClient("https://clob.polymarket.com")
book = client.get_order_book("TOKEN_ID")
def calculate_depth(orders, levels=10):
"""Calculate cumulative depth for the top N price levels."""
cumulative = 0.0
depth = []
for order in orders[:levels]:
size = float(order["size"])
price = float(order["price"])
cumulative += size
depth.append({
"price": price,
"size": size,
"cumulative": cumulative,
"notional": cumulative * price
})
return depth
bid_depth = calculate_depth(book.bids)
ask_depth = calculate_depth(book.asks)
print("Bid depth (top 10 levels):")
for level in bid_depth:
print(f" ${level['price']:.2f} | {level['size']:.0f} shares | "
f"cumulative: {level['cumulative']:.0f} | "
f"${level['notional']:.2f} notional")
Related Methods
| Method | What It Returns | Auth Required |
|---|---|---|
get_order_book(token_id) | Full order book (bids + asks) | No |
get_order_books([BookParams]) | Multiple order books in one call | No |
get_price(token_id, side) | Best price for BUY or SELL side | No |
get_midpoint(token_id) | Midpoint between best bid and ask | No |
get_spread(token_id) | Bid-ask spread | No |
For order placement methods that interact with the order book, see create_order().
Common Errors
| Error | Cause | Fix |
|---|---|---|
Invalid token ID | Token ID doesn’t exist or is malformed | Verify the token ID from the Gamma API or CLI: polymarket markets get SLUG |
| Empty bids/asks | Market has no resting orders on one side | Check len(book.bids) and len(book.asks) before accessing indices |
ConnectionError | CLOB API is unreachable | Retry with exponential backoff. Check Polymarket status |
429 Too Many Requests | Rate limit exceeded | Back off and retry. See the Rate Limits Guide |
| Stale data | Order book snapshot may be milliseconds old | For real-time data, use the WebSocket feed |
CLI Equivalent
You can also fetch order books via the Polymarket CLI:
# Fetch order book for a token
polymarket clob book TOKEN_ID
# JSON output for scripting
polymarket -o json clob book TOKEN_ID
# Quick midpoint check
polymarket clob midpoint TOKEN_ID
See Also
- py_clob_client Complete Reference — Every method documented
- py_clob_client create_order() — Place orders against the book
- py_clob_client get_balance_allowance() — Check funds before trading
- py_clob_client get_positions() — View your current holdings
- Prediction Market API Reference — Polymarket vs Kalshi comparison
- Polymarket Rate Limits Guide — Handle 429 errors
- API Playground — Test endpoints live
- Agent Betting Glossary — Key terms defined
{{ partial “marketplace-cta.html” . }}
This reference is maintained by AgentBets.ai. Found an error or SDK change we missed? Let us know on Twitter.
Not financial advice. Built for builders.