This is the complete method reference for py_clob_client, Polymarket’s official Python SDK for interacting with the CLOB (Central Limit Order Book) API. Every method is documented with its signature, parameters, return type, and a working code example.
For a conceptual overview of how the Polymarket API ecosystem works, see the Polymarket API Guide. For side-by-side comparison with Kalshi’s Python SDK, see the Prediction Market API Reference.
Try it live: Test Polymarket endpoints in the API Playground — no setup required.
Installation and Setup
Installing py_clob_client
pip install py-clob-client
The package name uses hyphens (py-clob-client) but the Python import uses underscores (py_clob_client).
ClobClient Initialization
ClobClient is the main entry point for all SDK operations.
Signature:
ClobClient(
host: str,
key: str = None,
chain_id: int = None,
signature_type: int = 0,
funder: str = None
)
Parameters:
| Parameter | Type | Required | Description |
|---|---|---|---|
host | str | Yes | CLOB API base URL. Use https://clob.polymarket.com for production |
key | str | For trading | Your Ethereum private key (hex string with or without 0x prefix) |
chain_id | int | For trading | Blockchain chain ID. Use 137 for Polygon mainnet |
signature_type | int | No | Wallet type: 0 = EOA (MetaMask), 1 = Magic/email wallet, 2 = browser wallet proxy |
funder | str | For proxy wallets | The proxy wallet address that holds your funds on Polymarket |
Example — Read-only client (no authentication):
from py_clob_client.client import ClobClient
client = ClobClient("https://clob.polymarket.com")
# Public endpoints work without auth
price = client.get_price(token_id="<token-id>", side="BUY")
Example — Authenticated client (EOA wallet):
from py_clob_client.client import ClobClient
client = ClobClient(
"https://clob.polymarket.com",
key="<your-private-key>",
chain_id=137
)
client.set_api_creds(client.create_or_derive_api_creds())
Example — Authenticated client (Magic/email wallet):
from py_clob_client.client import ClobClient
client = ClobClient(
"https://clob.polymarket.com",
key="<your-private-key>",
chain_id=137,
signature_type=1,
funder="<your-proxy-wallet-address>"
)
client.set_api_creds(client.create_or_derive_api_creds())
Authentication: create_or_derive_api_creds()
Derives or creates API credentials from your wallet signature. Call this once, then reuse the credentials.
Signature:
client.create_or_derive_api_creds() -> ApiCreds
Returns: An ApiCreds object containing your API key, secret, and passphrase. Pass this to set_api_creds() to enable authenticated endpoints.
Usage:
creds = client.create_or_derive_api_creds()
client.set_api_creds(creds)
# Now you can use authenticated endpoints (trading, balance, etc.)
You only need to derive credentials once per session. The credentials are deterministic — deriving them again with the same wallet produces the same result.
Balance Methods
get_balance() Method
Returns your USDC balance on Polymarket. This is the simplest way to check how much USDC you have available for trading.
Signature:
client.get_balance() -> str
Parameters: None.
Returns: A string representing your USDC balance in wei (1 USDC = 10^6 wei). You need to convert this to a human-readable amount.
Example:
from py_clob_client.client import ClobClient
client = ClobClient(
"https://clob.polymarket.com",
key="<your-private-key>",
chain_id=137
)
client.set_api_creds(client.create_or_derive_api_creds())
balance_wei = client.get_balance()
balance_usdc = int(balance_wei) / 1e6
print(f"Balance: {balance_usdc:.2f} USDC")
# Example output: Balance: 1250.00 USDC
Common pitfall: The return value is in wei (micro-USDC), not USDC. Divide by 1e6 (or 10**6) to get the USDC amount. Forgetting this conversion is a frequent source of bugs.
get_balance_allowance() Method
Returns both your balance and the token allowance for a specific asset type. This is more detailed than get_balance() and is essential for checking whether you have sufficient allowance set for trading.
Signature:
client.get_balance_allowance(params: BalanceAllowanceParams = None) -> dict
Parameters:
| Parameter | Type | Required | Description |
|---|---|---|---|
params | BalanceAllowanceParams | No | Specifies the asset type and optional token ID |
BalanceAllowanceParams fields:
| Field | Type | Description |
|---|---|---|
asset_type | AssetType | AssetType.COLLATERAL for USDC, or AssetType.CONDITIONAL for outcome tokens |
token_id | str | Required when asset_type is CONDITIONAL — the specific outcome token ID |
Returns: A dictionary with balance and allowance fields, both as strings in wei.
Example — Check USDC balance and allowance:
from py_clob_client.client import ClobClient
from py_clob_client.clob_types import BalanceAllowanceParams, AssetType
client = ClobClient(
"https://clob.polymarket.com",
key="<your-private-key>",
chain_id=137
)
client.set_api_creds(client.create_or_derive_api_creds())
result = client.get_balance_allowance(
BalanceAllowanceParams(asset_type=AssetType.COLLATERAL)
)
print(f"Balance: {int(result['balance']) / 1e6:.2f} USDC")
print(f"Allowance: {result['allowance']}")
Example — Check conditional token balance:
result = client.get_balance_allowance(
BalanceAllowanceParams(
asset_type=AssetType.CONDITIONAL,
token_id="<outcome-token-id>"
)
)
print(f"Token balance: {result['balance']}")
print(f"Token allowance: {result['allowance']}")
When to use get_balance() vs get_balance_allowance():
- Use
get_balance()for a quick USDC balance check (e.g., before placing an order). - Use
get_balance_allowance()when you need to verify allowances are set (important for EOA wallets) or when checking conditional token balances for specific outcomes.
Position Methods
get_positions() Method
Retrieves your current positions across all markets. Each position represents your holdings of a specific outcome token.
Signature:
client.get_positions() -> list
Parameters: None required. The method fetches all positions for the authenticated user.
Returns: A list of position dictionaries, each containing details about a specific token holding.
Response fields per position:
| Field | Type | Description |
|---|---|---|
asset | dict | Token details including token_id and condition_id |
size | str | Number of shares held |
avgPrice | str | Average entry price per share |
side | str | Side of the position |
Example — List all positions:
from py_clob_client.client import ClobClient
client = ClobClient(
"https://clob.polymarket.com",
key="<your-private-key>",
chain_id=137,
signature_type=1,
funder="<your-proxy-address>"
)
client.set_api_creds(client.create_or_derive_api_creds())
positions = client.get_positions()
for pos in positions:
token_id = pos["asset"]["token_id"]
size = float(pos["size"])
avg_price = float(pos["avgPrice"])
print(f"Token: {token_id[:16]}... | Shares: {size} | Avg Price: ${avg_price:.2f}")
Example — Check if you have an existing position before placing an order:
def has_position(client, target_token_id):
"""Check if we already hold a position in this outcome."""
positions = client.get_positions()
for pos in positions:
if pos["asset"]["token_id"] == target_token_id:
return float(pos["size"]) > 0
return False
# Only buy if we don't already have a position
if not has_position(client, "<token-id>"):
order = OrderArgs(token_id="<token-id>", price=0.50, size=10.0, side=BUY)
signed = client.create_order(order)
client.post_order(signed, OrderType.GTC)
Note: For querying positions via the public Data API (which doesn’t require authentication), you can use:
curl "https://data-api.polymarket.com/positions?user=YOUR_WALLET_ADDRESS"
Or via the Polymarket CLI:
polymarket data positions YOUR_WALLET_ADDRESS
Order Types
MarketOrderArgs
MarketOrderArgs is the data class for specifying market orders — orders that execute immediately against resting liquidity at the best available price.
Import:
from py_clob_client.clob_types import MarketOrderArgs, OrderType
from py_clob_client.order_builder.constants import BUY, SELL
Fields:
| Field | Type | Required | Description |
|---|---|---|---|
token_id | str | Yes | The outcome token ID to trade |
amount | float | Yes | Dollar amount in USDC to spend (for BUY) or number of shares to sell (for SELL) |
side | str | Yes | BUY or SELL |
order_type | OrderType | Yes | Must be OrderType.FOK (fill-or-kill) for market orders |
fee_rate_bps | int | No | Custom fee rate in basis points. Defaults to the standard rate |
Example — Buy $25 worth of YES tokens at market price:
from py_clob_client.clob_types import MarketOrderArgs, OrderType
from py_clob_client.order_builder.constants import BUY
market_order = MarketOrderArgs(
token_id="<token-id>",
amount=25.0,
side=BUY,
order_type=OrderType.FOK
)
signed = client.create_market_order(market_order)
response = client.post_order(signed, OrderType.FOK)
print(response)
Example — Sell 10 shares at market price:
from py_clob_client.order_builder.constants import SELL
sell_order = MarketOrderArgs(
token_id="<token-id>",
amount=10.0,
side=SELL,
order_type=OrderType.FOK
)
signed = client.create_market_order(sell_order)
response = client.post_order(signed, OrderType.FOK)
Market orders use FOK (fill-or-kill) — the order must fill completely or it’s rejected entirely. If there isn’t enough resting liquidity to fill your full amount, the order fails. For partial fills, use a limit order with FAK (fill-and-kill) instead.
OrderArgs
OrderArgs is the data class for limit orders — orders that specify an exact price and rest on the order book until filled.
Import:
from py_clob_client.clob_types import OrderArgs, OrderType
from py_clob_client.order_builder.constants import BUY, SELL
Fields:
| Field | Type | Required | Description |
|---|---|---|---|
token_id | str | Yes | The outcome token ID to trade |
price | float | Yes | Price per share in USDC (0.01 to 0.99) |
size | float | Yes | Number of shares to buy or sell |
side | str | Yes | BUY or SELL |
expiration | int | No | Unix timestamp for order expiration. If omitted, order is GTC |
Example — Place a limit buy order:
from py_clob_client.clob_types import OrderArgs, OrderType
from py_clob_client.order_builder.constants import BUY
order = OrderArgs(
token_id="<token-id>",
price=0.50,
size=10.0,
side=BUY
)
signed = client.create_order(order)
response = client.post_order(signed, OrderType.GTC)
print(response)
Key difference from MarketOrderArgs: OrderArgs uses price + size (price per share and number of shares), while MarketOrderArgs uses amount (total USDC to spend). Limit orders can use GTC (good til cancelled), FOK, or FAK order types, while market orders must use FOK.
Order Placement Methods
create_order() and post_order()
Order placement in py_clob_client is a two-step process: first sign the order locally, then post it to the CLOB API.
Signatures:
client.create_order(order_args: OrderArgs) -> SignedOrder
client.post_order(signed_order: SignedOrder, order_type: OrderType, post_only: bool = False) -> dict
create_order() Parameters:
| Parameter | Type | Description |
|---|---|---|
order_args | OrderArgs | The order specification (token, price, size, side) |
post_order() Parameters:
| Parameter | Type | Description |
|---|---|---|
signed_order | SignedOrder | The signed order from create_order() |
order_type | OrderType | OrderType.GTC, OrderType.FOK, or OrderType.FAK |
post_only | bool | If True, rejects the order if it would immediately match. Use for market-making strategies |
Example:
from py_clob_client.clob_types import OrderArgs, OrderType
from py_clob_client.order_builder.constants import BUY
order = OrderArgs(
token_id="<token-id>",
price=0.45,
size=20.0,
side=BUY
)
signed = client.create_order(order)
response = client.post_order(signed, OrderType.GTC)
print(f"Order ID: {response['orderID']}")
Post-only example (for market makers):
signed = client.create_order(order)
response = client.post_order(signed, OrderType.GTC, post_only=True)
# Rejects if the order would cross the spread
create_market_order()
Creates and signs a market order for immediate execution.
Signature:
client.create_market_order(order_args: MarketOrderArgs) -> SignedOrder
Example:
from py_clob_client.clob_types import MarketOrderArgs, OrderType
from py_clob_client.order_builder.constants import BUY
market_order = MarketOrderArgs(
token_id="<token-id>",
amount=50.0,
side=BUY,
order_type=OrderType.FOK
)
signed = client.create_market_order(market_order)
response = client.post_order(signed, OrderType.FOK)
Batch Orders
Place up to 15 orders in a single API call. Essential for market makers updating multiple price levels.
Signature:
client.post_orders(signed_orders: list[SignedOrder], order_type: OrderType) -> dict
Example:
from py_clob_client.clob_types import OrderArgs, OrderType
from py_clob_client.order_builder.constants import BUY
orders = []
for price in [0.48, 0.49, 0.50]:
order = OrderArgs(
token_id="<token-id>",
price=price,
size=50.0,
side=BUY
)
orders.append(client.create_order(order))
response = client.post_orders(orders, OrderType.GTC)
Order Management Methods
get_order()
Retrieves a single order by its ID.
Signature:
client.get_order(order_id: str) -> dict
Example:
order = client.get_order("<order-id>")
print(f"Status: {order['status']}")
print(f"Filled: {order['size_matched']} / {order['original_size']}")
get_orders()
Retrieves all your open orders, optionally filtered by market.
Signature:
client.get_orders(params: GetOrdersParams = None) -> list
Example:
open_orders = client.get_orders()
for order in open_orders:
print(f"Order {order['id']}: {order['side']} {order['original_size']} @ {order['price']}")
cancel()
Cancels a single order by ID.
Signature:
client.cancel(order_id: str) -> dict
Example:
response = client.cancel(order_id="<order-id>")
print(response)
cancel_all()
Cancels all your open orders across all markets.
Signature:
client.cancel_all() -> dict
Example:
response = client.cancel_all()
print(f"Cancelled all open orders")
Price and Order Book Methods
get_price()
Returns the current price for a specific token and side.
Signature:
client.get_price(token_id: str, side: str) -> str
Parameters:
| Parameter | Type | Description |
|---|---|---|
token_id | str | The outcome token ID |
side | str | "BUY" or "SELL" — the side you want the price for |
Example:
buy_price = client.get_price(token_id="<token-id>", side="BUY")
sell_price = client.get_price(token_id="<token-id>", side="SELL")
print(f"Buy at: ${buy_price} | Sell at: ${sell_price}")
get_midpoint()
Returns the midpoint between the best bid and best ask.
Signature:
client.get_midpoint(token_id: str) -> str
Example:
mid = client.get_midpoint(token_id="<token-id>")
print(f"Midpoint: ${mid}")
get_order_book()
Returns the full order book for a token.
Signature:
client.get_order_book(token_id: str) -> dict
Returns: A dictionary with bids and asks arrays, each containing [price, size] entries sorted by price.
Example:
book = client.get_order_book(token_id="<token-id>")
print("Top 5 bids:")
for bid in book["bids"][:5]:
print(f" ${bid['price']} — {bid['size']} shares")
print("Top 5 asks:")
for ask in book["asks"][:5]:
print(f" ${ask['price']} — {ask['size']} shares")
get_order_books()
Batch endpoint — fetch order books for multiple tokens in one request.
Signature:
client.get_order_books(params: list[BookParams]) -> list
Example:
from py_clob_client.clob_types import BookParams
books = client.get_order_books([
BookParams(token_id="<token-id-1>"),
BookParams(token_id="<token-id-2>"),
])
Frequently Asked Questions
How do I check my balance with py_clob_client?
Use client.get_balance() to get your USDC balance in wei as a string. Divide by 1e6 to convert to USDC. For balance plus token allowance details, use client.get_balance_allowance() with a BalanceAllowanceParams specifying the asset type. See the get_balance() Method and get_balance_allowance() Method sections above for full examples.
How do I get my positions using py_clob_client?
Call client.get_positions() to retrieve all your open positions. The response includes the token ID, size (number of shares), and average entry price for each position. See the get_positions() Method section for a complete example including how to check for existing positions before placing orders.
What is MarketOrderArgs in py_clob_client?
MarketOrderArgs is a data class for specifying market orders. It takes token_id, amount (in USDC), side (BUY or SELL), and order_type (must be OrderType.FOK for fill-or-kill execution). Use it with client.create_market_order(). See the MarketOrderArgs section for the full field reference.
What is the difference between OrderArgs and MarketOrderArgs?
OrderArgs is for limit orders — you specify a price and size (number of shares). MarketOrderArgs is for market orders — you specify an amount (total USDC to spend). Limit orders rest on the book at your specified price, while market orders execute immediately against available liquidity. See OrderArgs and MarketOrderArgs for complete field references.
How do I handle rate limits with py_clob_client?
The SDK does not handle rate limits automatically. If you hit a 429 error, implement exponential backoff with jitter. See our dedicated Polymarket Rate Limits Guide for retry code, header documentation, and strategies for staying within limits.
See Also
- Polymarket API: The Complete Developer Guide — Conceptual overview of all five Polymarket APIs
- Prediction Market API Reference — Side-by-side Polymarket vs Kalshi comparison
- Polymarket Rate Limits Guide — 429 errors, headers, and retry strategies
- py-clob-client on GitHub — Official source code and issues
- API Playground — Test endpoints live in your browser
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.