PHP code example of danielgnh / polymarket-php

1. Go to this page and download the library: Download danielgnh/polymarket-php library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

danielgnh / polymarket-php example snippets




use PolymarketPhp\Polymarket\Client;

/*
* Let's initialize the client.
* In case if you defined the POLYMARKET_API_KEY you don't need to pass any parameters in Client
*/
$client = new Client();

/*
* In case if you want to define any other API Key, you can do it as well.
*/
$client = new Client('api-key');

/* Market data */
$client->gamma()->markets()->list();

/* Trading & Orders */
$client->clob()->orders()->create([...]);

/* Cross-chain deposits */
$client->bridge()->deposits()->generate([...]);

use PolymarketPhp\Polymarket\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,
]);

$markets = $client->gamma()->markets()->list(
    filters: ['active' => true, 'category' => 'politics'],
    limit: 100,
    offset: 0
);

$market = $client->gamma()->markets()->get('market-id');

$results = $client->gamma()->markets()->search(
    query: 'election',
    filters: ['active' => true],
    limit: 50
);

$orders = $client->clob()->orders()->list(
    filters: ['status' => 'open'],
    limit: 100,
    offset: 0
);

$order = $client->clob()->orders()->get('order-id');

use PolymarketPhp\Polymarket\Enums\OrderSide;
use PolymarketPhp\Polymarket\Enums\OrderType;

$order = $client->clob()->orders()->create([
    'market_id' => 'market-id',
    'side' => OrderSide::BUY->value,
    'type' => OrderType::GTC->value,
    'price' => '0.52',
    'amount' => '10.00',
]);

$result = $client->clob()->orders()->cancel('order-id');

$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";
}

$addresses = $client->bridge()->deposits()->generate([
    'destination_address' => '0xYourPolygonWalletAddress',
    'amount_usd' => '100'
]);

// Access deposit addresses for different chains
echo "EVM Chains Address: {$addresses['evm']}\n";
echo "Solana Address: {$addresses['solana']}\n";
echo "Bitcoin Address: {$addresses['bitcoin']}\n";

use PolymarketPhp\Polymarket\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";

use PolymarketPhp\Polymarket\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();
}

use PolymarketPhp\Polymarket\Enums\OrderSide;

OrderSide::BUY   // Buy shares
OrderSide::SELL  // Sell shares

use PolymarketPhp\Polymarket\Enums\OrderType;

OrderType::FOK  // Fill-Or-Kill: Execute immediately in full or cancel
OrderType::FAK  // Fill-And-Kill: Execute immediately for available shares, cancel remainder
OrderType::GTC  // Good-Til-Cancelled: Active until fulfilled or cancelled
OrderType::GTD  // Good-Til-Date: Active until specified date

use PolymarketPhp\Polymarket\Enums\OrderStatus;

OrderStatus::MATCHED    // Matched with existing order
OrderStatus::LIVE       // Resting on the order book
OrderStatus::DELAYED    // Marketable but subject to matching delay
OrderStatus::UNMATCHED  // Marketable but experiencing delay

use PolymarketPhp\Polymarket\Enums\SignatureType;

SignatureType::POLYMARKET_PROXY_EMAIL   // Email/Magic account (value: 1)
SignatureType::POLYMARKET_PROXY_WALLET  // Browser wallet (value: 2)
SignatureType::EOA                      // Externally owned account (value: 0)

use PolymarketPhp\Polymarket\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',
]);

// 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,
]);

use PolymarketPhp\Polymarket\Client;

$client = new Client('your-api-key');

// Fetch multiple markets by ID
$marketIds = ['id-1', 'id-2', 'id-3', 'id-4', 'id-5'];
$result = $client->gamma()->markets()->getMany($marketIds, concurrency: 10);

// Iterate over successful results (BatchResult implements ArrayAccess)
foreach ($result as $id => $market) {
    echo $market['question'] . PHP_EOL;
}

// Handle any failures
if ($result->hasFailures()) {
    foreach ($result->failed as $id => $exception) {
        error_log("Failed to fetch market {$id}: {$exception->getMessage()}");
    }
}

use GuzzleHttp\Promise\Utils;

$promise1 = $client->gamma()->markets()->getAsync('market-1');
$promise2 = $client->gamma()->markets()->getAsync('market-2');
$promise3 = $client->gamma()->markets()->listAsync(['active' => true]);

// Wait for all promises
$results = Utils::unwrap([
    'market1' => $promise1,
    'market2' => $promise2,
    'list' => $promise3,
]);

echo $results['market1']['question'];

$client = new Client('your-api-key', [
    'default_concurrency' => 10,  // Max concurrent requests (default: 10)
    'async_timeout' => 30,        // Timeout per request in seconds (default: 30)
]);
bash
composer