### Manage Orders with py-clob-client (Python) Source: https://github.com/polymarket/py-clob-client/blob/main/README.md This example illustrates how to manage existing orders using the ClobClient. It shows how to retrieve all open orders, cancel a specific order by its ID, and cancel all open orders associated with the authenticated user. Client initialization and API credential setup are required. ```python 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 = "" FUNDER = "" 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() ``` -------------------------------- ### Install Polymarket Python CLOB Client Source: https://github.com/polymarket/py-clob-client/blob/main/README.md This command installs the Polymarket Python CLOB client library from PyPI. It requires Python 3.9 or newer to function correctly. This is the essential first step to set up the client for interacting with the Polymarket Central Limit Order Book. ```bash pip install py-clob-client ``` -------------------------------- ### Retrieve Market Data using py-clob-client Source: https://context7.com/polymarket/py-clob-client/llms.txt Demonstrates how to fetch various market metrics such as midpoint prices, side-specific prices, spreads, and tick sizes. It includes examples for both individual token queries and batch requests using BookParams. ```python # Get midpoint price (average of best bid and ask) midpoint = client.get_midpoint(token_id) print(f"Midpoint: {midpoint}") # {"mid": "0.50"} # Get market price for a specific side buy_price = client.get_price(token_id, side="BUY") sell_price = client.get_price(token_id, side="SELL") print(f"Buy at: {buy_price}, Sell at: {sell_price}") # Get spread (difference between best bid and ask) spread = client.get_spread(token_id) print(f"Spread: {spread}") # Batch requests for multiple tokens params = [BookParams(token_id=token_id)] midpoints = client.get_midpoints(params) prices = client.get_prices([BookParams(token_id=token_id, side="BUY")]) spreads = client.get_spreads(params) # Get last trade price last_price = client.get_last_trade_price(token_id) print(f"Last trade: {last_price}") # Get tick size (minimum price increment) tick_size = client.get_tick_size(token_id) print(f"Tick size: {tick_size}") # "0.01" or "0.001" ``` -------------------------------- ### Retrieve Market Data from Polymarket CLOB in Python Source: https://github.com/polymarket/py-clob-client/blob/main/README.md This example demonstrates how to fetch various market data points from the Polymarket CLOB using a read-only client. It shows how to obtain the midpoint price, the current price for a specific trading side, and full order books for one or multiple token IDs. A valid `token_id` is required as input for these queries. ```python 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 = "" # 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)) ``` -------------------------------- ### Retrieve User Trades with py-clob-client (Python) Source: https://github.com/polymarket/py-clob-client/blob/main/README.md This example shows how to fetch user-specific trade data, including the last trade price for a given token ID and a list of all user trades. It requires client authentication via a private key and API credentials. EOA/MetaMask users should ensure token allowances are set. ```python from py_clob_client.client import ClobClient HOST = "https://clob.polymarket.com" CHAIN_ID = 137 PRIVATE_KEY = "" FUNDER = "" 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()) last = client.get_last_trade_price("") trades = client.get_trades() print(last, len(trades)) ``` -------------------------------- ### Initialize Polymarket CLOB Client for Proxy Wallet Trading in Python Source: https://github.com/polymarket/py-clob-client/blob/main/README.md This snippet initializes the `ClobClient` for trading with a proxy wallet, demonstrating setup for email/Magic wallet signatures (`signature_type=1`). It requires a private key, the chain ID, and a `PROXY_FUNDER` address, which is the actual address holding your funds. The funder address is crucial for ensuring orders are correctly attributed to your funded account. ```python from py_clob_client.client import ClobClient HOST = "https://clob.polymarket.com" CHAIN_ID = 137 PRIVATE_KEY = "" PROXY_FUNDER = "" # Address that holds your funds 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=PROXY_FUNDER # Address that holds your funds ) client.set_api_creds(client.create_or_derive_api_creds()) ``` -------------------------------- ### Initialize Read-Only Polymarket CLOB Client in Python Source: https://github.com/polymarket/py-clob-client/blob/main/README.md This snippet demonstrates how to initialize the `ClobClient` for read-only operations without requiring any authentication. It connects to the specified Polymarket CLOB API endpoint and can be used to retrieve basic server status and time. This setup is ideal for fetching public market data without needing a private key. ```python 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) ``` -------------------------------- ### Get open orders from Polymarket CLOB Source: https://context7.com/polymarket/py-clob-client/llms.txt Retrieve all open orders or filter by market ID, asset ID, or specific order ID. Supports optional filtering parameters through OpenOrderParams to narrow results by market or token. Returns a list of order objects with full order details. ```python from py_clob_client.client import ClobClient from py_clob_client.clob_types import ApiCreds, OpenOrderParams client = ClobClient( "https://clob.polymarket.com", key="0x_your_private_key", chain_id=137, creds=ApiCreds( api_key="your_api_key", api_secret="your_api_secret", api_passphrase="your_passphrase" ) ) # Get all open orders all_orders = client.get_orders() print(f"Total open orders: {len(all_orders)}") # Get orders filtered by market market_orders = client.get_orders( OpenOrderParams(market="0x37a6a2dd9f3469495d9ec2467b0a764c5905371a294ce544bc3b2c944eb3e84a") ) # Get orders filtered by asset ID (token) asset_orders = client.get_orders( OpenOrderParams(asset_id="71321045679252212594626385532706912750332728571942532289631379312455583992563") ) # Get a specific order by ID order = client.get_order("0x_order_id") print(order) ``` -------------------------------- ### Get trade history from Polymarket CLOB Source: https://context7.com/polymarket/py-clob-client/llms.txt Retrieve trade history with optional filtering by maker address, market, asset, and time range. Supports TradeParams for granular filtering and returns individual trade records or market trade events by condition ID. ```python from py_clob_client.client import ClobClient from py_clob_client.clob_types import ApiCreds, TradeParams client = ClobClient( "https://clob.polymarket.com", key="0x_your_private_key", chain_id=137, creds=ApiCreds( api_key="your_api_key", api_secret="your_api_secret", api_passphrase="your_passphrase" ) ) # Get all trades trades = client.get_trades() print(f"Total trades: {len(trades)}") # Get trades with filters filtered_trades = client.get_trades( TradeParams( maker_address=client.get_address(), market="0x5f65177b394277fd294cd75650044e32ba009a95022d88a0c1d565897d72f8f1", asset_id="token_id", # Optional: filter by specific token before=1699900000, # Optional: trades before this timestamp after=1699800000 # Optional: trades after this timestamp ) ) for trade in filtered_trades: print(f"Trade: {trade}") # Get market trade events by condition ID events = client.get_market_trades_events("0x_condition_id") print(events) ``` -------------------------------- ### Create and Post Limit Orders with py-clob-client Source: https://context7.com/polymarket/py-clob-client/llms.txt Shows how to initialize the ClobClient and execute a limit order. This process involves defining OrderArgs, signing the order locally, and posting it to the order book with specific execution instructions like GTC or post-only. ```python from py_clob_client.client import ClobClient from py_clob_client.clob_types import ApiCreds, OrderArgs, OrderType from py_clob_client.order_builder.constants import BUY, SELL client = ClobClient( "https://clob.polymarket.com", key="0x_your_private_key", chain_id=137, creds=ApiCreds( api_key="your_api_key", api_secret="your_api_secret", api_passphrase="your_passphrase" ) ) # Create a limit buy order: 20 shares at $0.50 each order_args = OrderArgs( token_id="71321045679252212594626385532706912750332728571942532289631379312455583992563", price=0.50, # Price per share ($0.00 to $1.00) size=20.0, # Number of shares side=BUY, # BUY or SELL fee_rate_bps=0, # Fee rate in basis points (optional) expiration=0, # Unix timestamp, 0 = no expiration ) # Create and sign the order signed_order = client.create_order(order_args) # Post the order to the order book # OrderType: GTC (Good Till Cancelled), GTD (Good Till Date), FOK (Fill or Kill), FAK (Fill and Kill) response = client.post_order(signed_order, orderType=OrderType.GTC) print(response) # Post as post-only order (only adds liquidity, never takes) response = client.post_order(signed_order, orderType=OrderType.GTC, post_only=True) # Convenience method: create and post in one call response = client.create_and_post_order(order_args) ``` -------------------------------- ### Place a Limit Order with py-clob-client (Python) Source: https://github.com/polymarket/py-clob-client/blob/main/README.md This snippet demonstrates how to initialize the ClobClient, set API credentials, and place a limit order on Polymarket. It defines order parameters like token ID, price, size, and side (BUY), then signs and posts the order. EOA/MetaMask users must set token allowances beforehand. ```python 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 = "" FUNDER = "" 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="", 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) ``` -------------------------------- ### Initialize ClobClient with Authentication Levels - Python Source: https://context7.com/polymarket/py-clob-client/llms.txt Initialize the ClobClient with different authentication levels for various use cases. Level 0 requires only the host URL for read-only access, Level 1 adds a private key for signing, and Level 2 adds API credentials for full trading capabilities. Supports multiple wallet types including EOA, Magic/email wallets, and proxy wallets. ```python from py_clob_client.client import ClobClient from py_clob_client.clob_types import ApiCreds # Level 0: Read-only access (no authentication) client = ClobClient("https://clob.polymarket.com") # Level 1: Signed access with private key client = ClobClient( "https://clob.polymarket.com", key="0x_your_private_key", chain_id=137 # Polygon mainnet ) # Level 2: Full trading access with API credentials creds = ApiCreds( api_key="your_api_key", api_secret="your_api_secret", api_passphrase="your_passphrase" ) client = ClobClient( "https://clob.polymarket.com", key="0x_your_private_key", chain_id=137, creds=creds, signature_type=0, # 0=EOA, 1=Magic/email wallet, 2=Browser proxy funder="0x_funder_address" # Required for proxy wallets ) # Create or derive API credentials automatically client = ClobClient("https://clob.polymarket.com", key="0x_your_private_key", chain_id=137) client.set_api_creds(client.create_or_derive_api_creds()) ``` -------------------------------- ### Create and Manage RFQ Quotes in Python Source: https://context7.com/polymarket/py-clob-client/llms.txt Demonstrates the market maker workflow for RFQs, including fetching active requests, submitting quotes, and retrieving quote history. It also covers finding the best available quote for a specific request. ```python from py_clob_client.client import ClobClient from py_clob_client.clob_types import ApiCreds from py_clob_client.rfq import RfqUserQuote, GetRfqRequestsParams, CancelRfqQuoteParams from py_clob_client.order_builder.constants import SELL client = ClobClient( "https://clob.polymarket.com", key="0x_your_private_key", chain_id=137, creds=ApiCreds( api_key="your_api_key", api_secret="your_api_secret", api_passphrase="your_passphrase" ) ) # Get active RFQ requests to quote on active_requests = client.rfq.get_rfq_requests( GetRfqRequestsParams(state="active") ) print(f"Active requests: {active_requests}") # Create a quote for a request (as the quoter/market maker) quote = RfqUserQuote( request_id="019a83a9-f4c7-7c96-9139-2da2b2d934ef", token_id="34097058504275310827233323421517291090691602969494795225921954353603704046623", price=0.50, # Your quoted price side=SELL, # Quoter's side (opposite of requester) size=100.0 # Size you're willing to trade ) response = client.rfq.create_rfq_quote(quote) quote_id = response.get("quoteId") print(f"Quote created: {quote_id}") # Get quotes you've made (as quoter) my_quotes = client.rfq.get_rfq_quoter_quotes() print(my_quotes) # Get quotes on your requests (as requester) received_quotes = client.rfq.get_rfq_requester_quotes() print(received_quotes) # Get best quote for a specific request from py_clob_client.rfq import GetRfqBestQuoteParams best = client.rfq.get_rfq_best_quote( GetRfqBestQuoteParams(request_id="request_id") ) print(f"Best quote: {best}") # Cancel a quote client.rfq.cancel_rfq_quote(CancelRfqQuoteParams(quote_id=quote_id)) ``` -------------------------------- ### Create and Manage RFQ Requests Source: https://context7.com/polymarket/py-clob-client/llms.txt Details the process of creating a Request-for-Quote (RFQ) to solicit prices from market makers for large block trades, and how to retrieve existing requests. ```python from py_clob_client.client import ClobClient from py_clob_client.clob_types import ApiCreds from py_clob_client.rfq import RfqUserRequest from py_clob_client.order_builder.constants import BUY, SELL client = ClobClient( "https://clob.polymarket.com", key="0x_your_private_key", chain_id=137, creds=ApiCreds( api_key="your_api_key", api_secret="your_api_secret", api_passphrase="your_passphrase" ) ) # Create an RFQ request to buy tokens request = RfqUserRequest( token_id="34097058504275310827233323421517291090691602969494795225921954353603704046623", price=0.50, # Target price per token side=BUY, # BUY or SELL size=100.0 # Number of tokens ) response = client.rfq.create_rfq_request(request) request_id = response.get("requestId") print(f"RFQ Request created: {request_id}") # Get your RFQ requests requests = client.rfq.get_rfq_requests() print(requests) ``` -------------------------------- ### Execute Market Orders with py-clob-client Source: https://context7.com/polymarket/py-clob-client/llms.txt Explains how to perform market orders where execution happens immediately at the best available price. Note that 'amount' refers to USD for BUY orders and share count for SELL orders. ```python from py_clob_client.client import ClobClient from py_clob_client.clob_types import ApiCreds, MarketOrderArgs, OrderType from py_clob_client.order_builder.constants import BUY, SELL client = ClobClient( "https://clob.polymarket.com", key="0x_your_private_key", chain_id=137, creds=ApiCreds( api_key="your_api_key", api_secret="your_api_secret", api_passphrase="your_passphrase" ) ) # Market buy order: spend $100 at market price buy_args = MarketOrderArgs( token_id="71321045679252212594626385532706912750332728571942532289631379312455583992563", amount=100.0, # Dollar amount to spend (for BUY) side=BUY, order_type=OrderType.FOK # Fill-or-Kill ensures full execution or cancellation ) signed_buy = client.create_market_order(buy_args) response = client.post_order(signed_buy, orderType=OrderType.FOK) print(response) # Market sell order: sell 50 shares at market price sell_args = MarketOrderArgs( token_id="71321045679252212594626385532706912750332728571942532289631379312455583992563", amount=50.0, # Number of shares to sell (for SELL) side=SELL, order_type=OrderType.FOK ) signed_sell = client.create_market_order(sell_args) response = client.post_order(signed_sell, orderType=OrderType.FOK) print(response) ``` -------------------------------- ### Execute Full RFQ Trade Lifecycle with py-clob-client Source: https://context7.com/polymarket/py-clob-client/llms.txt Illustrates the end-to-end process of an RFQ trade between a requester and a quoter. It involves creating a request, providing a quote, accepting the quote, and finally approving the order for execution. ```python from py_clob_client.client import ClobClient from py_clob_client.clob_types import ApiCreds from py_clob_client.rfq import ( RfqUserRequest, RfqUserQuote, AcceptQuoteParams, ApproveOrderParams ) from py_clob_client.order_builder.constants import BUY, SELL import time # Initialize requester and quoter clients requester = ClobClient( "https://clob.polymarket.com", key="0x_requester_private_key", chain_id=137, creds=ApiCreds(api_key="req_key", api_secret="req_secret", api_passphrase="req_pass") ) quoter = ClobClient( "https://clob.polymarket.com", key="0x_quoter_private_key", chain_id=137, creds=ApiCreds(api_key="quo_key", api_secret="quo_secret", api_passphrase="quo_pass") ) TOKEN_ID = "34097058504275310827233323421517291090691602969494795225921954353603704046623" # Step 1: Requester creates RFQ request request_response = requester.rfq.create_rfq_request( RfqUserRequest(token_id=TOKEN_ID, price=0.50, side=BUY, size=100.0) ) request_id = request_response["requestId"] # Step 2: Quoter creates quote quote_response = quoter.rfq.create_rfq_quote( RfqUserQuote(request_id=request_id, token_id=TOKEN_ID, price=0.50, side=SELL, size=100.0) ) quote_id = quote_response["quoteId"] # Step 3: Requester accepts the quote expiration = int(time.time()) + 3600 # 1 hour from now accept_result = requester.rfq.accept_rfq_quote( AcceptQuoteParams(request_id=request_id, quote_id=quote_id, expiration=expiration) ) print(f"Quote accepted: {accept_result}") # Step 4: Quoter approves the order approve_result = quoter.rfq.approve_rfq_order( ApproveOrderParams(request_id=request_id, quote_id=quote_id, expiration=expiration) ) print(f"Order approved: {approve_result}") # Get RFQ configuration config = requester.rfq.rfq_config() print(f"RFQ Config: {config}") ``` -------------------------------- ### Fetch Order Book with Bids and Asks - Python Source: https://context7.com/polymarket/py-clob-client/llms.txt Retrieve the current order book for a token showing all bids and asks with prices and sizes. Supports fetching single or multiple order books and generating orderbook hashes for verification purposes. ```python from py_clob_client.client import ClobClient from py_clob_client.clob_types import BookParams client = ClobClient("https://clob.polymarket.com") token_id = "34097058504275310827233323421517291090691602969494795225921954353603704046623" # Get single order book orderbook = client.get_order_book(token_id) print(f"Market: {orderbook.market}") print(f"Bids: {orderbook.bids}") # [OrderSummary(price='0.45', size='100'), ...] print(f"Asks: {orderbook.asks}") # [OrderSummary(price='0.55', size='50'), ...] print(f"Tick Size: {orderbook.tick_size}") # Generate orderbook hash for verification hash = client.get_order_book_hash(orderbook) print(f"Orderbook hash: {hash}") # Get multiple order books in one request books = client.get_order_books([ BookParams(token_id="token_id_1"), BookParams(token_id="token_id_2") ]) for book in books: print(f"{book.market}: {len(book.bids)} bids, {len(book.asks)} asks") ``` -------------------------------- ### Manage API Credentials and Authentication Levels Source: https://context7.com/polymarket/py-clob-client/llms.txt Demonstrates how to upgrade from Level 1 (private key) to Level 2 authentication by creating or deriving API keys. It also covers managing read-only keys for monitoring purposes without trading permissions. ```python # Initialize with private key only (Level 1) client = ClobClient( "https://clob.polymarket.com", key="0x_your_private_key", chain_id=137 ) # Create a new API key new_creds = client.create_api_key() print(f"API Key: {new_creds.api_key}") print(f"Secret: {new_creds.api_secret}") print(f"Passphrase: {new_creds.api_passphrase}") # Derive existing API key (if already created) existing_creds = client.derive_api_key() # Create or derive (tries create first, falls back to derive) creds = client.create_or_derive_api_creds() client.set_api_creds(creds) # Now client is Level 2 authenticated # Get all API keys for this address keys = client.get_api_keys() print(keys) # Delete current API key client.delete_api_key() # Create read-only API key (for monitoring without trading) readonly_key = client.create_readonly_api_key() print(f"Readonly key: {readonly_key.api_key}") # Get all readonly keys readonly_keys = client.get_readonly_api_keys() # Delete a readonly key client.delete_readonly_api_key(key="readonly_api_key") # Validate a readonly key (public endpoint) is_valid = client.validate_readonly_api_key( address="0x_wallet_address", key="readonly_api_key" ) ``` -------------------------------- ### Place a Market Order on Polymarket CLOB in Python Source: https://github.com/polymarket/py-clob-client/blob/main/README.md This snippet illustrates how to place a market order to buy a specified amount of a token on the Polymarket CLOB. It requires an authenticated client, a `token_id`, the desired amount, and the trading side (BUY). EOA/MetaMask users must ensure token allowances are properly configured before executing trades. ```python 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 = "" FUNDER = "" 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="", 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) ``` -------------------------------- ### Submit Batch Orders with py-clob-client Source: https://context7.com/polymarket/py-clob-client/llms.txt Demonstrates the efficient submission of multiple orders in a single network request. This is useful for market making or managing multiple positions simultaneously. ```python from py_clob_client.client import ClobClient from py_clob_client.clob_types import ApiCreds, OrderArgs, OrderType, PostOrdersArgs from py_clob_client.order_builder.constants import BUY, SELL client = ClobClient( "https://clob.polymarket.com", key="0x_your_private_key", chain_id=137, creds=ApiCreds( api_key="your_api_key", api_secret="your_api_secret", api_passphrase="your_passphrase" ) ) token_id = "71321045679252212594626385532706912750332728571942532289631379312455583992563" # Create multiple orders order1 = client.create_order(OrderArgs(token_id=token_id, price=0.45, size=10.0, side=BUY)) order2 = client.create_order(OrderArgs(token_id=token_id, price=0.55, size=10.0, side=SELL)) ``` -------------------------------- ### Fetch Market Data with py-clob-client (Python) Source: https://github.com/polymarket/py-clob-client/blob/main/README.md This snippet demonstrates how to retrieve read-only market data using the ClobClient. It initializes the client with just the host URL and then calls `get_simplified_markets()` to fetch market information, printing the first entry. ```python from py_clob_client.client import ClobClient client = ClobClient("https://clob.polymarket.com") markets = client.get_simplified_markets() print(markets["data"][:1]) ``` -------------------------------- ### Initialize Polymarket CLOB Client for EOA Trading in Python Source: https://github.com/polymarket/py-clob-client/blob/main/README.md This code initializes the `ClobClient` for trading using an Externally Owned Account (EOA), specifically configured for email/Magic wallet signatures (`signature_type=1`). It requires a private key, the chain ID (e.g., 137 for Polygon), and optionally a funder address. Users must ensure token allowances are set before attempting to place trades. ```python from py_clob_client.client import ClobClient HOST = "https://clob.polymarket.com" CHAIN_ID = 137 PRIVATE_KEY = "" FUNDER = "" 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()) ``` -------------------------------- ### Retrieve Current Market Prices and Midpoints - Python Source: https://context7.com/polymarket/py-clob-client/llms.txt Fetch current market prices, midpoints, and spreads for tokens. Provides price discovery functionality for informed trading decisions. ```python from py_clob_client.client import ClobClient from py_clob_client.clob_types import BookParams client = ClobClient("https://clob.polymarket.com") token_id = "34097058504275310827233323421517291090691602969494795225921954353603704046623" ``` -------------------------------- ### Implement Session Heartbeat and Dead Man's Switch Source: https://context7.com/polymarket/py-clob-client/llms.txt Demonstrates how to maintain an active session using heartbeats. If a heartbeat is not received within 10 seconds, the system automatically cancels all open orders as a safety measure. ```python from py_clob_client.client import ClobClient from py_clob_client.clob_types import ApiCreds import time import threading client = ClobClient( "https://clob.polymarket.com", key="0x_your_private_key", chain_id=137, creds=ApiCreds( api_key="your_api_key", api_secret="your_api_secret", api_passphrase="your_passphrase" ) ) # Start heartbeat (first call initiates the heartbeat mode) heartbeat_id = "my_session_123" response = client.post_heartbeat(heartbeat_id) print(response) # Keep-alive loop - must send within 10 seconds def heartbeat_loop(): while True: try: client.post_heartbeat(heartbeat_id) time.sleep(5) # Send every 5 seconds to be safe except Exception as e: print(f"Heartbeat failed: {e}") break # Run in background thread thread = threading.Thread(target=heartbeat_loop, daemon=True) thread.start() ``` -------------------------------- ### Monitor Order Scoring for Liquidity Rewards Source: https://context7.com/polymarket/py-clob-client/llms.txt Explains how to verify if specific orders are currently being scored for rewards in the liquidity mining program. Supports both single order checks and batch processing. ```python from py_clob_client.client import ClobClient from py_clob_client.clob_types import ApiCreds, OrderScoringParams, OrdersScoringParams client = ClobClient( "https://clob.polymarket.com", key="0x_your_private_key", chain_id=137, creds=ApiCreds( api_key="your_api_key", api_secret="your_api_secret", api_passphrase="your_passphrase" ) ) # Check if a single order is scoring is_scoring = client.is_order_scoring( OrderScoringParams(orderId="0x_order_id") ) print(f"Order scoring: {is_scoring}") # Check multiple orders at once scoring_results = client.are_orders_scoring( OrdersScoringParams(orderIds=["0x_order_id_1", "0x_order_id_2"]) ) print(scoring_results) ``` -------------------------------- ### Retrieve Available Prediction Markets - Python Source: https://context7.com/polymarket/py-clob-client/llms.txt Fetch available prediction markets from the CLOB with full or simplified details. Markets contain condition IDs and token IDs needed for trading. Supports filtering for specific markets and sampling markets for liquidity providers. ```python from py_clob_client.client import ClobClient client = ClobClient("https://clob.polymarket.com") # Get all markets with full details markets = client.get_markets() print(markets) # {"data": [{"condition_id": "0x...", "tokens": [...], ...}], "next_cursor": "..."} # Get simplified market data (lighter payload) simplified = client.get_simplified_markets() print(simplified["data"][:1]) # Get a specific market by condition ID market = client.get_market("0x_condition_id") print(market) # Get sampling markets for liquidity providers sampling = client.get_sampling_markets() sampling_simplified = client.get_sampling_simplified_markets() ``` -------------------------------- ### Retrieve and Manage Trading Notifications Source: https://context7.com/polymarket/py-clob-client/llms.txt Methods for fetching account-specific trading notifications and dismissing them individually or in bulk to manage the notification queue. ```python from py_clob_client.client import ClobClient from py_clob_client.clob_types import ApiCreds, DropNotificationParams client = ClobClient( "https://clob.polymarket.com", key="0x_your_private_key", chain_id=137, creds=ApiCreds( api_key="your_api_key", api_secret="your_api_secret", api_passphrase="your_passphrase" ) ) # Get all notifications notifications = client.get_notifications() print(notifications) # Drop/dismiss specific notifications client.drop_notifications( DropNotificationParams(ids=["notification_id_1", "notification_id_2"]) ) # Drop all notifications client.drop_notifications() ``` -------------------------------- ### Batch post orders to Polymarket CLOB Source: https://context7.com/polymarket/py-clob-client/llms.txt Submit multiple orders simultaneously to the Polymarket CLOB with different order types and parameters. Supports Good-Till-Canceled (GTC) orders with optional post-only restrictions. Returns a response object containing order confirmation details. ```python response = client.post_orders([ PostOrdersArgs(order=order1, orderType=OrderType.GTC), PostOrdersArgs(order=order2, orderType=OrderType.GTC, postOnly=True) ]) print(response) ``` -------------------------------- ### Check balance and allowance in Polymarket Source: https://context7.com/polymarket/py-clob-client/llms.txt Query USDC collateral balance and conditional token balances for specific outcomes. Supports BalanceAllowanceParams to filter by asset type and token ID. Includes cache update functionality to refresh balance data. ```python from py_clob_client.client import ClobClient from py_clob_client.clob_types import ApiCreds, BalanceAllowanceParams, AssetType client = ClobClient( "https://clob.polymarket.com", key="0x_your_private_key", chain_id=137, creds=ApiCreds( api_key="your_api_key", api_secret="your_api_secret", api_passphrase="your_passphrase" ) ) # Get USDC (collateral) balance and allowance collateral = client.get_balance_allowance( params=BalanceAllowanceParams(asset_type=AssetType.COLLATERAL) ) print(f"USDC Balance: {collateral}") # Get conditional token balance for a specific outcome yes_balance = client.get_balance_allowance( params=BalanceAllowanceParams( asset_type=AssetType.CONDITIONAL, token_id="52114319501245915516055106046884209969926127482827954674443846427813813222426" ) ) print(f"YES token balance: {yes_balance}") no_balance = client.get_balance_allowance( params=BalanceAllowanceParams( asset_type=AssetType.CONDITIONAL, token_id="71321045679252212594626385532706912750332728571942532289631379312455583992563" ) ) print(f"NO token balance: {no_balance}") # Update/refresh balance allowance cache client.update_balance_allowance( params=BalanceAllowanceParams(asset_type=AssetType.COLLATERAL) ) ``` -------------------------------- ### Retrieve Contract Addresses via Python Client Source: https://context7.com/polymarket/py-clob-client/llms.txt Provides methods to retrieve the blockchain addresses for the user's wallet, USDC collateral, conditional tokens, and the exchange contracts (standard and negative risk). ```python from py_clob_client.client import ClobClient client = ClobClient( "https://clob.polymarket.com", key="0x_your_private_key", chain_id=137 ) # Get your wallet address address = client.get_address() print(f"Wallet: {address}") # Get USDC collateral token address collateral = client.get_collateral_address() print(f"USDC: {collateral}") # 0x2791Bca1f2de4661ED88A30C99A7a9449Aa84174 # Get conditional tokens contract address conditional = client.get_conditional_address() print(f"Conditional Tokens: {conditional}") # 0x4D97DCd97eC945f40cF65F87097ACe5EA0476045 # Get exchange address (standard or neg-risk) exchange = client.get_exchange_address(neg_risk=False) print(f"Exchange: {exchange}") # 0x4bFb41d5B3570DeFd03C39a9A4D8dE6Bd8B8982E neg_risk_exchange = client.get_exchange_address(neg_risk=True) print(f"Neg Risk Exchange: {neg_risk_exchange}") # 0xC5d563A36AE78145C45a50134d48A1215220f80a ``` -------------------------------- ### Check Server Health and Retrieve Timestamp - Python Source: https://context7.com/polymarket/py-clob-client/llms.txt Check server health status and retrieve the current server timestamp. These endpoints require no authentication and return simple status indicators and Unix timestamps for synchronization purposes. ```python from py_clob_client.client import ClobClient client = ClobClient("https://clob.polymarket.com") # Health check - returns "OK" if server is up status = client.get_ok() print(status) # "OK" # Get server timestamp server_time = client.get_server_time() print(server_time) # 1699876543 ``` -------------------------------- ### Cancel orders in Polymarket CLOB Source: https://context7.com/polymarket/py-clob-client/llms.txt Cancel individual orders by ID, multiple orders at once, all orders for a specific market, or all open orders globally. Supports granular cancellation with optional asset filtering. Returns confirmation with list of canceled order IDs. ```python from py_clob_client.client import ClobClient from py_clob_client.clob_types import ApiCreds client = ClobClient( "https://clob.polymarket.com", key="0x_your_private_key", chain_id=137, creds=ApiCreds( api_key="your_api_key", api_secret="your_api_secret", api_passphrase="your_passphrase" ) ) # Cancel a single order response = client.cancel(order_id="0x_order_id") print(response) # {"canceled": "0x_order_id"} # Cancel multiple specific orders response = client.cancel_orders(["0x_order_id_1", "0x_order_id_2"]) print(response) # Cancel all orders for a specific market response = client.cancel_market_orders( market="0x_condition_id", asset_id="token_id" # optional ) # Cancel ALL open orders response = client.cancel_all() print(response) # {"canceled": [...]} ``` -------------------------------- ### Cancel RFQ Request using py-clob-client Source: https://context7.com/polymarket/py-clob-client/llms.txt Cancels an existing Request for Quote (RFQ) by its unique request ID. This is used by the requester to stop receiving quotes for a specific market. ```python from py_clob_client.rfq import CancelRfqRequestParams client.rfq.cancel_rfq_request(CancelRfqRequestParams(request_id=request_id)) ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.