### Install Polymarket PHP SDK using Composer Source: https://github.com/polymarket-php/polymarket/blob/main/README.md Installs the Polymarket PHP SDK package using Composer. This is the primary method for adding the SDK to your PHP project. ```bash composer require polymarket-php/polymarket ``` -------------------------------- ### Search Polymarket Data using Gamma API (PHP) Source: https://context7.com/polymarket-php/polymarket/llms.txt Shows how to perform a global search across markets, events, and profiles using the Polymarket PHP SDK's Gamma API. The example demonstrates searching for markets containing a specific keyword and processing the results. ```php gamma()->search('election', [ 'limit' => 25, ]); // Results include markets, events, and profiles if (isset($results['markets'])) { foreach ($results['markets'] as $market) { echo "Found market: {$market['question']}\n"; } } if (isset($results['events'])) { foreach ($results['events'] as $event) { echo "Found event: {$event['title']}\n"; } } ``` -------------------------------- ### Complete Example: Polymarket PHP SDK Bridge Deposit Source: https://github.com/polymarket-php/polymarket/blob/main/README.md Demonstrates how to use the Polymarket PHP SDK to check supported assets and generate deposit addresses for various blockchains. It initializes the client, retrieves supported assets, and then generates deposit addresses for specified amounts and destination addresses. ```php use Danielgnh\PolymarketPhp\Client; $client = new Client(); // 1. Check supported assets $assets = $client->bridge()->deposits()->supportedAssets(); echo "Supported Chains:\n"; foreach ($assets['chains'] as $chain) { echo " - {$chain['name']}\n"; } // 2. Generate deposit addresses $addresses = $client->bridge()->deposits()->generate([ 'destination_address' => '0xYourPolygonAddress', 'amount_usd' => '100' ]); // 3. Display addresses to user echo "\nDeposit Addresses:\n"; echo "Send USDC/ETH from Ethereum/Arbitrum to: {$addresses['evm']}\n"; echo "Send USDC/SOL from Solana to: {$addresses['solana']}\n"; echo "Send BTC from Bitcoin to: {$addresses['bitcoin']}\n"; ``` -------------------------------- ### Polymarket PHP SDK Enum Usage Example Source: https://github.com/polymarket-php/polymarket/blob/main/README.md Provides a practical example of using Polymarket PHP SDK enums (OrderSide and OrderType) when creating an order via the CLOB (Central Limit Order Book) client. This demonstrates how to integrate enums into API calls for better type safety. ```php use Danielgnh\PolymarketPhp\Enums\{OrderSide, OrderType}; $order = $client->clob()->orders()->create([ 'market_id' => 'market-id', 'side' => OrderSide::BUY->value, 'type' => OrderType::GTC->value, 'price' => '0.52', 'amount' => '10.00', ]); ``` -------------------------------- ### Comprehensive Error Handling with Polymarket Exceptions (PHP) Source: https://context7.com/polymarket-php/polymarket/llms.txt Implement robust error handling for Polymarket API interactions using a comprehensive exception hierarchy. This example demonstrates catching specific exceptions like AuthenticationException, ValidationException, RateLimitException, and others, as well as a general PolymarketException. ```php gamma()->markets()->get('invalid-id'); } catch (AuthenticationException $e) { // 401/403 authentication errors echo "Auth failed: " . $e->getMessage(); } catch (ClobAuthenticationException $e) { // CLOB-specific authentication errors (missing private key, etc.) echo "CLOB auth failed: " . $e->getMessage(); } catch (ValidationException $e) { // 400/422 validation errors echo "Validation failed: " . $e->getMessage(); } catch (RateLimitException $e) { // 429 rate limit exceeded echo "Rate limited: " . $e->getMessage(); // Implement exponential backoff } catch (NotFoundException $e) { // 404 resource not found echo "Not found: " . $e->getMessage(); } catch (SigningException $e) { // EIP-712 signature errors echo "Signing failed: " . $e->getMessage(); } catch (JsonParseException $e) { // JSON parsing errors echo "JSON parse failed: " . $e->getMessage(); } catch (ApiException $e) { // Other API errors (5xx) echo "API error: " . $e->getMessage(); $statusCode = $e->getCode(); } catch (PolymarketException $e) { // Catch-all for any SDK exception echo "Error: " . $e->getMessage(); } ``` -------------------------------- ### Access Polymarket Series and Comments using PHP Source: https://context7.com/polymarket-php/polymarket/llms.txt This code example shows how to access series information and market/event comments using the Polymarket PHP SDK. It includes operations for listing and retrieving series, as well as listing and retrieving comments, including comments by a user's wallet address. ```php gamma()->series()->list(); $series = $client->gamma()->series()->get('series-id'); // Comments operations $comments = $client->gamma()->comments()->list(); $comment = $client->gamma()->comments()->get('comment-id'); // Get comments by user wallet address $userComments = $client->gamma()->comments()->byUserAddress('0xUserWalletAddress'); foreach ($userComments as $comment) { echo "Comment: {$comment['content']}\n"; } ``` -------------------------------- ### CLOB API - Spreads Source: https://context7.com/polymarket-php/polymarket/llms.txt Get bid-ask spread information for markets. ```APIDOC ## CLOB API - Spreads ### Description Get bid-ask spread information for markets. ### Method GET ### Endpoint `/clob/spreads` ### Parameters #### Query Parameters - **token_id** (string) - Required - The identifier of the token. ### Request Example ```php // Get spread for single token $spread = $client->clob()->spreads()->get('token-id'); // Get spreads for multiple tokens $spreads = $client->clob()->spreads()->getMultiple([ ['token_id' => 'token-id-1'], ['token_id' => 'token-id-2'], ]); ``` ### Response #### Success Response (200) - **spread** (float) - The bid-ask spread for the token. #### Response Example ```json { "spread": 0.0010 } ``` ``` -------------------------------- ### Fetch Polymarket Markets using Gamma API (PHP) Source: https://context7.com/polymarket-php/polymarket/llms.txt Demonstrates how to retrieve prediction market data using the Polymarket PHP SDK's Gamma API. It includes fetching a list of active markets with pagination, getting a specific market by ID or slug, and retrieving tags associated with a market. ```php gamma()->markets()->list( filters: ['active' => true], limit: 10, offset: 0 ); foreach ($markets as $market) { echo "Market: {$market['question']}\n"; echo " ID: {$market['id']}\n"; echo " Slug: {$market['slug']}\n"; } // Get specific market by ID $market = $client->gamma()->markets()->get('market-id-here'); echo "Question: {$market['question']}\n"; // Get market by slug $market = $client->gamma()->markets()->getBySlug('will-trump-win-2024'); // Get tags for a market $tags = $client->gamma()->markets()->tags('market-id-here'); foreach ($tags as $tag) { echo "Tag: {$tag['label']}\n"; } } catch (PolymarketException $e) { echo "Error: " . $e->getMessage(); } ``` -------------------------------- ### Get Supported Assets for Bridge Deposits (PHP) Source: https://github.com/polymarket-php/polymarket/blob/main/README.md Retrieves information about supported blockchains, tokens, and minimum deposit amounts for cross-chain deposits. Essential for planning deposits. ```php $assets = $client->bridge()->deposits()->supportedAssets(); // Example response structure foreach ($assets['chains'] as $chain) { echo "Chain: {$chain['name']} (ID: {$chain['id']})\n"; } foreach ($assets['tokens'] as $token) { echo "Token: {$token['symbol']} - Min: ${$token['minimum_usd']}\n"; } ``` -------------------------------- ### Manage Polymarket Orders using PHP Source: https://context7.com/polymarket-php/polymarket/llms.txt This PHP snippet demonstrates how to manage trading orders through the Polymarket CLOB API. It covers listing orders with filters, retrieving specific orders, getting open orders, creating new orders, posting single or multiple orders, and cancelling orders by ID, payload, or market. ```php auth(); // Required for order operations try { // List orders with filters $orders = $client->clob()->orders()->list( filters: ['market' => 'token-id'], limit: 50, offset: 0 ); // Get specific order $order = $client->clob()->orders()->get('order-id'); echo "Order status: {$order['status']}\n"; // Get open orders $openOrders = $client->clob()->orders()->getOpen([ 'market' => 'token-id', ]); // Create a new order (use strings for price/amount to maintain precision) $newOrder = $client->clob()->orders()->create([ 'market_id' => 'token-id', 'side' => OrderSide::BUY->value, 'type' => OrderType::GTC->value, 'price' => '0.52', 'amount' => '10.00', ]); echo "Created order: {$newOrder['id']}\n"; // Post single order (alternative endpoint) $postedOrder = $client->clob()->orders()->post([ 'market_id' => 'token-id', 'side' => OrderSide::SELL->value, 'type' => OrderType::FOK->value, 'price' => '0.65', 'amount' => '5.00', ]); // Post multiple orders at once $multipleOrders = $client->clob()->orders()->postMultiple([ [ 'market_id' => 'token-id-1', 'side' => OrderSide::BUY->value, 'type' => OrderType::GTC->value, 'price' => '0.40', 'amount' => '20.00', ], [ 'market_id' => 'token-id-2', 'side' => OrderSide::BUY->value, 'type' => OrderType::GTC->value, 'price' => '0.55', 'amount' => '15.00', ], ]); // Cancel single order by ID $result = $client->clob()->orders()->cancel('order-id'); // Cancel with payload $result = $client->clob()->orders()->cancel([ 'order_id' => 'order-id', 'reason' => 'user_requested', ]); // Cancel multiple orders $result = $client->clob()->orders()->cancelMultiple([ 'order-id-1', 'order-id-2', 'order-id-3', ]); // Cancel all orders $result = $client->clob()->orders()->cancelAll(); // Cancel all orders for a specific market $result = $client->clob()->orders()->cancelMarketOrders([ 'market' => 'token-id', ]); } catch (PolymarketException $e) { echo "Order error: " . $e->getMessage(); } ``` -------------------------------- ### CLOB API - Server Health and Info (PHP) Source: https://context7.com/polymarket-php/polymarket/llms.txt Interact with the CLOB API to perform server health checks, retrieve server time, and get fee rates for specific tokens. Requires an initialized Polymarket Client. ```php clob()->server()->healthCheck(); echo "Server status: {$health['status']}\n"; // Get server time $time = $client->clob()->server()->getTime(); echo "Server time: {$time['time']}\n"; // Get fee rate for a token $feeRate = $client->clob()->server()->getFeeRate('token-id'); echo "Maker fee: {$feeRate['maker']}\n"; echo "Taker fee: {$feeRate['taker']}\n"; ``` -------------------------------- ### Get Order by ID (PHP) Source: https://github.com/polymarket-php/polymarket/blob/main/README.md Fetches details for a specific order using its unique identifier. This is useful for retrieving the status or full data of a single order. ```php $order = $client->clob()->orders()->get('order-id'); ``` -------------------------------- ### Get Market by ID using Gamma API Source: https://github.com/polymarket-php/polymarket/blob/main/README.md Retrieves a specific market's data by its unique identifier using the Polymarket Gamma API. Requires the market ID as a string parameter. ```php $market = $client->gamma()->markets()->get('market-id'); ``` -------------------------------- ### Access Polymarket Order Book using PHP Source: https://context7.com/polymarket-php/polymarket/llms.txt This PHP code snippet illustrates how to access order book data, tick sizes, and negative risk information for markets using the Polymarket CLOB API. It covers fetching the order book for a single token, multiple tokens, getting the tick size, and checking negative risk status. ```php clob()->book()->get('token-id'); echo "Bids: " . count($book['bids'] ?? []) . "\n"; echo "Asks: " . count($book['asks'] ?? []) . "\n"; // Get order books for multiple tokens $books = $client->clob()->book()->getMultiple([ ['token_id' => 'token-id-1'], ['token_id' => 'token-id-2'], ]); // Get tick size for a market $tickSize = $client->clob()->book()->getTickSize('token-id'); echo "Tick size: {$tickSize['minimum_tick_size']}\n"; // Get negative risk status $negRisk = $client->clob()->book()->getNegRisk('token-id'); ``` -------------------------------- ### Client Initialization Source: https://github.com/polymarket-php/polymarket/blob/main/README.md Demonstrates how to initialize the Polymarket SDK client, with options for custom API keys and base URLs for different API systems. ```APIDOC ## Client Initialization ### Description Initializes the Polymarket SDK client. You can use the default API key from environment variables or provide a custom API key and configure base URLs for Gamma, CLOB, and Bridge APIs, along with request timeout, retries, and SSL verification. ### Method ```php new Client(string $apiKey = null, array $config = []) ``` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```php use Danielgnh\PolymarketPhp\Client; // Initialize with default API key from environment variables $client = new Client(); // Initialize with a custom API key $client = new Client('your-api-key'); // Initialize with custom configuration $client = new Client('your-api-key', [ 'gamma_base_url' => 'https://gamma-api.polymarket.com', 'clob_base_url' => 'https://clob.polymarket.com', 'bridge_base_url' => 'https://bridge-api.polymarket.com', 'timeout' => 30, 'retries' => 3, 'verify_ssl' => true, ]); ``` ### Response #### Success Response (200) An instance of the `Client` class. #### Response Example ```php // $client object is returned $client = new Client(); ``` ``` -------------------------------- ### Initialize Polymarket PHP Client Source: https://context7.com/polymarket-php/polymarket/llms.txt Demonstrates how to initialize the Polymarket PHP SDK client. It shows basic initialization using environment variables, explicit API key usage, and full configuration with custom API endpoints, timeouts, retries, SSL verification, private key, and chain ID. ```php 'https://gamma-api.polymarket.com', 'clob_base_url' => 'https://clob.polymarket.com', 'bridge_base_url' => 'https://bridge-api.polymarket.com', 'timeout' => 30, 'retries' => 3, 'verify_ssl' => true, 'private_key' => '0x...', // For CLOB write operations 'chain_id' => 137, // Polygon mainnet ]); ``` -------------------------------- ### Initialize Polymarket PHP Client with Custom Configuration Source: https://github.com/polymarket-php/polymarket/blob/main/README.md Shows how to initialize the Polymarket PHP SDK client with custom configuration options, including base URLs for different APIs, timeout, retries, and SSL verification. ```php use Danielgnh\PolymarketPhp\Client; /* There is a way to initialize the client with custom configuration */ $client = new Client('your-api-key', [ 'gamma_base_url' => 'https://gamma-api.polymarket.com', 'clob_base_url' => 'https://clob.polymarket.com', 'bridge_base_url' => 'https://bridge-api.polymarket.com', 'timeout' => 30, 'retries' => 3, 'verify_ssl' => true, ]); ``` -------------------------------- ### Initialize Polymarket PHP Client Source: https://github.com/polymarket-php/polymarket/blob/main/README.md Demonstrates how to initialize the Polymarket PHP SDK client. It can be initialized with default credentials from environment variables or with a custom API key. ```php clob()->orders()->create([ 'market_id' => 'market-id', 'side' => OrderSide::BUY->value, 'type' => OrderType::GTC->value, 'price' => '0.52', 'amount' => '10.00', ]); ``` -------------------------------- ### Access Polymarket API Endpoints Source: https://github.com/polymarket-php/polymarket/blob/main/README.md Illustrates how to access different Polymarket API endpoints (Gamma, CLOB, Bridge) using the initialized client object. This allows for fetching market data, creating orders, and managing deposits. ```php /* Market data */ $client->gamma()->markets()->list(); /* Trading & Orders */ $client->clob()->orders()->create([...]); /* Cross-chain deposits */ $client->bridge()->deposits()->generate([...]); ``` -------------------------------- ### Error Handling with Polymarket PHP SDK Exceptions Source: https://github.com/polymarket-php/polymarket/blob/main/README.md Illustrates how to implement robust error handling using the Polymarket PHP SDK's exception hierarchy. It shows how to catch specific exceptions like AuthenticationException, ValidationException, RateLimitException, NotFoundException, and ApiException, as well as a general PolymarketException for broader error management. ```php use Danielgnh\PolymarketPhp\Exceptions\{ PolymarketException, AuthenticationException, ValidationException, RateLimitException, NotFoundException, ApiException }; try { $market = $client->gamma()->markets()->get('invalid-id'); } catch (AuthenticationException $e) { // Handle 401/403 authentication errors echo "Authentication failed: " . $e->getMessage(); } catch (ValidationException $e) { // Handle 400/422 validation errors echo "Validation error: " . $e->getMessage(); } catch (RateLimitException $e) { // Handle 429 rate limit errors echo "Rate limit exceeded: " . $e->getMessage(); } catch (NotFoundException $e) { // Handle 404 not found errors echo "Resource not found: " . $e->getMessage(); } catch (ApiException $e) { // Handle other API errors (5xx) echo "API error: " . $e->getMessage(); } catch (PolymarketException $e) { // Catch-all for any SDK exception echo "Error: " . $e->getMessage(); // Get additional error details $statusCode = $e->getCode(); $response = $e->getResponse(); } ``` -------------------------------- ### Fetch Polymarket Events using Gamma API (PHP) Source: https://context7.com/polymarket-php/polymarket/llms.txt Illustrates how to fetch event data using the Polymarket PHP SDK's Gamma API. This includes listing active events with pagination, retrieving a specific event by ID or slug, and fetching tags associated with an event. ```php gamma()->events()->list( filters: ['active' => true], limit: 20, offset: 0 ); foreach ($events as $event) { echo "Event: {$event['title']}\n"; echo " Markets count: " . count($event['markets'] ?? []) . "\n"; } // Get event by ID $event = $client->gamma()->events()->get('event-id-here'); // Get event by slug $event = $client->gamma()->events()->getBySlug('2024-presidential-election'); // Get tags for an event $tags = $client->gamma()->events()->tags('event-id-here'); ``` -------------------------------- ### List Markets using Gamma API Source: https://github.com/polymarket-php/polymarket/blob/main/README.md Fetches a list of markets from the Polymarket Gamma API. Supports filtering by category and status, and pagination using limit and offset parameters. ```php $markets = $client->gamma()->markets()->list( filters: ['active' => true, 'category' => 'politics'], limit: 100, offset: 0 ); ``` -------------------------------- ### Manage Polymarket Tags using PHP Source: https://context7.com/polymarket-php/polymarket/llms.txt This snippet demonstrates how to manage and query tags for categorizing markets and events using the Polymarket PHP SDK. It covers listing all tags, retrieving a tag by ID or slug, and finding related tags. ```php gamma()->tags()->list(); foreach ($tags as $tag) { echo "Tag: {$tag['label']} (slug: {$tag['slug']})\n"; } // Get tag by ID $tag = $client->gamma()->tags()->get('tag-id'); // Get tag by slug $tag = $client->gamma()->tags()->getBySlug('politics'); // Get related tags $relatedTags = $client->gamma()->tags()->relatedTags('tag-id'); $relatedTagsBySlug = $client->gamma()->tags()->relatedTagsBySlug('politics'); // Get tags related to a specific tag $tagsRelated = $client->gamma()->tags()->getTagsRelatedToTag('tag-id'); $tagsRelatedBySlug = $client->gamma()->tags()->getTagsRelatedToTagBySlug('politics'); ``` -------------------------------- ### Development: Checking Code Style with PHP CS Fixer Source: https://github.com/polymarket-php/polymarket/blob/main/README.md Presents the Composer command to check the code style of the project using PHP CS Fixer without making any modifications. This is useful for verifying compliance with coding standards. ```bash composer cs-check ``` -------------------------------- ### Development: Generating Test Coverage Report Source: https://github.com/polymarket-php/polymarket/blob/main/README.md Details the Composer command used to generate a test coverage report for the Polymarket PHP project. The reports are typically saved in the `coverage/` directory. ```bash composer test-coverage ``` -------------------------------- ### CLOB API - Account Source: https://context7.com/polymarket-php/polymarket/llms.txt Manage account balances, allowances, and notifications. ```APIDOC ## CLOB API - Account ### Description Manage account balances, allowances, and notifications. ### Method GET / POST ### Endpoint `/clob/account` ### Parameters #### Query Parameters - **asset_type** (string) - Required for `getBalanceAllowance` and `updateBalanceAllowance` - The type of asset (e.g., 'COLLATERAL'). - **ids** (array) - Required for `dropNotifications` - An array of notification IDs to drop. ### Request Example ```php // Get balance and allowance $balanceAllowance = $client->clob()->account()->getBalanceAllowance([ 'asset_type' => 'COLLATERAL', ]); // Update balance allowance $updated = $client->clob()->account()->updateBalanceAllowance([ 'asset_type' => 'COLLATERAL', ]); // Get notifications $notifications = $client->clob()->account()->getNotifications(); // Drop/dismiss notifications $result = $client->clob()->account()->dropNotifications([ 'ids' => ['notification-id-1', 'notification-id-2'], ]); // Check if account is in closed-only mode $closedOnlyMode = $client->clob()->account()->getClosedOnlyMode(); ``` ### Response #### Success Response (200) - **balance** (float) - The account balance. - **allowance** (float) - The account allowance. - **message** (string) - The notification message. - **closed_only** (boolean) - Indicates if the account is in closed-only mode. #### Response Example ```json { "balance": 1000.0, "allowance": 500.0, "closed_only": false } ``` ``` -------------------------------- ### Markets (Gamma API) Source: https://github.com/polymarket-php/polymarket/blob/main/README.md Provides endpoints for accessing read-only market data through the Gamma API. ```APIDOC ## Markets (Gamma API) ### Description The Markets resource provides access to prediction market data via the Gamma API. This includes listing, retrieving by ID, and searching for markets. ### Method ```php $client->gamma()->markets() ``` ### Endpoint `https://gamma-api.polymarket.com` (Base URL) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### List Markets #### Description Retrieves a list of markets, with options for filtering, limiting results, and pagination. #### Method ```php list(array $filters = null, int $limit = 100, int $offset = 0) ``` #### Parameters - `filters` (array, optional): Filtering options for markets (e.g., `['active' => true, 'category' => 'politics']`). - `limit` (int, optional): Maximum number of results to return. Defaults to 100. - `offset` (int, optional): Pagination offset. Defaults to 0. #### Request Example ```php $markets = $client->gamma()->markets()->list( filters: ['active' => true, 'category' => 'politics'], limit: 100, offset: 0 ); ``` #### Response ##### Success Response (200) An array of market data objects. ##### Response Example ```json [ { "id": "market-id-1", "title": "Will the next US president be elected in 2024?", "category": "politics", "status": "active" }, { "id": "market-id-2", "title": "Will it rain tomorrow?", "category": "weather", "status": "active" } ] ``` ### Get Market by ID #### Description Retrieves a specific market's data using its unique identifier. #### Method ```php get(string $marketId) ``` #### Parameters - `marketId` (string): The unique identifier of the market. #### Request Example ```php $market = $client->gamma()->markets()->get('market-id-1'); ``` #### Response ##### Success Response (200) A market data object. ##### Response Example ```json { "id": "market-id-1", "title": "Will the next US president be elected in 2024?", "category": "politics", "status": "active" } ``` ### Search Markets #### Description Searches for markets based on a query string, with optional filtering and result limiting. #### Method ```php search(string $query, array $filters = null, int $limit = 100) ``` #### Parameters - `query` (string): The search query string. - `filters` (array, optional): Additional filtering options. - `limit` (int, optional): Maximum number of results to return. Defaults to 100. #### Request Example ```php $results = $client->gamma()->markets()->search( query: 'election', filters: ['active' => true], limit: 50 ); ``` #### Response ##### Success Response (200) An array of market data objects matching the search query. ##### Response Example ```json [ { "id": "market-id-1", "title": "US Presidential Election 2024 Odds", "category": "politics", "status": "active" } ] ``` ``` -------------------------------- ### CLOB API - Pricing Source: https://context7.com/polymarket-php/polymarket/llms.txt Retrieve price data, midpoints, and historical prices for various tokens. ```APIDOC ## CLOB API - Pricing ### Description Retrieve price data, midpoints, and historical prices for various tokens. ### Method GET ### Endpoint `/clob/pricing` ### Parameters #### Query Parameters - **token_id** (string) - Required - The identifier of the token. - **side** (string) - Optional - The order side (BUY or SELL). - **market** (string) - Required for `getPricesHistory` - The market identifier. - **startTs** (integer) - Required for `getPricesHistory` - The start timestamp for historical data. - **endTs** (integer) - Required for `getPricesHistory` - The end timestamp for historical data. - **fidelity** (integer) - Optional for `getPricesHistory` - The interval in minutes for historical data points. ### Request Example ```php // Get current price for a side $price = $client->clob()->pricing()->getPrice('token-id', OrderSide::BUY->value); // Get prices for multiple tokens and sides $prices = $client->clob()->pricing()->getPrices([ ['token_id' => 'token-id-1', 'side' => 'BUY'], ['token_id' => 'token-id-1', 'side' => 'SELL'], ['token_id' => 'token-id-2', 'side' => 'BUY'], ]); // Get midpoint price $midpoint = $client->clob()->pricing()->getMidpoint('token-id'); // Get midpoints for multiple tokens $midpoints = $client->clob()->pricing()->getMidpoints([ ['token_id' => 'token-id-1'], ['token_id' => 'token-id-2'], ]); // Get last trade price $lastPrice = $client->clob()->pricing()->getLastTradePrice('token-id'); // Get last trade prices for multiple tokens $lastPrices = $client->clob()->pricing()->getLastTradesPrices([ ['token_id' => 'token-id-1'], ['token_id' => 'token-id-2'], ]); // Get price history $history = $client->clob()->pricing()->getPricesHistory([ 'market' => 'token-id', 'startTs' => strtotime('-7 days'), 'endTs' => time(), 'fidelity' => 60, // 1-minute intervals ]); ``` ### Response #### Success Response (200) - **price** (float) - The price of the token. - **mid** (float) - The midpoint price between bid and ask. - **history** (array) - An array of historical price data points. - **last_trade_price** (float) - The price of the last trade. #### Response Example ```json { "price": 1.2345, "mid": 1.2350, "last_trade_price": 1.2340 } ``` ``` -------------------------------- ### Gamma API - Tags Source: https://context7.com/polymarket-php/polymarket/llms.txt Manage and query tags for categorizing markets and events. Supports listing all tags, retrieving tags by ID or slug, and finding related tags. ```APIDOC ## Gamma API - Tags ### Description Manage and query tags for categorizing markets and events. ### Method GET ### Endpoint `/gamma/tags` ### Parameters #### Query Parameters - **id** (string) - Optional - The ID of the tag to retrieve. - **slug** (string) - Optional - The slug of the tag to retrieve. ### Request Example ```php // List all tags $tags = $client->gamma()->tags()->list(); // Get tag by ID $tag = $client->gamma()->tags()->get('tag-id'); // Get tag by slug $tag = $client->gamma()->tags()->getBySlug('politics'); ``` ### Response #### Success Response (200) - **tags** (array) - A list of tag objects, each containing 'label' and 'slug'. - **tag** (object) - A single tag object. #### Response Example ```json { "label": "Politics", "slug": "politics" } ``` ## Gamma API - Related Tags ### Description Retrieve tags related to a specific tag, either by ID or slug. ### Method GET ### Endpoint `/gamma/tags/{tag_id}/related` or `/gamma/tags/slug/{slug}/related` ### Parameters #### Path Parameters - **tag_id** (string) - Required - The ID of the tag. - **slug** (string) - Required - The slug of the tag. ### Request Example ```php // Get related tags by ID $relatedTags = $client->gamma()->tags()->relatedTags('tag-id'); // Get related tags by slug $relatedTagsBySlug = $client->gamma()->tags()->relatedTagsBySlug('politics'); ``` ### Response #### Success Response (200) - **related_tags** (array) - A list of related tag objects. #### Response Example ```json [ { "label": "Elections", "slug": "elections" } ] ``` ## Gamma API - Tags Related to Tag ### Description Retrieve tags that are related to a specific tag, identified by its ID or slug. ### Method GET ### Endpoint `/gamma/tags/{tag_id}/related_to` or `/gamma/tags/slug/{slug}/related_to` ### Parameters #### Path Parameters - **tag_id** (string) - Required - The ID of the tag. - **slug** (string) - Required - The slug of the tag. ### Request Example ```php // Get tags related to a specific tag by ID $tagsRelated = $client->gamma()->tags()->getTagsRelatedToTag('tag-id'); // Get tags related to a specific tag by slug $tagsRelatedBySlug = $client->gamma()->tags()->getTagsRelatedToTagBySlug('politics'); ``` ### Response #### Success Response (200) - **tags_related** (array) - A list of tag objects related to the specified tag. #### Response Example ```json [ { "label": "US Politics", "slug": "us-politics" } ] ``` ``` -------------------------------- ### Search Markets using Gamma API Source: https://github.com/polymarket-php/polymarket/blob/main/README.md Searches for markets based on a query string using the Polymarket Gamma API. Allows for additional filtering and limiting the number of results. ```php $results = $client->gamma()->markets()->search( query: 'election', filters: ['active' => true], limit: 50 ); ``` -------------------------------- ### Orders (CLOB API) Source: https://github.com/polymarket-php/polymarket/blob/main/README.md Manages trading operations and order creation/cancellation via the CLOB API. ```APIDOC ## Orders (CLOB API) ### Description The Orders resource handles order management and execution via the CLOB API. This includes creating, canceling, and retrieving order information. ### Method ```php $client->clob()->orders() ``` ### Endpoint `https://clob.polymarket.com` (Base URL) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Create Order #### Description Creates a new order on the CLOB. #### Method ```php create(array $orderData) ``` #### Parameters - `orderData` (array): An array containing the details of the order to be created. The exact structure depends on the CLOB API specification (e.g., market ID, side, price, amount). #### Request Example ```php $order = $client->clob()->orders()->create([ 'marketId' => 'market-id-1', 'side' => 'buy', 'price' => 0.5, 'amount' => 10, // ... other required order parameters ]); ``` #### Response ##### Success Response (200) An object representing the created order. ##### Response Example ```json { "id": "order-id-123", "marketId": "market-id-1", "side": "buy", "price": 0.5, "amount": 10, "status": "open" } ``` ### Cancel Order #### Description Cancels an existing order. #### Method ```php cancel(string $orderId) ``` #### Parameters - `orderId` (string): The unique identifier of the order to cancel. #### Request Example ```php $result = $client->clob()->orders()->cancel('order-id-123'); ``` #### Response ##### Success Response (200) A confirmation message or status indicating the order was cancelled. ##### Response Example ```json { "message": "Order order-id-123 cancelled successfully." } ``` ### Get Order #### Description Retrieves the details of a specific order. #### Method ```php get(string $orderId) ``` #### Parameters - `orderId` (string): The unique identifier of the order. #### Request Example ```php $order = $client->clob()->orders()->get('order-id-123'); ``` #### Response ##### Success Response (200) An object representing the order details. ##### Response Example ```json { "id": "order-id-123", "marketId": "market-id-1", "side": "buy", "price": 0.5, "amount": 10, "status": "open" } ``` ``` -------------------------------- ### Polymarket PHP SDK: Working with Decimal Values Source: https://github.com/polymarket-php/polymarket/blob/main/README.md Highlights the importance of using string representation for financial values like prices and amounts when interacting with the Polymarket PHP SDK to maintain precision. It contrasts the correct string-based approach with the incorrect float-based approach that can lead to precision loss. ```php // Good - maintains precision $order = $client->clob()->orders()->create([ 'price' => '0.52', 'amount' => '10.00', ]); // Bad - may lose precision $order = $client->clob()->orders()->create([ 'price' => 0.52, // Float loses precision! 'amount' => 10.00, ]); ``` -------------------------------- ### CLOB API - Rewards Source: https://context7.com/polymarket-php/polymarket/llms.txt Access liquidity rewards and earnings information. ```APIDOC ## CLOB API - Rewards ### Description Access liquidity rewards and earnings information. ### Method GET ### Endpoint `/clob/rewards` ### Parameters #### Query Parameters - **condition_id** (string) - Required for `getForMarket` - The condition identifier. - **date** (string) - Required for earnings endpoints - The date in 'YYYY-MM-DD' format. ### Request Example ```php // Get current rewards markets $currentRewards = $client->clob()->rewards()->getCurrentRewards(); // Get rewards for specific market $marketRewards = $client->clob()->rewards()->getForMarket('condition-id'); // Get earnings for a specific day $earnings = $client->clob()->rewards()->getEarningsForDay([ 'date' => '2024-01-15', ]); // Get total earnings for a day $totalEarnings = $client->clob()->rewards()->getTotalEarningsForDay([ 'date' => '2024-01-15', ]); // Get user earnings and market config $earningsConfig = $client->clob()->rewards()->getUserEarningsAndMarketsConfig([ 'date' => '2024-01-15', ]); // Get liquidity reward percentages $percentages = $client->clob()->rewards()->getRewardPercentages(); ``` ### Response #### Success Response (200) - **condition_id** (string) - The condition identifier. - **reward_rate** (float) - The reward rate. - **total** (float) - The total earnings. - **liquidity_reward_percentage** (float) - The liquidity reward percentage. #### Response Example ```json { "condition_id": "condition-abc", "reward_rate": 0.05, "total": 10.75, "liquidity_reward_percentage": 0.1 } ``` ``` -------------------------------- ### CLOB API Pricing with PHP Source: https://context7.com/polymarket-php/polymarket/llms.txt Retrieve current prices, midpoints, last trade prices, and historical price data for tokens using the Polymarket PHP SDK. This function requires a valid client instance and token identifiers. ```php clob()->pricing()->getPrice('token-id', OrderSide::BUY->value); echo "Buy price: {$price['price']}\n"; // Get prices for multiple tokens and sides $prices = $client->clob()->pricing()->getPrices([ ['token_id' => 'token-id-1', 'side' => 'BUY'], ['token_id' => 'token-id-1', 'side' => 'SELL'], ['token_id' => 'token-id-2', 'side' => 'BUY'], ]); // Get midpoint price $midpoint = $client->clob()->pricing()->getMidpoint('token-id'); echo "Midpoint: {$midpoint['mid']}\n"; // Get midpoints for multiple tokens $midpoints = $client->clob()->pricing()->getMidpoints([ ['token_id' => 'token-id-1'], ['token_id' => 'token-id-2'], ]); // Get last trade price $lastPrice = $client->clob()->pricing()->getLastTradePrice('token-id'); echo "Last trade: {$lastPrice['price']}\n"; // Get last trade prices for multiple tokens $lastPrices = $client->clob()->pricing()->getLastTradesPrices([ ['token_id' => 'token-id-1'], ['token_id' => 'token-id-2'], ]); // Get price history $history = $client->clob()->pricing()->getPricesHistory([ 'market' => 'token-id', 'startTs' => strtotime('-7 days'), 'endTs' => time(), 'fidelity' => 60, // 1-minute intervals ]); ```