Skip to main content

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

VariableDescription
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

VariableDefaultDescription
POLYMARKET_TEST_SYMBOLSBLIX-KC-YESSymbol for order placement demo
POLYMARKET_VERBOSEfalseEnable verbose logging
POLYMARKET_TIMEOUT30Request timeout (seconds)

REST API Examples

ExampleDescription
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)

ExampleDescription
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)

ExampleDescription
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