Skip to main content

REST API Client Sample

polymarketus_client.py provides a complete REST API client for testing connectivity and familiarizing yourself with the Polymarket Trading Gateway API.
This sample is configured for pre-production testing only. Use this to test your connection and credentials, and to understand the API before building your own integration.

Features

  • ✅ Username/password authentication with token management
  • ✅ Account information and management
  • ✅ Order placement with validation
  • ✅ Order cancellation (single and bulk)
  • ✅ Open order queries
  • ✅ Random order generation for testing
  • ✅ Interactive CLI menu
  • ✅ Comprehensive error handling

Quick Start

Download the Sample

Download polymarketus_client.py

Run the Client

python polymarketus_client.py
The interactive menu will guide you through:
  1. Authentication
  2. Getting user information
  3. Placing orders
  4. Viewing open orders
  5. Canceling orders

Code Walkthrough

Authentication

The client uses username/password authentication specific to the Trading Gateway:
def login(self, username: str, password: str) -> Dict[str, Any]:
    """Authenticate with the Trading Gateway API and store tokens."""
    url = f"{self.base_url}/auth/v1beta1/login"
    headers = {
        "accept": "application/json",
        "Content-Type": "application/json"
    }
    data = {
        "username": username,
        "password": password
    }

    response = requests.post(url, headers=headers, json=data)
    response.raise_for_status()

    token_data = response.json()
    self.access_token = token_data["access_token"]
    self.refresh_token = token_data["refresh_token"]

    return token_data

Placing Orders

def place_order(self, order_data: Dict[str, Any]) -> Dict[str, Any]:
    """Place a trading order."""
    url = f"{self.base_url}/api/v1beta1/insert_order"
    response = requests.post(url, headers=self.get_headers(), json=order_data)
    response.raise_for_status()
    return response.json()
Example order data:
order_data = {
    "type": "ORDER_TYPE_LIMIT",
    "side": "SIDE_BUY",
    "order_qty": 10,
    "symbol": "aec-nfl-buf-nyj-2025-01-15",
    "price": 0.55,
    "time_in_force": "TIME_IN_FORCE_GOOD_TILL_CANCEL",
    "clord_id": str(uuid.uuid4()),
    "account": client.trading_account
}

Getting Open Orders

def get_open_orders(self) -> Dict[str, Any]:
    """Get open orders."""
    url = f"{self.base_url}/api/v1beta1/get_open_orders"
    response = requests.post(url, headers=self.get_headers(), json={})
    response.raise_for_status()
    return response.json()

Canceling Orders

Single order cancellation:
def cancel_order(self, order_id: str, symbol: str) -> bool:
    """Cancel an open order."""
    url = f"{self.base_url}/api/v1beta1/cancel_order"
    data = {
        "orderId": order_id,
        "symbol": symbol
    }
    response = requests.post(url, headers=self.get_headers(), json=data)
    return response.status_code == 200
Bulk cancellation:
def cancel_all_orders(self) -> Dict[str, Any]:
    """Cancel all open orders."""
    open_orders_response = self.get_open_orders()
    orders = open_orders_response.get("orders", [])

    cancel_list = [
        {"orderId": order.get("id"), "symbol": order.get("symbol")}
        for order in orders
    ]

    url = f"{self.base_url}/api/v1beta1/cancel_order_list"
    response = requests.post(url, headers=self.get_headers(), json={"requests": cancel_list})
    return response.json()

Configuration

Endpoint

The client is configured for pre-production testing:
client = PolymarketClient(
    base_url="https://rest.preprod.polymarketexchange.com"  # Pre-production default
)
Contact your account manager for production credentials and endpoints when you’re ready to go live.

Error Handling

The client includes comprehensive error handling:
if not response.ok:
    error_msg = f"HTTP {response.status_code}: {response.reason}"
    try:
        error_data = response.json()
        if 'message' in error_data:
            error_msg += f" - {error_data['message']}"
        if 'details' in error_data:
            error_msg += f" - Details: {error_data['details']}"
    except:
        error_msg += f" - Response: {response.text}"

    raise requests.exceptions.HTTPError(error_msg, response=response)