polymarket-apis

repository·main·Indexed 41 days ago

https://github.com/qualiaenjoyer/polymarket-apis

Unified Python clients for Polymarket v2 APIs with Pydantic data validation. Includes clients for Clob, Gamma, Data, Web3, Websockets, and GraphQL to manage order books, market metadata, portfolio tracking, and on-chain operations like splitting and merging positions.

Tokens
10.2K
Snippets
34
Records
51
Agent score
43%

What's inside polymarket-apis

  1. What is Negative Risk and Conversion?

    main

    Negative Risk

    An Event supports negative risk if its constituent Markets collectively cover a complete universe of possibilities where only one winner is possible. In such cases, certain combinations of positions are mathematically equivalent.

    Example: In a market for {0, 1, 2...} rate cuts, holding a No token in the "0 rate cuts" market is mathematically equivalent to holding a Yes token in every other market ({1, 2, 3...}).

    Conversions

    Polymarket provides a smart contract that allows for a one-way conversion from No tokens into a collection of Yes tokens and pUSD before the market resolves. This is designed to improve capital efficiency for traders holding specific risk profiles.

  2. Understand the Polymarket hierarchy: Events, Markets, and Outcomes

    main

    The Polymarket ecosystem follows a hierarchical structure that you must understand to navigate the APIs correctly. While different APIs (Clob, Gamma, etc.) may use different object names (e.g., ClobMarket vs GammaMarket), they all refer to the same underlying entities using consistent identifiers.

    • Event: The high-level proposition or question (e.g., "How many Fed rate cuts in 2025?").
      • Key identifiers: slug (human-readable string) and id (numeric).
    • Market: A specific option within an Event (e.g., "1 rate cut in 2025"). An Event contains one or more Markets.
      • Key identifiers: condition id (hexadecimal address), slug (human-readable string), and id (numeric).
    • Outcome: A specific result within a Market (e.g., Yes or No).
      • Key identifier: token id (large numeric string representing the blockchain token).
  3. How the Unified Order Book functions

    main

    Polymarket utilizes a Central Limit Order Book (CLOB) where orders are matched based on price and time priority.

    Because Yes and No outcomes in a market form a complete probability universe, the order book is unified. This means:

    • A BUY order for Outcome 1 at price X is mathematically equivalent to a SELL order for Outcome 2 at price (100¢ - X).
    • This unification allows the matching engine to treat these as the same liquidity pool, resulting in deeper liquidity and tighter spreads than if Yes and No had separate books.
  4. How Tokens, Splits, and Merges work

    main

    In Polymarket, Tokens are the blockchain implementation of Outcomes. They are tradable digital assets on the Polygon blockchain.

    Splits and Merges

    Polymarket uses a mathematical relationship between complementary outcomes to manage liquidity:

    • Splits: The process of creating tokens. 1 pUSD can be split into 1 Yes share and 1 No share. This can be done manually by a user or automatically by the matching engine when buy orders for complementary outcomes are matched.
    • Merges: The process of combining tokens. Holding 1 Yes share and 1 No share in the same market covers the entire universe of possibilities and can be merged back into 1 pUSD, guaranteeing a $1.00 payout regardless of the outcome.

    This mechanism ensures that the sum of probabilities across a market remains consistent.

  5. Handle and retry HTTP errors

    main

    When dealing with PolymarketHTTPError, you can inspect the status_code, response_body, and retry_after fields. To determine if an error is safe to retry (e.g., a 429 Rate Limit or a 5xx Server Error), use the is_retryable() method.

    Retryable Status Codes: 429, 500, 502, 503, 504.

    try:
        # Perform API call
        pass
    except PolymarketHTTPError as e:
        print(f"Error: {e.message} (Status: {e.status_code})")
        if e.is_retryable():
            wait_time = e.retry_after or 1.0
            # logic to retry after wait_time
  6. Initialize PolymarketGaslessWeb3Client for gasless transactions

    main

    Use PolymarketGaslessWeb3Client to perform transactions without paying gas directly from your wallet by using a relayer. This client supports three specific signature_type modes:

    • 1: Poly proxy wallets
    • 2: Safe wallets
    • 3: Deposit wallets

    To initialize the client, you must provide a private_key and either a relayer_api_key or builder_creds. You can also specify the chain_id (defaults to Polygon) and rpc_url.

    from polymarket_apis.clients.web3_client import PolymarketGaslessWeb3Client
    
    client = PolymarketGaslessWeb3Client(
        private_key="YOUR_PRIVATE_KEY_HEX",
        signature_type=1,  # 1 for Poly proxy, 2 for Safe, 3 for Deposit
        relayer_api_key="YOUR_RELAYER_API_KEY"
    )
  7. Handle Polymarket SDK errors

    main

    All errors in the SDK inherit from PolymarketError. You can catch this base class to handle any SDK-related issue, or catch more specific subclasses to implement granular error handling logic (e.g., retrying on network errors vs. stopping on authentication errors).

    Error Hierarchy Overview

    1. PolymarketError: The base exception for all SDK errors.
    2. PolymarketHTTPError: Errors occurring at the HTTP layer (e.g., BadRequestError, AuthenticationError, RateLimitError, ServerError).
    3. PolymarketDomainError: Business-logic errors that occur before or during a request (e.g., InvalidPriceError, LiquidityError).
    4. PolymarketOrderError: Specific to the order lifecycle (e.g., OrderPlacementError, OrderCancellationError).
    5. PolymarketWeb3Error: Blockchain-level issues (e.g., TransactionFailedError, NonceError).
  8. Use PolymarketGraphQLClient for subgraph queries

    main

    Use PolymarketGraphQLClient or AsyncPolymarketGraphQLClient to execute Goldsky-hosted subgraph queries.

    Available Endpoints:

    • activity_subgraph
    • fpmm_subgraph
    • open_interest_subgraph
    • orderbook_subgraph
    • pnl_subgraph
    • positions_subgraph
    • sports_oracle_subgraph
    • wallet_subgraph

    Usage: Call .query() with a GraphQL query string to receive the raw JSON response.

  9. Use PolymarketDataClient for portfolio and activity tracking

    main

    Use PolymarketDataClient to track user-specific financial data and performance.

    Key Capabilities:

    • Positions: Get user positions with pagination and filters for size, redeemability, and condition_id.
    • Activity & Trades: Retrieve user activity and trade history with various filters (side, taker-only, amount).
    • Performance (PnL): Get PnL timeseries (e.g., 1d, 1w, 1m, all) with configurable frequency, and view overall PnL/volume or user rank on leaderboards.
    • Market Data: Get open interest for condition_ids and live volume for an event.
  10. Use PolymarketClobClient for trading and order management

    main

    Use PolymarketClobClient for active trading operations. This client requires authentication via private_key and address.

    Authentication & Wallet Types:

    • signature_type=0: EOA (Externally Owned Accounts)
    • signature_type=1: Email/Magic wallets
    • signature_type=2: Safe/Gnosis wallets
    • signature_type=3: Deposit wallets

    Core Operations:

    • Orders: Create/post limit or market orders, cancel orders by order_id, or cancel all orders for a specific condition_id/token_id.
    • Trades: Retrieve user trade history with filters for condition_id, token_id, trade_id, and time windows.
    • Rewards: Check if orders are scoring for liquidity rewards, get daily earned rewards, or find active reward markets using get_reward_markets().
    • Balances: Get pUSD balance or specific token balances by token_id.
  11. Use PolymarketWebsocketsClient for real-time data streams

    main

    Use AsyncPolymarketWebsocketsClient for production bots and PolymarketWebsocketsClient for a blocking wrapper.

    Connection Management:

    • open_*_connection(): Starts a stream and returns a handle for health checks and dynamic subscription.
    • run_*_stream(): Starts a stream and waits until it closes.
    • connection.close(): Fast shutdown (may drop queued events).
    • connection.graceful_close(): Drains queued callback events before returning (recommended for recorders/audit pipelines).

    Available Streams:

    • Market Socket: Subscriptions for token_ids to receive book snapshots, price changes, and trade updates.
    • User Socket: Receive order (live, canceled, matched) and trade events.
    • Real-time Data Socket: Receive trades, orders, crypto/equity prices, and comment events.
    • Sports Socket: Receive game state updates (score, period, etc.).
    from polymarket_apis import AsyncPolymarketWebsocketsClient
    
    async def on_event(event: object) -> None:
        print(event)
    
    client = AsyncPolymarketWebsocketsClient()
    
    connection = await client.open_market_connection(
        token_ids=["token_id_1", "token_id_2"],
        process_event=on_event,
    )
    
    # Check health
    print(connection.health()) 
    
    # Shutdown
    await connection.graceful_close()
    await client.close()