Disclosure: PredScope may receive compensation when you sign up for prediction market platforms through links on this site. This does not influence our ratings or reviews. Learn more.

HomeGuides › Polymarket API

Polymarket API Guide: Complete Developer Tutorial (2026)

Updated March 2026 — Everything you need to fetch market data, build dashboards, and place trades programmatically using the Polymarket Gamma API and CLOB API. Working Python and JavaScript examples included.

Quick Reference

Table of Contents

  1. What Is the Polymarket API?
  2. Two APIs: Gamma vs. CLOB
  3. API Endpoints Overview
  4. Getting Market Data
  5. Order Book & CLOB API
  6. Authentication
  7. Rate Limits & Best Practices
  8. Python Code Examples
  9. JavaScript / Node.js Examples
  10. Use Cases: Bots, Dashboards, Analytics
  11. Polymarket API vs. Kalshi API
  12. Frequently Asked Questions

What Is the Polymarket API?

The Polymarket API is a set of REST endpoints that give developers programmatic access to the world's largest prediction market. You can fetch real-time market data, historical prices, event metadata, and — with the right setup — place trades directly from your code.

Polymarket exposes two separate APIs, each serving a different purpose:

Whether you want to build a price-tracking dashboard, a custom analytics tool, an arbitrage bot, or simply pull Polymarket data into a spreadsheet, the API is your starting point. No API key is required for reading data — you can start making requests right now.

Try it now: Open your browser and visit https://gamma-api.polymarket.com/events?limit=5&active=true — you will see live Polymarket event data in JSON format, no authentication needed.

Two APIs: Gamma API vs. CLOB API

Understanding which API to use is the first step. Here is a breakdown:

Feature Gamma API CLOB API
Base URL gamma-api.polymarket.com clob.polymarket.com
Purpose Market data & metadata Order book & trading
Auth required No Polygon wallet for trades
Read data Events, markets, prices Order books, trades, spreads
Write/trade No Yes (place, cancel, amend orders)
Best for Dashboards, analytics, data pulls Trading bots, market making

Rule of thumb: If you only need to read data, use the Gamma API. If you need to trade or see the live order book, use the CLOB API.

API Endpoints Overview

Gamma API Endpoints

Endpoint Method Description
/events GET List events (categories of related markets)
/events/{id} GET Get a single event by ID
/markets GET List all markets with prices and metadata
/markets/{id} GET Get a single market by condition ID

Common Query Parameters (Gamma API)

Parameter Type Example Description
limit int 100 Number of results (max varies by endpoint)
offset int 0 Pagination offset
active bool true Filter for active/open markets only
closed bool false Filter for closed/resolved markets
order string volume24hr Sort order (volume24hr, startDate, etc.)
ascending bool false Sort direction

CLOB API Endpoints

Endpoint Method Description
/book GET Get order book for a token ID
/midpoint GET Get midpoint price for a token
/price GET Get best bid/ask for a token
/order POST Place a new order (auth required)
/order/{id} DELETE Cancel an order (auth required)
/orders GET List your open orders (auth required)
/trades GET Get recent trades for a market

Getting Market Data

The Gamma API is the easiest way to pull Polymarket data. All requests are simple GET calls that return JSON. No authentication, no setup — just send an HTTP request.

Fetching Active Events

An event is a group of related markets. For example, "2028 Presidential Election" is an event that contains markets for each candidate.

# Fetch the 10 most active events
GET https://gamma-api.polymarket.com/events?limit=10&active=true&order=volume24hr&ascending=false

The response includes each event's title, description, markets array, total volume, and more. Each market within the event has its own condition ID, token IDs (for Yes/No shares), and current prices.

Fetching Markets

To get individual markets directly:

# Fetch 100 active markets sorted by volume
GET https://gamma-api.polymarket.com/markets?limit=100&active=true&order=volume24hr&ascending=false

Key Fields in Market Response

Field Type Description
condition_id string Unique market identifier
question string The market question (e.g., "Will Bitcoin hit $200K by 2027?")
tokens array Yes/No token objects with token_id and price
outcomePrices string JSON string of current prices, e.g., "[0.65, 0.35]"
volume number All-time volume in USDC
volume24hr number 24-hour trading volume
active bool Whether the market is open for trading
closed bool Whether the market has resolved
endDate string Market expiration date (ISO 8601)

Understanding Token IDs

Every binary market on Polymarket has two tokens: Yes and No. Each token has a unique token_id which you need when querying the CLOB API for order books or placing trades.

Example market response (simplified):
condition_id: "0x1234..."
question: "Will BTC exceed $150,000 by June 2026?"
tokens[0]: { token_id: "71321...", outcome: "Yes", price: 0.42 }
tokens[1]: { token_id: "71322...", outcome: "No", price: 0.58 }

Order Book & CLOB API

The CLOB (Central Limit Order Book) API gives you access to the live order book — the actual bids and asks that make up Polymarket's market. This is essential for trading bots, market making, and understanding true liquidity.

Fetching the Order Book

# Get the order book for a specific token
GET https://clob.polymarket.com/book?token_id=YOUR_TOKEN_ID

The response contains arrays of bids and asks, each with a price and size:

{
  "bids": [
    { "price": "0.64", "size": "5000" },
    { "price": "0.63", "size": "12000" },
    { "price": "0.62", "size": "8000" }
  ],
  "asks": [
    { "price": "0.66", "size": "3000" },
    { "price": "0.67", "size": "7000" },
    { "price": "0.68", "size": "4500" }
  ]
}

Getting the Midpoint Price

# Get the midpoint (average of best bid and best ask)
GET https://clob.polymarket.com/midpoint?token_id=YOUR_TOKEN_ID

# Response: { "mid": "0.6500" }

Getting Best Bid/Ask

# Get best available prices
GET https://clob.polymarket.com/price?token_id=YOUR_TOKEN_ID&side=buy
GET https://clob.polymarket.com/price?token_id=YOUR_TOKEN_ID&side=sell

Placing Orders (Authenticated)

To place orders through the CLOB API, you need to sign your orders with a Polygon wallet. Orders are submitted as signed EIP-712 typed data. The recommended approach is to use the official py_clob_client Python library or the @polymarket/clob-client npm package, which handle the signing logic for you.

Important: Trading Requires a Polygon Wallet

Read-only endpoints (order books, prices, midpoints) on the CLOB API are public and require no authentication. But placing, canceling, or amending orders requires a Polygon-compatible wallet with a funded USDC balance. You will need your wallet's private key to sign orders.

Authentication

Read-Only: No Auth Needed

All Gamma API endpoints and CLOB API read endpoints (book, price, midpoint, trades) are completely public. No API key, no tokens, no registration. Just send HTTP requests and get JSON back.

Trading: Wallet-Based Authentication

For placing orders, Polymarket uses wallet-based authentication rather than traditional API keys. Here is how it works:

  1. Create a Polygon wallet (or use an existing one) with a private key you control
  2. Fund it with USDC on the Polygon network
  3. Enable trading by approving the Polymarket contracts (the client libraries handle this)
  4. Sign orders using EIP-712 typed data with your private key
  5. Submit signed orders to the CLOB API
Security note: Your private key never leaves your machine. Orders are signed locally and the signature is sent to Polymarket. This is a key advantage of blockchain-based authentication — Polymarket never has custody of your keys.

Setting Up the Python CLOB Client

pip install py_clob_client

from py_clob_client.client import ClobClient
from py_clob_client.clob_types import OrderArgs, OrderType

# Initialize with your private key
client = ClobClient(
    host="https://clob.polymarket.com",
    key="YOUR_PRIVATE_KEY",         # Polygon wallet private key
    chain_id=137                     # 137 = Polygon mainnet
)

# Derive your Polymarket API credentials
client.set_api_creds(client.create_or_derive_api_creds())

Rate Limits & Best Practices

Polymarket does not publish official rate limit numbers, but the developer community has established practical guidelines through experience:

API Estimated Limit Notes
Gamma API (reads) ~10 requests/second Generous for data pulls; paginate large requests
CLOB API (reads) ~5 requests/second Stricter; use WebSocket for real-time data
CLOB API (orders) ~2 orders/second Per-wallet limit; bulk endpoints available

Best Practices

  1. Implement exponential backoff. If you receive a 429 (Too Many Requests) response, wait 1 second, then 2, then 4, etc. before retrying.
  2. Cache aggressively. Event and market metadata rarely changes — cache it for 5-15 minutes. Prices change frequently, but a 1-second cache is still helpful.
  3. Use pagination. Always use limit and offset parameters. Do not try to fetch all markets in a single request.
  4. Prefer WebSocket for real-time data. If you need live price updates, use the CLOB WebSocket instead of polling the REST API repeatedly.
  5. Handle errors gracefully. The API can return 500 errors during high-traffic periods. Build retry logic into your code.
  6. Respect the infrastructure. Polymarket provides this API for free. Do not spam it with unnecessary requests.

Pro Tip: Use PredScope for Aggregated Data

If you need market data from multiple prediction platforms (Polymarket, Kalshi, etc.) in one place, PredScope aggregates and normalizes data across platforms — saving you the complexity of managing multiple API integrations. Check our prediction market API overview for details.

Python Code Examples

1. Fetch All Active Events

import requests
import json

GAMMA_API = "https://gamma-api.polymarket.com"

def get_active_events(limit=100):
    """Fetch active Polymarket events sorted by 24h volume."""
    url = f"{GAMMA_API}/events"
    params = {
        "limit": limit,
        "active": "true",
        "order": "volume24hr",
        "ascending": "false"
    }
    response = requests.get(url, params=params)
    response.raise_for_status()
    return response.json()

events = get_active_events(limit=10)
for event in events:
    title = event.get("title", "Untitled")
    markets = event.get("markets", [])
    print(f"{title} ({len(markets)} markets)")
    for market in markets:
        prices = json.loads(market.get("outcomePrices", "[]"))
        yes_price = float(prices[0]) if prices else 0
        print(f"  - {market['question']}: Yes {yes_price:.0%}")

2. Fetch Markets with Pagination

import requests
import time

GAMMA_API = "https://gamma-api.polymarket.com"

def get_all_active_markets():
    """Fetch all active markets using pagination."""
    all_markets = []
    offset = 0
    limit = 100

    while True:
        url = f"{GAMMA_API}/markets"
        params = {
            "limit": limit,
            "offset": offset,
            "active": "true"
        }
        response = requests.get(url, params=params)
        response.raise_for_status()
        markets = response.json()

        if not markets:
            break

        all_markets.extend(markets)
        offset += limit
        time.sleep(0.2)  # Be respectful of rate limits

    return all_markets

markets = get_all_active_markets()
print(f"Total active markets: {len(markets)}")

3. Get Order Book Data from the CLOB API

import requests

CLOB_API = "https://clob.polymarket.com"

def get_order_book(token_id):
    """Fetch the full order book for a token."""
    url = f"{CLOB_API}/book"
    params = {"token_id": token_id}
    response = requests.get(url, params=params)
    response.raise_for_status()
    return response.json()

def get_midpoint(token_id):
    """Get the midpoint price for a token."""
    url = f"{CLOB_API}/midpoint"
    params = {"token_id": token_id}
    response = requests.get(url, params=params)
    response.raise_for_status()
    return response.json()

# Example: get order book for a token
# Replace with an actual token_id from the Gamma API
token_id = "71321045863788113099852471857300918457691"
book = get_order_book(token_id)

print("=== ORDER BOOK ===")
print(f"Top 3 Bids (buy orders):")
for bid in book.get("bids", [])[:3]:
    print(f"  {bid['price']} - {bid['size']} shares")

print(f"Top 3 Asks (sell orders):")
for ask in book.get("asks", [])[:3]:
    print(f"  {ask['price']} - {ask['size']} shares")

mid = get_midpoint(token_id)
print(f"Midpoint: {mid.get('mid', 'N/A')}")

4. Monitor Market Prices in Real-Time

import requests
import time
import json

GAMMA_API = "https://gamma-api.polymarket.com"

def monitor_market(condition_id, interval=30):
    """Poll a market's price every N seconds."""
    url = f"{GAMMA_API}/markets/{condition_id}"

    print(f"Monitoring market {condition_id}...")
    print(f"Polling every {interval} seconds. Press Ctrl+C to stop.\n")

    try:
        while True:
            response = requests.get(url)
            response.raise_for_status()
            market = response.json()

            question = market.get("question", "Unknown")
            prices = json.loads(market.get("outcomePrices", "[]"))
            volume = market.get("volume24hr", 0)

            yes_price = float(prices[0]) if prices else 0
            timestamp = time.strftime("%H:%M:%S")

            print(f"[{timestamp}] {question}")
            print(f"  Yes: {yes_price:.1%} | 24h Vol: ${volume:,.0f}")
            print()

            time.sleep(interval)
    except KeyboardInterrupt:
        print("Monitoring stopped.")

# Usage: monitor_market("YOUR_CONDITION_ID", interval=30)

5. Place a Limit Order with py_clob_client

from py_clob_client.client import ClobClient
from py_clob_client.clob_types import OrderArgs, OrderType

# Initialize the CLOB client
client = ClobClient(
    host="https://clob.polymarket.com",
    key="YOUR_POLYGON_PRIVATE_KEY",  # Never hardcode in production!
    chain_id=137                      # Polygon mainnet
)

# Derive API credentials (one-time setup)
client.set_api_creds(client.create_or_derive_api_creds())

# Place a limit buy order
# Buy 100 Yes shares at $0.45 each
order_args = OrderArgs(
    price=0.45,
    size=100,
    side="BUY",
    token_id="YOUR_YES_TOKEN_ID"
)

signed_order = client.create_order(order_args)
response = client.post_order(signed_order, OrderType.GTC)  # Good Till Cancel
print(f"Order placed: {response}")

# Cancel an order
# client.cancel(order_id="YOUR_ORDER_ID")

Security Warning

Never hardcode private keys in your source code. Use environment variables or a secure secrets manager:

import os
private_key = os.environ.get("POLYMARKET_PRIVATE_KEY")

JavaScript / Node.js Examples

1. Fetch Active Events (Node.js)

// Fetch active Polymarket events
const GAMMA_API = "https://gamma-api.polymarket.com";

async function getActiveEvents(limit = 10) {
  const url = `${GAMMA_API}/events?limit=${limit}&active=true&order=volume24hr&ascending=false`;
  const response = await fetch(url);

  if (!response.ok) {
    throw new Error(`HTTP ${response.status}: ${response.statusText}`);
  }

  return response.json();
}

// Usage
const events = await getActiveEvents(10);
events.forEach(event => {
  console.log(`${event.title} (${event.markets?.length || 0} markets)`);
  event.markets?.forEach(market => {
    const prices = JSON.parse(market.outcomePrices || "[]");
    const yesPrice = (parseFloat(prices[0]) * 100).toFixed(0);
    console.log(`  - ${market.question}: Yes ${yesPrice}%`);
  });
});

2. Fetch Markets with Pagination (Node.js)

const GAMMA_API = "https://gamma-api.polymarket.com";

async function getAllActiveMarkets() {
  const allMarkets = [];
  let offset = 0;
  const limit = 100;

  while (true) {
    const url = `${GAMMA_API}/markets?limit=${limit}&offset=${offset}&active=true`;
    const response = await fetch(url);
    const markets = await response.json();

    if (!markets.length) break;

    allMarkets.push(...markets);
    offset += limit;

    // Respect rate limits
    await new Promise(resolve => setTimeout(resolve, 200));
  }

  return allMarkets;
}

const markets = await getAllActiveMarkets();
console.log(`Total active markets: ${markets.length}`);

3. Get Order Book (Node.js)

const CLOB_API = "https://clob.polymarket.com";

async function getOrderBook(tokenId) {
  const url = `${CLOB_API}/book?token_id=${tokenId}`;
  const response = await fetch(url);
  return response.json();
}

async function getSpread(tokenId) {
  const book = await getOrderBook(tokenId);
  const bestBid = parseFloat(book.bids?.[0]?.price || 0);
  const bestAsk = parseFloat(book.asks?.[0]?.price || 1);
  const spread = bestAsk - bestBid;
  const mid = (bestBid + bestAsk) / 2;

  return { bestBid, bestAsk, spread, mid };
}

// Usage
const tokenId = "YOUR_TOKEN_ID";
const { bestBid, bestAsk, spread, mid } = await getSpread(tokenId);
console.log(`Best Bid: $${bestBid.toFixed(3)}`);
console.log(`Best Ask: $${bestAsk.toFixed(3)}`);
console.log(`Spread:   $${spread.toFixed(3)} (${(spread / mid * 100).toFixed(1)}%)`);

4. Build a Simple Price Dashboard

const GAMMA_API = "https://gamma-api.polymarket.com";

async function buildDashboard() {
  const url = `${GAMMA_API}/markets?limit=20&active=true&order=volume24hr&ascending=false`;
  const response = await fetch(url);
  const markets = await response.json();

  console.log("=== TOP 20 POLYMARKET MARKETS BY VOLUME ===\n");
  console.log("Market".padEnd(55) + "Yes".padStart(8) + "Volume 24h".padStart(15));
  console.log("-".repeat(78));

  markets.forEach(market => {
    const prices = JSON.parse(market.outcomePrices || "[]");
    const yesPrice = prices[0] ? `${(parseFloat(prices[0]) * 100).toFixed(0)}%` : "N/A";
    const vol24h = market.volume24hr
      ? `$${Number(market.volume24hr).toLocaleString()}`
      : "$0";

    const question = market.question?.substring(0, 52) || "Unknown";
    console.log(question.padEnd(55) + yesPrice.padStart(8) + vol24h.padStart(15));
  });
}

buildDashboard();

Use Cases: Bots, Dashboards, Analytics

The Polymarket API opens up a wide range of possibilities for developers and traders. Here are the most common use cases:

1. Price Tracking Dashboards

Build custom dashboards that show real-time Polymarket prices alongside other data sources. Pull event data from the Gamma API, display it with your preferred charting library (D3.js, Chart.js, Recharts), and auto-refresh on a timer. PredScope is an example of this — we aggregate prices from multiple prediction markets into a single dashboard.

2. Automated Trading Bots

Use the CLOB API with the py_clob_client library to build bots that trade based on signals. Common strategies include:

3. Data Analytics & Research

Researchers and journalists use the Gamma API to track how prediction market odds change over time. Pull historical data, analyze calibration, and study how markets respond to news events.

4. Portfolio Tracking

Build tools that track your Polymarket positions across multiple markets, calculate P&L, and alert you to significant price changes.

5. Spreadsheet Integration

Use Google Apps Script or Python to pull Polymarket prices directly into Google Sheets or Excel. Great for tracking a watchlist of markets without building a full application.

# Quick script to export top markets to CSV
import requests
import csv
import json

markets = requests.get(
    "https://gamma-api.polymarket.com/markets",
    params={"limit": 50, "active": "true", "order": "volume24hr", "ascending": "false"}
).json()

with open("polymarket_data.csv", "w", newline="") as f:
    writer = csv.writer(f)
    writer.writerow(["Question", "Yes Price", "No Price", "Volume 24h", "Total Volume"])
    for m in markets:
        prices = json.loads(m.get("outcomePrices", "[]"))
        writer.writerow([
            m.get("question", ""),
            prices[0] if len(prices) > 0 else "",
            prices[1] if len(prices) > 1 else "",
            m.get("volume24hr", 0),
            m.get("volume", 0)
        ])

print(f"Exported {len(markets)} markets to polymarket_data.csv")

6. Cross-Platform Arbitrage Detection

import requests
import json

def find_arbitrage_opportunities():
    """Compare Polymarket prices against other platforms."""
    # Fetch Polymarket markets
    poly_markets = requests.get(
        "https://gamma-api.polymarket.com/markets",
        params={"limit": 100, "active": "true"}
    ).json()

    opportunities = []
    for market in poly_markets:
        prices = json.loads(market.get("outcomePrices", "[]"))
        if len(prices) < 2:
            continue

        yes_price = float(prices[0])
        no_price = float(prices[1])

        # Check if Yes + No prices deviate from 1.00
        # (indicates potential mispricing)
        total = yes_price + no_price
        if abs(total - 1.0) > 0.02:
            opportunities.append({
                "question": market["question"],
                "yes": yes_price,
                "no": no_price,
                "sum": total,
                "deviation": abs(total - 1.0)
            })

    # Sort by deviation
    opportunities.sort(key=lambda x: x["deviation"], reverse=True)
    return opportunities

opps = find_arbitrage_opportunities()
for opp in opps[:10]:
    print(f"{opp['question'][:60]}")
    print(f"  Yes: {opp['yes']:.3f} | No: {opp['no']:.3f} | Sum: {opp['sum']:.3f}\n")

Start Building with Polymarket

Create a free account to access trading APIs and build on the world's largest prediction market.

Sign Up on Polymarket → Compare All APIs

Polymarket API vs. Kalshi API

Kalshi and Polymarket are the two biggest prediction market platforms with developer APIs. Here is how they compare:

Feature Polymarket API Kalshi API
Base URL gamma-api.polymarket.com trading-api.kalshi.com
Auth (read) None required API key required
Auth (trade) Polygon wallet + private key API key + secret
Cost Free Free
Documentation Community docs, GitHub Official docs site
Client libraries py_clob_client (Python) Official Python & JS SDKs
Rate limits ~10 req/s (undocumented) 10 req/s (documented, headers)
WebSocket Yes (CLOB) Yes
Settlement USDC on Polygon blockchain USD (traditional)
Market count 1,000+ active 300+ active
Volume Higher (crypto-native) Lower but growing
Regulation Unregulated (offshore) CFTC-regulated (US)

When to Use Polymarket's API

When to Use Kalshi's API

For a broader comparison, see our best prediction markets guide or the full prediction market API overview.

Frequently Asked Questions

Is the Polymarket API free to use?

Yes. Both the Gamma API and CLOB API are completely free. There are no API fees, no usage tiers, and no payment required. Read-only endpoints require no authentication at all. For trading, you only pay standard Polymarket trading fees (near-zero) and Polygon gas fees.

Do I need an API key for Polymarket?

No API key is needed for read-only operations. You can fetch events, markets, prices, and order book data without any authentication. For placing trades through the CLOB API, you need a Polygon wallet with a private key to sign orders — but there is no separate API key registration system like traditional APIs.

What is the difference between the Gamma API and CLOB API?

The Gamma API (gamma-api.polymarket.com) is for read-only market data — listing events, markets, prices, and metadata. The CLOB API (clob.polymarket.com) is for the order book — viewing bids/asks, getting real-time prices, and placing or canceling trades. Use Gamma for data and analytics, and CLOB for trading.

What are the Polymarket API rate limits?

Polymarket does not publish official rate limits. Based on community testing, the Gamma API allows approximately 10 requests per second, and the CLOB API is slightly stricter. If you hit rate limits, you will receive a 429 HTTP status code. Implement exponential backoff and caching to stay within limits.

Can I build a trading bot with the Polymarket API?

Yes. The CLOB API supports programmatic order placement. Use the py_clob_client Python library to create, sign, and submit orders. You will need a funded Polygon wallet, a trading strategy, and robust error handling. Many traders use bots for market making, arbitrage, and automated position management on Polymarket.

Does Polymarket have a WebSocket API?

Yes. The CLOB API supports WebSocket connections for real-time order book updates and trade notifications. This is essential for building low-latency trading bots and live dashboards. The WebSocket feed provides instant price updates without the overhead and latency of polling REST endpoints.

How do I get historical price data from Polymarket?

The Gamma API provides current prices but limited historical data. For historical price tracking, you can poll the API periodically and store results in your own database, or use third-party data providers that archive Polymarket prices. Some community-built tools on GitHub also offer historical data exports.

Can I use the Polymarket API from a browser (frontend JavaScript)?

The Gamma API supports CORS and can be called directly from browser-based JavaScript. The CLOB API read endpoints also work from the browser. However, you should never expose wallet private keys in frontend code. For trading functionality, use a backend server to sign and submit orders securely.

Trade on Polymarket

The world's largest prediction market — near-zero fees, deep liquidity, and open APIs.

Visit Polymarket → Compare All Platforms

Get Prediction Market Insights

Weekly analysis of prediction market trends, API updates, and trading strategies. Free, no spam.

Join 2,000+ traders and developers.

Related Guides

See also: Kalshi API — learn more about Kalshi API.

Related guides: Polymarket App Polymarket US Polymarket Promo Code Is Polymarket Legal? Is Polymarket Safe?

More guides: Polymarket Invite Code How to Bet on Polymarket