Documentation Index Fetch the complete documentation index at: https://docs.polymarket.us/llms.txt
Use this file to discover all available pages before exploring further.
Overview
The Python sample code demonstrates how to authenticate and use the Polymarket Exchange API . It includes a complete client library with 20 example scripts covering REST endpoints, gRPC streaming, and advanced features like pagination and historical data.
Download Sample Code Download the complete sample code package including Python and Go examples.
Whatβs Included
REST API Client - Complete client for all REST endpoints
gRPC Client - Streaming client for real-time market data and order updates
20 Example Scripts - Covering REST, gRPC streaming, pagination, and advanced features
Authentication - Private key JWT authentication flow
Generated Protos - Pre-generated protocol buffer bindings
Prerequisites
Python 3.6 or higher
Credentials (Client ID and private key) provided by Polymarket
A registered trading account
Installation
# Extract the download
unzip polymarket-us-client-sample-code.zip
cd client_sample_code/python
# Install dependencies
pip3 install -r requirements.txt
Configuration
Copy the sample environment file and fill in your credentials:
cp sample_env.sh my_env.sh
nano my_env.sh # Edit with your credentials
source my_env.sh
Required Environment Variables
Variable Description POLYMARKET_CLIENT_IDYour Client ID (provided by Polymarket) POLYMARKET_PRIVATE_KEY_PATHPath to your RSA private key (PEM format) POLYMARKET_API_URLAPI base URL (e.g., https://api.preprod.polymarketexchange.com) POLYMARKET_AUTH_DOMAINAuthentication domain (e.g., pmx-preprod.us.auth0.com) POLYMARKET_AUTH_AUDIENCEAuthentication audience (matches API URL) POLYMARKET_PARTICIPANT_IDYour participant ID (e.g., firms/Your-Firm/users/your-user) POLYMARKET_ACCOUNTYour trading account (e.g., firms/Your-Firm/accounts/your-account)
Optional Environment Variables
Variable Default Description POLYMARKET_TEST_SYMBOLSBLIX-KC-YESSymbol for order placement demo POLYMARKET_VERBOSEfalseEnable verbose logging POLYMARKET_TIMEOUT30Request timeout (seconds)
REST API Examples
Example Description 01_health_check.pyHealth check (no authentication required) 02_whoami.pyGet current user info 03_list_accounts.pyList trading accounts 04_get_balance.pyGet account balance 05_list_positions.pyList positions 06_list_instruments.pyList tradeable instruments 07_list_symbols.pyList all symbols 08_search_orders.pySearch order history 09_list_users.pyList users in firm 10_place_and_cancel_order.pyPlace and cancel order (safe demo)
gRPC Streaming Examples (11-15)
Example Description 11_grpc_market_data_stream.pyReal-time L2 order book updates 12_grpc_order_subscription.pyLive order status and execution updates 13_grpc_position_subscription.pyReal-time position changes 14_grpc_funding_subscription.pyFunding notifications 15_grpc_dropcopy_subscription.pyExecution reports (drop copy feed)
Advanced Examples (16-20)
Example Description 16_pagination.pyPaginating through large result sets 17_historical_positions.pyQuerying historical position data 18_instrument_filters.pyFiltering instruments by criteria 19_grpc_bidi_market_data_stream.pyBidirectional streaming market data 20_sports_refdata.pySports reference data queries
Running Examples
Run All Examples
cd examples
python3 run_all.py
Run Individual Examples
python3 examples/01_health_check.py
python3 examples/02_whoami.py
python3 examples/10_place_and_cancel_order.py
Code Examples
Authentication Flow
The client uses private_key_jwt authentication:
import jwt
from cryptography.hazmat.primitives import serialization
def create_client_assertion ( client_id : str , domain : str , private_key_path : str ) -> str :
"""Create a signed JWT for client authentication."""
with open (private_key_path, 'rb' ) as f:
private_key = serialization.load_pem_private_key(f.read(), password = None )
now = int (time.time())
claims = {
"iss" : client_id,
"sub" : client_id,
"aud" : f "https:// { domain } /oauth/token" ,
"iat" : now,
"exp" : now + 300 , # 5 minutes
"jti" : str (uuid.uuid4()),
}
return jwt.encode(claims, private_key, algorithm = "RS256" )
Using the API Client
from config import load_config
from api_client import PolymarketClient
# Load configuration from environment
config = load_config()
# Create client
client = PolymarketClient(config)
# Make API calls
status, result = client.health()
print ( f "Health: { result } " )
status, result = client.whoami()
print ( f "User: { result.get( 'user' ) } " )
status, result = client.get_balance(config.account, "USD" )
print ( f "Balance: $ { float (result.get( 'balance' , 0 )) :,.2f} " )
Placing and Canceling Orders
import uuid
# Generate unique client order ID
clord_id = f "sample- { uuid.uuid4() } "
# Place order at unattractive price (won't fill)
status, result = client.place_order(
symbol = "SBLIX-KC-YES" ,
side = "SIDE_BUY" ,
order_type = "ORDER_TYPE_LIMIT" ,
quantity = 1 ,
price = 1 , # $0.01 - very unattractive
account = config.account,
clord_id = clord_id,
)
order_id = result.get( "orderId" , "" ) or result.get( "order_id" , "" )
print ( f "Order placed: { order_id } " )
# Cancel the order immediately
cancel_status, cancel_result = client.cancel_order(
order_id = order_id,
account = config.account,
symbol = "SBLIX-KC-YES"
)
print ( f "Order cancelled: { cancel_status } " )
File Structure
client_sample_code/python/
βββ README.md # Python-specific setup
βββ requirements.txt # Dependencies (PyJWT, cryptography)
βββ sample_env.sh # Sample environment configuration
βββ config.py # Configuration loading and validation
βββ auth.py # Authentication
βββ api_client.py # REST API client
βββ grpc_client.py # gRPC streaming client
βββ gen/ # Generated protocol buffer code
β βββ README.md # Explains auto-generated files
β βββ polymarket/v1/ # Generated proto bindings
βββ examples/
βββ 01_health_check.py # Health check (no auth)
βββ 02_whoami.py # Get current user
βββ 03_list_accounts.py # List accounts
βββ 04_get_balance.py # Get balance
βββ 05_list_positions.py # List positions
βββ 06_list_instruments.py # List instruments
βββ 07_list_symbols.py # List symbols
βββ 08_search_orders.py # Search orders
βββ 09_list_users.py # List users
βββ 10_place_and_cancel_order.py # Place and cancel order
βββ 11_grpc_market_data_stream.py # Real-time market data
βββ 12_grpc_order_subscription.py # Order updates
βββ 13_grpc_position_subscription.py # Position updates
βββ 14_grpc_funding_subscription.py # Funding notifications
βββ 15_grpc_dropcopy_subscription.py # Execution reports
βββ 16_pagination.py # Pagination examples
βββ 17_historical_positions.py # Historical data
βββ 18_instrument_filters.py # Filtering instruments
βββ 19_grpc_bidi_market_data_stream.py # Bidirectional streaming
βββ 20_sports_refdata.py # Sports reference data
βββ run_all.py # Run all examples
Troubleshooting
βPrivate key file not foundβ
Ensure POLYMARKET_PRIVATE_KEY_PATH points to a valid PEM file:
ls -la $POLYMARKET_PRIVATE_KEY_PATH
openssl rsa -in $POLYMARKET_PRIVATE_KEY_PATH -check -noout
βMissing required environment variablesβ
Source your environment file before running:
source my_env.sh
python3 examples/run_all.py
βAuthentication server returned 401β
Verify your Client ID is correct
Ensure your private key matches the public key registered with Polymarket
Check that your credentials havenβt expired