### Manage Trading Orders with Polymarket Client Source: https://context7.com/qualiaenjoyer/polymarket-apis/llms.txt Demonstrates how to create, post, and manage limit and market orders. Includes examples for batch operations, order filtering, and order cancellation. ```python order_args = OrderArgs(token_id="15353185604353847122370324954202969073036867278400776447048296624042585335546", price=0.55, size=10.0, side="BUY", fee_rate_bps=0, expiration=0) signed_order = client.create_order(order_args) response = client.post_order(signed_order, order_type=OrderType.GTC) # Batch and Market orders orders = [OrderArgs(token_id=token_id, price=0.45, size=5.0, side="BUY"), OrderArgs(token_id=token_id, price=0.55, size=5.0, side="SELL")] responses = client.create_and_post_orders(orders, [OrderType.GTC, OrderType.GTC]) # Cancellation client.cancel_all() ``` -------------------------------- ### Get Live Volume - Python Source: https://context7.com/qualiaenjoyer/polymarket-apis/llms.txt Fetches the 24-hour trading volume for a specific event. This provides real-time insight into market activity and liquidity. ```python # Get live volume for an event live_vol = client.get_live_volume(event_id=16085) print(f"24h volume: ${live_vol.volume_24h}") ``` -------------------------------- ### Get All and GraphQL Positions - Python Source: https://context7.com/qualiaenjoyer/polymarket-apis/llms.txt Fetches all positions for a user without a size threshold and demonstrates using GraphQL for more efficient retrieval of large datasets. This is useful for comprehensive portfolio analysis. ```python # Get all positions (no size threshold) all_positions = client.get_all_positions(user_address) # Get positions via GraphQL subgraph (more efficient for large datasets) gql_positions = client.get_all_positions_gql(user=user_address, size_threshold=0.0) ``` -------------------------------- ### GET /portfolio/value Source: https://context7.com/qualiaenjoyer/polymarket-apis/llms.txt Calculates the total or market-specific portfolio value for a user. ```APIDOC ## GET /portfolio/value ### Description Get the current monetary value of a user's portfolio. ### Method GET ### Parameters #### Query Parameters - **user** (string) - Required - User wallet address - **condition_ids** (string/array) - Optional - Filter by specific market conditions ### Response #### Success Response (200) - **value** (float) - Total portfolio value in USD ``` -------------------------------- ### Get User Metrics - Python Source: https://context7.com/qualiaenjoyer/polymarket-apis/llms.txt Fetches specific user metrics such as profit or trading volume over a defined window (e.g., 30 days, all time). This provides insights into user performance and activity. ```python # Get user metrics (profit/volume) profit = client.get_user_metric(user=user_address, metric="profit", window="30d") volume = client.get_user_metric(user=user_address, metric="volume", window="all") print(f"30d profit: ${profit.value}, All-time volume: ${volume.value}") ``` -------------------------------- ### GET /positions Source: https://context7.com/qualiaenjoyer/polymarket-apis/llms.txt Retrieves user position data including size, PnL, and market-specific filters. ```APIDOC ## GET /positions ### Description Fetch a user's current positions with optional filtering and sorting. ### Method GET ### Parameters #### Query Parameters - **user** (string) - Required - User wallet address - **size_threshold** (float) - Optional - Minimum position size to return - **sort_by** (string) - Optional - Field to sort by (e.g., CURRENT, CASHPNL) - **condition_id** (string) - Optional - Filter by specific market condition ### Response #### Success Response (200) - **positions** (array) - List of position objects containing title, size, and PnL metrics ``` -------------------------------- ### Get Public Profile - Python Source: https://context7.com/qualiaenjoyer/polymarket-apis/llms.txt Fetches the public profile information for a given user address. It demonstrates how to access and print details like username and bio from the retrieved profile object. ```python # Get public profile profile = client.get_public_profile("0x...") print(f"Username: {profile.username}, Bio: {profile.bio}") ``` -------------------------------- ### Get Portfolio Value - Python Source: https://context7.com/qualiaenjoyer/polymarket-apis/llms.txt Calculates the total portfolio value for a user, or the value for specific markets. It supports retrieving the value for a single market condition ID or multiple market condition IDs. ```python # Get position value total_value = client.get_value(user=user_address) # Total portfolio value market_value = client.get_value(user=user_address, condition_ids="0x...") # Single market multi_value = client.get_value(user=user_address, condition_ids=["0x...", "0x..."]) print(f"Portfolio value: ${total_value.value}") ``` -------------------------------- ### GET /tags Source: https://context7.com/qualiaenjoyer/polymarket-apis/llms.txt Retrieves market tags, event-specific tags, or related tags based on slugs. ```APIDOC ## GET /tags ### Description Retrieve tags associated with markets or events. ### Method GET ### Parameters #### Query Parameters - **event_id** (integer) - Optional - Filter tags by event ID - **market_id** (string) - Optional - Filter tags by market ID - **slug** (string) - Optional - Retrieve related tags by slug ### Response #### Success Response (200) - **tags** (array) - List of tag objects ``` -------------------------------- ### Get PnL Timeseries - Python Source: https://context7.com/qualiaenjoyer/polymarket-apis/llms.txt Retrieves the Profit and Loss (PnL) history for a user over a specified period and frequency. This allows for detailed analysis of trading performance over time. ```python # Get PnL timeseries pnl_history = client.get_pnl( user=user_address, period="1m", # all, 1m, 1w, 1d frequency="1d" # 1h, 3h, 12h, 1d ) for point in pnl_history: print(f"{point.t}: ${point.p}") ``` -------------------------------- ### Get Top Holders for a Market - Python Source: https://context7.com/qualiaenjoyer/polymarket-apis/llms.txt Retrieves a list of top token holders for a specific market, including their addresses and balances. It allows setting a minimum balance and limiting the number of holders returned. The output shows token IDs and holder details. ```python # Get top holders for a market holders = client.get_holders( condition_id="0x...", limit=100, min_balance=1 ) for holder_data in holders: print(f"Token: {holder_data.token_id}") for h in holder_data.holders[:5]: print(f" {h.address}: {h.balance} shares") ``` -------------------------------- ### Get Trading Statistics - Python Source: https://context7.com/qualiaenjoyer/polymarket-apis/llms.txt Fetches the total number of unique markets a user has traded on. This provides a simple metric for user trading activity. ```python # Get trading stats markets_traded = client.get_total_markets_traded(user_address) print(f"Markets traded: {markets_traded}") ``` -------------------------------- ### Get Activity Log - Python Source: https://context7.com/qualiaenjoyer/polymarket-apis/llms.txt Fetches a user's activity log, including trades, splits, merges, redeems, and rewards. It supports filtering by activity type, date range, and sorting. The output includes details like activity type, tokens, and cash involved. ```python # Get activity (trades, splits, merges, redeems, rewards, etc.) from datetime import datetime, timedelta, UTC activity = client.get_activity( user=user_address, type=["trade", "split", "merge"], # or single: type="trade" start=datetime.now(UTC) - timedelta(days=30), end=datetime.now(UTC), sort_by="TIMESTAMP", sort_direction="DESC" ) for act in activity: print(f"{act.type}: {act.tokens} tokens, ${act.cash}") ``` -------------------------------- ### Get Trades with Filters - Python Source: https://context7.com/qualiaenjoyer/polymarket-apis/llms.txt Retrieves trades executed by a user, with options to filter by taker-only status, side (BUY/SELL), and cash amount. It iterates through the trades and prints details such as side, size, price, and cash amount. ```python # Get trades with filters trades = client.get_trades( user=user_address, limit=100, taker_only=True, side="BUY", filter_type="CASH", filter_amount=100 # Minimum $100 trades ) for trade in trades: print(f"{trade.side} {trade.size}@{trade.price} - ${trade.cash_amount}") ``` -------------------------------- ### Get Open Interest - Python Source: https://context7.com/qualiaenjoyer/polymarket-apis/llms.txt Retrieves the open interest value for specified markets. This metric indicates the total number of outstanding derivative contracts that have not been settled. ```python # Get open interest for markets oi = client.get_open_interest(condition_ids=["0x...", "0x..."]) for market_oi in oi: print(f"{market_oi.market}: ${market_oi.value}") ``` -------------------------------- ### Get Sports Data - Python Source: https://context7.com/qualiaenjoyer/polymarket-apis/llms.txt Fetches sports-related data, including teams for a specific league with a limit, all teams for a league, and general sports metadata. This is useful for applications requiring sports statistics or information. ```python # Get sports data teams = client.get_teams(league="nba", limit=50) all_nba_teams = client.get_all_teams(league="nba") sports_metadata = client.get_sports_metadata() ``` -------------------------------- ### Get Tags and Series Data - Python Source: https://context7.com/qualiaenjoyer/polymarket-apis/llms.txt Retrieves various tag-related information (all, single, related by slug) and series data (recurring events, all, single by ID). It demonstrates fetching data based on different parameters and printing results. ```python all_tags = client.get_all_tags() tag = client.get_tag("123") related_tags = client.get_related_tags_by_slug("crypto") print(f"Related to crypto: {[t.label for t in related_tags]}") # Get tags for event or market event_tags = client.get_event_tags(event_id=16085) market_tags = client.get_market_tags(market_id="516724") # Get series (recurring events) series = client.get_series(recurrence="daily", closed=False) all_series = client.get_all_series() single_series = client.get_series_by_id("123") ``` -------------------------------- ### Get Positions with Filters - Python Source: https://context7.com/qualiaenjoyer/polymarket-apis/llms.txt Retrieves a user's positions with various filtering and sorting options, such as size threshold, redeemable status, mergeable status, sorting criteria, and direction. It iterates through the results and prints position details. ```python from polymarket_apis import PolymarketDataClient client = PolymarketDataClient() user_address = "0x..." # Get positions with filters positions = client.get_positions( user=user_address, size_threshold=1.0, # Minimum position size redeemable=False, mergeable=False, sort_by="CURRENT", # TOKENS, CURRENT, INITIAL, CASHPNL, PERCENTPNL, etc. sort_direction="DESC", limit=100, offset=0 ) for pos in positions: print(f"{pos.title}: {pos.size} shares @ ${pos.current_value}") print(f" PnL: ${pos.cash_pnl} ({pos.percent_pnl}%)") ``` -------------------------------- ### Get Polymarket Leaderboard Data Source: https://context7.com/qualiaenjoyer/polymarket-apis/llms.txt Retrieve user ranks, top traders, and market rankings from the Polymarket leaderboard. Supports various metrics and time windows for analysis. Also includes functionality to download accounting snapshots as CSV files. ```python rank = client.get_leaderboard_user_rank(user=user_address, metric="profit", window="30d") print(f"Rank: #{rank.rank}") top_traders = client.get_leaderboard_top_users(metric="profit", window="7d", limit=10) for i, trader in enumerate(top_traders): print(f"#{i+1}: {trader.address} - ${trader.value}") rankings = client.get_leaderboard_rankings( category="POLITICS", time_period="WEEK", order_by="PNL", limit=25 ) csvs = client.get_accounting_snapshot_csvs(user_address) print(csvs.positions_csv) print(csvs.equity_csv) ``` -------------------------------- ### Subscribe to Real-Time Market and User Data via WebSockets Source: https://context7.com/qualiaenjoyer/polymarket-apis/llms.txt Demonstrates how to initialize the PolymarketWebsocketsClient to listen for market updates, user-specific events, live activity, and sports scores. It uses event parsing functions to handle incoming data streams for specific token IDs or subscription channels. ```python from polymarket_apis import PolymarketWebsocketsClient, ApiCreds from polymarket_apis.clients import parse_market_event, parse_user_event, parse_live_data_event client = PolymarketWebsocketsClient() def handle_market_event(text): event = parse_market_event(text) if event is None: return if hasattr(event, 'bids'): print(f"Order book update: {len(event.bids)} bids") elif hasattr(event, 'price'): print(f"Price change: {event.price}") token_ids = ["15353185604353847122370324954202969073036867278400776447048296624042585335546"] client.market_socket(token_ids=token_ids, process_event=handle_market_event) creds = ApiCreds(apiKey="...", secret="...", passphrase="...") client.user_socket(creds=creds, process_event=lambda text: print(parse_user_event(text))) subscriptions = [{"channel": "trades", "market_slug": "will-bitcoin-hit-100k"}] client.live_data_socket(subscriptions=subscriptions, process_event=lambda text: print(parse_live_data_event(text))) ``` -------------------------------- ### GET /trades Source: https://context7.com/qualiaenjoyer/polymarket-apis/llms.txt Retrieves trade history for a specific user with various filtering options. ```APIDOC ## GET /trades ### Description Fetch historical trade data for a user. ### Method GET ### Parameters #### Query Parameters - **user** (string) - Required - User wallet address - **side** (string) - Optional - Filter by BUY or SELL - **limit** (integer) - Optional - Number of records to return ### Response #### Success Response (200) - **trades** (array) - List of trade objects ``` -------------------------------- ### Access Market Data with PolymarketReadOnlyClobClient Source: https://context7.com/qualiaenjoyer/polymarket-apis/llms.txt Demonstrates how to initialize the read-only CLOB client to retrieve order books, price history, market details, and crypto outcomes. This client does not require authentication and is suitable for public market data analysis. ```python from polymarket_apis import PolymarketReadOnlyClobClient client = PolymarketReadOnlyClobClient() token_id = "15353185604353847122370324954202969073036867278400776447048296624042585335546" # Get order book and market stats order_book = client.get_order_book(token_id) print(f"Bids: {order_book.bids[:3]}") # Get price history history = client.get_recent_history(token_id, interval="1d", fidelity=5) # Get market details by condition_id condition_id = "0x8e9b6942b4dac3117dadfacac2edb390b6d62d59c14152774bb5fcd983fc134e" market = client.get_market(condition_id) print(f"Question: {market.question}") ``` -------------------------------- ### Perform Authenticated Trading with PolymarketClobClient Source: https://context7.com/qualiaenjoyer/polymarket-apis/llms.txt Shows how to initialize the authenticated CLOB client using a private key or API credentials. This client allows for account-specific operations such as checking USDC and token balances. ```python from polymarket_apis import PolymarketClobClient, ApiCreds private_key = "0x..." address = "0x..." # Initialize with signature type for wallet support client = PolymarketClobClient( private_key=private_key, address=address, signature_type=1, chain_id=137 ) # Check balances usdc_balance = client.get_usdc_balance() token_balance = client.get_token_balance("token_id_here") print(f"USDC: ${usdc_balance}, Token: {token_balance} shares") ``` -------------------------------- ### Get Closed Positions - Python Source: https://context7.com/qualiaenjoyer/polymarket-apis/llms.txt Retrieves a list of closed positions for a user, displaying the title and final PnL for each. This is useful for reviewing past performance and closed trades. ```python # Get closed positions closed = client.get_closed_positions(user=user_address) for pos in closed: print(f"{pos.title}: Final PnL ${pos.cash_pnl}") ``` -------------------------------- ### Retrieve Liquidity Rewards and Trade History Source: https://context7.com/qualiaenjoyer/polymarket-apis/llms.txt Shows how to track order scoring for liquidity rewards, fetch market reward information, and retrieve historical trade data. ```python is_scoring = client.is_order_scoring(order_id="0x...") rewards = client.get_market_rewards(condition_id) trades = client.get_trades(condition_id=condition_id, after=datetime.now(UTC) - timedelta(days=7)) ``` -------------------------------- ### Filter Positions by Market or Event - Python Source: https://context7.com/qualiaenjoyer/polymarket-apis/llms.txt Demonstrates how to filter a user's positions by a specific market condition ID or event ID. This allows for focused analysis of positions related to particular markets or events. ```python # Filter positions by market market_positions = client.get_positions( user=user_address, condition_id="0x..." ) # Filter positions by event event_positions = client.get_positions( user=user_address, event_id=16085 ) ``` -------------------------------- ### PolymarketClobClient - Miscellaneous Operations Source: https://github.com/qualiaenjoyer/polymarket-apis/blob/main/README.md Provides access to account balances and token balances. ```APIDOC ## GET /balance/usdc ### Description Retrieves the USDC balance for the authenticated user. ### Method GET ### Endpoint `/balance/usdc` ### Response #### Success Response (200) - **usdcBalance** (string) - The USDC balance. #### Response Example ```json { "usdcBalance": "1000.00" } ``` ``` ```APIDOC ## GET /balance/token ### Description Retrieves the token balance for a specific `token_id` for the authenticated user. ### Method GET ### Endpoint `/balance/token` ### Parameters #### Query Parameters - **token_id** (string) - Required - The ID of the token. ### Response #### Success Response (200) - **tokenBalance** (string) - The token balance. #### Response Example ```json { "tokenBalance": "500.00" } ``` ``` -------------------------------- ### Execute GraphQL Queries against Polymarket Subgraphs Source: https://context7.com/qualiaenjoyer/polymarket-apis/llms.txt Shows how to use both synchronous and asynchronous GraphQL clients to fetch data from Goldsky-hosted subgraphs. This includes querying user balances, market open interest, and PnL snapshots. ```python from polymarket_apis import PolymarketGraphQLClient, AsyncPolymarketGraphQLClient import asyncio # Synchronous query client = PolymarketGraphQLClient(endpoint_name="positions_subgraph") query = "query { userBalances(where: { user: \"0x...\" }) { balance } }" result = client.query(query) # Asynchronous query async def fetch_pnl(): async_client = AsyncPolymarketGraphQLClient(endpoint_name="pnl_subgraph") query = "query { pnlSnapshots(where: { user: \"0x...\" }) { totalPnl } }" return await async_client.query(query) data = asyncio.run(fetch_pnl()) ``` -------------------------------- ### Get Comments - Python Source: https://context7.com/qualiaenjoyer/polymarket-apis/llms.txt Retrieves comments associated with a specific event or by a particular user. It allows filtering by parent entity type and ID, and sorting options for comments. User comments can be fetched using their address. ```python # Get comments for an event comments = client.get_comments( parent_entity_type="Event", parent_entity_id=16085, limit=100, order="createdAt", ascending=False ) # Get comments by user user_comments = client.get_comments_by_user_address("0x...") ``` -------------------------------- ### PolymarketGammaClient - Miscellaneous Operations Source: https://github.com/qualiaenjoyer/polymarket-apis/blob/main/README.md Provides access to public user profiles. ```APIDOC ## GET /profile/{user_address} ### Description Retrieves the public profile for a user by their address. ### Method GET ### Endpoint `/profile/{user_address}` ### Parameters #### Path Parameters - **user_address** (string) - Required - The user's address. ### Response #### Success Response (200) - **profile** (object) - The user's public profile information. #### Response Example ```json { "profile": { "address": "0x123...", "ensName": "user.eth" } } ``` ``` -------------------------------- ### PolymarketGammaClient - Market Operations Source: https://github.com/qualiaenjoyer/polymarket-apis/blob/main/README.md Provides access to market data, including individual markets, lists of markets with filtering and pagination, and market tags. ```APIDOC ## GET /markets/{market_id} ### Description Retrieves a `GammaMarket` by its `market_id`. ### Method GET ### Endpoint `/markets/{market_id}` ### Parameters #### Path Parameters - **market_id** (string) - Required - The ID of the market. ### Response #### Success Response (200) - **gammaMarket** (object) - The `GammaMarket` object. #### Response Example ```json { "gammaMarket": { "id": "market_id_1", "slug": "market_slug_1" } } ``` ``` ```APIDOC ## GET /markets/slug/{slug} ### Description Retrieves a `GammaMarket` by its `slug`. ### Method GET ### Endpoint `/markets/slug/{slug}` ### Parameters #### Path Parameters - **slug** (string) - Required - The slug of the market. ### Response #### Success Response (200) - **gammaMarket** (object) - The `GammaMarket` object. #### Response Example ```json { "gammaMarket": { "id": "market_id_1", "slug": "market_slug_1" } } ``` ``` ```APIDOC ## GET /markets ### Description Retrieves `GammaMarkets` with pagination and filtering by various criteria. ### Method GET ### Endpoint `/markets` ### Parameters #### Query Parameters - **limit** (integer) - Optional - Number of results per page. - **offset** (integer) - Optional - Offset for pagination. - **slug** (string) - Optional - Filter by slug. - **market_id** (string) - Optional - Filter by market ID. - **token_id** (string) - Optional - Filter by token ID. - **condition_id** (string) - Optional - Filter by condition ID. - **tag_id** (string) - Optional - Filter by tag ID. - **status** (string) - Optional - Filter by status (active, closed, archived). - **liquidity_window** (string) - Optional - Filter by liquidity window. - **volume_window** (string) - Optional - Filter by volume window. - **start_date_window** (string) - Optional - Filter by start date window. - **end_date_window** (string) - Optional - Filter by end date window. - **order_by** (string) - Optional - Field to order by. ### Response #### Success Response (200) - **gammaMarkets** (array) - A list of `GammaMarket` objects. #### Response Example ```json { "gammaMarkets": [ { "id": "market_id_1", "slug": "market_slug_1" } ] } ``` ``` ```APIDOC ## GET /markets/{market_id}/tags ### Description Retrieves tags for a market by `market_id`. ### Method GET ### Endpoint `/markets/{market_id}/tags` ### Parameters #### Path Parameters - **market_id** (string) - Required - The ID of the market. ### Response #### Success Response (200) - **tags** (array) - A list of tags associated with the market. #### Response Example ```json { "tags": [ { "id": "tag_id_1", "name": "Tag Name" } ] } ``` ``` -------------------------------- ### PolymarketDataClient - Activity Operations Source: https://github.com/qualiaenjoyer/polymarket-apis/blob/main/README.md Provides access to user activity data, including retrieval with pagination and filtering. ```APIDOC ## GET /activity ### Description Retrieves user activity with pagination, filtered by type, `condition_id`, time window, side, and sort order. ### Method GET ### Endpoint `/activity` ### Parameters #### Query Parameters - **user_address** (string) - Required - The address of the user. - **limit** (integer) - Optional - Number of results per page. - **offset** (integer) - Optional - Offset for pagination. - **type** (string) - Optional - Filter by activity type (e.g., 'trade', 'liquidity'). - **condition_id** (string) - Optional - Filter by condition ID. - **start_time** (integer) - Optional - Start of the time window. - **end_time** (integer) - Optional - End of the time window. - **side** (string) - Optional - Filter by side ('buy' or 'sell'). - **sort_order** (string) - Optional - Sort order ('asc' or 'desc'). ### Response #### Success Response (200) - **activity** (array) - A list of activity objects. #### Response Example ```json { "activity": [ { "type": "trade", "condition_id": "condition_123", "timestamp": 1678893600, "side": "buy" } ] } ``` ``` -------------------------------- ### PolymarketGaslessWeb3Client - Relayed Blockchain Operations Source: https://context7.com/qualiaenjoyer/polymarket-apis/llms.txt Perform blockchain operations without requiring POL for gas fees using the PolymarketGaslessWeb3Client. This client supports only proxy (Magic/Email) and Safe wallets. Initialization requires a private key and signature type, with optional builder credentials for higher rate limits. ```python from polymarket_apis import PolymarketGaslessWeb3Client, ApiCreds client = PolymarketGaslessWeb3Client( private_key="0x...", signature_type=1, # Proxy wallet chain_id=137 ) builder_creds = ApiCreds(apiKey="...", secret="...", passphrase="") client = PolymarketGaslessWeb3Client( private_key="0x...", signature_type=1, builder_creds=builder_creds ) usdc = client.get_usdc_balance() tokens = client.get_token_balance(token_id="...") receipt = client.split_position( condition_id="0x...", amount=10.0, neg_risk=True ) print(f"Gasless split: {receipt.transaction_hash}") receipt = client.merge_position( condition_id="0x...", amount=10.0, neg_risk=True ) receipt = client.redeem_position( condition_id="0x...", amounts=[10.0, 0.0], neg_risk=True ) receipt = client.convert_positions( question_ids=["0x...01", "0x...02"], amount=5.0 ) ``` -------------------------------- ### PolymarketGammaClient - Event Operations Source: https://github.com/qualiaenjoyer/polymarket-apis/blob/main/README.md Provides access to event data, including individual events, lists of events with filtering and pagination, event search, and event summaries. ```APIDOC ## GET /events/{event_id} ### Description Retrieves an `Event` by its `event_id`. ### Method GET ### Endpoint `/events/{event_id}` ### Parameters #### Path Parameters - **event_id** (string) - Required - The ID of the event. ### Response #### Success Response (200) - **event** (object) - The `Event` object. #### Response Example ```json { "event": { "id": "event_id_1", "slug": "event_slug_1" } } ``` ``` ```APIDOC ## GET /events/slug/{slug} ### Description Retrieves an `Event` by its `slug`. ### Method GET ### Endpoint `/events/slug/{slug}` ### Parameters #### Path Parameters - **slug** (string) - Required - The slug of the event. ### Response #### Success Response (200) - **event** (object) - The `Event` object. #### Response Example ```json { "event": { "id": "event_id_1", "slug": "event_slug_1" } } ``` ``` ```APIDOC ## GET /events ### Description Retrieves `Events` with pagination and filtering by various criteria. ### Method GET ### Endpoint `/events` ### Parameters #### Query Parameters - **limit** (integer) - Optional - Number of results per page. - **offset** (integer) - Optional - Offset for pagination. - **slug** (string) - Optional - Filter by slug. - **event_id** (string) - Optional - Filter by event ID. - **tag_id** (string) - Optional - Filter by tag ID. - **status** (string) - Optional - Filter by status (active, closed, archived). - **liquidity_window** (string) - Optional - Filter by liquidity window. - **volume_window** (string) - Optional - Filter by volume window. - **start_date_window** (string) - Optional - Filter by start date window. - **end_date_window** (string) - Optional - Filter by end date window. - **order_by** (string) - Optional - Field to order by. ### Response #### Success Response (200) - **events** (array) - A list of `Event` objects. #### Response Example ```json { "events": [ { "id": "event_id_1", "slug": "event_slug_1" } ] } ``` ``` ```APIDOC ## GET /events/search ### Description Searches for `Events`, `Tags`, and `Profiles` by text query, tags, status, recurrence, and multiple sort modes. ### Method GET ### Endpoint `/events/search` ### Parameters #### Query Parameters - **query** (string) - Required - The search query. - **tags** (string) - Optional - Filter by tags. - **status** (string) - Optional - Filter by status. - **recurrence** (string) - Optional - Filter by recurrence. - **sort_mode** (string) - Optional - The sort mode. ### Response #### Success Response (200) - **searchResults** (object) - An object containing search results for events, tags, and profiles. #### Response Example ```json { "searchResults": { "events": [], "tags": [], "profiles": [] } } ``` ``` ```APIDOC ## GET /events/slug/{slug}/summary ### Description Grok an event summary by event `slug`. ### Method GET ### Endpoint `/events/slug/{slug}/summary` ### Parameters #### Path Parameters - **slug** (string) - Required - The slug of the event. ### Response #### Success Response (200) - **eventSummary** (string) - A summary of the event. #### Response Example ```json { "eventSummary": "This is a summary of the event." } ``` ``` ```APIDOC ## GET /events/{event_id}/tags ### Description Retrieves tags for an event by `event_id`. ### Method GET ### Endpoint `/events/{event_id}/tags` ### Parameters #### Path Parameters - **event_id** (string) - Required - The ID of the event. ### Response #### Success Response (200) - **tags** (array) - A list of tags associated with the event. #### Response Example ```json { "tags": [ { "id": "tag_id_1", "name": "Tag Name" } ] } ``` ``` -------------------------------- ### PolymarketClobClient - Order Operations Source: https://github.com/qualiaenjoyer/polymarket-apis/blob/main/README.md Manages orders, including creation, cancellation, retrieval, and maintaining order liveness. ```APIDOC ## POST /orders ### Description Creates and posts a limit or market order. ### Method POST ### Endpoint `/orders` ### Parameters #### Request Body - **orderType** (string) - Required - Type of order ('limit' or 'market'). - **token_id** (string) - Required - The ID of the token. - **side** (string) - Required - The side of the order ('buy' or 'sell'). - **amount** (string) - Required - The amount of the token. - **price** (string) - Optional - The price for limit orders. ### Response #### Success Response (200) - **orderId** (string) - The ID of the created order. #### Response Example ```json { "orderId": "order_123" } ``` ``` ```APIDOC ## DELETE /orders ### Description Cancels one or more orders by their `order_id`. ### Method DELETE ### Endpoint `/orders` ### Parameters #### Query Parameters - **order_id** (string or array) - Required - The ID(s) of the order(s) to cancel. ### Response #### Success Response (200) - **status** (string) - Confirmation of cancellation. #### Response Example ```json { "status": "Orders cancelled successfully." } ``` ``` ```APIDOC ## GET /orders/active ### Description Retrieves all active orders. ### Method GET ### Endpoint `/orders/active` ### Response #### Success Response (200) - **activeOrders** (array) - A list of active orders. #### Response Example ```json { "activeOrders": [ { "orderId": "order_123", "tokenId": "token_abc", "side": "buy", "amount": "100", "price": "0.90" } ] } ``` ``` ```APIDOC ## POST /orders/heartbeat ### Description Sends a heartbeat to keep active orders alive. ### Method POST ### Endpoint `/orders/heartbeat` ### Response #### Success Response (200) - **status** (string) - Confirmation of heartbeat. #### Response Example ```json { "status": "Heartbeat sent successfully." } ``` ``` -------------------------------- ### Access Market Metadata via Gamma API Source: https://context7.com/qualiaenjoyer/polymarket-apis/llms.txt Utilizes the PolymarketGammaClient to search for events, retrieve market details by ID or slug, and filter markets based on liquidity and volume metrics. ```python client = PolymarketGammaClient() results = client.search(query="bitcoin", status="active", sort="volume_24hr") event = client.get_event_by_slug("how-many-fed-rate-cuts-in-2025") market = client.get_market("516724") ``` -------------------------------- ### AI-powered Summaries and Explanations - Python Source: https://context7.com/qualiaenjoyer/polymarket-apis/llms.txt Utilizes AI capabilities to generate summaries for events and explanations for election candidates. The `grok_event_summary` function prints streaming output, while `grok_election_market_explanation` provides detailed context. ```python # AI-powered summaries (prints to stdout with streaming) client.grok_event_summary("how-many-fed-rate-cuts-in-2025") # AI election candidate info client.grok_election_market_explanation("Donald Trump", "2024 US Presidential Election") ``` -------------------------------- ### PolymarketGammaClient - Tag Operations Source: https://github.com/qualiaenjoyer/polymarket-apis/blob/main/README.md Provides access to tag data, including lists of tags with pagination and filtering, individual tags, and tag relations. ```APIDOC ## GET /tags ### Description Retrieves `Tags` with pagination, ordered by any tag field. ### Method GET ### Endpoint `/tags` ### Parameters #### Query Parameters - **limit** (integer) - Optional - Number of results per page. - **offset** (integer) - Optional - Offset for pagination. - **order_by** (string) - Optional - Field to order by. ### Response #### Success Response (200) - **tags** (array) - A list of `Tag` objects. #### Response Example ```json { "tags": [ { "id": "tag_id_1", "name": "Tag Name" } ] } ``` ``` ```APIDOC ## GET /tags/{tag_id} ### Description Retrieves a `Tag` by its `tag_id`. ### Method GET ### Endpoint `/tags/{tag_id}` ### Parameters #### Path Parameters - **tag_id** (string) - Required - The ID of the tag. ### Response #### Success Response (200) - **tag** (object) - The `Tag` object. #### Response Example ```json { "tag": { "id": "tag_id_1", "name": "Tag Name" } } ``` ``` ```APIDOC ## GET /tags/{tag_id}/relations ### Description Retrieves tag relations by `tag_id` or `slug`. ### Method GET ### Endpoint `/tags/{tag_id}/relations` ### Parameters #### Path Parameters - **tag_id** (string) - Required - The ID of the tag. ### Response #### Success Response (200) - **tagRelations** (array) - A list of related tags. #### Response Example ```json { "tagRelations": [ { "id": "related_tag_id_1", "name": "Related Tag Name" } ] } ``` ``` ```APIDOC ## GET /tags/relations/{tag_id_or_slug} ### Description Retrieves tags related to a tag by `tag_id` or `slug`. ### Method GET ### Endpoint `/tags/relations/{tag_id_or_slug}` ### Parameters #### Path Parameters - **tag_id_or_slug** (string) - Required - The ID or slug of the tag. ### Response #### Success Response (200) - **relatedTags** (array) - A list of related tags. #### Response Example ```json { "relatedTags": [ { "id": "related_tag_id_1", "name": "Related Tag Name" } ] } ``` ``` -------------------------------- ### PolymarketWeb3Client - Standard Blockchain Operations Source: https://context7.com/qualiaenjoyer/polymarket-apis/llms.txt Interact directly with the blockchain for token transfers, splits, merges, redemptions, and approvals using the PolymarketWeb3Client. This client requires POL for gas fees. Initialization involves specifying private key, signature type, chain ID, and RPC URL. ```python from polymarket_apis import PolymarketWeb3Client client = PolymarketWeb3Client( private_key="0x...", signature_type=1, # Magic/Email wallet chain_id=137, # Polygon mainnet (or 80002 for Amoy testnet) rpc_url="https://polygon-rpc.com" ) print(f"Base address: {client.get_base_address()}") print(f"Proxy address: {client.address}") pol_balance = client.get_pol_balance() usdc_balance = client.get_usdc_balance() token_balance = client.get_token_balance(token_id="...") print(f"POL: {pol_balance}, USDC: ${usdc_balance}, Tokens: {token_balance}") receipts = client.set_all_approvals() for receipt in receipts: print(f"Approval tx: {receipt.transaction_hash}, Gas: {receipt.gas_used}") condition_id = "0x..." receipt = client.split_position( condition_id=condition_id, amount=10.0, # USDC amount neg_risk=True # True for multi-outcome events ) print(f"Split tx: {receipt.transaction_hash}") receipt = client.merge_position( condition_id=condition_id, amount=10.0, # Number of complete sets (1 Yes + 1 No) neg_risk=True ) receipt = client.redeem_position( condition_id=condition_id, amounts=[10.0, 0.0], # [Yes shares, No shares] neg_risk=True ) question_ids = [ "0x...01", # Question ID for market 1 "0x...02" # Question ID for market 2 ] receipt = client.convert_positions( question_ids=question_ids, amount=5.0 # Shares to convert ) receipt = client.transfer_usdc( recipient="0x...", amount=100.0 ) receipt = client.transfer_token( token_id="...", recipient="0x...", amount=10.0 ) eoa_client = PolymarketWeb3Client(private_key="0x...", signature_type=0) safe_address = eoa_client.get_safe_proxy_address() print(f"Safe address will be: {safe_address}") receipt = eoa_client.deploy_safe() print(f"Safe deployed: {receipt.transaction_hash}") complement = client.get_token_complement(token_id="...") print(f"Complement token: {complement}") ``` -------------------------------- ### PolymarketReadOnlyClobClient - Miscellaneous Operations Source: https://github.com/qualiaenjoyer/polymarket-apis/blob/main/README.md Provides access to miscellaneous read-only data, including crypto outcomes, price history, and Clob markets. ```APIDOC ## GET /outcomes ### Description Retrieves crypto outcomes for up/down markets by `slug`. ### Method GET ### Endpoint `/outcomes` ### Parameters #### Query Parameters - **slug** (string) - Required - The slug of the market. ### Response #### Success Response (200) - **outcomes** (array) - A list of crypto outcomes. #### Response Example ```json { "outcomes": [ { "name": "Yes", "id": "outcome_yes_id" }, { "name": "No", "id": "outcome_no_id" } ] } ``` ``` ```APIDOC ## GET /price_history ### Description Retrieves recent price history for a `token_id` within a specified time frame (last 1h, 6h, 1d, 1w, 1m) or a custom start/end interval. ### Method GET ### Endpoint `/price_history` ### Parameters #### Query Parameters - **token_id** (string) - Required - The ID of the token. - **timeframe** (string) - Optional - The timeframe for the price history (e.g., '1h', '6h', '1d', '1w', '1m'). - **start_time** (integer) - Optional - The start timestamp for custom interval. - **end_time** (integer) - Optional - The end timestamp for custom interval. ### Response #### Success Response (200) - **priceHistory** (array) - An array of price data points, each with a timestamp and price. #### Response Example ```json { "priceHistory": [ { "timestamp": 1678886400, "price": "0.95" }, { "timestamp": 1678890000, "price": "0.96" } ] } ``` ``` ```APIDOC ## GET /clob_markets ### Description Retrieves all `ClobMarket` objects. ### Method GET ### Endpoint `/clob_markets` ### Response #### Success Response (200) - **clobMarkets** (array) - A list of `ClobMarket` objects. #### Response Example ```json { "clobMarkets": [ { "id": "market_id_1", "slug": "market_slug_1" }, { "id": "market_id_2", "slug": "market_slug_2" } ] } ``` ``` ```APIDOC ## GET /clob_markets/{condition_id} ### Description Retrieves a specific `ClobMarket` by its `condition_id`. ### Method GET ### Endpoint `/clob_markets/{condition_id}` ### Parameters #### Path Parameters - **condition_id** (string) - Required - The ID of the market condition. ### Response #### Success Response (200) - **clobMarket** (object) - The `ClobMarket` object. #### Response Example ```json { "clobMarket": { "id": "market_id_1", "slug": "market_slug_1", "condition_id": "condition_id_1" } } ``` ```