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

ParameterTypeRequiredDescription
token_idstrYesThe 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:

FieldTypeDescription
marketstrThe market/condition ID
asset_idstrThe token ID queried
bidslistBuy orders, sorted highest price first. Each entry has price (str) and size (str)
askslistSell 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

ParameterTypeRequiredDescription
paramslist[BookParams]YesList 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")

MethodWhat It ReturnsAuth Required
get_order_book(token_id)Full order book (bids + asks)No
get_order_books([BookParams])Multiple order books in one callNo
get_price(token_id, side)Best price for BUY or SELL sideNo
get_midpoint(token_id)Midpoint between best bid and askNo
get_spread(token_id)Bid-ask spreadNo

For order placement methods that interact with the order book, see create_order().


Common Errors

ErrorCauseFix
Invalid token IDToken ID doesn’t exist or is malformedVerify the token ID from the Gamma API or CLI: polymarket markets get SLUG
Empty bids/asksMarket has no resting orders on one sideCheck len(book.bids) and len(book.asks) before accessing indices
ConnectionErrorCLOB API is unreachableRetry with exponential backoff. Check Polymarket status
429 Too Many RequestsRate limit exceededBack off and retry. See the Rate Limits Guide
Stale dataOrder book snapshot may be milliseconds oldFor 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


{{ 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.