Update Polymarket documentation (2026-02-19)

- Added new documentation URLs from llms.txt index
- Updated TARGET.md with 244 total documentation pages
- Scraped new pages for trading, concepts, and API reference sections
- Updated changelog and new index pages
This commit is contained in:
AI Agent
2026-02-19 14:31:02 +01:00
parent 81f77eff3c
commit b2a29fe51f
250 changed files with 33306 additions and 9659 deletions
+118 -154
View File
@@ -2,195 +2,159 @@
> Fetch the complete documentation index at: https://docs.polymarket.com/llms.txt
> Use this file to discover all available pages before exploring further.
# Fetching Market Data
# Fetching Markets
> Fetch Polymarket data in minutes with no authentication required
Get market data with zero setup. No API key, no authentication, no wallet required.
***
## Understanding the Data Model
Before fetching data, understand how Polymarket structures its markets:
<Steps>
<Step title="Event">
The top-level object representing a question like "Will X happen?"
</Step>
<Step title="Market">
Each event contains one or more markets. Each market is a specific tradable binary outcome.
</Step>
<Step title="Outcomes & Prices">
Markets have `outcomes` and `outcomePrices` arrays that map 1:1. These prices represent implied probabilities.
</Step>
</Steps>
```json theme={null}
{
"outcomes": "[\"Yes\", \"No\"]",
"outcomePrices": "[\"0.20\", \"0.80\"]"
}
// Index 0: "Yes" → 0.20 (20% probability)
// Index 1: "No" → 0.80 (80% probability)
```
***
## Fetch Active Events
List all currently active events on Polymarket:
```bash theme={null}
curl "https://gamma-api.polymarket.com/events?active=true&closed=false&limit=5"
```
<Accordion title="Example Response">
```json theme={null}
[
{
"id": "123456",
"slug": "will-bitcoin-reach-100k-by-2025",
"title": "Will Bitcoin reach $100k by 2025?",
"active": true,
"closed": false,
"tags": [
{ "id": "21", "label": "Crypto", "slug": "crypto" }
],
"markets": [
{
"id": "789",
"question": "Will Bitcoin reach $100k by 2025?",
"clobTokenIds": ["TOKEN_YES_ID", "TOKEN_NO_ID"],
"outcomes": "[\"Yes\", \"No\"]",
"outcomePrices": "[\"0.65\", \"0.35\"]"
}
]
}
]
```
</Accordion>
> Three strategies for discovering and querying markets
<Tip>
Always use `active=true&closed=false` to filter for live, tradable events.
Both the events and markets endpoints are paginated. See
[pagination](#pagination) for details.
</Tip>
***
There are three main strategies for retrieving market data, each optimized for different use cases:
## Market Discovery Best Practices
### For Sports Events
Use the `/sports` endpoint to discover leagues, then query by `series_id`:
```bash theme={null}
# Get all supported sports leagues
curl "https://gamma-api.polymarket.com/sports"
# Get events for a specific league (e.g., NBA series_id=10345)
curl "https://gamma-api.polymarket.com/events?series_id=10345&active=true&closed=false"
# Filter to just game bets (not futures) using tag_id=100639
curl "https://gamma-api.polymarket.com/events?series_id=10345&tag_id=100639&active=true&closed=false&order=startTime&ascending=true"
```
<Note>
`/sports` only returns automated leagues. For others (UFC, Boxing, F1, Golf, Chess), use tag IDs via `/events?tag_id=<tag_id>`.
</Note>
### For Non-Sports Topics
Use `/tags` to discover all available categories, then filter events:
```bash theme={null}
# Get all available tags
curl "https://gamma-api.polymarket.com/tags?limit=100"
# Query events by topic
curl "https://gamma-api.polymarket.com/events?tag_id=2&active=true&closed=false"
```
<Tip>
Each event response includes a `tags` array, useful for discovering categories from live data and building your own tag mapping.
</Tip>
1. **By Slug** — Best for fetching specific individual markets or events
2. **By Tags** — Ideal for filtering markets by category or sport
3. **Via Events Endpoint** — Most efficient for retrieving all active markets
***
## Get Market Details
## Fetch by Slug
Once you have an event, get details for a specific market using its ID or slug:
**Use case:** When you need to retrieve a specific market or event that you already know about.
```bash theme={null}
curl "https://gamma-api.polymarket.com/markets?slug=will-bitcoin-reach-100k-by-2025"
Individual markets and events are best fetched using their unique slug identifier. The slug can be found directly in the Polymarket frontend URL.
### How to Extract the Slug
From any Polymarket URL, the slug is the path segment after `/event/`:
```
https://polymarket.com/event/fed-decision-in-october
Slug: fed-decision-in-october
```
The response includes `clobTokenIds`, you'll need these to fetch prices and place orders.
### Examples
```bash theme={null}
# Fetch an event by slug (query parameter)
curl "https://gamma-api.polymarket.com/events?slug=fed-decision-in-october"
# Or use the path endpoint
curl "https://gamma-api.polymarket.com/events/slug/fed-decision-in-october"
```
```bash theme={null}
# Fetch a market by slug (query parameter)
curl "https://gamma-api.polymarket.com/markets?slug=fed-decision-in-october"
# Or use the path endpoint
curl "https://gamma-api.polymarket.com/markets/slug/fed-decision-in-october"
```
***
## Get Current Price
## Fetch by Tags
Query the CLOB for the current price of any token:
**Use case:** When you want to filter markets by category, sport, or topic.
Tags provide a way to categorize and filter markets. You can discover available tags and then use them to filter your requests.
### Discover Available Tags
**General tags:** `GET /tags` (Gamma API)
**Sports tags and metadata:** `GET /sports` (Gamma API)
The `/sports` endpoint returns metadata for sports including tag IDs, images, resolution sources, and series information.
### Filter by Tag
Once you have tag IDs, use the `tag_id` parameter in both events and markets endpoints:
```bash theme={null}
curl "https://clob.polymarket.com/price?token_id=YOUR_TOKEN_ID&side=buy"
# Fetch events for a specific tag
curl "https://gamma-api.polymarket.com/events?tag_id=100381&limit=10&active=true&closed=false"
```
<Accordion title="Example Response">
```json theme={null}
{
"price": "0.65"
}
```
</Accordion>
### Additional Tag Filtering
You can also:
* Use `related_tags=true` to include related tag markets
* Exclude specific tags with `exclude_tag_id`
```bash theme={null}
# Include related tags
curl "https://gamma-api.polymarket.com/events?tag_id=100381&related_tags=true&active=true&closed=false"
```
***
## Get Orderbook Depth
## Fetch All Active Markets
See all bids and asks for a market:
**Use case:** When you need to retrieve all available active markets, typically for broader analysis or market discovery.
The most efficient approach is to use the events endpoint with `active=true&closed=false`, as events contain their associated markets.
```bash theme={null}
curl "https://clob.polymarket.com/book?token_id=YOUR_TOKEN_ID"
curl "https://gamma-api.polymarket.com/events?active=true&closed=false&limit=100"
```
<Accordion title="Example Response">
```json theme={null}
{
"market": "0x...",
"asset_id": "YOUR_TOKEN_ID",
"bids": [
{ "price": "0.64", "size": "500" },
{ "price": "0.63", "size": "1200" }
],
"asks": [
{ "price": "0.66", "size": "300" },
{ "price": "0.67", "size": "800" }
]
}
```
</Accordion>
### Key Parameters
| Parameter | Description |
| ----------- | ---------------------------------------------------------------------------------------------------------------- |
| `order` | Field to order by (`volume_24hr`, `volume`, `liquidity`, `start_date`, `end_date`, `competitive`, `closed_time`) |
| `ascending` | Sort direction (`true` for ascending, `false` for descending). Default: `false` |
| `active` | Filter by active status (`true` for live tradable events) |
| `closed` | Filter by closed status |
| `limit` | Results per page |
| `offset` | Number of results to skip for pagination |
```bash theme={null}
# Get the highest volume active events
curl "https://gamma-api.polymarket.com/events?active=true&closed=false&order=volume_24hr&ascending=false&limit=100"
```
***
## More Data APIs
## Pagination
All list endpoints return paginated responses with `limit` and `offset` parameters:
```bash theme={null}
# Page 1: First 50 results
curl "https://gamma-api.polymarket.com/events?active=true&closed=false&limit=50&offset=0"
# Page 2: Next 50 results
curl "https://gamma-api.polymarket.com/events?active=true&closed=false&limit=50&offset=50"
# Page 3: Next 50 results
curl "https://gamma-api.polymarket.com/events?active=true&closed=false&limit=50&offset=100"
```
***
## Best Practices
1. **For individual markets:** Use the slug method for direct lookups
2. **For category browsing:** Use tag filtering to reduce API calls
3. **For complete market discovery:** Use the events endpoint with pagination
4. **Always include `active=true&closed=false`** unless you specifically need historical data
5. **Use the events endpoint** and work backwards — events contain their associated markets, reducing the number of API calls needed
***
## Next Steps
<CardGroup cols={2}>
<Card title="Gamma API" icon="database" href="/developers/gamma-markets-api/overview">
Deep dive into market discovery
<Card title="API Reference" icon="code" href="/api-reference/introduction">
Full endpoint documentation with parameters and response schemas.
</Card>
<Card title="Data API" icon="table" href="/developers/misc-endpoints/data-api-get-positions">
Positions, activity, and holders data
</Card>
<Card title="WebSocket" icon="bolt" href="/developers/CLOB/websocket/wss-overview">
Real-time orderbook updates
</Card>
<Card title="RTDS" icon="signal-stream" href="/developers/RTDS/RTDS-overview">
Real-time data streaming service
<Card title="Subgraph" icon="share-nodes" href="/market-data/subgraph">
Query onchain data directly from the Polymarket subgraph.
</Card>
</CardGroup>
+170 -245
View File
@@ -2,301 +2,226 @@
> Fetch the complete documentation index at: https://docs.polymarket.com/llms.txt
> Use this file to discover all available pages before exploring further.
# Placing Your First Order
# Quickstart
> Set up authentication and submit your first trade
> Place your first order on Polymarket
This guide walks you through placing an order on Polymarket using your own wallet.
This guide walks you through placing an order on Polymarket end-to-end.
***
<Steps>
<Step title="Install the SDK">
<CodeGroup>
```bash TypeScript theme={null}
npm install @polymarket/clob-client ethers@5
```
## Installation
```bash Python theme={null}
pip install py-clob-client
```
</CodeGroup>
</Step>
<CodeGroup>
```bash TypeScript theme={null}
npm install @polymarket/clob-client ethers@5
```
<Step title="Set Up Your Client">
Derive your API credentials and initialize the trading client. This example uses an EOA wallet (type `0`) — your wallet pays its own gas and acts as the funder:
```bash Python theme={null}
pip install py-clob-client
```
<CodeGroup>
```typescript TypeScript theme={null}
import { ClobClient } from "@polymarket/clob-client";
import { Wallet } from "ethers"; // v5.8.0
```bash Rust theme={null}
cargo add polymarket-client-sdk
```
</CodeGroup>
const HOST = "https://clob.polymarket.com";
const CHAIN_ID = 137; // Polygon mainnet
const signer = new Wallet(process.env.PRIVATE_KEY);
***
// Derive API credentials
const tempClient = new ClobClient(HOST, CHAIN_ID, signer);
const apiCreds = await tempClient.createOrDeriveApiKey();
## Step 1: Initialize Client with Private Key
// Initialize trading client
const client = new ClobClient(
HOST,
CHAIN_ID,
signer,
apiCreds,
0, // EOA
signer.address,
);
```
<CodeGroup>
```typescript TypeScript theme={null}
import { ClobClient } from "@polymarket/clob-client";
import { Wallet } from "ethers"; // v5.8.0
```python Python theme={null}
from py_clob_client.client import ClobClient
import os
const HOST = "https://clob.polymarket.com";
const CHAIN_ID = 137; // Polygon mainnet
const signer = new Wallet(process.env.PRIVATE_KEY);
host = "https://clob.polymarket.com"
chain_id = 137 # Polygon mainnet
private_key = os.getenv("PRIVATE_KEY")
const client = new ClobClient(HOST, CHAIN_ID, signer);
```
# Derive API credentials
temp_client = ClobClient(host, key=private_key, chain_id=chain_id)
api_creds = temp_client.create_or_derive_api_creds()
```python Python theme={null}
from py_clob_client.client import ClobClient
import os
# Initialize trading client
client = ClobClient(
host,
key=private_key,
chain_id=chain_id,
creds=api_creds,
signature_type=0, # EOA
funder="YOUR_WALLET_ADDRESS"
)
```
</CodeGroup>
host = "https://clob.polymarket.com"
chain_id = 137 # Polygon mainnet
private_key = os.getenv("PRIVATE_KEY")
<Note>
If you have a Polymarket.com account, your funds are in a proxy wallet — use
signature type `1` or `2` instead. See [Signature
Types](/trading/overview#signature-types) for details.
</Note>
client = ClobClient(host, key=private_key, chain_id=chain_id)
```
</CodeGroup>
<Warning>
Before trading, your funder address needs **USDC.e** (for buying outcome
tokens) and **POL** (for gas, if using EOA type `0`). Proxy wallet users
(types `1` and `2`) can use Polymarket's gasless relayer instead.
</Warning>
</Step>
***
<Step title="Place an Order">
Get a token ID from the [Markets API](/market-data/fetching-markets), then create and submit your order:
## Step 2: Derive User API Credentials
<CodeGroup>
```typescript TypeScript theme={null}
import { Side, OrderType } from "@polymarket/clob-client";
Your private key is used once to derive API credentials. These credentials authenticate all subsequent requests.
const response = await client.createAndPostOrder(
{
tokenID: "YOUR_TOKEN_ID",
price: 0.5,
size: 10,
side: Side.BUY,
},
{
tickSize: "0.01",
negRisk: false, // Set to true for multi-outcome markets
},
OrderType.GTC,
);
<CodeGroup>
```typescript TypeScript theme={null}
// Get existing API key, or create one if none exists
const userApiCreds = await client.createOrDeriveApiKey();
console.log("Order ID:", response.orderID);
console.log("Status:", response.status);
```
console.log("API Key:", userApiCreds.apiKey);
console.log("Secret:", userApiCreds.secret);
console.log("Passphrase:", userApiCreds.passphrase);
```
```python Python theme={null}
from py_clob_client.clob_types import OrderArgs, OrderType
from py_clob_client.order_builder.constants import BUY
```python Python theme={null}
# Get existing API key, or create one if none exists
user_api_creds = client.create_or_derive_api_creds()
response = client.create_and_post_order(
OrderArgs(
token_id="YOUR_TOKEN_ID",
price=0.50,
size=10,
side=BUY,
),
options={
"tick_size": "0.01",
"neg_risk": False, # Set to True for multi-outcome markets
},
order_type=OrderType.GTC
)
print("API Key:", user_api_creds["apiKey"])
print("Secret:", user_api_creds["secret"])
print("Passphrase:", user_api_creds["passphrase"])
```
</CodeGroup>
print("Order ID:", response["orderID"])
print("Status:", response["status"])
```
</CodeGroup>
***
<Tip>
Look up a market's `tickSize` and `negRisk` values using the SDK's
`getTickSize()` and `getNegRisk()` methods, or from the market object returned
by the API.
</Tip>
</Step>
## Step 3: Configure Signature Type and Funder
<Step title="Check Your Orders">
<CodeGroup>
```typescript TypeScript theme={null}
// View all open orders
const openOrders = await client.getOpenOrders();
console.log(`You have ${openOrders.length} open orders`);
Before reinitializing the client, determine your **signature type** and **funder address**:
// View your trade history
const trades = await client.getTrades();
console.log(`You've made ${trades.length} trades`);
| How do you want to trade? | Type | Value | Funder Address |
| ----------------------------------------------------------------------------------------- | ------------ | ----- | ------------------------- |
| I want to use an EOA wallet. It holds USDCe and position tokens, and I'll pay my own gas. | EOA | `0` | Your EOA wallet address |
| I want to trade through my Polymarket.com account (Magic Link email/Google login). | POLY\_PROXY | `1` | Your proxy wallet address |
| I want to trade through my Polymarket.com account (browser wallet connection). | GNOSIS\_SAFE | `2` | Your proxy wallet address |
// Cancel an order
await client.cancelOrder(response.orderID);
```
<Note>
If you have a Polymarket.com account, your funds are in a proxy wallet (visible in the profile dropdown). Use type 1 or 2. Type 0 is for standalone EOA wallets only.
</Note>
```python Python theme={null}
# View all open orders
open_orders = client.get_orders()
print(f"You have {len(open_orders)} open orders")
***
# View your trade history
trades = client.get_trades()
print(f"You've made {len(trades)} trades")
## Step 4: Reinitialize with Full Authentication
<CodeGroup>
```typescript TypeScript theme={null}
// Choose based on your wallet type (see table above)
const SIGNATURE_TYPE = 0; // EOA example
const FUNDER_ADDRESS = signer.address; // For EOA, funder is your wallet
const client = new ClobClient(
HOST,
CHAIN_ID,
signer,
userApiCreds,
SIGNATURE_TYPE,
FUNDER_ADDRESS
);
```
```python Python theme={null}
# Choose based on your wallet type (see table above)
signature_type = 0 # EOA example
funder_address = "YOUR_WALLET_ADDRESS" # For EOA, funder is your wallet
client = ClobClient(
host,
key=private_key,
chain_id=chain_id,
creds=user_api_creds,
signature_type=signature_type,
funder=funder_address
)
```
</CodeGroup>
<Warning>
**Do not use Builder API credentials in place of User API credentials!** Builder credentials are for order attribution, not user authentication. See [Builder Order Attribution](/developers/builders/order-attribution).
</Warning>
***
## Step 5: Place an Order
Now you're ready to trade! First, get a token ID from the [Gamma API](/developers/gamma-markets-api/get-markets).
<CodeGroup>
```typescript TypeScript theme={null}
import { Side, OrderType } from "@polymarket/clob-client";
// Get market info first
const market = await client.getMarket("TOKEN_ID");
const response = await client.createAndPostOrder(
{
tokenID: "TOKEN_ID",
price: 0.50, // Price per share ($0.50)
size: 10, // Number of shares
side: Side.BUY, // BUY or SELL
},
{
tickSize: market.tickSize,
negRisk: market.negRisk, // true for multi-outcome events
},
OrderType.GTC // Good-Til-Cancelled
);
console.log("Order ID:", response.orderID);
console.log("Status:", response.status);
```
```python Python theme={null}
from py_clob_client.clob_types import OrderArgs, OrderType
from py_clob_client.order_builder.constants import BUY
# Get market info first
market = client.get_market("TOKEN_ID")
response = client.create_and_post_order(
OrderArgs(
token_id="TOKEN_ID",
price=0.50, # Price per share ($0.50)
size=10, # Number of shares
side=BUY, # BUY or SELL
),
options={
"tick_size": market["tickSize"],
"neg_risk": market["negRisk"], # True for multi-outcome events
},
order_type=OrderType.GTC # Good-Til-Cancelled
)
print("Order ID:", response["orderID"])
print("Status:", response["status"])
```
</CodeGroup>
***
## Step 6: Check Your Orders
<CodeGroup>
```typescript TypeScript theme={null}
// View all open orders
const openOrders = await client.getOpenOrders();
console.log(`You have ${openOrders.length} open orders`);
// View your trade history
const trades = await client.getTrades();
console.log(`You've made ${trades.length} trades`);
// Cancel an order
await client.cancelOrder(response.orderID);
```
```python Python theme={null}
# View all open orders
open_orders = trading_client.get_open_orders()
print(f"You have {len(open_orders)} open orders")
# View your trade history
trades = trading_client.get_trades()
print(f"You've made {len(trades)} trades")
# Cancel an order
trading_client.cancel_order(response["orderID"])
```
</CodeGroup>
# Cancel an order
client.cancel(order_id=response["orderID"])
```
</CodeGroup>
</Step>
</Steps>
***
## Troubleshooting
<AccordionGroup>
<Accordion title="Invalid Signature / L2 Auth Not Available">
Wrong private key, signature type, or funder address for the derived User API credentials.
<Accordion title="L2_AUTH_NOT_AVAILABLE / Invalid Signature">
Wrong private key, signature type, or funder address for the derived API credentials.
Double check the following values when creating User API credentials via `createOrDeriveApiKey()`:
* Do not use Builder API credentials in place of User API credentials
* Check `signatureType` matches your account type (0, 1, or 2)
* Check that `signatureType` matches your account type (`0`, `1`, or `2`)
* Ensure `funder` is correct for your wallet type
* Re-derive credentials with `createOrDeriveApiKey()` if unsure
</Accordion>
<Accordion title="Unauthorized / Invalid API Key">
Wrong API key, secret, or passphrase.
<Accordion title="Order rejected: insufficient balance">
Your funder address doesn't have enough tokens:
Re-derive credentials with `createOrDeriveApiKey()` and update your config.
* **BUY orders**: need USDC.e in your funder address
* **SELL orders**: need outcome tokens in your funder address
* Ensure you have more USDC.e than what's committed in open orders
</Accordion>
<Accordion title="Not Enough Balance / Allowance">
Either not enough USDCe / position tokens in your funder address, or you lack approvals to spend your tokens.
<Accordion title="Order rejected: insufficient allowance">
You need to approve the Exchange contract to spend your tokens. This is
typically done through the Polymarket UI on your first trade, or using the CTF
contract's `setApprovalForAll()` method.
</Accordion>
* Deposit USDCe to your funder address.
* Ensure you have more USDCe than what's committed in open orders.
* Check that you've set all necessary token approvals.
<Accordion title="What's my funder address?">
Your funder address is the wallet where your funds are held:
* **EOA (type 0)**: Your wallet address directly
* **Proxy wallet (type 1 or 2)**: Go to [polymarket.com/settings](https://polymarket.com/settings) and look for the wallet address in the profile dropdown
If the proxy wallet doesn't exist, log into Polymarket.com first (it's deployed on first login).
</Accordion>
<Accordion title="Blocked by Cloudflare / Geoblock">
You're trying to place a trade from a restricted region.
See [Geographic Restrictions](/developers/CLOB/geoblock) for details.
You're trying to place a trade from a restricted region. See [Geographic Restrictions](/api-reference/geoblock) for details.
</Accordion>
</AccordionGroup>
***
## Adding Builder API Credentials
## Next Steps
If you're building an app that routes orders for your users, you can add builder credentials to get attribution on the [Builder Leaderboard](https://builders.polymarket.com/):
<CardGroup cols={2}>
<Card title="Create Orders" icon="plus" href="/trading/orders/create">
Order types, tick sizes, and error handling
</Card>
```typescript TypeScript theme={null}
import { BuilderConfig, BuilderApiKeyCreds } from "@polymarket/builder-signing-sdk";
const builderCreds: BuilderApiKeyCreds = {
key: process.env.POLY_BUILDER_API_KEY!,
secret: process.env.POLY_BUILDER_SECRET!,
passphrase: process.env.POLY_BUILDER_PASSPHRASE!,
};
const builderConfig = new BuilderConfig({ localBuilderCreds: builderCreds });
// Add builderConfig as the last parameter
const client = new ClobClient(
HOST,
CHAIN_ID,
signer,
userApiCreds,
signatureType,
funderAddress,
undefined,
false,
builderConfig
);
```
<Info>
Builder credentials are **separate** from user credentials. You use your builder
credentials to tag orders, but each user still needs their own L2 credentials to trade.
</Info>
<Card title="Full Builder Guide" icon="hammer" href="/developers/builders/order-attribution">
Complete documentation for order attribution and gasless transactions
</Card>
<Card title="Order Attribution" icon="tag" href="/trading/orders/attribution">
Attribute orders to your builder account for volume credit
</Card>
</CardGroup>
+98 -81
View File
@@ -2,108 +2,125 @@
> Fetch the complete documentation index at: https://docs.polymarket.com/llms.txt
> Use this file to discover all available pages before exploring further.
# API Rate Limits
# Rate Limits
## How Rate Limiting Works
> API rate limits for all Polymarket endpoints
All rate limits are enforced using Cloudflare's throttling system. When you exceed the maximum configured rate for any endpoint, requests are throttled rather than immediately rejected. This means:
All API rate limits are enforced using Cloudflare's throttling system. When you exceed the limit for any endpoint, requests are throttled (delayed/queued) rather than immediately rejected. Limits reset on sliding time windows.
* **Throttling**: Requests over the limit are delayed/queued rather than dropped
* **Burst Allowances**: Some endpoints allow short bursts above the sustained rate
* **Time Windows**: Limits reset based on sliding time windows (e.g., per 10 seconds, per minute)
***
## General Rate Limits
## General
| Endpoint | Limit | Notes |
| --------------------- | -------------------- | -------------------------------------------------- |
| General Rate Limiting | 15000 requests / 10s | Throttle requests over the maximum configured rate |
| "OK" Endpoint | 100 requests / 10s | Throttle requests over the maximum configured rate |
| Endpoint | Limit |
| --------------------- | ---------------- |
| General rate limiting | 15,000 req / 10s |
| Health check (`/ok`) | 100 req / 10s |
## Data API Rate Limits
***
| Endpoint | Limit | Notes |
| ---------------------------- | ------------------- | -------------------------------------------------- |
| Data API (General) | 1000 requests / 10s | Throttle requests over the maximum configured rate |
| Data API `/trades` | 200 requests / 10s | Throttle requests over the maximum configured rate |
| Data API `/positions` | 150 requests / 10s | Throttle requests over the maximum configured rate |
| Data API `/closed-positions` | 150 requests / 10s | Throttle requests over the maximum configured rate |
| Data API "OK" Endpoint | 100 requests / 10s | Throttle requests over the maximum configured rate |
## Gamma API
## GAMMA API Rate Limits
Base URL: `https://gamma-api.polymarket.com`
| Endpoint | Limit | Notes |
| -------------------------------- | ------------------- | -------------------------------------------------- |
| GAMMA (General) | 4000 requests / 10s | Throttle requests over the maximum configured rate |
| GAMMA Get Comments | 200 requests / 10s | Throttle requests over the maximum configured rate |
| GAMMA `/events` | 500 requests / 10s | Throttle requests over the maximum configured rate |
| GAMMA `/markets` | 300 requests / 10s | Throttle requests over the maximum configured rate |
| GAMMA `/markets` /events listing | 900 requests / 10s | Throttle requests over the maximum configured rate |
| GAMMA Tags | 200 requests / 10s | Throttle requests over the maximum configured rate |
| GAMMA Search | 350 requests / 10s | Throttle requests over the maximum configured rate |
| Endpoint | Limit |
| ------------------------------ | --------------- |
| General | 4,000 req / 10s |
| `/events` | 500 req / 10s |
| `/markets` | 300 req / 10s |
| `/markets` + `/events` listing | 900 req / 10s |
| `/comments` | 200 req / 10s |
| `/tags` | 200 req / 10s |
| `/public-search` | 350 req / 10s |
## CLOB API Rate Limits
***
### General CLOB Endpoints
## Data API
| Endpoint | Limit | Notes |
| ----------------------------- | ------------------- | -------------------------------------------------- |
| CLOB (General) | 9000 requests / 10s | Throttle requests over the maximum configured rate |
| CLOB GET Balance Allowance | 200 requests / 10s | Throttle requests over the maximum configured rate |
| CLOB UPDATE Balance Allowance | 50 requests / 10s | Throttle requests over the maximum configured rate |
Base URL: `https://data-api.polymarket.com`
### CLOB Market Data
| Endpoint | Limit |
| -------------------- | --------------- |
| General | 1,000 req / 10s |
| `/trades` | 200 req / 10s |
| `/positions` | 150 req / 10s |
| `/closed-positions` | 150 req / 10s |
| Health check (`/ok`) | 100 req / 10s |
| Endpoint | Limit | Notes |
| ----------------- | ------------------- | -------------------------------------------------- |
| CLOB `/book` | 1500 requests / 10s | Throttle requests over the maximum configured rate |
| CLOB `/books` | 500 requests / 10s | Throttle requests over the maximum configured rate |
| CLOB `/price` | 1500 requests / 10s | Throttle requests over the maximum configured rate |
| CLOB `/prices` | 500 requests / 10s | Throttle requests over the maximum configured rate |
| CLOB `/midprice` | 1500 requests / 10s | Throttle requests over the maximum configured rate |
| CLOB `/midprices` | 500 requests / 10s | Throttle requests over the maximum configured rate |
***
### CLOB Ledger Endpoints
## CLOB API
| Endpoint | Limit | Notes |
| ----------------------------------------------------------- | ------------------ | -------------------------------------------------- |
| CLOB Ledger (`/trades` `/orders` `/notifications` `/order`) | 900 requests / 10s | Throttle requests over the maximum configured rate |
| CLOB Ledger `/data/orders` | 500 requests / 10s | Throttle requests over the maximum configured rate |
| CLOB Ledger `/data/trades` | 500 requests / 10s | Throttle requests over the maximum configured rate |
| CLOB `/notifications` | 125 requests / 10s | Throttle requests over the maximum configured rate |
Base URL: `https://clob.polymarket.com`
### CLOB Markets & Pricing
### General
| Endpoint | Limit | Notes |
| --------------------- | ------------------- | -------------------------------------------------- |
| CLOB Price History | 1000 requests / 10s | Throttle requests over the maximum configured rate |
| CLOB Market Tick Size | 200 requests / 10s | Throttle requests over the maximum configured rate |
| Endpoint | Limit |
| -------------------------- | --------------- |
| General | 9,000 req / 10s |
| `GET` balance allowance | 200 req / 10s |
| `UPDATE` balance allowance | 50 req / 10s |
### CLOB Authentication
### Market Data
| Endpoint | Limit | Notes |
| ------------- | ------------------ | -------------------------------------------------- |
| CLOB API Keys | 100 requests / 10s | Throttle requests over the maximum configured rate |
| Endpoint | Limit |
| ----------------- | --------------- |
| `/book` | 1,500 req / 10s |
| `/books` | 500 req / 10s |
| `/price` | 1,500 req / 10s |
| `/prices` | 500 req / 10s |
| `/midpoint` | 1,500 req / 10s |
| `/midpoints` | 500 req / 10s |
| `/prices-history` | 1,000 req / 10s |
| Market tick size | 200 req / 10s |
### CLOB Trading Endpoints
### Ledger
| Endpoint | Limit | Notes |
| ----------------------------------- | ---------------------------------- | ---------------------------------------------------------- |
| CLOB POST `/order` | 3500 requests / 10s (500/s) | BURST - Throttle requests over the maximum configured rate |
| CLOB POST `/order` | 36000 requests / 10 minutes (60/s) | Throttle requests over the maximum configured rate |
| CLOB DELETE `/order` | 3000 requests / 10s (300/s) | BURST - Throttle requests over the maximum configured rate |
| CLOB DELETE `/order` | 30000 requests / 10 minutes (50/s) | Throttle requests over the maximum configured rate |
| CLOB POST `/orders` | 1000 requests / 10s (100/s) | BURST - Throttle requests over the maximum configured rate |
| CLOB POST `/orders` | 15000 requests / 10 minutes (25/s) | Throttle requests over the maximum configured rate |
| CLOB DELETE `/orders` | 1000 requests / 10s (100/s) | BURST - Throttle requests over the maximum configured rate |
| CLOB DELETE `/orders` | 15000 requests / 10 minutes (25/s) | Throttle requests over the maximum configured rate |
| CLOB DELETE `/cancel-all` | 250 requests / 10s (25/s) | BURST - Throttle requests over the maximum configured rate |
| CLOB DELETE `/cancel-all` | 6000 requests / 10 minutes (10/s) | Throttle requests over the maximum configured rate |
| CLOB DELETE `/cancel-market-orders` | 1000 requests / 10s (100/s) | BURST - Throttle requests over the maximum configured rate |
| CLOB DELETE `/cancel-market-orders` | 1500 requests / 10 minutes (25/s) | Throttle requests over the maximum configured rate |
| Endpoint | Limit |
| ------------------------------------------------ | ------------- |
| `/trades`, `/orders`, `/notifications`, `/order` | 900 req / 10s |
| `/data/orders` | 500 req / 10s |
| `/data/trades` | 500 req / 10s |
| `/notifications` | 125 req / 10s |
## Other API Rate Limits
### Authentication
| Endpoint | Limit | Notes |
| ----------------- | ---------------------- | -------------------------------------------------- |
| RELAYER `/submit` | 25 requests / 1 minute | Throttle requests over the maximum configured rate |
| User PNL API | 200 requests / 10s | Throttle requests over the maximum configured rate |
| Endpoint | Limit |
| ----------------- | ------------- |
| API key endpoints | 100 req / 10s |
### Trading
Trading endpoints have both **burst** limits (short spikes allowed) and **sustained** limits (longer-term average).
| Endpoint | Burst Limit | Sustained Limit |
| ------------------------------ | --------------- | ------------------- |
| `POST /order` | 3,500 req / 10s | 36,000 req / 10 min |
| `DELETE /order` | 3,000 req / 10s | 30,000 req / 10 min |
| `POST /orders` | 1,000 req / 10s | 15,000 req / 10 min |
| `DELETE /orders` | 1,000 req / 10s | 15,000 req / 10 min |
| `DELETE /cancel-all` | 250 req / 10s | 6,000 req / 10 min |
| `DELETE /cancel-market-orders` | 1,000 req / 10s | 1,500 req / 10 min |
***
## Other
| Endpoint | Limit |
| ----------------- | -------------- |
| Relayer `/submit` | 25 req / 1 min |
| User PNL API | 200 req / 10s |
***
## Next Steps
<CardGroup cols={2}>
<Card title="Authentication" icon="key" href="/api-reference/authentication">
Learn how to authenticate trading requests.
</Card>
<Card title="Clients & SDKs" icon="cube" href="/api-reference/clients-sdks">
Official TypeScript, Python, and Rust libraries.
</Card>
</CardGroup>
+202 -103
View File
@@ -2,121 +2,220 @@
> Fetch the complete documentation index at: https://docs.polymarket.com/llms.txt
> Use this file to discover all available pages before exploring further.
# Developer Quickstart
# Quickstart
> Get started building with Polymarket APIs
> Fetch a market and place your first order
Polymarket provides a suite of APIs and SDKs for building prediction market applications. This guide will help you understand what's available and where to find it.
Get up and running with the Polymarket API in minutes — fetch market data and place your first order.
<Steps>
<Step title="Fetch a Market">
All data endpoints are public — no API key or authentication needed. Use the markets endpoint to find a market and get its token IDs:
<Tabs>
<Tab title="cURL">
```bash theme={null}
curl "https://gamma-api.polymarket.com/markets?active=true&closed=false&limit=1"
```
</Tab>
<Tab title="TypeScript">
```typescript theme={null}
const response = await fetch(
"https://gamma-api.polymarket.com/markets?active=true&closed=false&limit=1"
);
const markets = await response.json();
const market = markets[0];
console.log(market.question);
console.log(market.clobTokenIds);
// ["123456...", "789012..."] — [Yes token ID, No token ID]
```
</Tab>
<Tab title="Python">
```python theme={null}
import requests
response = requests.get(
"https://gamma-api.polymarket.com/markets",
params={"active": "true", "closed": "false", "limit": 1}
)
markets = response.json()
market = markets[0]
print(market["question"])
print(market["clobTokenIds"])
# ["123456...", "789012..."] — [Yes token ID, No token ID]
```
</Tab>
</Tabs>
Save a token ID from `clobTokenIds` — you'll need it to place an order. The first ID is the Yes token, the second is the No token. See [Fetching Markets](/market-data/fetching-markets) for more strategies like fetching by slug, tag, or event.
</Step>
<Step title="Install the SDK">
<CodeGroup>
```bash TypeScript theme={null}
npm install @polymarket/clob-client ethers@5
```
```bash Python theme={null}
pip install py-clob-client
```
</CodeGroup>
</Step>
<Step title="Set Up Your Client">
Derive API credentials and initialize the trading client:
<Tabs>
<Tab title="TypeScript">
```typescript theme={null}
import { ClobClient } from "@polymarket/clob-client";
import { Wallet } from "ethers"; // v5.8.0
const HOST = "https://clob.polymarket.com";
const CHAIN_ID = 137; // Polygon mainnet
const signer = new Wallet(process.env.PRIVATE_KEY);
// Derive API credentials (L1 → L2 auth)
const tempClient = new ClobClient(HOST, CHAIN_ID, signer);
const apiCreds = await tempClient.createOrDeriveApiKey();
// Initialize trading client
const client = new ClobClient(
HOST,
CHAIN_ID,
signer,
apiCreds,
0, // Signature type: 0 = EOA
signer.address, // Funder address
);
```
</Tab>
<Tab title="Python">
```python theme={null}
from py_clob_client.client import ClobClient
import os
host = "https://clob.polymarket.com"
chain_id = 137 # Polygon mainnet
private_key = os.getenv("PRIVATE_KEY")
# Derive API credentials (L1 → L2 auth)
temp_client = ClobClient(host, key=private_key, chain_id=chain_id)
api_creds = temp_client.create_or_derive_api_creds()
# Initialize trading client
client = ClobClient(
host,
key=private_key,
chain_id=chain_id,
creds=api_creds,
signature_type=0, # Signature type: 0 = EOA
funder="YOUR_WALLET_ADDRESS", # Funder address
)
```
</Tab>
</Tabs>
<Note>
This example uses an EOA wallet (signature type `0`) — your wallet pays its
own gas. Proxy wallet users (types `1` and `2`) can use Polymarket's gasless
relayer instead. See [Authentication](/api-reference/authentication) for
details on signature types.
</Note>
<Warning>
Before trading, your funder address needs **USDC.e** (for buying outcome
tokens) and **POL** (for gas, if using EOA type `0`).
</Warning>
</Step>
<Step title="Place an Order">
Use the `token_id` from Step 1 to place a limit order:
<Tabs>
<Tab title="TypeScript">
```typescript theme={null}
import { Side, OrderType } from "@polymarket/clob-client";
// Fetch market details to get tick size and neg risk
const market = await client.getMarket("YOUR_CONDITION_ID");
const tickSize = String(market.minimum_tick_size); // e.g., "0.01"
const negRisk = market.neg_risk; // e.g., false
const response = await client.createAndPostOrder(
{
tokenID: "YOUR_TOKEN_ID", // From Step 1
price: 0.50,
size: 10,
side: Side.BUY,
orderType: OrderType.GTC,
},
{
tickSize,
negRisk,
},
);
console.log("Order ID:", response.orderID);
console.log("Status:", response.status);
```
</Tab>
<Tab title="Python">
```python theme={null}
from py_clob_client.clob_types import OrderArgs, OrderType
from py_clob_client.order_builder.constants import BUY
# Fetch market details to get tick size and neg risk
market = client.get_market("YOUR_CONDITION_ID")
tick_size = str(market["minimum_tick_size"]) # e.g., "0.01"
neg_risk = market["neg_risk"] # e.g., False
response = client.create_and_post_order(
OrderArgs(
token_id="YOUR_TOKEN_ID", # From Step 1
price=0.50,
size=10,
side=BUY,
order_type=OrderType.GTC,
),
options={
"tick_size": tick_size,
"neg_risk": neg_risk,
},
)
print("Order ID:", response["orderID"])
print("Status:", response["status"])
```
</Tab>
</Tabs>
</Step>
</Steps>
***
## What Can You Build?
| If you want to... | Start here |
| ----------------------------- | ------------------------------------------------------------------- |
| Fetch markets & prices | [Fetching Market Data](/quickstart/fetching-data) |
| Place orders for yourself | [Placing Your First Order](/quickstart/first-order) |
| Build a trading app for users | [Builders Program Introduction](/developers/builders/builder-intro) |
| Provide liquidity | [Market Makers](/developers/market-makers/introduction) |
***
## APIs at a Glance
### Markets & Data
## Next Steps
<CardGroup cols={2}>
<Card title="Gamma API" icon="database" href="/developers/gamma-markets-api/overview">
**Market discovery & metadata**
Fetch events, markets, categories, and resolution data. This is where you discover what's tradeable.
`https://gamma-api.polymarket.com`
<Card title="Authentication" icon="lock" href="/api-reference/authentication">
Understand L1/L2 auth, signature types, and API credentials.
</Card>
<Card title="CLOB API" icon="book" href="/developers/CLOB/introduction">
**Prices, orderbooks & trading**
Get real-time prices, orderbook depth, and place orders. The core trading API.
`https://clob.polymarket.com`
<Card title="Trading Quickstart" icon="bolt" href="/trading/quickstart">
Detailed trading guide with order management and troubleshooting.
</Card>
<Card title="Data API" icon="chart-bar" href="/developers/misc-endpoints/data-api-get-positions">
**Positions, activity & history**
Query user positions, trade history, and portfolio data.
`https://data-api.polymarket.com`
<Card title="Fetching Markets" icon="magnifying-glass" href="/market-data/fetching-markets">
Strategies for discovering markets by slug, tag, or category.
</Card>
<Card title="WebSocket" icon="bolt" href="/developers/CLOB/websocket/wss-overview">
**Real-time updates**
Subscribe to orderbook changes, price updates, and order status.
`wss://ws-subscriptions-clob.polymarket.com`
</Card>
</CardGroup>
### Additional Data Sources
<CardGroup cols={2}>
<Card title="RTDS" icon="signal-stream" href="/developers/RTDS/RTDS-overview">
**Low-latency data stream**
Real-time crypto prices and comments. Optimized for market makers.
</Card>
<Card title="Subgraph" icon="diagram-project" href="/developers/subgraph/overview">
**Onchain queries**
Query blockchain state directly via GraphQL.
</Card>
</CardGroup>
### Trading Infrastructure
<CardGroup cols={2}>
<Card title="CTF Operations" icon="arrows-split-up-and-left" href="/developers/CTF/overview">
**Token split/merge/redeem**
Convert between USDC and outcome tokens. Essential for inventory management.
</Card>
<Card title="Relayer Client" icon="gas-pump" href="/developers/builders/relayer-client">
**Gasless transactions**
Builders can offer gasfree transactions via Polymarket's relayer.
</Card>
</CardGroup>
***
## SDKs & Libraries
<Card title="CLOB Client (TypeScript)" icon="npm" href="https://github.com/Polymarket/clob-client">
`npm install @polymarket/clob-client`
</Card>
<CardGroup cols={2}>
<Card title="CLOB Client (Python)" icon="python" href="https://github.com/Polymarket/py-clob-client">
`pip install py-clob-client`
</Card>
<Card title="CLOB Client (Rust)" icon="rust" href="https://github.com/Polymarket/rs-clob-client">
`cargo add polymarket-client-sdk`
</Card>
</CardGroup>
For builders routing orders for users:
<CardGroup cols={2}>
<Card title="Relayer Client" icon="bolt" href="https://github.com/Polymarket/builder-relayer-client">
Gasless wallet operations
</Card>
<Card title="Signing SDK" icon="key" href="https://github.com/Polymarket/builder-signing-sdk">
Builder authentication headers
<Card title="Core Concepts" icon="book" href="/concepts/markets-events">
Understand markets, events, prices, and positions.
</Card>
</CardGroup>
+40 -83
View File
@@ -2,101 +2,58 @@
> Fetch the complete documentation index at: https://docs.polymarket.com/llms.txt
> Use this file to discover all available pages before exploring further.
# Endpoints
# Introduction
> All Polymarket API URLs and base endpoints
> Overview of the Polymarket APIs
All base URLs for Polymarket APIs. See individual API documentation for available routes and parameters.
The Polymarket API provides programmatic access to the world's largest prediction market. The platform is served by three separate APIs, each handling a different domain.
***
## REST APIs
## APIs
| API | Base URL | Description |
| ------------- | ---------------------------------- | ------------------------------------ |
| **CLOB API** | `https://clob.polymarket.com` | Order management, prices, orderbooks |
| **Gamma API** | `https://gamma-api.polymarket.com` | Market discovery, metadata, events |
| **Data API** | `https://data-api.polymarket.com` | User positions, activity, history |
<CardGroup cols={1}>
<Card title="Gamma API" icon="database">
**`https://gamma-api.polymarket.com`**
Markets, events, tags, series, comments, sports, search, and public profiles. This is the primary API for discovering and browsing market data.
</Card>
<Card title="Data API" icon="chart-line">
**`https://data-api.polymarket.com`**
User positions, trades, activity, holder data, open interest, leaderboards, and builder analytics.
</Card>
<Card title="CLOB API" icon="arrows-rotate">
**`https://clob.polymarket.com`**
Orderbook data, pricing, midpoints, spreads, and price history. Also handles order placement, cancellation, and other trading operations. Trading endpoints require [authentication](/api-reference/authentication).
</Card>
</CardGroup>
<Info>
A separate **Bridge API** (`https://bridge.polymarket.com`) handles deposits and withdrawals. Bridges are not handled by Polymarket, it is a proxy of fun.xyz service.
</Info>
***
## WebSocket Endpoints
## Authentication
| Service | URL | Description |
| ------------------ | ------------------------------------------------ | ----------------------------------- |
| **CLOB WebSocket** | `wss://ws-subscriptions-clob.polymarket.com/ws/` | Orderbook updates, order status |
| **RTDS** | `wss://ws-live-data.polymarket.com` | Low-latency crypto prices, comments |
The Gamma API and Data API are fully public — no authentication required.
The CLOB API has both public endpoints (orderbook, prices) and authenticated endpoints (order management). See [Authentication](/api-reference/authentication) for details.
***
## Quick Reference
## Next Steps
### CLOB API
<CardGroup cols={2}>
<Card title="Authentication" icon="key" href="/api-reference/authentication">
Learn how to authenticate requests for trading endpoints.
</Card>
```
https://clob.polymarket.com
```
Common endpoints:
* `GET /price` — Get current price for a token
* `GET /book` — Get orderbook for a token
* `GET /midpoint` — Get midpoint price
* `POST /order` — Place an order (auth required)
* `DELETE /order` — Cancel an order (auth required)
[Full CLOB documentation →](/developers/CLOB/introduction)
### Gamma API
```
https://gamma-api.polymarket.com
```
Common endpoints:
* `GET /events` — List events
* `GET /markets` — List markets
* `GET /events/{id}` — Get event details
[Full Gamma documentation →](/developers/gamma-markets-api/overview)
### Data API
```
https://data-api.polymarket.com
```
Common endpoints:
* `GET /positions` — Get user positions
* `GET /activity` — Get user activity
* `GET /trades` — Get trade history
[Full Data API documentation →](/developers/misc-endpoints/data-api-get-positions)
### CLOB WebSocket
```
wss://ws-subscriptions-clob.polymarket.com/ws/
```
Channels:
* `market` — Orderbook and price updates (public)
* `user` — Order status updates (authenticated)
[Full WebSocket documentation →](/developers/CLOB/websocket/wss-overview)
### RTDS (Real-Time Data Stream)
```
wss://ws-live-data.polymarket.com
```
Channels:
* Crypto price feeds
* Comment streams
[Full RTDS documentation →](/developers/RTDS/RTDS-overview)
<Card title="Clients & SDKs" icon="cube" href="/api-reference/clients-sdks">
Official TypeScript, Python, and Rust libraries.
</Card>
</CardGroup>
+1 -79
View File
@@ -1,79 +1 @@
> ## Documentation Index
> Fetch the complete documentation index at: https://docs.polymarket.com/llms.txt
> Use this file to discover all available pages before exploring further.
# Glossary
> Key terms and concepts for Polymarket developers
## Markets & Events
| Term | Definition |
| ---------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| **Event** | A collection of related markets grouped under a common topic. Example: "2024 US Presidential Election" contains markets for each candidate. |
| **Market** | A single tradeable outcome within an event. Each market has a Yes and No side. Corresponds to a condition ID, question ID, and pair of token IDs. |
| **Token** | Represents a position in a specific outcome (Yes or No). Prices range from 0.00 to 1.00. Winning tokens redeem for \$1 USDCe. Also called *outcome token* or referenced by *token ID*. |
| **Token ID** | The unique identifier for a specific outcome token. Required when placing orders or querying prices. |
| **Condition ID** | Onchain identifier for a market's resolution condition. Used in CTF operations. |
| **Question ID** | Identifier linking a market to its resolution oracle (UMA). |
| **Slug** | Human-readable URL identifier for a market or event. Found in Polymarket URLs: `polymarket.com/event/[slug]` |
***
## Trading
| Term | Definition |
| ------------- | -------------------------------------------------------------------------------------------------------------------------- |
| **CLOB** | Central Limit Order Book. Polymarket's off-chain order matching system. Orders are matched here before onchain settlement. |
| **Tick Size** | The minimum price increment for a market. Usually `0.01` (1 cent) or `0.001` (0.1 cent). |
| **Fill** | When an order is matched and executed. Orders can be partially or fully filled. |
***
## Order Types
| Term | Definition |
| ------- | ---------------------------------------------------------------------------------------------------------------- |
| **GTC** | Good-Til-Cancelled. An order that remains open until filled or manually cancelled. |
| **GTD** | Good-Til-Date. An order that expires at a specified time if not filled. |
| **FOK** | Fill-Or-Kill. An order that must be filled entirely and immediately, or it's cancelled. No partial fills. |
| **FAK** | Fill-And-Kill. An order that fills as much as possible immediately, then cancels any remaining unfilled portion. |
***
## Market Types
| Term | Definition |
| --------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------- |
| **Binary Market** | A market with exactly two outcomes: Yes and No. The prices always sum to approximately \$1. |
| **Negative Risk (NegRisk)** | A multi-outcome event where only one outcome can resolve Yes. Requires `negRisk: true` in order parameters. [Details](/developers/neg-risk/overview) |
***
## Wallets
| Term | Definition |
| ------------------ | ------------------------------------------------------------------------------------------------ |
| **EOA** | Externally Owned Account. A standard Ethereum wallet controlled by a private key. |
| **Funder Address** | The wallet address that holds funds and tokens for trading. |
| **Signature Type** | Identifies wallet type when trading. `0` = EOA, `1` = Magic Link proxy, `2` = Gnosis Safe proxy. |
***
## Token Operations (CTF)
| Term | Definition |
| ---------- | ------------------------------------------------------------------------------------ |
| **CTF** | Conditional Token Framework. The onchain smart contracts that manage outcome tokens. |
| **Split** | Convert USDCe into a complete set of outcome tokens (one Yes + one No). |
| **Merge** | Convert a complete set of outcome tokens back into USDCe. |
| **Redeem** | After resolution, exchange winning tokens for \$1 USDCe each. |
***
## Infrastructure
| Term | Definition |
| ----------- | ------------------------------------------------------------------------- |
| **Polygon** | The blockchain network where Polymarket operates. Chain ID: `137`. |
| **USDCe** | The stablecoin used as collateral on Polymarket. Bridged USDC on Polygon. |
null
+140 -120
View File
@@ -2,160 +2,180 @@
> Fetch the complete documentation index at: https://docs.polymarket.com/llms.txt
> Use this file to discover all available pages before exploring further.
# WSS Quickstart
# Overview
The following code samples and explanation will show you how to subscribe to the Marker and User channels of the Websocket.
You'll need your API keys to do this so we'll start with that.
> Real-time market data and trading updates via WebSocket
## Getting your API Keys
Polymarket provides WebSocket channels for near real-time streaming of orderbook data, trades, and personal order activity. There are four available channels: `market`, `user`, `sports`, and `RTDS` (Real-Time Data Socket).
<CodeGroup>
```python DeriveAPIKeys-Python [expandable] theme={null}
from py_clob_client.client import ClobClient
## Channels
host: str = "https://clob.polymarket.com"
key: str = "" #This is your Private Key. If using email login export from https://reveal.magic.link/polymarket otherwise export from your Web3 Application
chain_id: int = 137 #No need to adjust this
POLYMARKET_PROXY_ADDRESS: str = '' #This is the address you deposit/send USDC to to FUND your Polymarket account.
| Channel | Endpoint | Auth |
| ----------------------------------- | ------------------------------------------------------ | -------- |
| Market | `wss://ws-subscriptions-clob.polymarket.com/ws/market` | No |
| User | `wss://ws-subscriptions-clob.polymarket.com/ws/user` | Yes |
| Sports | `wss://sports-api.polymarket.com/ws` | No |
| [RTDS](/market-data/websocket/rtds) | `wss://ws-live-data.polymarket.com` | Optional |
#Select from the following 3 initialization options to matches your login method, and remove any unused lines so only one client is initialized.
### Market Channel
### Initialization of a client using a Polymarket Proxy associated with an Email/Magic account. If you login with your email use this example.
client = ClobClient(host, key=key, chain_id=chain_id, signature_type=1, funder=POLYMARKET_PROXY_ADDRESS)
| Type | Description | Custom Feature |
| ------------------ | ----------------------- | -------------- |
| `book` | Full orderbook snapshot | No |
| `price_change` | Price level updates | No |
| `tick_size_change` | Tick size changes | No |
| `last_trade_price` | Trade executions | No |
| `best_bid_ask` | Best prices update | Yes |
| `new_market` | New market created | Yes |
| `market_resolved` | Market resolution | Yes |
### Initialization of a client using a Polymarket Proxy associated with a Browser Wallet(Metamask, Coinbase Wallet, etc)
client = ClobClient(host, key=key, chain_id=chain_id, signature_type=2, funder=POLYMARKET_PROXY_ADDRESS)
Types marked "Custom Feature" require `custom_feature_enabled: true` in your subscription.
### Initialization of a client that trades directly from an EOA.
client = ClobClient(host, key=key, chain_id=chain_id)
### User Channel
print( client.derive_api_key() )
| Type | Description |
| ------- | --------------------------------------------- |
| `trade` | Trade lifecycle updates (MATCHED → CONFIRMED) |
| `order` | Order placements, updates, and cancellations |
```
### Sports
```javascript DeriveAPIKeys-TS [expandable] theme={null}
//npm install @polymarket/clob-client
//npm install ethers
//Client initialization example and dumping API Keys
import {ClobClient, ApiKeyCreds } from "@polymarket/clob-client";
import { Wallet } from "@ethersproject/wallet";
| Type | Description |
| -------------- | ------------------------------------- |
| `sport_result` | Live game scores, periods, and status |
const host = 'https://clob.polymarket.com';
const signer = new Wallet("YourPrivateKey"); //This is your Private Key. If using email login export from https://reveal.magic.link/polymarket otherwise export from your Web3 Application
## Subscribing
// Initialize the clob client
// NOTE: the signer must be approved on the CTFExchange contract
const clobClient = new ClobClient(host, 137, signer);
Send a subscription message after connecting to specify which data you want to receive.
(async () => {
const apiKey = await clobClient.deriveApiKey();
console.log(apiKey);
})();
```
</CodeGroup>
### Market Channel
## Using those keys to connect to the Market or User Websocket
```json theme={null}
{
"assets_ids": [
"21742633143463906290569050155826241533067272736897614950488156847949938836455",
"48331043336612883890938759509493159234755048973500640148014422747788308965732"
],
"type": "market",
"custom_feature_enabled": true
}
```
<CodeGroup>
```python WSS-Connection [expandable] theme={null}
from websocket import WebSocketApp
import json
import time
import threading
| Field | Type | Description |
| ------------------------ | --------- | ----------------------------------------------------------------- |
| `assets_ids` | string\[] | Token IDs to subscribe to |
| `type` | string | Channel identifier |
| `custom_feature_enabled` | boolean | Enable `best_bid_ask`, `new_market`, and `market_resolved` events |
MARKET_CHANNEL = "market"
USER_CHANNEL = "user"
### User Channel
```json theme={null}
{
"auth": {
"apiKey": "your-api-key",
"secret": "your-api-secret",
"passphrase": "your-passphrase"
},
"markets": ["0x1234...condition_id"],
"type": "user"
}
```
class WebSocketOrderBook:
def __init__(self, channel_type, url, data, auth, message_callback, verbose):
self.channel_type = channel_type
self.url = url
self.data = data
self.auth = auth
self.message_callback = message_callback
self.verbose = verbose
furl = url + "/ws/" + channel_type
self.ws = WebSocketApp(
furl,
on_message=self.on_message,
on_error=self.on_error,
on_close=self.on_close,
on_open=self.on_open,
)
self.orderbooks = {}
<Note>
The `auth` fields (`apiKey`, `secret`, `passphrase`) are **only required for
the user channel**. For the market channel, these fields are optional and can
be omitted.
</Note>
def on_message(self, ws, message):
print(message)
pass
| Field | Type | Description |
| --------- | --------- | -------------------------------------------------- |
| `auth` | object | API credentials (`apiKey`, `secret`, `passphrase`) |
| `markets` | string\[] | Condition IDs to receive events for |
| `type` | string | Channel identifier |
def on_error(self, ws, error):
print("Error: ", error)
exit(1)
<Note>
The user channel subscribes by **condition IDs** (market identifiers), not
asset IDs. Each market has one condition ID but two asset IDs (Yes and No
tokens).
</Note>
def on_close(self, ws, close_status_code, close_msg):
print("closing")
exit(0)
### Sports Channel
def on_open(self, ws):
if self.channel_type == MARKET_CHANNEL:
ws.send(json.dumps({"assets_ids": self.data, "type": MARKET_CHANNEL}))
elif self.channel_type == USER_CHANNEL and self.auth:
ws.send(
json.dumps(
{"markets": self.data, "type": USER_CHANNEL, "auth": self.auth}
)
)
else:
exit(1)
No subscription message required. Connect and start receiving data for all active sports events.
thr = threading.Thread(target=self.ping, args=(ws,))
thr.start()
## Dynamic Subscription
Modify subscriptions without reconnecting.
def subscribe_to_tokens_ids(self, assets_ids):
if self.channel_type == MARKET_CHANNEL:
self.ws.send(json.dumps({"assets_ids": assets_ids, "operation": "subscribe"}))
### Subscribe to more assets
def unsubscribe_to_tokens_ids(self, assets_ids):
if self.channel_type == MARKET_CHANNEL:
self.ws.send(json.dumps({"assets_ids": assets_ids, "operation": "unsubscribe"}))
```json theme={null}
{
"assets_ids": ["new_asset_id_1", "new_asset_id_2"],
"operation": "subscribe",
"custom_feature_enabled": true
}
```
### Unsubscribe from assets
def ping(self, ws):
while True:
ws.send("PING")
time.sleep(10)
```json theme={null}
{
"assets_ids": ["asset_id_to_remove"],
"operation": "unsubscribe"
}
```
def run(self):
self.ws.run_forever()
For the user channel, use `markets` instead of `assets_ids`:
```json theme={null}
{
"markets": ["0x1234...condition_id"],
"operation": "subscribe"
}
```
if __name__ == "__main__":
url = "wss://ws-subscriptions-clob.polymarket.com"
#Complete these by exporting them from your initialized client.
api_key = ""
api_secret = ""
api_passphrase = ""
## Heartbeats
asset_ids = [
"109681959945973300464568698402968596289258214226684818748321941747028805721376",
]
condition_ids = [] # no really need to filter by this one
### Market & User Channels
auth = {"apiKey": api_key, "secret": api_secret, "passphrase": api_passphrase}
Send `PING` every 10 seconds. The server responds with `PONG`.
market_connection = WebSocketOrderBook(
MARKET_CHANNEL, url, asset_ids, auth, None, True
)
user_connection = WebSocketOrderBook(
USER_CHANNEL, url, condition_ids, auth, None, True
)
```
PING
```
market_connection.subscribe_to_tokens_ids(["123"])
# market_connection.unsubscribe_to_tokens_ids(["123"])
### Sports Channel
market_connection.run()
# user_connection.run()
```
</CodeGroup>
The server sends `ping` every 5 seconds. Respond with `pong` within 10 seconds.
```
pong
```
<Warning>
If you don't respond to the server's ping within 10 seconds, the connection
will be closed.
</Warning>
## Troubleshooting
<Accordion title="Connection closes immediately after opening">
Send a valid subscription message immediately after connecting. The server may
close connections that don't subscribe within a timeout period.
</Accordion>
<Accordion title="Connection drops after ~10 seconds">
You're not sending heartbeats. Send `PING` every 10 seconds for market/user
channels, or respond to server `ping` with `pong` for the sports channel.
</Accordion>
<Accordion title="Not receiving any messages">
1. Verify your asset IDs or condition IDs are correct 2. Check that the
markets are active (not resolved) 3. Set `custom_feature_enabled: true` if
expecting `best_bid_ask`, `new_market`, or `market_resolved` events
</Accordion>
<Accordion title="Authentication failed (user channel)">
Verify your API credentials are correct and haven't expired.
</Accordion>