Polymarket Python CLOB Client

repository·main·Indexed 22 days ago

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

A Python client for interacting with the Polymarket Central Limit Order Book (CLOB). It enables users to fetch market data, prices, and order books, as well as place and manage market and limit orders. The client features a tiered authentication model (Levels 0, 1, and 2) to support read-only access, order signing via private keys, and full order management using API credentials.

Tokens
4.3K
Snippets
7
Records
17
Agent score
29%

What's inside py-clob-client

  1. Initialize ClobClient for read-only access

    main

    To perform read-only operations (like checking server time or getting market data) without authentication, initialize ClobClient with only the host URL.

    from py_clob_client.client import ClobClient
    
    client = ClobClient("https://clob.polymarket.com")  # Level 0 (no auth)
    
    ok = client.get_ok()
    time = client.get_server_time()
    print(ok, time)
  2. Initialize ClobClient for trading (EOA and Proxy Wallets)

    main

    To place orders, you must initialize the client with authentication credentials. The configuration depends on your wallet type.

    Signature Types

    • signature_type=0 (default): Standard EOA (Externally Owned Account) signatures (e.g., MetaMask, hardware wallets).
    • signature_type=1: Email/Magic wallet signatures (delegated signing).
    • signature_type=2: Browser wallet proxy signatures.

    Funder Address

    For proxy/smart wallets, the funder parameter must be the address that actually holds the funds, as the signing key may differ from the funded address.

    from py_clob_client.client import ClobClient
    
    HOST = "https://clob.polymarket.com"
    CHAIN_ID = 137
    PRIVATE_KEY = "<your-private-key>"
    FUNDER = "<your-funder-address>"
    
    client = ClobClient(
        HOST,  # The CLOB API endpoint
        key=PRIVATE_KEY,  # Your wallet's private key
        chain_id=CHAIN_ID,  # Polygon chain ID (137)
        signature_type=1,  # 1 for email/Magic wallet signatures
        funder=FUNDER  # Address that holds your funds
    )
    client.set_api_creds(client.create_or_derive_api_creds())
  3. How ClobClient authentication levels work

    main

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

    • Level 0 (L0): Unauthenticated. Use this for public data like market information or order books.
    • Level 1 (L1): Signer-based authentication. Requires a private key. This level is necessary for signing and creating orders (create_order, create_market_order).
    • Level 2 (L2): API Key authentication. Requires both a Signer (private key) and ApiCreds. This level is required for managing orders (cancel, get_orders), managing API keys, and accessing user-specific data like get_trades or get_notifications.

    Methods like assert_level_1_auth() and assert_level_2_auth() are used internally to ensure the client is configured with sufficient permissions for the requested action.

  4. Initialize the ClobClient

    main

    The ClobClient is the primary entrypoint for interacting with the Polymarket CLOB API. It can be initialized in three authentication modes depending on the level of access required:

    1. Level 0: Requires only the host URL. Provides access to unauthenticated/open endpoints.
    2. Level 1: Requires host, chain_id, and a private key. Provides access to L1 authenticated endpoints (e.g., creating orders).
    3. Level 2: Requires host, chain_id, key, and creds (ApiCreds). Provides access to all endpoints, including order management and API key operations.

    If a key is provided, the client initializes a Signer and an OrderBuilder.

  5. Set token allowances for MetaMask/EOA users

    main

    If you are using MetaMask or a hardware wallet, you must grant permission (allowance) to Polymarket exchange contracts to access your funds. This only needs to be done once per wallet.

    Tokens to Approve

    1. USDC (Trading currency): 0x2791Bca1f2de4661ED88A30C99A7a9449Aa84174
    2. Conditional Tokens (Outcome tokens): 0x4D97DCd97eC945f40cF65F87097ACe5EA0476045

    Contracts to Approve For

    You must approve both tokens for the following three contracts:

    • 0x4bFb41d5B3570DeFd03C39a9A4D8dE6Bd8B8982E (Main exchange)
    • 0xC5d563A36AE78145C45a50134d48A1215220f80a (Neg risk markets)
    • 0xd91E80cF2E7be2e162c6513ceD06f1dD0dA35296 (Neg risk adapter)
  6. Place a limit order (shares at a price)

    main

    Execute a limit order by specifying a price and the number of shares.

    Note: MetaMask/EOA users must set token allowances before trading. Use OrderArgs to define the order and post_order to submit it.

    from py_clob_client.client import ClobClient
    from py_clob_client.clob_types import OrderArgs, OrderType
    from py_clob_client.order_builder.constants import BUY
    
    HOST = "https://clob.polymarket.com"
    CHAIN_ID = 137
    PRIVATE_KEY = "<your-private-key>"
    FUNDER = "<your-funder-address>"
    
    client = ClobClient(
        HOST,  # The CLOB API endpoint
        key=PRIVATE_KEY,  # Your wallet's private key
        chain_id=CHAIN_ID,  # Polygon chain ID (137)
        signature_type=1,  # 1 for email/Magic wallet signatures
        funder=FUNDER  # Address that holds your funds
    )
    client.set_api_creds(client.create_or_derive_api_creds())
    
    order = OrderArgs(token_id="<token-id>", price=0.01, size=5.0, side=BUY)  # Get a token ID: https://docs.polymarket.com/developers/gamma-markets-api/get-markets
    signed = client.create_order(order)
    resp = client.post_order(signed, OrderType.GTC)
    print(resp)
  7. Find markets, prices, and orderbooks

    main

    Use the authenticated or read-only client to retrieve market information. You will need a token_id (obtainable via the Gamma Markets API).

    from py_clob_client.client import ClobClient
    from py_clob_client.clob_types import BookParams
    
    client = ClobClient("https://clob.polymarket.com")  # read-only
    
    token_id = "<token-id>"  # Get a token ID: https://docs.polymarket.com/developers/gamma-markets-api/get-markets
    
    mid = client.get_midpoint(token_id)
    price = client.get_price(token_id, side="BUY")
    book = client.get_order_book(token_id)
    books = client.get_order_books([BookParams(token_id=token_id)])
    print(mid, price, book.market, len(books))
  8. Manage orders (cancel and list)

    main

    Retrieve open orders using get_orders with OpenOrderParams and cancel them using cancel(order_id) or cancel_all().

    from py_clob_client.client import ClobClient
    from py_clob_client.clob_types import OpenOrderParams
    
    HOST = "https://clob.polymarket.com"
    CHAIN_ID = 137
    PRIVATE_KEY = "<your-private-key>"
    FUNDER = "<your-funder-address>"
    
    client = ClobClient(
        HOST,  # The CLOB API endpoint
        key=PRIVATE_KEY,  # Your wallet's private key
        chain_id=CHAIN_ID,  # Polygon chain ID (137)
        signature_type=1,  # 1 for email/Magic wallet signatures
        funder=FUNDER  # Address that holds your funds
    )
    client.set_api_creds(client.create_or_derive_api_creds())
    
    open_orders = client.get_orders(OpenOrderParams())
    
    order_id = open_orders[0]["id"] if open_orders else None
    if order_id:
        client.cancel(order_id)
    
    client.cancel_all()
  9. Place a market order (buy by $ amount)

    main

    Execute a market order by specifying a dollar amount.

    Note: MetaMask/EOA users must set token allowances before trading. Use MarketOrderArgs to define the order and post_order to submit it.

    from py_clob_client.client import ClobClient
    from py_clob_client.clob_types import MarketOrderArgs, OrderType
    from py_clob_client.order_builder.constants import BUY
    
    HOST = "https://clob.polymarket.com"
    CHAIN_ID = 137
    PRIVATE_KEY = "<your-private-key>"
    FUNDER = "<your-funder-address>"
    
    client = ClobClient(
        HOST,  # The CLOB API endpoint
        key=PRIVATE_KEY,  # Your wallet's private key
        chain_id=CHAIN_ID,  # Polygon chain ID (137)
        signature_type=1,  # 1 for email/Magic wallet signatures
        funder=FUNDER  # Address that holds your funds
    )
    client.set_api_creds(client.create_or_derive_api_creds())
    
    mo = MarketOrderArgs(token_id="<token-id>", amount=25.0, side=BUY, order_type=OrderType.FOK)  # Get a token ID: https://docs.polymarket.com/developers/gamma-markets-api/get-markets
    signed = client.create_market_order(mo)
    resp = client.post_order(signed, OrderType.FOK)
    print(resp)
  10. Cancel Orders

    main

    Manage active orders using the following methods. All require Level 2 authentication:

    • cancel(order_id): Cancels a specific order by its ID.
    • cancel_orders(order_ids: list): Cancels multiple orders by providing a list of IDs.
    • cancel_all(): Cancels all available orders for the authenticated user.
    • cancel_market_orders(market: str = "", asset_id: str = ""): Cancels orders associated with a specific market or asset ID.
  11. Get User Account and Order Information

    main

    Access user-specific data. These methods require Level 2 authentication:

    • get_orders(params: OpenOrderParams = None, next_cursor="MA=="): Gets open orders for the API key. Supports pagination via next_cursor.
    • get_order(order_id): Fetches a specific order by ID.
    • get_trades(params: TradeParams = None, next_cursor="MA=="): Fetches trade history for the user. Supports pagination.
    • get_balance_allowance(params: BalanceAllowanceParams = None): Fetches user balance and allowance.
    • update_balance_allowance(params: BalanceAllowanceParams = None): Updates balance allowance.
    • get_notifications(): Fetches user notifications.
    • drop_notifications(params: DropNotificationParams = None): Drops user notifications.