Polymarket Python CLOB Client v2

repository·main·Indexed 41 days ago

https://github.com/polymarket/py-clob-client-v2

A Python client for interacting with the Polymarket Central Limit Order Book (CLOB) v2 API. It supports REST and WebSocket communications, featuring a tiered authentication model (L0 public, L1 wallet, and L2 API key). The client enables developers to manage API keys, fetch market and order book data, and execute limit and market orders using OrderType.GTC, OrderType.FOK, and OrderType.FAK.

Tokens
3.4K
Snippets
10
Records
18
Agent score
2%

What's inside Polymarket

  1. Initialize a fully-authenticated ClobClient

    main

    Authentication in the CLOB client occurs in two levels:

    1. L1 (Wallet Signature): Uses your private key (EIP-712) to create or derive API credentials.
    2. L2 (HMAC): Uses the derived ApiCreds (API Key, Secret, and Passphrase) for performing actions like order placement, cancellation, and accessing account data.

    To use the client for trading, you must first perform L1 authentication to get credentials, then re-initialize the client with those credentials for L2 authentication.

    import os
    from py_clob_client_v2 import ClobClient, ApiCreds
    
    host = "<polymarket-clob-host>"
    chain_id = 137  # or 80002 for Amoy testnet
    
    # Step 1: L1 Auth - Obtain API credentials using your wallet
    client = ClobClient(host=host, chain_id=chain_id, key=os.environ["PK"])
    creds = client.create_or_derive_api_key()
    
    # Step 2: L2 Auth - Initialize fully-authenticated client
    client = ClobClient(host=host, chain_id=chain_id, key=os.environ["PK"], creds=creds)
  2. How authentication levels work in ClobClient

    main

    The ClobClient uses a tiered authentication model to control access to different API capabilities:

    • Level 0 (L0): No authentication. Used for public endpoints like get_markets, get_order_book, or get_price.
    • Level 1 (L1): Authenticated via a private key (signer). Required for operations that need to identify the user, such as get_address or create_api_key.
    • Level 2 (L2): Authenticated via both a private key and API credentials (creds). Required for state-changing operations like post_order, cancel_order, or update_balance_allowance.

    Methods like assert_level_1_auth() and assert_level_2_auth() are used internally to ensure the client is in the correct mode before attempting an operation.

  3. Initialize the ClobClient

    main

    The ClobClient is the primary entry point for interacting with the Polymarket CLOB. It supports three authentication modes based on the provided arguments:

    1. L0 (No Auth): No key or creds provided. Used for public read-only data.
    2. L1 (Wallet Auth): key (private key) is provided. Allows access to user-specific data and signing orders.
    3. L2 (API Key Auth): Both key and creds (ApiCreds) are provided. Required for posting orders and managing API keys.

    Parameters

    • host: The CLOB API host URL.
    • chain_id: The blockchain chain ID.
    • key (Optional): Private key for L1 authentication.
    • creds (Optional): ApiCreds object for L2 authentication.
    • builder_config (Optional): Configuration for the OrderBuilder.
    • use_server_time (bool): If true, uses the server's timestamp for requests.
    • retry_on_error (bool): If true, retries requests on error.
    • fee_slippage (float): Maximum allowed fee slippage.
    from py_clob_client_v2 import ClobClient
    
    client = ClobClient(
        host="https://clob.polymarket.com",
        chain_id=137,
        key="YOUR_PRIVATE_KEY",
        creds=my_api_creds  # Optional for L2
    )
  4. Place a market order

    main

    Use client.create_and_post_market_order to execute market orders. Unlike limit orders, market orders use MarketOrderArgs where the amount represents the amount in USDC rather than the token size.

    Supported OrderType behaviors for market orders:

    • OrderType.FOK (Fill or Kill): The entire order must fill immediately or it is cancelled.
    • OrderType.FAK (Fill and Kill): Fills as much as possible, and the remainder is cancelled.
    from py_clob_client_v2 import MarketOrderArgs, OrderType, PartialCreateOrderOptions, Side
    
    # Market buy — amount is in USDC
    resp = client.create_and_post_market_order(
        order_args=MarketOrderArgs(
            token_id="",
            amount=100,  # USDC
            side=Side.BUY,
            order_type=OrderType.FOK,
        ),
        options=PartialCreateOrderOptions(tick_size="0.01"),
        order_type=OrderType.FOK,
    )
  5. Place a resting limit order (GTC)

    main

    Use client.create_and_post_order to place a limit order. For a standard resting order, use OrderType.GTC (Good 'Til Cancelled). You must provide OrderArgs specifying the token_id, price, side, and size.

    from py_clob_client_v2 import OrderArgs, OrderType, PartialCreateOrderOptions, Side
    
    resp = client.create_and_post_order(
        order_args=OrderArgs(
            token_id="",  # token ID of the market outcome
            price=0.4,
            side=Side.BUY,
            size=100,
        ),
        options=PartialCreateOrderOptions(tick_size="0.01"),
        order_type=OrderType.GTC,
    )
  6. Configure ApiCreds for L2 Authentication

    main

    If you already have API credentials, you can initialize the ClobClient with an ApiCreds object to bypass the L1 derivation step.

    from py_clob_client_v2 import ApiCreds, ClobClient
    
    creds = ApiCreds(
        api_key=os.environ["CLOB_API_KEY"],
        api_secret=os.environ["CLOB_SECRET"],
        api_passphrase=os.environ["CLOB_PASS_PHRASE"],
    )
    client = ClobClient(host=host, chain_id=chain_id, key=os.environ["PK"], creds=creds)
  7. Check if orders are scoring

    main

    Check the scoring status of one or more orders. This method requires Level 2 authentication.

    Methods:

    • is_order_scoring(params: OrderScoringParams = None): Checks the status for a single orderId provided in params.
    • are_orders_scoring(params: OrdersScoringParams = None): Checks the status for a list of orderIds provided in params.
  8. Create and post a market order

    main

    Market orders are executed immediately at the best available price. Use create_and_post_market_order.

    Parameters

    • order_args: A MarketOrderArgsV2 object. Note that for market orders, you typically provide amount (in USDC) rather than size (in tokens) if user_usdc_balance is provided.
    • order_type: Defaults to OrderType.FOK (Fill or Kill).
    • defer_exec (bool): If true, returns immediately without waiting for trade resolution.
    from py_clob_client_v2.clob_types import MarketOrderArgsV2, Side, OrderType
    
    market_order_args = MarketOrderArgsV2(
        token_id="TOKEN_ID",
        side=Side.BUY,
        amount=50.0,  # Amount in USDC
        order_type=OrderType.FOK
    )
    
    response = client.create_and_post_market_order(market_order_args)
  9. Retrieve user earnings data

    main

    Fetch earnings information for a user for a specific date. These methods require Level 2 authentication.

    Methods:

    • get_earnings_for_user_for_day(date: str): Returns a list of all earnings entries for the given date. This method handles pagination internally using cursors.
    • get_total_earnings_for_user_for_day(date: str): Returns the total aggregated earnings for the given date.
    • get_user_earnings_and_markets_config(date: str, order_by: str = "", position: str = "", no_competition: bool = False): Returns earnings and market configuration data for a specific date. This method also handles pagination internally.