Add scraped Polymarket documentation (117 files)

This commit is contained in:
Etherdrake
2026-02-14 12:59:26 +01:00
parent 26c6b35691
commit 9263557be6
119 changed files with 27955 additions and 0 deletions
+202
View File
@@ -0,0 +1,202 @@
# Polymarket Documentation Scraper Instructions
## Overview
This document contains instructions for scraping Polymarket documentation from `docs.polymarket.com` and organizing it into the GitHub repository.
The target URLs are stored in `TARGET.md` - edit that file to add/remove URLs to scrape.
## How It Works
1. **TARGET.md** - Contains the list of URLs to scrape (one per line)
2. **INSTRUCTIONS.md** - This file with scraping instructions
3. **scrape.sh** - The automation script that reads from TARGET.md
## Quick Start
```bash
cd /home/himalaya/clawd/PolymarketDocumentation
./scrape.sh
```
## Directory Structure
Organize the scraped files into the following structure:
```
PolymarketDocumentation/
├── TARGET.md # Source URLs (edit this file)
├── INSTRUCTIONS.md # This file
├── scrape.sh # Automation script
├── quickstart/
│ ├── overview.md
│ ├── fetching-data.md
│ ├── first-order.md
│ └── reference/
│ ├── glossary.md
│ ├── endpoints.md
│ └── introduction/
│ └── rate-limits.md
├── developers/
│ ├── market-makers/
│ │ ├── introduction.md
│ │ ├── setup.md
│ │ ├── trading.md
│ │ ├── liquidity-rewards.md
│ │ ├── maker-rebates-program.md
│ │ ├── data-feeds.md
│ │ └── inventory.md
│ ├── CLOB/
│ │ ├── introduction.md
│ │ ├── status.md
│ │ ├── quickstart.md
│ │ ├── authentication.md
│ │ ├── geoblock.md
│ │ ├── timeseries.md
│ │ ├── clients/
│ │ │ ├── methods-overview.md
│ │ │ ├── methods-public.md
│ │ │ ├── methods-l1.md
│ │ │ ├── methods-l2.md
│ │ │ └── methods-builder.md
│ │ ├── orders/
│ │ │ ├── orders.md
│ │ │ ├── create-order.md
│ │ │ ├── create-order-batch.md
│ │ │ ├── get-order.md
│ │ │ ├── get-active-order.md
│ │ │ ├── check-scoring.md
│ │ │ ├── cancel-orders.md
│ │ │ └── onchain-order-info.md
│ │ ├── trades/
│ │ │ ├── trades-overview.md
│ │ │ └── trades.md
│ │ └── websocket/
│ │ ├── wss-overview.md
│ │ ├── wss-auth.md
│ │ ├── user-channel.md
│ │ └── market-channel.md
│ ├── sports-websocket/
│ │ ├── overview.md
│ │ ├── message-format.md
│ │ └── quickstart.md
│ ├── RTDS/
│ │ ├── RTDS-overview.md
│ │ ├── RTDS-crypto-prices.md
│ │ └── RTDS-comments.md
│ └── gamma-markets-api/
│ ├── overview.md
│ ├── gamma-structure.md
│ └── fetch-markets-guide.md
├── api-reference/
│ ├── orderbook/
│ │ ├── get-order-book-summary.md
│ │ └── get-multiple-order-books-summaries-by-request.md
│ ├── pricing/
│ │ ├── get-market-price.md
│ │ ├── get-multiple-market-prices.md
│ │ ├── get-multiple-market-prices-by-request.md
│ │ ├── get-midpoint-price.md
│ │ └── get-price-history-for-a-traded-token.md
│ └── spreads/
│ └── get-bid-ask-spreads.md
└── quickstart-websocket/
└── WSS-Quickstart.md
```
## The Scrape Script (scrape.sh)
```bash
#!/bin/bash
# Base URL
BASE_URL="https://docs.polymarket.com"
# Output directory
OUTPUT_DIR="PolymarketDocumentation"
# Create output directory
mkdir -p "$OUTPUT_DIR"
# Read URLs from TARGET.md (skip comments and empty lines)
grep -v '^#' "$OUTPUT_DIR/TARGET.md" | grep -v '^$' | while read -r url; do
# Extract the path portion (remove https://docs.polymarket.com/)
path="${url#https://docs.polymarket.com/}"
# Remove .md extension for directory structure
filename=$(basename "$path" .md)
dir=$(dirname "$path")
# Create directory
mkdir -p "$OUTPUT_DIR/$dir"
# Determine output file path
output_file="$OUTPUT_DIR/$path"
# Fetch the page
echo "Fetching: $url -> $output_file"
curl -s "$url" -o "$output_file"
# Check if successful
if [ $? -eq 0 ] && [ -s "$output_file" ]; then
echo " ✅ Success: $filename"
else
echo " ❌ Failed: $filename"
fi
# Rate limit (0.5 seconds between requests)
sleep 0.5
done
echo "Done! Scraped files to $OUTPUT_DIR/"
```
## Alternative: Using Python Script
```python
#!/usr/bin/env python3
import os
import urllib.request
import time
import re
BASE_URL = "https://docs.polymarket.com"
OUTPUT_DIR = "PolymarketDocumentation"
# Read URLs from TARGET.md
with open("TARGET.md", "r") as f:
urls = [line.strip() for line in f if line.strip() and not line.startswith("#")]
for url in urls:
# Extract path and create directories
path = url.replace("https://docs.polymarket.com/", "")
filepath = os.path.join(OUTPUT_DIR, path)
os.makedirs(os.path.dirname(filepath), exist_ok=True)
# Fetch the page
print(f"Fetching: {url}")
try:
urllib.request.urlretrieve(url, filepath)
print(f" ✅ Saved: {filepath}")
except Exception as e:
print(f" ❌ Error: {e}")
# Rate limit
time.sleep(0.5)
print("Done!")
```
## Notes
- The `.md` suffix converts HTML pages to markdown format automatically
- Some URLs may require authentication - handle accordingly
- Rate limiting should be respected between requests
- Check for HTTP 200 status codes to verify successful fetches
## Adding New URLs
To add new URLs to scrape, simply edit `TARGET.md` and add the URL on a new line:
```markdown
## New Section
https://docs.polymarket.com/new-section/page.md
```
Then run the scrape script again to fetch the new URLs.
+188
View File
@@ -0,0 +1,188 @@
# Target URLs for Polymarket Documentation
These URLs will be scraped and organized into the repository.
## Quickstart
https://docs.polymarket.com/quickstart/overview.md
https://docs.polymarket.com/quickstart/fetching-data.md
https://docs.polymarket.com/quickstart/first-order.md
https://docs.polymarket.com/quickstart/reference/glossary.md
https://docs.polymarket.com/quickstart/introduction/rate-limits.md
https://docs.polymarket.com/quickstart/reference/endpoints.md
## Market Makers
https://docs.polymarket.com/developers/market-makers/introduction.md
https://docs.polymarket.com/developers/market-makers/setup.md
https://docs.polymarket.com/developers/market-makers/trading.md
https://docs.polymarket.com/developers/market-makers/liquidity-rewards.md
https://docs.polymarket.com/developers/market-makers/maker-rebates-program.md
https://docs.polymarket.com/developers/market-makers/data-feeds.md
https://docs.polymarket.com/developers/market-makers/inventory.md
## Polymarket Builders Program
https://docs.polymarket.com/developers/builders/builder-intro.md
https://docs.polymarket.com/developers/builders/builder-tiers.md
https://docs.polymarket.com/developers/builders/builder-profile.md
https://docs.polymarket.com/developers/builders/order-attribution.md
https://docs.polymarket.com/developers/builders/relayer-client.md
https://docs.polymarket.com/developers/builders/blockchain-data-resources.md
## Central Limit Order Book (CLOB)
https://docs.polymarket.com/developers/CLOB/introduction.md
https://docs.polymarket.com/developers/CLOB/status.md
https://docs.polymarket.com/developers/CLOB/quickstart.md
https://docs.polymarket.com/developers/CLOB/authentication.md
https://docs.polymarket.com/developers/CLOB/geoblock.md
https://docs.polymarket.com/developers/CLOB/clients/methods-overview.md
https://docs.polymarket.com/developers/CLOB/clients/methods-public.md
https://docs.polymarket.com/developers/CLOB/clients/methods-l1.md
https://docs.polymarket.com/developers/CLOB/clients/methods-l2.md
https://docs.polymarket.com/developers/CLOB/clients/methods-builder.md
## API Reference - Orderbook
https://docs.polymarket.com/api-reference/orderbook/get-order-book-summary.md
https://docs.polymarket.com/api-reference/orderbook/get-multiple-order-books-summaries-by-request.md
## API Reference - Pricing
https://docs.polymarket.com/api-reference/pricing/get-market-price.md
https://docs.polymarket.com/api-reference/pricing/get-multiple-market-prices.md
https://docs.polymarket.com/api-reference/pricing/get-multiple-market-prices-by-request.md
https://docs.polymarket.com/api-reference/pricing/get-midpoint-price.md
https://docs.polymarket.com/api-reference/pricing/get-price-history-for-a-traded-token.md
## API Reference - Spreads
https://docs.polymarket.com/api-reference/spreads/get-bid-ask-spreads.md
## Historical Timeseries Data
https://docs.polymarket.com/developers/CLOB/timeseries.md
## Order Management
https://docs.polymarket.com/developers/CLOB/orders/orders.md
https://docs.polymarket.com/developers/CLOB/orders/create-order.md
https://docs.polymarket.com/developers/CLOB/orders/create-order-batch.md
https://docs.polymarket.com/developers/CLOB/orders/get-order.md
https://docs.polymarket.com/developers/CLOB/orders/get-active-order.md
https://docs.polymarket.com/developers/CLOB/orders/check-scoring.md
https://docs.polymarket.com/developers/CLOB/orders/cancel-orders.md
https://docs.polymarket.com/developers/CLOB/orders/onchain-order-info.md
## Trades
https://docs.polymarket.com/developers/CLOB/trades/trades-overview.md
https://docs.polymarket.com/developers/CLOB/trades/trades.md
## Websocket
https://docs.polymarket.com/developers/CLOB/websocket/wss-overview.md
https://docs.polymarket.com/quickstart/websocket/WSS-Quickstart.md
https://docs.polymarket.com/developers/CLOB/websocket/wss-auth.md
https://docs.polymarket.com/developers/CLOB/websocket/user-channel.md
https://docs.polymarket.com/developers/CLOB/websocket/market-channel.md
## Sports Websocket
https://docs.polymarket.com/developers/sports-websocket/overview.md
https://docs.polymarket.com/developers/sports-websocket/message-format.md
https://docs.polymarket.com/developers/sports-websocket/quickstart.md
## Real Time Data Stream
https://docs.polymarket.com/developers/RTDS/RTDS-overview.md
https://docs.polymarket.com/developers/RTDS/RTDS-crypto-prices.md
https://docs.polymarket.com/developers/RTDS/RTDS-comments.md
## Gamma Structure
https://docs.polymarket.com/developers/gamma-markets-api/overview.md
https://docs.polymarket.com/developers/gamma-markets-api/gamma-structure.md
https://docs.polymarket.com/developers/gamma-markets-api/fetch-markets-guide.md
## Gamma Endpoints - Status
https://docs.polymarket.com/api-reference/gamma-status/gamma-api-health-check.md
## API Reference - Sports
https://docs.polymarket.com/api-reference/sports/list-teams.md
https://docs.polymarket.com/api-reference/sports/get-sports-metadata-information.md
https://docs.polymarket.com/api-reference/sports/get-valid-sports-market-types.md
## API Reference - Tags
https://docs.polymarket.com/api-reference/tags/list-tags.md
https://docs.polymarket.com/api-reference/tags/get-tag-by-id.md
https://docs.polymarket.com/api-reference/tags/get-tag-by-slug.md
https://docs.polymarket.com/api-reference/tags/get-related-tags-relationships-by-tag-id.md
https://docs.polymarket.com/api-reference/tags/get-related-tags-relationships-by-tag-slug.md
https://docs.polymarket.com/api-reference/tags/get-tags-related-to-a-tag-id.md
https://docs.polymarket.com/api-reference/tags/get-tags-related-to-a-tag-slug.md
## API Reference - Events
https://docs.polymarket.com/api-reference/events/list-events.md
https://docs.polymarket.com/api-reference/events/get-event-by-id.md
https://docs.polymarket.com/api-reference/events/get-event-tags.md
https://docs.polymarket.com/api-reference/events/get-event-by-slug.md
## API Reference - Markets
https://docs.polymarket.com/api-reference/markets/list-markets.md
https://docs.polymarket.com/api-reference/markets/get-market-by-id.md
https://docs.polymarket.com/api-reference/markets/get-market-tags-by-id.md
https://docs.polymarket.com/api-reference/markets/get-market-by-slug.md
## API Reference - Series
https://docs.polymarket.com/api-reference/series/list-series.md
https://docs.polymarket.com/api-reference/series/get-series-by-id.md
## API Reference - Comments
https://docs.polymarket.com/api-reference/comments/list-comments.md
https://docs.polymarket.com/api-reference/comments/get-comments-by-comment-id.md
https://docs.polymarket.com/api-reference/comments/get-comments-by-user-address.md
## API Reference - Profiles
https://docs.polymarket.com/api-reference/profiles/get-public-profile-by-wallet-address.md
## API Reference - Search
https://docs.polymarket.com/api-reference/search/search-markets-events-and-profiles.md
## API Reference - Data API Status
https://docs.polymarket.com/api-reference/data-api-status/data-api-health-check.md
## API Reference - Misc
https://docs.polymarket.com/api-reference/misc/download-an-accounting-snapshot-zip-of-csvs.md
https://docs.polymarket.com/api-reference/misc/get-total-markets-a-user-has-traded.md
https://docs.polymarket.com/api-reference/misc/get-open-interest.md
https://docs.polymarket.com/api-reference/misc/get-live-volume-for-an-event.md
## API Reference - Core
https://docs.polymarket.com/api-reference/core/get-current-positions-for-a-user.md
https://docs.polymarket.com/api-reference/core/get-trades-for-a-user-or-markets.md
https://docs.polymarket.com/api-reference/core/get-user-activity.md
https://docs.polymarket.com/api-reference/core/get-top-holders-for-markets.md
https://docs.polymarket.com/api-reference/core/get-total-value-of-a-users-positions.md
https://docs.polymarket.com/api-reference/core/get-closed-positions-for-a-user.md
https://docs.polymarket.com/api-reference/core/get-trader-leaderboard-rankings.md
## API Reference - Builders
https://docs.polymarket.com/api-reference/builders/get-aggregated-builder-leaderboard.md
https://docs.polymarket.com/api-reference/builders/get-daily-builder-volume-time-series.md
## Bridge & Swap - Overview
https://docs.polymarket.com/developers/misc-endpoints/bridge-overview.md
## API Reference - Bridge
https://docs.polymarket.com/api-reference/bridge/get-supported-assets.md
https://docs.polymarket.com/api-reference/bridge/get-a-quote.md
https://docs.polymarket.com/api-reference/bridge/create-deposit-addresses.md
https://docs.polymarket.com/api-reference/bridge/create-withdrawal-addresses.md
https://docs.polymarket.com/api-reference/bridge/get-transaction-status.md
## Subgraph
https://docs.polymarket.com/developers/subgraph/overview.md
## Resolution
https://docs.polymarket.com/developers/resolution/UMA.md
## Conditional Token Frameworks (CTF)
https://docs.polymarket.com/developers/CTF/overview.md
https://docs.polymarket.com/developers/CTF/split.md
https://docs.polymarket.com/developers/CTF/merge.md
https://docs.polymarket.com/developers/CTF/redeem.md
https://docs.polymarket.com/developers/CTF/deployment-resources.md
## Proxy Wallets
https://docs.polymarket.com/developers/proxy-wallet.md
## Negative Risk
https://docs.polymarket.com/developers/neg-risk/overview.md
@@ -0,0 +1,152 @@
> ## 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.
# Create deposit addresses
> Generate unique deposit addresses for depositing assets to your Polymarket wallet.
**How it works:**
1. Submit your Polymarket wallet address
2. Receive deposit addresses for each blockchain type (EVM, Solana, Bitcoin)
3. Send assets from any supported chain to the appropriate deposit address
4. Assets are automatically bridged and swapped to USDC.e on Polygon
5. USDC.e is credited to your Polymarket wallet for trading
**Supported Assets:**
Use `/supported-assets` to see all available chains and tokens you can deposit from.
## OpenAPI
````yaml api-reference/bridge-api-openapi.yaml post /deposit
openapi: 3.0.3
info:
title: Polymarket Bridge API
version: 1.0.0
description: >
HTTP API for Polymarket bridge and swap operations.
Polymarket uses USDC.e (Bridged USDC) on Polygon as collateral for all
trading activities. This API enables users to bridge assets from various
chains and swap them to USDC.e on Polygon for seamless trading.
servers:
- url: https://bridge.polymarket.com
description: Polymarket Bridge API
security: []
tags:
- name: Bridge
description: Bridge and swap operations for Polymarket
paths:
/deposit:
post:
tags:
- Bridge
summary: Create deposit addresses
description: >
Generate unique deposit addresses for depositing assets to your
Polymarket wallet.
**How it works:**
1. Submit your Polymarket wallet address
2. Receive deposit addresses for each blockchain type (EVM, Solana,
Bitcoin)
3. Send assets from any supported chain to the appropriate deposit
address
4. Assets are automatically bridged and swapped to USDC.e on Polygon
5. USDC.e is credited to your Polymarket wallet for trading
**Supported Assets:**
Use `/supported-assets` to see all available chains and tokens you can
deposit from.
requestBody:
required: true
content:
application/json:
schema:
$ref: '#/components/schemas/DepositRequest'
example:
address: '0x56687bf447db6ffa42ffe2204a05edaa20f55839'
responses:
'201':
description: Deposit addresses created successfully
content:
application/json:
schema:
$ref: '#/components/schemas/DepositResponse'
'400':
description: Bad Request - Invalid address or request body
content:
application/json:
schema:
$ref: '#/components/schemas/ErrorResponse'
'500':
description: Server Error
content:
application/json:
schema:
$ref: '#/components/schemas/ErrorResponse'
components:
schemas:
DepositRequest:
type: object
required:
- address
properties:
address:
$ref: '#/components/schemas/Address'
description: >-
Your Polymarket wallet address where deposited funds will be
credited as USDC.e
DepositResponse:
type: object
properties:
address:
type: object
description: Deposit addresses for different blockchain networks
properties:
evm:
type: string
description: >-
EVM-compatible deposit address (Ethereum, Polygon, Arbitrum,
Base, etc.)
example: '0x23566f8b2E82aDfCf01846E54899d110e97AC053'
svm:
type: string
description: Solana Virtual Machine deposit address
example: CrvTBvzryYxBHbWu2TiQpcqD5M7Le7iBKzVmEj3f36Jb
btc:
type: string
description: Bitcoin deposit address
example: bc1q8eau83qffxcj8ht4hsjdza3lha9r3egfqysj3g
note:
type: string
description: Additional information about the deposit addresses
example: >-
Only certain chains and tokens are supported. See /supported-assets
for details.
ErrorResponse:
type: object
properties:
error:
type: string
required:
- error
Address:
type: string
description: Ethereum address (0x-prefixed, 40 hex chars)
pattern: ^0x[a-fA-F0-9]{40}$
example: '0x56687bf447db6ffa42ffe2204a05edaa20f55839'
````
@@ -0,0 +1,192 @@
> ## 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.
# Create withdrawal addresses
> Generate unique deposit addresses for withdrawing USDC.e from your Polymarket wallet to any supported chain and token.
<Card>
**⚠️ Important:** Do not pre-generate withdrawal addresses. Only generate them when you are ready to execute the withdrawal. Each address is configured for a specific destination.
</Card>
**How it works:**
1. Specify your Polymarket wallet address, destination chain, token, and recipient address
2. Receive deposit addresses for each blockchain type (EVM, Solana, Bitcoin)
3. Send USDC.e from your Polymarket wallet to the appropriate deposit address
4. Funds are automatically bridged and swapped to your desired token
5. Funds arrive at your destination wallet
**Supported Destinations:**
Use `/supported-assets` to see all available chains and tokens you can withdraw to.
## OpenAPI
````yaml api-reference/bridge-api-openapi.yaml post /withdraw
openapi: 3.0.3
info:
title: Polymarket Bridge API
version: 1.0.0
description: >
HTTP API for Polymarket bridge and swap operations.
Polymarket uses USDC.e (Bridged USDC) on Polygon as collateral for all
trading activities. This API enables users to bridge assets from various
chains and swap them to USDC.e on Polygon for seamless trading.
servers:
- url: https://bridge.polymarket.com
description: Polymarket Bridge API
security: []
tags:
- name: Bridge
description: Bridge and swap operations for Polymarket
paths:
/withdraw:
post:
tags:
- Bridge
summary: Create withdrawal addresses
description: >
Generate unique deposit addresses for withdrawing USDC.e from your
Polymarket wallet to any supported chain and token.
<Card>
**⚠️ Important:** Do not pre-generate withdrawal addresses. Only
generate them when you are ready to execute the withdrawal. Each address
is configured for a specific destination.
</Card>
**How it works:**
1. Specify your Polymarket wallet address, destination chain, token, and
recipient address
2. Receive deposit addresses for each blockchain type (EVM, Solana,
Bitcoin)
3. Send USDC.e from your Polymarket wallet to the appropriate deposit
address
4. Funds are automatically bridged and swapped to your desired token
5. Funds arrive at your destination wallet
**Supported Destinations:**
Use `/supported-assets` to see all available chains and tokens you can
withdraw to.
requestBody:
required: true
content:
application/json:
schema:
$ref: '#/components/schemas/WithdrawalRequest'
example:
address: '0x9156dd10bea4c8d7e2d591b633d1694b1d764756'
toChainId: '1'
toTokenAddress: '0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48'
recipientAddr: '0xd8dA6BF26964aF9D7eEd9e03E53415D37aA96045'
responses:
'201':
description: Withdrawal addresses created successfully
content:
application/json:
schema:
$ref: '#/components/schemas/DepositResponse'
example:
address:
evm: '0x23566f8b2E82aDfCf01846E54899d110e97AC053'
svm: CrvTBvzryYxBHbWu2TiQpcqD5M7Le7iBKzVmEj3f36Jb
btc: bc1q8eau83qffxcj8ht4hsjdza3lha9r3egfqysj3g
note: >-
Send funds to these addresses to bridge to your destination
chain and token.
'400':
description: Bad Request - Invalid or missing parameters
content:
application/json:
schema:
$ref: '#/components/schemas/ErrorResponse'
'500':
description: Server Error
content:
application/json:
schema:
$ref: '#/components/schemas/ErrorResponse'
components:
schemas:
WithdrawalRequest:
type: object
required:
- address
- toChainId
- toTokenAddress
- recipientAddr
properties:
address:
$ref: '#/components/schemas/Address'
description: Source Polymarket wallet address on Polygon
toChainId:
type: string
description: >-
Destination chain ID (e.g., "1" for Ethereum, "8453" for Base,
"1151111081099710" for Solana)
example: '1'
toTokenAddress:
type: string
description: Destination token contract address
example: '0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48'
recipientAddr:
type: string
description: Destination wallet address where funds will be sent
example: '0xd8dA6BF26964aF9D7eEd9e03E53415D37aA96045'
DepositResponse:
type: object
properties:
address:
type: object
description: Deposit addresses for different blockchain networks
properties:
evm:
type: string
description: >-
EVM-compatible deposit address (Ethereum, Polygon, Arbitrum,
Base, etc.)
example: '0x23566f8b2E82aDfCf01846E54899d110e97AC053'
svm:
type: string
description: Solana Virtual Machine deposit address
example: CrvTBvzryYxBHbWu2TiQpcqD5M7Le7iBKzVmEj3f36Jb
btc:
type: string
description: Bitcoin deposit address
example: bc1q8eau83qffxcj8ht4hsjdza3lha9r3egfqysj3g
note:
type: string
description: Additional information about the deposit addresses
example: >-
Only certain chains and tokens are supported. See /supported-assets
for details.
ErrorResponse:
type: object
properties:
error:
type: string
required:
- error
Address:
type: string
description: Ethereum address (0x-prefixed, 40 hex chars)
pattern: ^0x[a-fA-F0-9]{40}$
example: '0x56687bf447db6ffa42ffe2204a05edaa20f55839'
````
+263
View File
@@ -0,0 +1,263 @@
> ## 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.
# Get a quote
> Get an estimated quote for a deposit or withdrawal, including output amounts, checkout time, and a detailed fee breakdown.
**Use Cases:**
- Preview fees and estimated output before executing a deposit or withdrawal
- Compare costs across different token/chain combinations
- Get the `quoteId` to reference this specific quote
**Notes:**
- Quotes are estimates and actual amounts may vary slightly due to market conditions
- See `/supported-assets` for a list of all supported chains and tokens
## OpenAPI
````yaml api-reference/bridge-api-openapi.yaml post /quote
openapi: 3.0.3
info:
title: Polymarket Bridge API
version: 1.0.0
description: >
HTTP API for Polymarket bridge and swap operations.
Polymarket uses USDC.e (Bridged USDC) on Polygon as collateral for all
trading activities. This API enables users to bridge assets from various
chains and swap them to USDC.e on Polygon for seamless trading.
servers:
- url: https://bridge.polymarket.com
description: Polymarket Bridge API
security: []
tags:
- name: Bridge
description: Bridge and swap operations for Polymarket
paths:
/quote:
post:
tags:
- Bridge
summary: Get a quote
description: >
Get an estimated quote for a deposit or withdrawal, including output
amounts, checkout time, and a detailed fee breakdown.
**Use Cases:**
- Preview fees and estimated output before executing a deposit or
withdrawal
- Compare costs across different token/chain combinations
- Get the `quoteId` to reference this specific quote
**Notes:**
- Quotes are estimates and actual amounts may vary slightly due to
market conditions
- See `/supported-assets` for a list of all supported chains and tokens
requestBody:
required: true
content:
application/json:
schema:
$ref: '#/components/schemas/QuoteRequest'
example:
fromAmountBaseUnit: '10000000'
fromChainId: '137'
fromTokenAddress: '0x3c499c542cEF5E3811e1192ce70d8cC03d5c3359'
recipientAddress: '0x17eC161f126e82A8ba337f4022d574DBEaFef575'
toChainId: '137'
toTokenAddress: '0x2791Bca1f2de4661ED88A30C99A7a9449Aa84174'
responses:
'200':
description: Quote retrieved successfully
content:
application/json:
schema:
$ref: '#/components/schemas/QuoteResponse'
example:
estCheckoutTimeMs: 25000
estFeeBreakdown:
appFeeLabel: Fun.xyz fee
appFeePercent: 0
appFeeUsd: 0
fillCostPercent: 0
fillCostUsd: 0
gasUsd: 0.003854
maxSlippage: 0
minReceived: 14.488305
swapImpact: 0
swapImpactUsd: 0
totalImpact: 0
totalImpactUsd: 0
estInputUsd: 14.488305
estOutputUsd: 14.488305
estToTokenBaseUnit: '14491203'
quoteId: >-
0x00c34ba467184b0146406d62b0e60aaa24ed52460bd456222b6155a0d9de0ad5
'400':
description: Bad Request - Missing required field
content:
application/json:
schema:
$ref: '#/components/schemas/ErrorResponse'
examples:
missingFromAmount:
value:
error: fromAmountBaseUnit is required
missingFromChainId:
value:
error: fromChainId is required
missingFromTokenAddress:
value:
error: fromTokenAddress is required
missingRecipientAddress:
value:
error: recipientAddress is required
missingToChainId:
value:
error: toChainId is required
missingToTokenAddress:
value:
error: toTokenAddress is required
'500':
description: Server Error
content:
application/json:
schema:
$ref: '#/components/schemas/ErrorResponse'
example:
error: cannot get quote
components:
schemas:
QuoteRequest:
type: object
required:
- fromAmountBaseUnit
- fromChainId
- fromTokenAddress
- recipientAddress
- toChainId
- toTokenAddress
properties:
fromAmountBaseUnit:
type: string
description: Amount of tokens to send
example: '10000000'
fromChainId:
type: string
description: Source Chain ID
example: '137'
fromTokenAddress:
type: string
description: Source token address
example: '0x3c499c542cEF5E3811e1192ce70d8cC03d5c3359'
recipientAddress:
type: string
description: Address of the recipient
example: '0x17eC161f126e82A8ba337f4022d574DBEaFef575'
toChainId:
type: string
description: Destination Chain ID
example: '137'
toTokenAddress:
type: string
description: Destination token address
example: '0x2791Bca1f2de4661ED88A30C99A7a9449Aa84174'
QuoteResponse:
type: object
properties:
estCheckoutTimeMs:
type: integer
description: Estimated time to complete the checkout in milliseconds
example: 25000
estFeeBreakdown:
$ref: '#/components/schemas/FeeBreakdown'
estInputUsd:
type: number
description: Estimated token amount received in USD
example: 14.488305
estOutputUsd:
type: number
description: Estimated token amount sent in USD
example: 14.488305
estToTokenBaseUnit:
type: string
description: Estimated token amount received
example: '14491203'
quoteId:
type: string
description: Unique quote id of the request
example: '0x00c34ba467184b0146406d62b0e60aaa24ed52460bd456222b6155a0d9de0ad5'
ErrorResponse:
type: object
properties:
error:
type: string
required:
- error
FeeBreakdown:
type: object
description: Breakdown of the estimated fees
properties:
appFeeLabel:
type: string
description: Label of the app fee
example: Fun.xyz fee
appFeePercent:
type: number
description: App fees as a percentage of the total amount sent
example: 0
appFeeUsd:
type: number
description: App fees in USD
example: 0
fillCostPercent:
type: number
description: Fill cost percentage of the total amount sent
example: 0
fillCostUsd:
type: number
description: Fill cost in USD
example: 0
gasUsd:
type: number
description: Gas fee in USD
example: 0.003854
maxSlippage:
type: number
description: Maximum potential slippage as a percentage
example: 0
minReceived:
type: number
description: Amount after factoring slippage
example: 14.488305
swapImpact:
type: number
description: Swap impact as a percentage of the total amount sent
example: 0
swapImpactUsd:
type: number
description: Swap impact of the transaction in USD
example: 0
totalImpact:
type: number
description: Total impact as a percentage of the total amount sent
example: 0
totalImpactUsd:
type: number
description: Impact cost of the transaction
example: 0
````
@@ -0,0 +1,132 @@
> ## 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.
# Get supported assets
> Retrieve all supported chains and tokens for deposits and withdrawals.
**USDC.e on Polygon:**
Polymarket uses USDC.e (Bridged USDC from Ethereum) on Polygon as the native collateral for all markets. When you deposit assets from other chains, they are automatically bridged and swapped to USDC.e on Polygon. When you withdraw, your USDC.e is bridged and swapped to your desired token on the destination chain.
**Minimum Amounts:**
Each asset has a `minCheckoutUsd` field indicating the minimum amount required in USD. Make sure your deposit or withdrawal meets this minimum to avoid transaction failures.
## OpenAPI
````yaml api-reference/bridge-api-openapi.yaml get /supported-assets
openapi: 3.0.3
info:
title: Polymarket Bridge API
version: 1.0.0
description: >
HTTP API for Polymarket bridge and swap operations.
Polymarket uses USDC.e (Bridged USDC) on Polygon as collateral for all
trading activities. This API enables users to bridge assets from various
chains and swap them to USDC.e on Polygon for seamless trading.
servers:
- url: https://bridge.polymarket.com
description: Polymarket Bridge API
security: []
tags:
- name: Bridge
description: Bridge and swap operations for Polymarket
paths:
/supported-assets:
get:
tags:
- Bridge
summary: Get supported assets
description: >
Retrieve all supported chains and tokens for deposits and withdrawals.
**USDC.e on Polygon:**
Polymarket uses USDC.e (Bridged USDC from Ethereum) on Polygon as the
native collateral for all markets. When you deposit assets from other
chains, they are automatically bridged and swapped to USDC.e on Polygon.
When you withdraw, your USDC.e is bridged and swapped to your desired
token on the destination chain.
**Minimum Amounts:**
Each asset has a `minCheckoutUsd` field indicating the minimum amount
required in USD. Make sure your deposit or withdrawal meets this minimum
to avoid transaction failures.
responses:
'200':
description: Successfully retrieved supported assets
content:
application/json:
schema:
$ref: '#/components/schemas/SupportedAssetsResponse'
'500':
description: Server Error
content:
application/json:
schema:
$ref: '#/components/schemas/ErrorResponse'
components:
schemas:
SupportedAssetsResponse:
type: object
properties:
supportedAssets:
type: array
items:
$ref: '#/components/schemas/SupportedAsset'
description: >-
List of supported assets with minimum amounts for deposits and
withdrawals
ErrorResponse:
type: object
properties:
error:
type: string
required:
- error
SupportedAsset:
type: object
properties:
chainId:
type: string
description: Chain ID
example: '1'
chainName:
type: string
description: Human-readable chain name
example: Ethereum
token:
$ref: '#/components/schemas/Token'
minCheckoutUsd:
type: number
description: Minimum amount in USD for deposits and withdrawals
example: 45
Token:
type: object
properties:
name:
type: string
description: Full token name
example: USD Coin
symbol:
type: string
description: Token symbol
example: USDC
address:
type: string
description: Token contract address
example: '0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48'
decimals:
type: integer
description: Token decimals
example: 6
````
@@ -0,0 +1,212 @@
> ## 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.
# Get transaction status
> Get the transaction status for all deposits and withdrawals associated with a given address.
**Usage:**
- Use the deposit address returned from the `/deposit` or `/withdraw` endpoint (EVM, SVM, or BTC address)
- Poll this endpoint to track the progress of your deposits and withdrawals
**Status Values:**
- `DEPOSIT_DETECTED`: Funds detected but not yet processing
- `PROCESSING`: Transaction is being routed and swapped
- `ORIGIN_TX_CONFIRMED`: Origin transaction has been confirmed on source chain
- `SUBMITTED`: Transaction has been submitted to destination chain
- `COMPLETED`: Transaction completed successfully
- `FAILED`: Transaction encountered an error and did not complete
**Notes:**
- Transactions typically complete within a few minutes, but may take longer depending on network conditions
- An empty transactions array means no transactions have been made to this address yet
## OpenAPI
````yaml api-reference/bridge-api-openapi.yaml get /status/{address}
openapi: 3.0.3
info:
title: Polymarket Bridge API
version: 1.0.0
description: >
HTTP API for Polymarket bridge and swap operations.
Polymarket uses USDC.e (Bridged USDC) on Polygon as collateral for all
trading activities. This API enables users to bridge assets from various
chains and swap them to USDC.e on Polygon for seamless trading.
servers:
- url: https://bridge.polymarket.com
description: Polymarket Bridge API
security: []
tags:
- name: Bridge
description: Bridge and swap operations for Polymarket
paths:
/status/{address}:
get:
tags:
- Bridge
summary: Get transaction status
description: >
Get the transaction status for all deposits and withdrawals associated
with a given address.
**Usage:**
- Use the deposit address returned from the `/deposit` or `/withdraw`
endpoint (EVM, SVM, or BTC address)
- Poll this endpoint to track the progress of your deposits and
withdrawals
**Status Values:**
- `DEPOSIT_DETECTED`: Funds detected but not yet processing
- `PROCESSING`: Transaction is being routed and swapped
- `ORIGIN_TX_CONFIRMED`: Origin transaction has been confirmed on source
chain
- `SUBMITTED`: Transaction has been submitted to destination chain
- `COMPLETED`: Transaction completed successfully
- `FAILED`: Transaction encountered an error and did not complete
**Notes:**
- Transactions typically complete within a few minutes, but may take
longer depending on network conditions
- An empty transactions array means no transactions have been made to
this address yet
parameters:
- name: address
in: path
required: true
description: >-
The address to query for transaction status (EVM, SVM, or BTC
address from the `/deposit` or `/withdraw` response)
schema:
type: string
example: EXoZue2avJae1d45B3fVw2unhkrtToSYQqHtHgfZ2cbE
responses:
'200':
description: Successfully retrieved transaction status
content:
application/json:
schema:
$ref: '#/components/schemas/TransactionStatusResponse'
example:
transactions:
- fromChainId: '1151111081099710'
fromTokenAddress: '11111111111111111111111111111111'
fromAmountBaseUnit: '13566635'
toChainId: '137'
toTokenAddress: '0x2791Bca1f2de4661ED88A30C99A7a9449Aa84174'
status: DEPOSIT_DETECTED
- fromChainId: '1151111081099710'
fromTokenAddress: '11111111111111111111111111111111'
fromAmountBaseUnit: '13400000'
toChainId: '137'
toTokenAddress: '0x2791Bca1f2de4661ED88A30C99A7a9449Aa84174'
createdTimeMs: 1757646914535
status: PROCESSING
- fromChainId: '1151111081099710'
fromTokenAddress: '11111111111111111111111111111111'
fromAmountBaseUnit: '13500152'
toChainId: '137'
toTokenAddress: '0x2791Bca1f2de4661ED88A30C99A7a9449Aa84174'
txHash: >-
3atr19NAiNCYt24RHM1WnzZp47RXskpTDzspJoCBBaMFwUB8fk37hFkxz35P5UEnnmWz21rb2t5wJ8pq3EE2XnxU
createdTimeMs: 1757531217339
status: COMPLETED
'400':
description: Bad Request - Missing address parameter
content:
application/json:
schema:
$ref: '#/components/schemas/ErrorResponse'
example:
error: address is required
'500':
description: Server Error
content:
application/json:
schema:
$ref: '#/components/schemas/ErrorResponse'
example:
error: cannot get transaction status
components:
schemas:
TransactionStatusResponse:
type: object
properties:
transactions:
type: array
items:
$ref: '#/components/schemas/Transaction'
description: List of transactions for the given address
ErrorResponse:
type: object
properties:
error:
type: string
required:
- error
Transaction:
type: object
properties:
fromChainId:
type: string
description: Source chain ID
example: '1151111081099710'
fromTokenAddress:
type: string
description: Source token contract address
example: '11111111111111111111111111111111'
fromAmountBaseUnit:
type: string
description: Amount in base units (without decimals)
example: '13566635'
toChainId:
type: string
description: Destination chain ID
example: '137'
toTokenAddress:
type: string
description: Destination token contract address
example: '0x2791Bca1f2de4661ED88A30C99A7a9449Aa84174'
status:
type: string
description: Current status of the transaction
enum:
- DEPOSIT_DETECTED
- PROCESSING
- ORIGIN_TX_CONFIRMED
- SUBMITTED
- COMPLETED
- FAILED
example: COMPLETED
txHash:
type: string
description: Transaction hash (only available when status is COMPLETED)
example: >-
3atr19NAiNCYt24RHM1WnzZp47RXskpTDzspJoCBBaMFwUB8fk37hFkxz35P5UEnnmWz21rb2t5wJ8pq3EE2XnxU
createdTimeMs:
type: number
description: >-
Unix timestamp in milliseconds when transaction was created (missing
when status is DEPOSIT_DETECTED)
example: 1757531217339
````
@@ -0,0 +1,121 @@
> ## 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.
# Get aggregated builder leaderboard
> Returns aggregated builder rankings with one entry per builder showing total for the specified time period. Supports pagination.
## OpenAPI
````yaml api-reference/data-api-openapi.yaml get /v1/builders/leaderboard
openapi: 3.0.3
info:
title: Polymarket Data API
version: 1.0.0
description: >
HTTP API for Polymarket data. This specification documents all public
routes.
servers:
- url: https://data-api.polymarket.com
description: Relative server (same host)
security: []
tags:
- name: Data API Status
description: Data API health check
- name: Core
- name: Builders
- name: Misc
paths:
/v1/builders/leaderboard:
get:
tags:
- Builders
summary: Get aggregated builder leaderboard
description: >-
Returns aggregated builder rankings with one entry per builder showing
total for the specified time period. Supports pagination.
parameters:
- in: query
name: timePeriod
schema:
type: string
enum:
- DAY
- WEEK
- MONTH
- ALL
default: DAY
description: |
The time period to aggregate results over.
- in: query
name: limit
schema:
type: integer
default: 25
minimum: 0
maximum: 50
description: Maximum number of builders to return
- in: query
name: offset
schema:
type: integer
default: 0
minimum: 0
maximum: 1000
description: Starting index for pagination
responses:
'200':
description: Success
content:
application/json:
schema:
type: array
items:
$ref: '#/components/schemas/LeaderboardEntry'
'400':
description: Bad Request
content:
application/json:
schema:
$ref: '#/components/schemas/ErrorResponse'
'500':
description: Server Error
content:
application/json:
schema:
$ref: '#/components/schemas/ErrorResponse'
components:
schemas:
LeaderboardEntry:
type: object
properties:
rank:
type: string
description: The rank position of the builder
builder:
type: string
description: The builder name or identifier
volume:
type: number
description: Total trading volume attributed to this builder
activeUsers:
type: integer
description: Number of active users for this builder
verified:
type: boolean
description: Whether the builder is verified
builderLogo:
type: string
description: URL to the builder's logo image
ErrorResponse:
type: object
properties:
error:
type: string
required:
- error
````
@@ -0,0 +1,110 @@
> ## 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.
# Get daily builder volume time-series
> Returns daily time-series volume data with multiple entries per builder (one per day), each including a `dt` timestamp. No pagination.
## OpenAPI
````yaml api-reference/data-api-openapi.yaml get /v1/builders/volume
openapi: 3.0.3
info:
title: Polymarket Data API
version: 1.0.0
description: >
HTTP API for Polymarket data. This specification documents all public
routes.
servers:
- url: https://data-api.polymarket.com
description: Relative server (same host)
security: []
tags:
- name: Data API Status
description: Data API health check
- name: Core
- name: Builders
- name: Misc
paths:
/v1/builders/volume:
get:
tags:
- Builders
summary: Get daily builder volume time-series
description: >-
Returns daily time-series volume data with multiple entries per builder
(one per day), each including a `dt` timestamp. No pagination.
parameters:
- in: query
name: timePeriod
schema:
type: string
enum:
- DAY
- WEEK
- MONTH
- ALL
default: DAY
description: |
The time period to fetch daily records for.
responses:
'200':
description: Success - Returns array of daily volume records
content:
application/json:
schema:
type: array
items:
$ref: '#/components/schemas/BuilderVolumeEntry'
'400':
description: Bad Request
content:
application/json:
schema:
$ref: '#/components/schemas/ErrorResponse'
'500':
description: Server Error
content:
application/json:
schema:
$ref: '#/components/schemas/ErrorResponse'
components:
schemas:
BuilderVolumeEntry:
type: object
properties:
dt:
type: string
format: date-time
description: The timestamp for this volume entry in ISO 8601 format
example: '2025-11-15T00:00:00Z'
builder:
type: string
description: The builder name or identifier
builderLogo:
type: string
description: URL to the builder's logo image
verified:
type: boolean
description: Whether the builder is verified
volume:
type: number
description: Trading volume for this builder on this date
activeUsers:
type: integer
description: Number of active users for this builder on this date
rank:
type: string
description: The rank position of the builder on this date
ErrorResponse:
type: object
properties:
error:
type: string
required:
- error
````
@@ -0,0 +1,212 @@
> ## 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.
# Get comments by comment id
## OpenAPI
````yaml api-reference/gamma-openapi.json get /comments/{id}
openapi: 3.0.3
info:
title: Markets API
version: 1.0.0
description: REST API specification for public endpoints used by the Markets service.
servers:
- url: https://gamma-api.polymarket.com
description: Polymarket Gamma API Production Server
security: []
tags:
- name: Gamma Status
description: Gamma API status and health check
- name: Sports
description: Sports-related endpoints including teams and game data
- name: Tags
description: Tag management and related tag operations
- name: Events
description: Event management and event-related operations
- name: Markets
description: Market data and market-related operations
- name: Comments
description: Comment system and user interactions
- name: Series
description: Series management and related operations
- name: Profiles
description: User profile management
- name: Search
description: Search functionality across different entity types
paths:
/comments/{id}:
get:
tags:
- Comments
summary: Get comments by comment id
operationId: getCommentsById
parameters:
- name: id
in: path
required: true
schema:
type: integer
- name: get_positions
in: query
schema:
type: boolean
responses:
'200':
description: Comments
content:
application/json:
schema:
type: array
items:
$ref: '#/components/schemas/Comment'
components:
schemas:
Comment:
type: object
properties:
id:
type: string
body:
type: string
nullable: true
parentEntityType:
type: string
nullable: true
parentEntityID:
type: integer
nullable: true
parentCommentID:
type: string
nullable: true
userAddress:
type: string
nullable: true
replyAddress:
type: string
nullable: true
createdAt:
type: string
format: date-time
nullable: true
updatedAt:
type: string
format: date-time
nullable: true
profile:
$ref: '#/components/schemas/CommentProfile'
reactions:
type: array
items:
$ref: '#/components/schemas/Reaction'
reportCount:
type: integer
nullable: true
reactionCount:
type: integer
nullable: true
CommentProfile:
type: object
properties:
name:
type: string
nullable: true
pseudonym:
type: string
nullable: true
displayUsernamePublic:
type: boolean
nullable: true
bio:
type: string
nullable: true
isMod:
type: boolean
nullable: true
isCreator:
type: boolean
nullable: true
proxyWallet:
type: string
nullable: true
baseAddress:
type: string
nullable: true
profileImage:
type: string
nullable: true
profileImageOptimized:
$ref: '#/components/schemas/ImageOptimization'
positions:
type: array
items:
$ref: '#/components/schemas/CommentPosition'
Reaction:
type: object
properties:
id:
type: string
commentID:
type: integer
nullable: true
reactionType:
type: string
nullable: true
icon:
type: string
nullable: true
userAddress:
type: string
nullable: true
createdAt:
type: string
format: date-time
nullable: true
profile:
$ref: '#/components/schemas/CommentProfile'
ImageOptimization:
type: object
properties:
id:
type: string
imageUrlSource:
type: string
nullable: true
imageUrlOptimized:
type: string
nullable: true
imageSizeKbSource:
type: number
nullable: true
imageSizeKbOptimized:
type: number
nullable: true
imageOptimizedComplete:
type: boolean
nullable: true
imageOptimizedLastUpdated:
type: string
nullable: true
relID:
type: integer
nullable: true
field:
type: string
nullable: true
relname:
type: string
nullable: true
CommentPosition:
type: object
properties:
tokenId:
type: string
nullable: true
positionSize:
type: string
nullable: true
````
@@ -0,0 +1,237 @@
> ## 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.
# Get comments by user address
## OpenAPI
````yaml api-reference/gamma-openapi.json get /comments/user_address/{user_address}
openapi: 3.0.3
info:
title: Markets API
version: 1.0.0
description: REST API specification for public endpoints used by the Markets service.
servers:
- url: https://gamma-api.polymarket.com
description: Polymarket Gamma API Production Server
security: []
tags:
- name: Gamma Status
description: Gamma API status and health check
- name: Sports
description: Sports-related endpoints including teams and game data
- name: Tags
description: Tag management and related tag operations
- name: Events
description: Event management and event-related operations
- name: Markets
description: Market data and market-related operations
- name: Comments
description: Comment system and user interactions
- name: Series
description: Series management and related operations
- name: Profiles
description: User profile management
- name: Search
description: Search functionality across different entity types
paths:
/comments/user_address/{user_address}:
get:
tags:
- Comments
- Profiles
summary: Get comments by user address
operationId: getCommentsByUserAddress
parameters:
- name: user_address
in: path
required: true
schema:
type: string
- $ref: '#/components/parameters/limit'
- $ref: '#/components/parameters/offset'
- $ref: '#/components/parameters/order'
- $ref: '#/components/parameters/ascending'
responses:
'200':
description: Comments
content:
application/json:
schema:
type: array
items:
$ref: '#/components/schemas/Comment'
components:
parameters:
limit:
name: limit
in: query
schema:
type: integer
minimum: 0
offset:
name: offset
in: query
schema:
type: integer
minimum: 0
order:
name: order
in: query
schema:
type: string
description: Comma-separated list of fields to order by
ascending:
name: ascending
in: query
schema:
type: boolean
schemas:
Comment:
type: object
properties:
id:
type: string
body:
type: string
nullable: true
parentEntityType:
type: string
nullable: true
parentEntityID:
type: integer
nullable: true
parentCommentID:
type: string
nullable: true
userAddress:
type: string
nullable: true
replyAddress:
type: string
nullable: true
createdAt:
type: string
format: date-time
nullable: true
updatedAt:
type: string
format: date-time
nullable: true
profile:
$ref: '#/components/schemas/CommentProfile'
reactions:
type: array
items:
$ref: '#/components/schemas/Reaction'
reportCount:
type: integer
nullable: true
reactionCount:
type: integer
nullable: true
CommentProfile:
type: object
properties:
name:
type: string
nullable: true
pseudonym:
type: string
nullable: true
displayUsernamePublic:
type: boolean
nullable: true
bio:
type: string
nullable: true
isMod:
type: boolean
nullable: true
isCreator:
type: boolean
nullable: true
proxyWallet:
type: string
nullable: true
baseAddress:
type: string
nullable: true
profileImage:
type: string
nullable: true
profileImageOptimized:
$ref: '#/components/schemas/ImageOptimization'
positions:
type: array
items:
$ref: '#/components/schemas/CommentPosition'
Reaction:
type: object
properties:
id:
type: string
commentID:
type: integer
nullable: true
reactionType:
type: string
nullable: true
icon:
type: string
nullable: true
userAddress:
type: string
nullable: true
createdAt:
type: string
format: date-time
nullable: true
profile:
$ref: '#/components/schemas/CommentProfile'
ImageOptimization:
type: object
properties:
id:
type: string
imageUrlSource:
type: string
nullable: true
imageUrlOptimized:
type: string
nullable: true
imageSizeKbSource:
type: number
nullable: true
imageSizeKbOptimized:
type: number
nullable: true
imageOptimizedComplete:
type: boolean
nullable: true
imageOptimizedLastUpdated:
type: string
nullable: true
relID:
type: integer
nullable: true
field:
type: string
nullable: true
relname:
type: string
nullable: true
CommentPosition:
type: object
properties:
tokenId:
type: string
nullable: true
positionSize:
type: string
nullable: true
````
@@ -0,0 +1,251 @@
> ## 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.
# List comments
## OpenAPI
````yaml api-reference/gamma-openapi.json get /comments
openapi: 3.0.3
info:
title: Markets API
version: 1.0.0
description: REST API specification for public endpoints used by the Markets service.
servers:
- url: https://gamma-api.polymarket.com
description: Polymarket Gamma API Production Server
security: []
tags:
- name: Gamma Status
description: Gamma API status and health check
- name: Sports
description: Sports-related endpoints including teams and game data
- name: Tags
description: Tag management and related tag operations
- name: Events
description: Event management and event-related operations
- name: Markets
description: Market data and market-related operations
- name: Comments
description: Comment system and user interactions
- name: Series
description: Series management and related operations
- name: Profiles
description: User profile management
- name: Search
description: Search functionality across different entity types
paths:
/comments:
get:
tags:
- Comments
summary: List comments
operationId: listComments
parameters:
- $ref: '#/components/parameters/limit'
- $ref: '#/components/parameters/offset'
- $ref: '#/components/parameters/order'
- $ref: '#/components/parameters/ascending'
- name: parent_entity_type
in: query
schema:
type: string
enum:
- Event
- Series
- market
- name: parent_entity_id
in: query
schema:
type: integer
- name: get_positions
in: query
schema:
type: boolean
- name: holders_only
in: query
schema:
type: boolean
responses:
'200':
description: List of comments
content:
application/json:
schema:
type: array
items:
$ref: '#/components/schemas/Comment'
components:
parameters:
limit:
name: limit
in: query
schema:
type: integer
minimum: 0
offset:
name: offset
in: query
schema:
type: integer
minimum: 0
order:
name: order
in: query
schema:
type: string
description: Comma-separated list of fields to order by
ascending:
name: ascending
in: query
schema:
type: boolean
schemas:
Comment:
type: object
properties:
id:
type: string
body:
type: string
nullable: true
parentEntityType:
type: string
nullable: true
parentEntityID:
type: integer
nullable: true
parentCommentID:
type: string
nullable: true
userAddress:
type: string
nullable: true
replyAddress:
type: string
nullable: true
createdAt:
type: string
format: date-time
nullable: true
updatedAt:
type: string
format: date-time
nullable: true
profile:
$ref: '#/components/schemas/CommentProfile'
reactions:
type: array
items:
$ref: '#/components/schemas/Reaction'
reportCount:
type: integer
nullable: true
reactionCount:
type: integer
nullable: true
CommentProfile:
type: object
properties:
name:
type: string
nullable: true
pseudonym:
type: string
nullable: true
displayUsernamePublic:
type: boolean
nullable: true
bio:
type: string
nullable: true
isMod:
type: boolean
nullable: true
isCreator:
type: boolean
nullable: true
proxyWallet:
type: string
nullable: true
baseAddress:
type: string
nullable: true
profileImage:
type: string
nullable: true
profileImageOptimized:
$ref: '#/components/schemas/ImageOptimization'
positions:
type: array
items:
$ref: '#/components/schemas/CommentPosition'
Reaction:
type: object
properties:
id:
type: string
commentID:
type: integer
nullable: true
reactionType:
type: string
nullable: true
icon:
type: string
nullable: true
userAddress:
type: string
nullable: true
createdAt:
type: string
format: date-time
nullable: true
profile:
$ref: '#/components/schemas/CommentProfile'
ImageOptimization:
type: object
properties:
id:
type: string
imageUrlSource:
type: string
nullable: true
imageUrlOptimized:
type: string
nullable: true
imageSizeKbSource:
type: number
nullable: true
imageSizeKbOptimized:
type: number
nullable: true
imageOptimizedComplete:
type: boolean
nullable: true
imageOptimizedLastUpdated:
type: string
nullable: true
relID:
type: integer
nullable: true
field:
type: string
nullable: true
relname:
type: string
nullable: true
CommentPosition:
type: object
properties:
tokenId:
type: string
nullable: true
positionSize:
type: string
nullable: true
````
@@ -0,0 +1,197 @@
> ## 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.
# Get closed positions for a user
> Fetches closed positions for a user(address)
## OpenAPI
````yaml api-reference/data-api-openapi.yaml get /closed-positions
openapi: 3.0.3
info:
title: Polymarket Data API
version: 1.0.0
description: >
HTTP API for Polymarket data. This specification documents all public
routes.
servers:
- url: https://data-api.polymarket.com
description: Relative server (same host)
security: []
tags:
- name: Data API Status
description: Data API health check
- name: Core
- name: Builders
- name: Misc
paths:
/closed-positions:
get:
tags:
- Core
summary: Get closed positions for a user
description: Fetches closed positions for a user(address)
parameters:
- in: query
name: user
required: true
schema:
$ref: '#/components/schemas/Address'
description: The address of the user in question
- in: query
name: market
style: form
explode: false
schema:
type: array
items:
$ref: '#/components/schemas/Hash64'
description: >-
The conditionId of the market in question. Supports multiple csv
separated values. Cannot be used with the eventId param.
- in: query
name: title
schema:
type: string
maxLength: 100
description: Filter by market title
- in: query
name: eventId
style: form
explode: false
schema:
type: array
items:
type: integer
minimum: 1
description: >-
The event id of the event in question. Supports multiple csv
separated values. Returns positions for all markets for those event
ids. Cannot be used with the market param.
- in: query
name: limit
schema:
type: integer
default: 10
minimum: 0
maximum: 50
description: The max number of positions to return
- in: query
name: offset
schema:
type: integer
default: 0
minimum: 0
maximum: 100000
description: The starting index for pagination
- in: query
name: sortBy
schema:
type: string
enum:
- REALIZEDPNL
- TITLE
- PRICE
- AVGPRICE
- TIMESTAMP
default: REALIZEDPNL
description: The sort criteria
- in: query
name: sortDirection
schema:
type: string
enum:
- ASC
- DESC
default: DESC
description: The sort direction
responses:
'200':
description: Success
content:
application/json:
schema:
type: array
items:
$ref: '#/components/schemas/ClosedPosition'
'400':
description: Bad Request
content:
application/json:
schema:
$ref: '#/components/schemas/ErrorResponse'
'401':
description: Unauthorized
content:
application/json:
schema:
$ref: '#/components/schemas/ErrorResponse'
'500':
description: Server Error
content:
application/json:
schema:
$ref: '#/components/schemas/ErrorResponse'
components:
schemas:
Address:
type: string
description: User Profile Address (0x-prefixed, 40 hex chars)
pattern: ^0x[a-fA-F0-9]{40}$
example: '0x56687bf447db6ffa42ffe2204a05edaa20f55839'
Hash64:
type: string
description: 0x-prefixed 64-hex string
pattern: ^0x[a-fA-F0-9]{64}$
example: '0xdd22472e552920b8438158ea7238bfadfa4f736aa4cee91a6b86c39ead110917'
ClosedPosition:
type: object
properties:
proxyWallet:
$ref: '#/components/schemas/Address'
asset:
type: string
conditionId:
$ref: '#/components/schemas/Hash64'
avgPrice:
type: number
totalBought:
type: number
realizedPnl:
type: number
curPrice:
type: number
timestamp:
type: integer
format: int64
title:
type: string
slug:
type: string
icon:
type: string
eventSlug:
type: string
outcome:
type: string
outcomeIndex:
type: integer
oppositeOutcome:
type: string
oppositeAsset:
type: string
endDate:
type: string
ErrorResponse:
type: object
properties:
error:
type: string
required:
- error
````
@@ -0,0 +1,224 @@
> ## 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.
# Get current positions for a user
> Returns positions filtered by user and optional filters.
## OpenAPI
````yaml api-reference/data-api-openapi.yaml get /positions
openapi: 3.0.3
info:
title: Polymarket Data API
version: 1.0.0
description: >
HTTP API for Polymarket data. This specification documents all public
routes.
servers:
- url: https://data-api.polymarket.com
description: Relative server (same host)
security: []
tags:
- name: Data API Status
description: Data API health check
- name: Core
- name: Builders
- name: Misc
paths:
/positions:
get:
tags:
- Core
summary: Get current positions for a user
description: Returns positions filtered by user and optional filters.
parameters:
- in: query
name: user
required: true
schema:
$ref: '#/components/schemas/Address'
description: User address (required)
- in: query
name: market
style: form
explode: false
schema:
type: array
items:
$ref: '#/components/schemas/Hash64'
description: >-
Comma-separated list of condition IDs. Mutually exclusive with
eventId.
- in: query
name: eventId
style: form
explode: false
schema:
type: array
items:
type: integer
minimum: 1
description: Comma-separated list of event IDs. Mutually exclusive with market.
- in: query
name: sizeThreshold
schema:
type: number
default: 1
minimum: 0
- in: query
name: redeemable
schema:
type: boolean
default: false
- in: query
name: mergeable
schema:
type: boolean
default: false
- in: query
name: limit
schema:
type: integer
default: 100
minimum: 0
maximum: 500
- in: query
name: offset
schema:
type: integer
default: 0
minimum: 0
maximum: 10000
- in: query
name: sortBy
schema:
type: string
enum:
- CURRENT
- INITIAL
- TOKENS
- CASHPNL
- PERCENTPNL
- TITLE
- RESOLVING
- PRICE
- AVGPRICE
default: TOKENS
- in: query
name: sortDirection
schema:
type: string
enum:
- ASC
- DESC
default: DESC
- in: query
name: title
schema:
type: string
maxLength: 100
responses:
'200':
description: Success
content:
application/json:
schema:
type: array
items:
$ref: '#/components/schemas/Position'
'400':
description: Bad Request
content:
application/json:
schema:
$ref: '#/components/schemas/ErrorResponse'
'401':
description: Unauthorized
content:
application/json:
schema:
$ref: '#/components/schemas/ErrorResponse'
'500':
description: Server Error
content:
application/json:
schema:
$ref: '#/components/schemas/ErrorResponse'
components:
schemas:
Address:
type: string
description: User Profile Address (0x-prefixed, 40 hex chars)
pattern: ^0x[a-fA-F0-9]{40}$
example: '0x56687bf447db6ffa42ffe2204a05edaa20f55839'
Hash64:
type: string
description: 0x-prefixed 64-hex string
pattern: ^0x[a-fA-F0-9]{64}$
example: '0xdd22472e552920b8438158ea7238bfadfa4f736aa4cee91a6b86c39ead110917'
Position:
type: object
properties:
proxyWallet:
$ref: '#/components/schemas/Address'
asset:
type: string
conditionId:
$ref: '#/components/schemas/Hash64'
size:
type: number
avgPrice:
type: number
initialValue:
type: number
currentValue:
type: number
cashPnl:
type: number
percentPnl:
type: number
totalBought:
type: number
realizedPnl:
type: number
percentRealizedPnl:
type: number
curPrice:
type: number
redeemable:
type: boolean
mergeable:
type: boolean
title:
type: string
slug:
type: string
icon:
type: string
eventSlug:
type: string
outcome:
type: string
outcomeIndex:
type: integer
oppositeOutcome:
type: string
oppositeAsset:
type: string
endDate:
type: string
negativeRisk:
type: boolean
ErrorResponse:
type: object
properties:
error:
type: string
required:
- error
````
@@ -0,0 +1,140 @@
> ## 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.
# Get top holders for markets
## OpenAPI
````yaml api-reference/data-api-openapi.yaml get /holders
openapi: 3.0.3
info:
title: Polymarket Data API
version: 1.0.0
description: >
HTTP API for Polymarket data. This specification documents all public
routes.
servers:
- url: https://data-api.polymarket.com
description: Relative server (same host)
security: []
tags:
- name: Data API Status
description: Data API health check
- name: Core
- name: Builders
- name: Misc
paths:
/holders:
get:
tags:
- Core
summary: Get top holders for markets
parameters:
- in: query
name: limit
schema:
type: integer
default: 20
minimum: 0
maximum: 20
description: Maximum number of holders to return per token. Capped at 20.
- in: query
name: market
required: true
style: form
explode: false
schema:
type: array
items:
$ref: '#/components/schemas/Hash64'
description: Comma-separated list of condition IDs.
- in: query
name: minBalance
schema:
type: integer
default: 1
minimum: 0
maximum: 999999
responses:
'200':
description: Success
content:
application/json:
schema:
type: array
items:
$ref: '#/components/schemas/MetaHolder'
'400':
description: Bad Request
content:
application/json:
schema:
$ref: '#/components/schemas/ErrorResponse'
'401':
description: Unauthorized
content:
application/json:
schema:
$ref: '#/components/schemas/ErrorResponse'
'500':
description: Server Error
content:
application/json:
schema:
$ref: '#/components/schemas/ErrorResponse'
components:
schemas:
Hash64:
type: string
description: 0x-prefixed 64-hex string
pattern: ^0x[a-fA-F0-9]{64}$
example: '0xdd22472e552920b8438158ea7238bfadfa4f736aa4cee91a6b86c39ead110917'
MetaHolder:
type: object
properties:
token:
type: string
holders:
type: array
items:
$ref: '#/components/schemas/Holder'
ErrorResponse:
type: object
properties:
error:
type: string
required:
- error
Holder:
type: object
properties:
proxyWallet:
$ref: '#/components/schemas/Address'
bio:
type: string
asset:
type: string
pseudonym:
type: string
amount:
type: number
displayUsernamePublic:
type: boolean
outcomeIndex:
type: integer
name:
type: string
profileImage:
type: string
profileImageOptimized:
type: string
Address:
type: string
description: User Profile Address (0x-prefixed, 40 hex chars)
pattern: ^0x[a-fA-F0-9]{40}$
example: '0x56687bf447db6ffa42ffe2204a05edaa20f55839'
````
@@ -0,0 +1,97 @@
> ## 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.
# Get total value of a user's positions
## OpenAPI
````yaml api-reference/data-api-openapi.yaml get /value
openapi: 3.0.3
info:
title: Polymarket Data API
version: 1.0.0
description: >
HTTP API for Polymarket data. This specification documents all public
routes.
servers:
- url: https://data-api.polymarket.com
description: Relative server (same host)
security: []
tags:
- name: Data API Status
description: Data API health check
- name: Core
- name: Builders
- name: Misc
paths:
/value:
get:
tags:
- Core
summary: Get total value of a user's positions
parameters:
- in: query
name: user
required: true
schema:
$ref: '#/components/schemas/Address'
- in: query
name: market
style: form
explode: false
schema:
type: array
items:
$ref: '#/components/schemas/Hash64'
responses:
'200':
description: Success
content:
application/json:
schema:
type: array
items:
$ref: '#/components/schemas/Value'
'400':
description: Bad Request
content:
application/json:
schema:
$ref: '#/components/schemas/ErrorResponse'
'500':
description: Server Error
content:
application/json:
schema:
$ref: '#/components/schemas/ErrorResponse'
components:
schemas:
Address:
type: string
description: User Profile Address (0x-prefixed, 40 hex chars)
pattern: ^0x[a-fA-F0-9]{40}$
example: '0x56687bf447db6ffa42ffe2204a05edaa20f55839'
Hash64:
type: string
description: 0x-prefixed 64-hex string
pattern: ^0x[a-fA-F0-9]{64}$
example: '0xdd22472e552920b8438158ea7238bfadfa4f736aa4cee91a6b86c39ead110917'
Value:
type: object
properties:
user:
$ref: '#/components/schemas/Address'
value:
type: number
ErrorResponse:
type: object
properties:
error:
type: string
required:
- error
````
@@ -0,0 +1,166 @@
> ## 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.
# Get trader leaderboard rankings
> Returns trader leaderboard rankings filtered by category, time period, and ordering.
## OpenAPI
````yaml api-reference/data-api-openapi.yaml get /v1/leaderboard
openapi: 3.0.3
info:
title: Polymarket Data API
version: 1.0.0
description: >
HTTP API for Polymarket data. This specification documents all public
routes.
servers:
- url: https://data-api.polymarket.com
description: Relative server (same host)
security: []
tags:
- name: Data API Status
description: Data API health check
- name: Core
- name: Builders
- name: Misc
paths:
/v1/leaderboard:
get:
tags:
- Core
summary: Get trader leaderboard rankings
description: >-
Returns trader leaderboard rankings filtered by category, time period,
and ordering.
parameters:
- in: query
name: category
schema:
type: string
enum:
- OVERALL
- POLITICS
- SPORTS
- CRYPTO
- CULTURE
- MENTIONS
- WEATHER
- ECONOMICS
- TECH
- FINANCE
default: OVERALL
description: Market category for the leaderboard
- in: query
name: timePeriod
schema:
type: string
enum:
- DAY
- WEEK
- MONTH
- ALL
default: DAY
description: Time period for leaderboard results
- in: query
name: orderBy
schema:
type: string
enum:
- PNL
- VOL
default: PNL
description: Leaderboard ordering criteria
- in: query
name: limit
schema:
type: integer
default: 25
minimum: 1
maximum: 50
description: Max number of leaderboard traders to return
- in: query
name: offset
schema:
type: integer
default: 0
minimum: 0
maximum: 1000
description: Starting index for pagination
- in: query
name: user
schema:
$ref: '#/components/schemas/Address'
description: Limit leaderboard to a single user by address
- in: query
name: userName
schema:
type: string
description: Limit leaderboard to a single username
responses:
'200':
description: Success
content:
application/json:
schema:
type: array
items:
$ref: '#/components/schemas/TraderLeaderboardEntry'
'400':
description: Bad Request
content:
application/json:
schema:
$ref: '#/components/schemas/ErrorResponse'
'500':
description: Server Error
content:
application/json:
schema:
$ref: '#/components/schemas/ErrorResponse'
components:
schemas:
Address:
type: string
description: User Profile Address (0x-prefixed, 40 hex chars)
pattern: ^0x[a-fA-F0-9]{40}$
example: '0x56687bf447db6ffa42ffe2204a05edaa20f55839'
TraderLeaderboardEntry:
type: object
properties:
rank:
type: string
description: The rank position of the trader
proxyWallet:
$ref: '#/components/schemas/Address'
userName:
type: string
description: The trader's username
vol:
type: number
description: Trading volume for this trader
pnl:
type: number
description: Profit and loss for this trader
profileImage:
type: string
description: URL to the trader's profile image
xUsername:
type: string
description: The trader's X (Twitter) username
verifiedBadge:
type: boolean
description: Whether the trader has a verified badge
ErrorResponse:
type: object
properties:
error:
type: string
required:
- error
````
@@ -0,0 +1,193 @@
> ## 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.
# Get trades for a user or markets
## OpenAPI
````yaml api-reference/data-api-openapi.yaml get /trades
openapi: 3.0.3
info:
title: Polymarket Data API
version: 1.0.0
description: >
HTTP API for Polymarket data. This specification documents all public
routes.
servers:
- url: https://data-api.polymarket.com
description: Relative server (same host)
security: []
tags:
- name: Data API Status
description: Data API health check
- name: Core
- name: Builders
- name: Misc
paths:
/trades:
get:
tags:
- Core
summary: Get trades for a user or markets
parameters:
- in: query
name: limit
schema:
type: integer
default: 100
minimum: 0
maximum: 10000
- in: query
name: offset
schema:
type: integer
default: 0
minimum: 0
maximum: 10000
- in: query
name: takerOnly
schema:
type: boolean
default: true
- in: query
name: filterType
schema:
type: string
enum:
- CASH
- TOKENS
description: Must be provided together with filterAmount.
- in: query
name: filterAmount
schema:
type: number
minimum: 0
description: Must be provided together with filterType.
- in: query
name: market
style: form
explode: false
schema:
type: array
items:
$ref: '#/components/schemas/Hash64'
description: >-
Comma-separated list of condition IDs. Mutually exclusive with
eventId.
- in: query
name: eventId
style: form
explode: false
schema:
type: array
items:
type: integer
minimum: 1
description: Comma-separated list of event IDs. Mutually exclusive with market.
- in: query
name: user
schema:
$ref: '#/components/schemas/Address'
- in: query
name: side
schema:
type: string
enum:
- BUY
- SELL
responses:
'200':
description: Success
content:
application/json:
schema:
type: array
items:
$ref: '#/components/schemas/Trade'
'400':
description: Bad Request
content:
application/json:
schema:
$ref: '#/components/schemas/ErrorResponse'
'401':
description: Unauthorized
content:
application/json:
schema:
$ref: '#/components/schemas/ErrorResponse'
'500':
description: Server Error
content:
application/json:
schema:
$ref: '#/components/schemas/ErrorResponse'
components:
schemas:
Hash64:
type: string
description: 0x-prefixed 64-hex string
pattern: ^0x[a-fA-F0-9]{64}$
example: '0xdd22472e552920b8438158ea7238bfadfa4f736aa4cee91a6b86c39ead110917'
Address:
type: string
description: User Profile Address (0x-prefixed, 40 hex chars)
pattern: ^0x[a-fA-F0-9]{40}$
example: '0x56687bf447db6ffa42ffe2204a05edaa20f55839'
Trade:
type: object
properties:
proxyWallet:
$ref: '#/components/schemas/Address'
side:
type: string
enum:
- BUY
- SELL
asset:
type: string
conditionId:
$ref: '#/components/schemas/Hash64'
size:
type: number
price:
type: number
timestamp:
type: integer
format: int64
title:
type: string
slug:
type: string
icon:
type: string
eventSlug:
type: string
outcome:
type: string
outcomeIndex:
type: integer
name:
type: string
pseudonym:
type: string
bio:
type: string
profileImage:
type: string
profileImageOptimized:
type: string
transactionHash:
type: string
ErrorResponse:
type: object
properties:
error:
type: string
required:
- error
````
@@ -0,0 +1,233 @@
> ## 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.
# Get user activity
> Returns on-chain activity for a user.
## OpenAPI
````yaml api-reference/data-api-openapi.yaml get /activity
openapi: 3.0.3
info:
title: Polymarket Data API
version: 1.0.0
description: >
HTTP API for Polymarket data. This specification documents all public
routes.
servers:
- url: https://data-api.polymarket.com
description: Relative server (same host)
security: []
tags:
- name: Data API Status
description: Data API health check
- name: Core
- name: Builders
- name: Misc
paths:
/activity:
get:
tags:
- Core
summary: Get user activity
description: Returns on-chain activity for a user.
parameters:
- in: query
name: limit
schema:
type: integer
default: 100
minimum: 0
maximum: 500
- in: query
name: offset
schema:
type: integer
default: 0
minimum: 0
maximum: 10000
- in: query
name: user
required: true
schema:
$ref: '#/components/schemas/Address'
- in: query
name: market
style: form
explode: false
schema:
type: array
items:
$ref: '#/components/schemas/Hash64'
description: >-
Comma-separated list of condition IDs. Mutually exclusive with
eventId.
- in: query
name: eventId
style: form
explode: false
schema:
type: array
items:
type: integer
minimum: 1
description: Comma-separated list of event IDs. Mutually exclusive with market.
- in: query
name: type
style: form
explode: false
schema:
type: array
items:
type: string
enum:
- TRADE
- SPLIT
- MERGE
- REDEEM
- REWARD
- CONVERSION
- MAKER_REBATE
- in: query
name: start
schema:
type: integer
minimum: 0
- in: query
name: end
schema:
type: integer
minimum: 0
- in: query
name: sortBy
schema:
type: string
enum:
- TIMESTAMP
- TOKENS
- CASH
default: TIMESTAMP
- in: query
name: sortDirection
schema:
type: string
enum:
- ASC
- DESC
default: DESC
- in: query
name: side
schema:
type: string
enum:
- BUY
- SELL
responses:
'200':
description: Success
content:
application/json:
schema:
type: array
items:
$ref: '#/components/schemas/Activity'
'400':
description: Bad Request
content:
application/json:
schema:
$ref: '#/components/schemas/ErrorResponse'
'401':
description: Unauthorized
content:
application/json:
schema:
$ref: '#/components/schemas/ErrorResponse'
'500':
description: Server Error
content:
application/json:
schema:
$ref: '#/components/schemas/ErrorResponse'
components:
schemas:
Address:
type: string
description: User Profile Address (0x-prefixed, 40 hex chars)
pattern: ^0x[a-fA-F0-9]{40}$
example: '0x56687bf447db6ffa42ffe2204a05edaa20f55839'
Hash64:
type: string
description: 0x-prefixed 64-hex string
pattern: ^0x[a-fA-F0-9]{64}$
example: '0xdd22472e552920b8438158ea7238bfadfa4f736aa4cee91a6b86c39ead110917'
Activity:
type: object
properties:
proxyWallet:
$ref: '#/components/schemas/Address'
timestamp:
type: integer
format: int64
conditionId:
$ref: '#/components/schemas/Hash64'
type:
type: string
enum:
- TRADE
- SPLIT
- MERGE
- REDEEM
- REWARD
- CONVERSION
- MAKER_REBATE
size:
type: number
usdcSize:
type: number
transactionHash:
type: string
price:
type: number
asset:
type: string
side:
type: string
enum:
- BUY
- SELL
outcomeIndex:
type: integer
title:
type: string
slug:
type: string
icon:
type: string
eventSlug:
type: string
outcome:
type: string
name:
type: string
pseudonym:
type: string
bio:
type: string
profileImage:
type: string
profileImageOptimized:
type: string
ErrorResponse:
type: object
properties:
error:
type: string
required:
- error
````
@@ -0,0 +1,52 @@
> ## 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.
# Data API Health check
## OpenAPI
````yaml api-reference/data-api-openapi.yaml get /
openapi: 3.0.3
info:
title: Polymarket Data API
version: 1.0.0
description: >
HTTP API for Polymarket data. This specification documents all public
routes.
servers:
- url: https://data-api.polymarket.com
description: Relative server (same host)
security: []
tags:
- name: Data API Status
description: Data API health check
- name: Core
- name: Builders
- name: Misc
paths:
/:
get:
tags:
- Data API Status
summary: Data API Health check
operationId: getDataApiHealth
responses:
'200':
description: OK
content:
application/json:
schema:
$ref: '#/components/schemas/HealthResponse'
components:
schemas:
HealthResponse:
type: object
properties:
data:
type: string
example: OK
````
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
+108
View File
@@ -0,0 +1,108 @@
> ## 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.
# Get event tags
## OpenAPI
````yaml api-reference/gamma-openapi.json get /events/{id}/tags
openapi: 3.0.3
info:
title: Markets API
version: 1.0.0
description: REST API specification for public endpoints used by the Markets service.
servers:
- url: https://gamma-api.polymarket.com
description: Polymarket Gamma API Production Server
security: []
tags:
- name: Gamma Status
description: Gamma API status and health check
- name: Sports
description: Sports-related endpoints including teams and game data
- name: Tags
description: Tag management and related tag operations
- name: Events
description: Event management and event-related operations
- name: Markets
description: Market data and market-related operations
- name: Comments
description: Comment system and user interactions
- name: Series
description: Series management and related operations
- name: Profiles
description: User profile management
- name: Search
description: Search functionality across different entity types
paths:
/events/{id}/tags:
get:
tags:
- Events
- Tags
summary: Get event tags
operationId: getEventTags
parameters:
- $ref: '#/components/parameters/pathId'
responses:
'200':
description: Tags attached to the event
content:
application/json:
schema:
type: array
items:
$ref: '#/components/schemas/Tag'
'404':
description: Not found
components:
parameters:
pathId:
name: id
in: path
required: true
schema:
type: integer
schemas:
Tag:
type: object
properties:
id:
type: string
label:
type: string
nullable: true
slug:
type: string
nullable: true
forceShow:
type: boolean
nullable: true
publishedAt:
type: string
nullable: true
createdBy:
type: integer
nullable: true
updatedBy:
type: integer
nullable: true
createdAt:
type: string
format: date-time
nullable: true
updatedAt:
type: string
format: date-time
nullable: true
forceHide:
type: boolean
nullable: true
isCarousel:
type: boolean
nullable: true
````
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,56 @@
> ## 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.
# Gamma API Health check
## OpenAPI
````yaml api-reference/gamma-openapi.json get /status
openapi: 3.0.3
info:
title: Markets API
version: 1.0.0
description: REST API specification for public endpoints used by the Markets service.
servers:
- url: https://gamma-api.polymarket.com
description: Polymarket Gamma API Production Server
security: []
tags:
- name: Gamma Status
description: Gamma API status and health check
- name: Sports
description: Sports-related endpoints including teams and game data
- name: Tags
description: Tag management and related tag operations
- name: Events
description: Event management and event-related operations
- name: Markets
description: Market data and market-related operations
- name: Comments
description: Comment system and user interactions
- name: Series
description: Series management and related operations
- name: Profiles
description: User profile management
- name: Search
description: Search functionality across different entity types
paths:
/status:
get:
tags:
- Gamma Status
summary: Gamma API Health check
operationId: getGammaStatus
responses:
'200':
description: OK
content:
text/plain:
schema:
type: string
example: OK
````
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,108 @@
> ## 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.
# Get market tags by id
## OpenAPI
````yaml api-reference/gamma-openapi.json get /markets/{id}/tags
openapi: 3.0.3
info:
title: Markets API
version: 1.0.0
description: REST API specification for public endpoints used by the Markets service.
servers:
- url: https://gamma-api.polymarket.com
description: Polymarket Gamma API Production Server
security: []
tags:
- name: Gamma Status
description: Gamma API status and health check
- name: Sports
description: Sports-related endpoints including teams and game data
- name: Tags
description: Tag management and related tag operations
- name: Events
description: Event management and event-related operations
- name: Markets
description: Market data and market-related operations
- name: Comments
description: Comment system and user interactions
- name: Series
description: Series management and related operations
- name: Profiles
description: User profile management
- name: Search
description: Search functionality across different entity types
paths:
/markets/{id}/tags:
get:
tags:
- Markets
- Tags
summary: Get market tags by id
operationId: getMarketTags
parameters:
- $ref: '#/components/parameters/pathId'
responses:
'200':
description: Tags attached to the market
content:
application/json:
schema:
type: array
items:
$ref: '#/components/schemas/Tag'
'404':
description: Not found
components:
parameters:
pathId:
name: id
in: path
required: true
schema:
type: integer
schemas:
Tag:
type: object
properties:
id:
type: string
label:
type: string
nullable: true
slug:
type: string
nullable: true
forceShow:
type: boolean
nullable: true
publishedAt:
type: string
nullable: true
createdBy:
type: integer
nullable: true
updatedBy:
type: integer
nullable: true
createdAt:
type: string
format: date-time
nullable: true
updatedAt:
type: string
format: date-time
nullable: true
forceHide:
type: boolean
nullable: true
isCarousel:
type: boolean
nullable: true
````
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,161 @@
> ## 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.
# Download an accounting snapshot (ZIP of CSVs)
> Public endpoint (no auth) that returns an `application/zip` containing two CSV files generated from the same snapshot time.
**ZIP contents**
1) `positions.csv` (0+ rows)
- Columns (in order):
- `conditionId` (string): market condition id
- `asset` (string): outcome token id (uniquely identifies the position within a market)
- `size` (number): tokens, 6 decimals
- `curPrice` (number): per-token price/value in USDC, 6 decimals
- `valuationTime` (string): RFC3339 UTC timestamp
2) `equity.csv` (0 or 1 row)
- Columns (in order):
- `cashBalance` (number): onchain USDC `balanceOf(user)` using Polygon USDC `0x2791bca1f2de4661ed88a30c99a7a9449aa84174`, 6 decimals
- `positionsValue` (number): \(\sum(\text{size} \times \text{curPrice})\) across `positions.csv`, 6 decimals
- `equity` (number): `cashBalance + positionsValue`, 6 decimals
- `valuationTime` (string): RFC3339 UTC timestamp (same snapshot time as `positions.csv`)
**Example `positions.csv`**
```csv
conditionId,asset,size,curPrice,valuationTime
0xd007d71fd17b0913b9d7ff198f617caa96a9e4aab1bed7d6f9abd76bb17dd507,65396714035221124737265515219989336303267439172398528294132309725835127126381,90548.087076,0.064500,2026-01-21T18:30:00Z
0x96f6fb6567b5938fc3c2e75f9829d7287340b9581a9c4817b8bc0aff82e1c45f,10057237541929696185971116542487795282113077727880089878027691009747516185940,45666.487374,0.495000,2026-01-21T18:30:00Z
```
**Example `equity.csv`**
```csv
cashBalance,positionsValue,equity,valuationTime
125000.000000,28481009.037705,28606009.037705,2026-01-21T18:30:00Z
```
## OpenAPI
````yaml api-reference/data-api-openapi.yaml get /v1/accounting/snapshot
openapi: 3.0.3
info:
title: Polymarket Data API
version: 1.0.0
description: >
HTTP API for Polymarket data. This specification documents all public
routes.
servers:
- url: https://data-api.polymarket.com
description: Relative server (same host)
security: []
tags:
- name: Data API Status
description: Data API health check
- name: Core
- name: Builders
- name: Misc
paths:
/v1/accounting/snapshot:
get:
tags:
- Misc
summary: Download an accounting snapshot (ZIP of CSVs)
description: >
Public endpoint (no auth) that returns an `application/zip` containing
two CSV files generated from the same snapshot time.
**ZIP contents**
1) `positions.csv` (0+ rows)
- Columns (in order):
- `conditionId` (string): market condition id
- `asset` (string): outcome token id (uniquely identifies the position within a market)
- `size` (number): tokens, 6 decimals
- `curPrice` (number): per-token price/value in USDC, 6 decimals
- `valuationTime` (string): RFC3339 UTC timestamp
2) `equity.csv` (0 or 1 row)
- Columns (in order):
- `cashBalance` (number): onchain USDC `balanceOf(user)` using Polygon USDC `0x2791bca1f2de4661ed88a30c99a7a9449aa84174`, 6 decimals
- `positionsValue` (number): \(\sum(\text{size} \times \text{curPrice})\) across `positions.csv`, 6 decimals
- `equity` (number): `cashBalance + positionsValue`, 6 decimals
- `valuationTime` (string): RFC3339 UTC timestamp (same snapshot time as `positions.csv`)
**Example `positions.csv`**
```csv
conditionId,asset,size,curPrice,valuationTime
0xd007d71fd17b0913b9d7ff198f617caa96a9e4aab1bed7d6f9abd76bb17dd507,65396714035221124737265515219989336303267439172398528294132309725835127126381,90548.087076,0.064500,2026-01-21T18:30:00Z
0x96f6fb6567b5938fc3c2e75f9829d7287340b9581a9c4817b8bc0aff82e1c45f,10057237541929696185971116542487795282113077727880089878027691009747516185940,45666.487374,0.495000,2026-01-21T18:30:00Z
```
**Example `equity.csv`**
```csv
cashBalance,positionsValue,equity,valuationTime
125000.000000,28481009.037705,28606009.037705,2026-01-21T18:30:00Z
```
parameters:
- in: query
name: user
required: true
schema:
$ref: '#/components/schemas/Address'
description: User address (0x-prefixed)
responses:
'200':
description: ZIP file containing `positions.csv` and `equity.csv`.
content:
application/zip:
schema:
type: string
format: binary
'400':
description: Bad Request
content:
application/json:
schema:
$ref: '#/components/schemas/ErrorResponse'
'500':
description: Server Error
content:
application/json:
schema:
$ref: '#/components/schemas/ErrorResponse'
components:
schemas:
Address:
type: string
description: User Profile Address (0x-prefixed, 40 hex chars)
pattern: ^0x[a-fA-F0-9]{40}$
example: '0x56687bf447db6ffa42ffe2204a05edaa20f55839'
ErrorResponse:
type: object
properties:
error:
type: string
required:
- error
````
@@ -0,0 +1,94 @@
> ## 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.
# Get live volume for an event
## OpenAPI
````yaml api-reference/data-api-openapi.yaml get /live-volume
openapi: 3.0.3
info:
title: Polymarket Data API
version: 1.0.0
description: >
HTTP API for Polymarket data. This specification documents all public
routes.
servers:
- url: https://data-api.polymarket.com
description: Relative server (same host)
security: []
tags:
- name: Data API Status
description: Data API health check
- name: Core
- name: Builders
- name: Misc
paths:
/live-volume:
get:
tags:
- Misc
summary: Get live volume for an event
parameters:
- in: query
name: id
required: true
schema:
type: integer
minimum: 1
responses:
'200':
description: Success
content:
application/json:
schema:
type: array
items:
$ref: '#/components/schemas/LiveVolume'
'400':
description: Bad Request
content:
application/json:
schema:
$ref: '#/components/schemas/ErrorResponse'
'500':
description: Server Error
content:
application/json:
schema:
$ref: '#/components/schemas/ErrorResponse'
components:
schemas:
LiveVolume:
type: object
properties:
total:
type: number
markets:
type: array
items:
$ref: '#/components/schemas/MarketVolume'
ErrorResponse:
type: object
properties:
error:
type: string
required:
- error
MarketVolume:
type: object
properties:
market:
$ref: '#/components/schemas/Hash64'
value:
type: number
Hash64:
type: string
description: 0x-prefixed 64-hex string
pattern: ^0x[a-fA-F0-9]{64}$
example: '0xdd22472e552920b8438158ea7238bfadfa4f736aa4cee91a6b86c39ead110917'
````
@@ -0,0 +1,87 @@
> ## 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.
# Get open interest
## OpenAPI
````yaml api-reference/data-api-openapi.yaml get /oi
openapi: 3.0.3
info:
title: Polymarket Data API
version: 1.0.0
description: >
HTTP API for Polymarket data. This specification documents all public
routes.
servers:
- url: https://data-api.polymarket.com
description: Relative server (same host)
security: []
tags:
- name: Data API Status
description: Data API health check
- name: Core
- name: Builders
- name: Misc
paths:
/oi:
get:
tags:
- Misc
summary: Get open interest
parameters:
- in: query
name: market
style: form
explode: false
schema:
type: array
items:
$ref: '#/components/schemas/Hash64'
responses:
'200':
description: Success
content:
application/json:
schema:
type: array
items:
$ref: '#/components/schemas/OpenInterest'
'400':
description: Bad Request
content:
application/json:
schema:
$ref: '#/components/schemas/ErrorResponse'
'500':
description: Server Error
content:
application/json:
schema:
$ref: '#/components/schemas/ErrorResponse'
components:
schemas:
Hash64:
type: string
description: 0x-prefixed 64-hex string
pattern: ^0x[a-fA-F0-9]{64}$
example: '0xdd22472e552920b8438158ea7238bfadfa4f736aa4cee91a6b86c39ead110917'
OpenInterest:
type: object
properties:
market:
$ref: '#/components/schemas/Hash64'
value:
type: number
ErrorResponse:
type: object
properties:
error:
type: string
required:
- error
````
@@ -0,0 +1,88 @@
> ## 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.
# Get total markets a user has traded
## OpenAPI
````yaml api-reference/data-api-openapi.yaml get /traded
openapi: 3.0.3
info:
title: Polymarket Data API
version: 1.0.0
description: >
HTTP API for Polymarket data. This specification documents all public
routes.
servers:
- url: https://data-api.polymarket.com
description: Relative server (same host)
security: []
tags:
- name: Data API Status
description: Data API health check
- name: Core
- name: Builders
- name: Misc
paths:
/traded:
get:
tags:
- Misc
summary: Get total markets a user has traded
parameters:
- in: query
name: user
required: true
schema:
$ref: '#/components/schemas/Address'
responses:
'200':
description: Success
content:
application/json:
schema:
$ref: '#/components/schemas/Traded'
'400':
description: Bad Request
content:
application/json:
schema:
$ref: '#/components/schemas/ErrorResponse'
'401':
description: Unauthorized
content:
application/json:
schema:
$ref: '#/components/schemas/ErrorResponse'
'500':
description: Server Error
content:
application/json:
schema:
$ref: '#/components/schemas/ErrorResponse'
components:
schemas:
Address:
type: string
description: User Profile Address (0x-prefixed, 40 hex chars)
pattern: ^0x[a-fA-F0-9]{40}$
example: '0x56687bf447db6ffa42ffe2204a05edaa20f55839'
Traded:
type: object
properties:
user:
$ref: '#/components/schemas/Address'
traded:
type: integer
ErrorResponse:
type: object
properties:
error:
type: string
required:
- error
````
@@ -0,0 +1,177 @@
> ## 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.
# Get multiple order books summaries by request
> Retrieves order book summaries for specified tokens via POST request
## OpenAPI
````yaml api-reference/clob-subset-openapi.yaml post /books
openapi: 3.0.3
info:
title: CLOB (Central Limit Order Book) API
description: >-
API for interacting with the Central Limit Order Book system, providing
orderbook data, prices, midpoints, and spreads
version: 1.0.0
contact:
name: CLOB API Team
license:
name: MIT
servers:
- url: https://clob.polymarket.com/
description: Production server
security: []
tags:
- name: Orderbook
description: Order book related operations
- name: Pricing
description: Price and midpoint operations
- name: Spreads
description: Spread calculation operations
paths:
/books:
post:
tags:
- Orderbook
summary: Get multiple order books summaries by request
description: Retrieves order book summaries for specified tokens via POST request
requestBody:
required: true
content:
application/json:
schema:
type: array
items:
$ref: '#/components/schemas/BookRequest'
maxItems: 500
example:
- token_id: '1234567890'
- token_id: '0987654321'
responses:
'200':
description: Successful response
content:
application/json:
schema:
type: array
items:
$ref: '#/components/schemas/OrderBookSummary'
'400':
description: Bad request - Invalid payload or exceeds limit
content:
application/json:
schema:
$ref: '#/components/schemas/Error'
examples:
invalid_payload:
value:
error: Invalid payload
exceeds_limit:
value:
error: Payload exceeds the limit
'500':
description: Internal server error
content:
application/json:
schema:
$ref: '#/components/schemas/Error'
components:
schemas:
BookRequest:
type: object
required:
- token_id
properties:
token_id:
type: string
description: The unique identifier for the token
example: '1234567890'
side:
type: string
enum:
- BUY
- SELL
description: Optional side parameter for certain operations
example: BUY
OrderBookSummary:
type: object
required:
- market
- asset_id
- timestamp
- hash
- bids
- asks
- min_order_size
- tick_size
- neg_risk
properties:
market:
type: string
description: Market identifier
example: '0x1b6f76e5b8587ee896c35847e12d11e75290a8c3934c5952e8a9d6e4c6f03cfa'
asset_id:
type: string
description: Asset identifier
example: '1234567890'
timestamp:
type: string
format: date-time
description: Timestamp of the order book snapshot
example: '2023-10-01T12:00:00Z'
hash:
type: string
description: Hash of the order book state
example: 0xabc123def456...
bids:
type: array
items:
$ref: '#/components/schemas/OrderLevel'
description: Array of bid levels
asks:
type: array
items:
$ref: '#/components/schemas/OrderLevel'
description: Array of ask levels
min_order_size:
type: string
description: Minimum order size for this market
example: '0.001'
tick_size:
type: string
description: Minimum price increment
example: '0.01'
neg_risk:
type: boolean
description: Whether negative risk is enabled
example: false
Error:
type: object
required:
- error
properties:
error:
type: string
description: Error message describing what went wrong
example: Invalid token id
OrderLevel:
type: object
required:
- price
- size
properties:
price:
type: string
description: Price level (as string to maintain precision)
example: '1800.50'
size:
type: string
description: Total size at this price level
example: '10.5'
````
@@ -0,0 +1,160 @@
> ## 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.
# Get order book summary
> Retrieves the order book summary for a specific token
## OpenAPI
````yaml api-reference/clob-subset-openapi.yaml get /book
openapi: 3.0.3
info:
title: CLOB (Central Limit Order Book) API
description: >-
API for interacting with the Central Limit Order Book system, providing
orderbook data, prices, midpoints, and spreads
version: 1.0.0
contact:
name: CLOB API Team
license:
name: MIT
servers:
- url: https://clob.polymarket.com/
description: Production server
security: []
tags:
- name: Orderbook
description: Order book related operations
- name: Pricing
description: Price and midpoint operations
- name: Spreads
description: Spread calculation operations
paths:
/book:
get:
tags:
- Orderbook
summary: Get order book summary
description: Retrieves the order book summary for a specific token
parameters:
- name: token_id
in: query
required: true
schema:
type: string
description: The unique identifier for the token
example: '1234567890'
responses:
'200':
description: Successful response
content:
application/json:
schema:
$ref: '#/components/schemas/OrderBookSummary'
'400':
description: Bad request
content:
application/json:
schema:
$ref: '#/components/schemas/Error'
example:
error: Invalid token id
'404':
description: Order book not found
content:
application/json:
schema:
$ref: '#/components/schemas/Error'
example:
error: No orderbook exists for the requested token id
'500':
description: Internal server error
content:
application/json:
schema:
$ref: '#/components/schemas/Error'
example:
error: error getting the orderbook
components:
schemas:
OrderBookSummary:
type: object
required:
- market
- asset_id
- timestamp
- hash
- bids
- asks
- min_order_size
- tick_size
- neg_risk
properties:
market:
type: string
description: Market identifier
example: '0x1b6f76e5b8587ee896c35847e12d11e75290a8c3934c5952e8a9d6e4c6f03cfa'
asset_id:
type: string
description: Asset identifier
example: '1234567890'
timestamp:
type: string
format: date-time
description: Timestamp of the order book snapshot
example: '2023-10-01T12:00:00Z'
hash:
type: string
description: Hash of the order book state
example: 0xabc123def456...
bids:
type: array
items:
$ref: '#/components/schemas/OrderLevel'
description: Array of bid levels
asks:
type: array
items:
$ref: '#/components/schemas/OrderLevel'
description: Array of ask levels
min_order_size:
type: string
description: Minimum order size for this market
example: '0.001'
tick_size:
type: string
description: Minimum price increment
example: '0.01'
neg_risk:
type: boolean
description: Whether negative risk is enabled
example: false
Error:
type: object
required:
- error
properties:
error:
type: string
description: Error message describing what went wrong
example: Invalid token id
OrderLevel:
type: object
required:
- price
- size
properties:
price:
type: string
description: Price level (as string to maintain precision)
example: '1800.50'
size:
type: string
description: Total size at this price level
example: '10.5'
````
@@ -0,0 +1,116 @@
> ## 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.
# Get market price
> Retrieves the market price for a specific token and side
## OpenAPI
````yaml api-reference/clob-subset-openapi.yaml get /price
openapi: 3.0.3
info:
title: CLOB (Central Limit Order Book) API
description: >-
API for interacting with the Central Limit Order Book system, providing
orderbook data, prices, midpoints, and spreads
version: 1.0.0
contact:
name: CLOB API Team
license:
name: MIT
servers:
- url: https://clob.polymarket.com/
description: Production server
security: []
tags:
- name: Orderbook
description: Order book related operations
- name: Pricing
description: Price and midpoint operations
- name: Spreads
description: Spread calculation operations
paths:
/price:
get:
tags:
- Pricing
summary: Get market price
description: Retrieves the market price for a specific token and side
parameters:
- name: token_id
in: query
required: true
schema:
type: string
description: The unique identifier for the token
example: '1234567890'
- name: side
in: query
required: true
schema:
type: string
enum:
- BUY
- SELL
description: The side of the market (BUY or SELL)
example: BUY
responses:
'200':
description: Successful response
content:
application/json:
schema:
$ref: '#/components/schemas/PriceResponse'
'400':
description: Bad request
content:
application/json:
schema:
$ref: '#/components/schemas/Error'
examples:
invalid_token:
value:
error: Invalid token id
invalid_side:
value:
error: Invalid side
'404':
description: Order book not found
content:
application/json:
schema:
$ref: '#/components/schemas/Error'
example:
error: No orderbook exists for the requested token id
'500':
description: Internal server error
content:
application/json:
schema:
$ref: '#/components/schemas/Error'
components:
schemas:
PriceResponse:
type: object
required:
- price
properties:
price:
type: string
description: The market price (as string to maintain precision)
example: '1800.50'
Error:
type: object
required:
- error
properties:
error:
type: string
description: Error message describing what went wrong
example: Invalid token id
````
@@ -0,0 +1,101 @@
> ## 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.
# Get midpoint price
> Retrieves the midpoint price for a specific token
## OpenAPI
````yaml api-reference/clob-subset-openapi.yaml get /midpoint
openapi: 3.0.3
info:
title: CLOB (Central Limit Order Book) API
description: >-
API for interacting with the Central Limit Order Book system, providing
orderbook data, prices, midpoints, and spreads
version: 1.0.0
contact:
name: CLOB API Team
license:
name: MIT
servers:
- url: https://clob.polymarket.com/
description: Production server
security: []
tags:
- name: Orderbook
description: Order book related operations
- name: Pricing
description: Price and midpoint operations
- name: Spreads
description: Spread calculation operations
paths:
/midpoint:
get:
tags:
- Pricing
summary: Get midpoint price
description: Retrieves the midpoint price for a specific token
parameters:
- name: token_id
in: query
required: true
schema:
type: string
description: The unique identifier for the token
example: '1234567890'
responses:
'200':
description: Successful response
content:
application/json:
schema:
$ref: '#/components/schemas/MidpointResponse'
'400':
description: Bad request
content:
application/json:
schema:
$ref: '#/components/schemas/Error'
example:
error: Invalid token id
'404':
description: Order book not found
content:
application/json:
schema:
$ref: '#/components/schemas/Error'
example:
error: No orderbook exists for the requested token id
'500':
description: Internal server error
content:
application/json:
schema:
$ref: '#/components/schemas/Error'
components:
schemas:
MidpointResponse:
type: object
required:
- mid
properties:
mid:
type: string
description: The midpoint price (as string to maintain precision)
example: '1800.75'
Error:
type: object
required:
- error
properties:
error:
type: string
description: Error message describing what went wrong
example: Invalid token id
````
@@ -0,0 +1,137 @@
> ## 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.
# Get multiple market prices by request
> Retrieves market prices for specified tokens and sides via POST request
## OpenAPI
````yaml api-reference/clob-subset-openapi.yaml post /prices
openapi: 3.0.3
info:
title: CLOB (Central Limit Order Book) API
description: >-
API for interacting with the Central Limit Order Book system, providing
orderbook data, prices, midpoints, and spreads
version: 1.0.0
contact:
name: CLOB API Team
license:
name: MIT
servers:
- url: https://clob.polymarket.com/
description: Production server
security: []
tags:
- name: Orderbook
description: Order book related operations
- name: Pricing
description: Price and midpoint operations
- name: Spreads
description: Spread calculation operations
paths:
/prices:
post:
tags:
- Pricing
summary: Get multiple market prices by request
description: Retrieves market prices for specified tokens and sides via POST request
requestBody:
required: true
content:
application/json:
schema:
type: array
items:
$ref: '#/components/schemas/PriceRequest'
maxItems: 500
example:
- token_id: '1234567890'
side: BUY
- token_id: '0987654321'
side: SELL
responses:
'200':
description: Successful response
content:
application/json:
schema:
$ref: '#/components/schemas/PricesResponse'
'400':
description: Bad request - Invalid payload, exceeds limit, or invalid side
content:
application/json:
schema:
$ref: '#/components/schemas/Error'
examples:
invalid_payload:
value:
error: Invalid payload
exceeds_limit:
value:
error: Payload exceeds the limit
invalid_side:
value:
error: Invalid side
'404':
description: Order book not found
content:
application/json:
schema:
$ref: '#/components/schemas/Error'
example:
error: No orderbook exists for the requested token id
'500':
description: Internal server error
content:
application/json:
schema:
$ref: '#/components/schemas/Error'
components:
schemas:
PriceRequest:
type: object
required:
- token_id
- side
properties:
token_id:
type: string
description: The unique identifier for the token
example: '1234567890'
side:
type: string
enum:
- BUY
- SELL
description: The side of the market (BUY or SELL)
example: BUY
PricesResponse:
type: object
additionalProperties:
type: object
additionalProperties:
type: string
description: Map of token_id to side to price
example:
'1234567890':
BUY: '1800.50'
SELL: '1801.00'
'0987654321':
BUY: '50.25'
SELL: '50.30'
Error:
type: object
required:
- error
properties:
error:
type: string
description: Error message describing what went wrong
example: Invalid token id
````
@@ -0,0 +1,88 @@
> ## 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.
# Get multiple market prices
> Retrieves market prices for multiple tokens and sides
## OpenAPI
````yaml api-reference/clob-subset-openapi.yaml get /prices
openapi: 3.0.3
info:
title: CLOB (Central Limit Order Book) API
description: >-
API for interacting with the Central Limit Order Book system, providing
orderbook data, prices, midpoints, and spreads
version: 1.0.0
contact:
name: CLOB API Team
license:
name: MIT
servers:
- url: https://clob.polymarket.com/
description: Production server
security: []
tags:
- name: Orderbook
description: Order book related operations
- name: Pricing
description: Price and midpoint operations
- name: Spreads
description: Spread calculation operations
paths:
/prices:
get:
tags:
- Pricing
summary: Get multiple market prices
description: Retrieves market prices for multiple tokens and sides
responses:
'200':
description: Successful response
content:
application/json:
schema:
$ref: '#/components/schemas/PricesResponse'
'400':
description: Bad request
content:
application/json:
schema:
$ref: '#/components/schemas/Error'
'500':
description: Internal server error
content:
application/json:
schema:
$ref: '#/components/schemas/Error'
components:
schemas:
PricesResponse:
type: object
additionalProperties:
type: object
additionalProperties:
type: string
description: Map of token_id to side to price
example:
'1234567890':
BUY: '1800.50'
SELL: '1801.00'
'0987654321':
BUY: '50.25'
SELL: '50.30'
Error:
type: object
required:
- error
properties:
error:
type: string
description: Error message describing what went wrong
example: Invalid token id
````
@@ -0,0 +1,146 @@
> ## 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.
# Get price history for a traded token
> Fetches historical price data for a specified market token
## OpenAPI
````yaml api-reference/clob-subset-openapi.yaml get /prices-history
openapi: 3.0.3
info:
title: CLOB (Central Limit Order Book) API
description: >-
API for interacting with the Central Limit Order Book system, providing
orderbook data, prices, midpoints, and spreads
version: 1.0.0
contact:
name: CLOB API Team
license:
name: MIT
servers:
- url: https://clob.polymarket.com/
description: Production server
security: []
tags:
- name: Orderbook
description: Order book related operations
- name: Pricing
description: Price and midpoint operations
- name: Spreads
description: Spread calculation operations
paths:
/prices-history:
get:
tags:
- Pricing
summary: Get price history for a traded token
description: Fetches historical price data for a specified market token
parameters:
- name: market
in: query
required: true
schema:
type: string
description: The CLOB token ID for which to fetch price history
example: '1234567890'
- name: startTs
in: query
required: false
schema:
type: number
description: The start time, a Unix timestamp in UTC
example: 1697875200
- name: endTs
in: query
required: false
schema:
type: number
description: The end time, a Unix timestamp in UTC
example: 1697961600
- name: interval
in: query
required: false
schema:
type: string
enum:
- 1m
- 1w
- 1d
- 6h
- 1h
- max
description: >-
A string representing a duration ending at the current time.
Mutually exclusive with startTs and endTs
example: 1d
- name: fidelity
in: query
required: false
schema:
type: number
description: The resolution of the data, in minutes
example: 60
responses:
'200':
description: A list of timestamp/price pairs
content:
application/json:
schema:
$ref: '#/components/schemas/PriceHistoryResponse'
'400':
description: Bad request
content:
application/json:
schema:
$ref: '#/components/schemas/Error'
'404':
description: Market not found
content:
application/json:
schema:
$ref: '#/components/schemas/Error'
'500':
description: Internal server error
content:
application/json:
schema:
$ref: '#/components/schemas/Error'
components:
schemas:
PriceHistoryResponse:
type: object
required:
- history
properties:
history:
type: array
items:
type: object
required:
- t
- p
properties:
t:
type: number
description: UTC timestamp
example: 1697875200
p:
type: number
description: Price
example: 1800.75
Error:
type: object
required:
- error
properties:
error:
type: string
description: Error message describing what went wrong
example: Invalid token id
````
@@ -0,0 +1,154 @@
> ## 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.
# Get public profile by wallet address
## OpenAPI
````yaml api-reference/gamma-openapi.json get /public-profile
openapi: 3.0.3
info:
title: Markets API
version: 1.0.0
description: REST API specification for public endpoints used by the Markets service.
servers:
- url: https://gamma-api.polymarket.com
description: Polymarket Gamma API Production Server
security: []
tags:
- name: Gamma Status
description: Gamma API status and health check
- name: Sports
description: Sports-related endpoints including teams and game data
- name: Tags
description: Tag management and related tag operations
- name: Events
description: Event management and event-related operations
- name: Markets
description: Market data and market-related operations
- name: Comments
description: Comment system and user interactions
- name: Series
description: Series management and related operations
- name: Profiles
description: User profile management
- name: Search
description: Search functionality across different entity types
paths:
/public-profile:
get:
tags:
- Profiles
summary: Get public profile by wallet address
operationId: getPublicProfile
parameters:
- name: address
in: query
required: true
description: The wallet address (proxy wallet or user address)
schema:
type: string
pattern: ^0x[a-fA-F0-9]{40}$
example: '0x7c3db723f1d4d8cb9c550095203b686cb11e5c6b'
responses:
'200':
description: Public profile information
content:
application/json:
schema:
$ref: '#/components/schemas/PublicProfileResponse'
'400':
description: Invalid address format
content:
application/json:
schema:
$ref: '#/components/schemas/PublicProfileError'
example:
type: validation error
error: invalid address
'404':
description: Profile not found
content:
application/json:
schema:
$ref: '#/components/schemas/PublicProfileError'
example:
type: not found error
error: profile not found
components:
schemas:
PublicProfileResponse:
type: object
properties:
createdAt:
type: string
format: date-time
description: ISO 8601 timestamp of when the profile was created
nullable: true
proxyWallet:
type: string
description: The proxy wallet address
nullable: true
profileImage:
type: string
format: uri
description: URL to the profile image
nullable: true
displayUsernamePublic:
type: boolean
description: Whether the username is displayed publicly
nullable: true
bio:
type: string
description: Profile bio
nullable: true
pseudonym:
type: string
description: Auto-generated pseudonym
nullable: true
name:
type: string
description: User-chosen display name
nullable: true
users:
type: array
description: Array of associated user objects
nullable: true
items:
$ref: '#/components/schemas/PublicProfileUser'
xUsername:
type: string
description: X (Twitter) username
nullable: true
verifiedBadge:
type: boolean
description: Whether the profile has a verified badge
nullable: true
PublicProfileError:
type: object
description: Error response for public profile endpoint
properties:
type:
type: string
description: Error type classification
error:
type: string
description: Error message
PublicProfileUser:
type: object
description: User object associated with a public profile
properties:
id:
type: string
description: User ID
creator:
type: boolean
description: Whether the user is a creator
mod:
type: boolean
description: Whether the user is a moderator
````
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,97 @@
> ## 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.
# Get sports metadata information
> Retrieves metadata for various sports including images, resolution sources, ordering preferences, tags, and series information. This endpoint provides comprehensive sport configuration data used throughout the platform.
## OpenAPI
````yaml api-reference/gamma-openapi.json get /sports
openapi: 3.0.3
info:
title: Markets API
version: 1.0.0
description: REST API specification for public endpoints used by the Markets service.
servers:
- url: https://gamma-api.polymarket.com
description: Polymarket Gamma API Production Server
security: []
tags:
- name: Gamma Status
description: Gamma API status and health check
- name: Sports
description: Sports-related endpoints including teams and game data
- name: Tags
description: Tag management and related tag operations
- name: Events
description: Event management and event-related operations
- name: Markets
description: Market data and market-related operations
- name: Comments
description: Comment system and user interactions
- name: Series
description: Series management and related operations
- name: Profiles
description: User profile management
- name: Search
description: Search functionality across different entity types
paths:
/sports:
get:
tags:
- Sports
summary: Get sports metadata information
description: >-
Retrieves metadata for various sports including images, resolution
sources, ordering preferences, tags, and series information. This
endpoint provides comprehensive sport configuration data used throughout
the platform.
operationId: getSportsMetadata
responses:
'200':
description: >-
List of sports metadata objects containing sport configuration
details, visual assets, and related identifiers
content:
application/json:
schema:
type: array
items:
$ref: '#/components/schemas/SportsMetadata'
components:
schemas:
SportsMetadata:
type: object
properties:
sport:
type: string
description: The sport identifier or abbreviation
image:
type: string
format: uri
description: URL to the sport's logo or image asset
resolution:
type: string
format: uri
description: >-
URL to the official resolution source for the sport (e.g., league
website)
ordering:
type: string
description: Preferred ordering for sport display, typically "home" or "away"
tags:
type: string
description: >-
Comma-separated list of tag IDs associated with the sport for
categorization and filtering
series:
type: string
description: >-
Series identifier linking the sport to a specific tournament or
season series
````
@@ -0,0 +1,71 @@
> ## 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.
# Get valid sports market types
> Get a list of all valid sports market types available on the platform. Use these values when filtering markets by the sportsMarketTypes parameter.
## OpenAPI
````yaml api-reference/gamma-openapi.json get /sports/market-types
openapi: 3.0.3
info:
title: Markets API
version: 1.0.0
description: REST API specification for public endpoints used by the Markets service.
servers:
- url: https://gamma-api.polymarket.com
description: Polymarket Gamma API Production Server
security: []
tags:
- name: Gamma Status
description: Gamma API status and health check
- name: Sports
description: Sports-related endpoints including teams and game data
- name: Tags
description: Tag management and related tag operations
- name: Events
description: Event management and event-related operations
- name: Markets
description: Market data and market-related operations
- name: Comments
description: Comment system and user interactions
- name: Series
description: Series management and related operations
- name: Profiles
description: User profile management
- name: Search
description: Search functionality across different entity types
paths:
/sports/market-types:
get:
tags:
- Sports
summary: Get valid sports market types
description: >-
Get a list of all valid sports market types available on the platform.
Use these values when filtering markets by the sportsMarketTypes
parameter.
operationId: getSportsMarketTypes
responses:
'200':
description: List of valid sports market types
content:
application/json:
schema:
$ref: '#/components/schemas/SportsMarketTypesResponse'
components:
schemas:
SportsMarketTypesResponse:
type: object
properties:
marketTypes:
type: array
description: List of all valid sports market types
items:
type: string
````
+137
View File
@@ -0,0 +1,137 @@
> ## 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.
# List teams
## OpenAPI
````yaml api-reference/gamma-openapi.json get /teams
openapi: 3.0.3
info:
title: Markets API
version: 1.0.0
description: REST API specification for public endpoints used by the Markets service.
servers:
- url: https://gamma-api.polymarket.com
description: Polymarket Gamma API Production Server
security: []
tags:
- name: Gamma Status
description: Gamma API status and health check
- name: Sports
description: Sports-related endpoints including teams and game data
- name: Tags
description: Tag management and related tag operations
- name: Events
description: Event management and event-related operations
- name: Markets
description: Market data and market-related operations
- name: Comments
description: Comment system and user interactions
- name: Series
description: Series management and related operations
- name: Profiles
description: User profile management
- name: Search
description: Search functionality across different entity types
paths:
/teams:
get:
tags:
- Sports
summary: List teams
operationId: listTeams
parameters:
- $ref: '#/components/parameters/limit'
- $ref: '#/components/parameters/offset'
- $ref: '#/components/parameters/order'
- $ref: '#/components/parameters/ascending'
- name: league
in: query
schema:
type: array
items:
type: string
- name: name
in: query
schema:
type: array
items:
type: string
- name: abbreviation
in: query
schema:
type: array
items:
type: string
responses:
'200':
description: List of teams
content:
application/json:
schema:
type: array
items:
$ref: '#/components/schemas/Team'
components:
parameters:
limit:
name: limit
in: query
schema:
type: integer
minimum: 0
offset:
name: offset
in: query
schema:
type: integer
minimum: 0
order:
name: order
in: query
schema:
type: string
description: Comma-separated list of fields to order by
ascending:
name: ascending
in: query
schema:
type: boolean
schemas:
Team:
type: object
properties:
id:
type: integer
name:
type: string
nullable: true
league:
type: string
nullable: true
record:
type: string
nullable: true
logo:
type: string
nullable: true
abbreviation:
type: string
nullable: true
alias:
type: string
nullable: true
createdAt:
type: string
format: date-time
nullable: true
updatedAt:
type: string
format: date-time
nullable: true
````
@@ -0,0 +1,119 @@
> ## 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.
# Get bid-ask spreads
> Retrieves bid-ask spreads for multiple tokens
## OpenAPI
````yaml api-reference/clob-subset-openapi.yaml post /spreads
openapi: 3.0.3
info:
title: CLOB (Central Limit Order Book) API
description: >-
API for interacting with the Central Limit Order Book system, providing
orderbook data, prices, midpoints, and spreads
version: 1.0.0
contact:
name: CLOB API Team
license:
name: MIT
servers:
- url: https://clob.polymarket.com/
description: Production server
security: []
tags:
- name: Orderbook
description: Order book related operations
- name: Pricing
description: Price and midpoint operations
- name: Spreads
description: Spread calculation operations
paths:
/spreads:
post:
tags:
- Spreads
summary: Get bid-ask spreads
description: Retrieves bid-ask spreads for multiple tokens
requestBody:
required: true
content:
application/json:
schema:
type: array
items:
$ref: '#/components/schemas/BookRequest'
maxItems: 500
example:
- token_id: '1234567890'
- token_id: '0987654321'
responses:
'200':
description: Successful response
content:
application/json:
schema:
$ref: '#/components/schemas/SpreadsResponse'
'400':
description: Bad request - Invalid payload or exceeds limit
content:
application/json:
schema:
$ref: '#/components/schemas/Error'
examples:
invalid_payload:
value:
error: Invalid payload
exceeds_limit:
value:
error: Payload exceeds the limit
'500':
description: Internal server error
content:
application/json:
schema:
$ref: '#/components/schemas/Error'
example:
error: error getting the spread
components:
schemas:
BookRequest:
type: object
required:
- token_id
properties:
token_id:
type: string
description: The unique identifier for the token
example: '1234567890'
side:
type: string
enum:
- BUY
- SELL
description: Optional side parameter for certain operations
example: BUY
SpreadsResponse:
type: object
additionalProperties:
type: string
description: Map of token_id to spread value
example:
'1234567890': '0.50'
'0987654321': '0.05'
Error:
type: object
required:
- error
properties:
error:
type: string
description: Error message describing what went wrong
example: Invalid token id
````
@@ -0,0 +1,94 @@
> ## 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.
# Get related tags (relationships) by tag id
## OpenAPI
````yaml api-reference/gamma-openapi.json get /tags/{id}/related-tags
openapi: 3.0.3
info:
title: Markets API
version: 1.0.0
description: REST API specification for public endpoints used by the Markets service.
servers:
- url: https://gamma-api.polymarket.com
description: Polymarket Gamma API Production Server
security: []
tags:
- name: Gamma Status
description: Gamma API status and health check
- name: Sports
description: Sports-related endpoints including teams and game data
- name: Tags
description: Tag management and related tag operations
- name: Events
description: Event management and event-related operations
- name: Markets
description: Market data and market-related operations
- name: Comments
description: Comment system and user interactions
- name: Series
description: Series management and related operations
- name: Profiles
description: User profile management
- name: Search
description: Search functionality across different entity types
paths:
/tags/{id}/related-tags:
get:
tags:
- Tags
summary: Get related tags (relationships) by tag id
operationId: getRelatedTagsById
parameters:
- $ref: '#/components/parameters/pathId'
- name: omit_empty
in: query
schema:
type: boolean
- name: status
in: query
schema:
type: string
enum:
- active
- closed
- all
responses:
'200':
description: Related tag relationships
content:
application/json:
schema:
type: array
items:
$ref: '#/components/schemas/RelatedTag'
components:
parameters:
pathId:
name: id
in: path
required: true
schema:
type: integer
schemas:
RelatedTag:
type: object
properties:
id:
type: string
tagID:
type: integer
nullable: true
relatedTagID:
type: integer
nullable: true
rank:
type: integer
nullable: true
````
@@ -0,0 +1,94 @@
> ## 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.
# Get related tags (relationships) by tag slug
## OpenAPI
````yaml api-reference/gamma-openapi.json get /tags/slug/{slug}/related-tags
openapi: 3.0.3
info:
title: Markets API
version: 1.0.0
description: REST API specification for public endpoints used by the Markets service.
servers:
- url: https://gamma-api.polymarket.com
description: Polymarket Gamma API Production Server
security: []
tags:
- name: Gamma Status
description: Gamma API status and health check
- name: Sports
description: Sports-related endpoints including teams and game data
- name: Tags
description: Tag management and related tag operations
- name: Events
description: Event management and event-related operations
- name: Markets
description: Market data and market-related operations
- name: Comments
description: Comment system and user interactions
- name: Series
description: Series management and related operations
- name: Profiles
description: User profile management
- name: Search
description: Search functionality across different entity types
paths:
/tags/slug/{slug}/related-tags:
get:
tags:
- Tags
summary: Get related tags (relationships) by tag slug
operationId: getRelatedTagsBySlug
parameters:
- $ref: '#/components/parameters/pathSlug'
- name: omit_empty
in: query
schema:
type: boolean
- name: status
in: query
schema:
type: string
enum:
- active
- closed
- all
responses:
'200':
description: Related tag relationships
content:
application/json:
schema:
type: array
items:
$ref: '#/components/schemas/RelatedTag'
components:
parameters:
pathSlug:
name: slug
in: path
required: true
schema:
type: string
schemas:
RelatedTag:
type: object
properties:
id:
type: string
tagID:
type: integer
nullable: true
relatedTagID:
type: integer
nullable: true
rank:
type: integer
nullable: true
````
+109
View File
@@ -0,0 +1,109 @@
> ## 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.
# Get tag by id
## OpenAPI
````yaml api-reference/gamma-openapi.json get /tags/{id}
openapi: 3.0.3
info:
title: Markets API
version: 1.0.0
description: REST API specification for public endpoints used by the Markets service.
servers:
- url: https://gamma-api.polymarket.com
description: Polymarket Gamma API Production Server
security: []
tags:
- name: Gamma Status
description: Gamma API status and health check
- name: Sports
description: Sports-related endpoints including teams and game data
- name: Tags
description: Tag management and related tag operations
- name: Events
description: Event management and event-related operations
- name: Markets
description: Market data and market-related operations
- name: Comments
description: Comment system and user interactions
- name: Series
description: Series management and related operations
- name: Profiles
description: User profile management
- name: Search
description: Search functionality across different entity types
paths:
/tags/{id}:
get:
tags:
- Tags
summary: Get tag by id
operationId: getTag
parameters:
- $ref: '#/components/parameters/pathId'
- name: include_template
in: query
schema:
type: boolean
responses:
'200':
description: Tag
content:
application/json:
schema:
$ref: '#/components/schemas/Tag'
'404':
description: Not found
components:
parameters:
pathId:
name: id
in: path
required: true
schema:
type: integer
schemas:
Tag:
type: object
properties:
id:
type: string
label:
type: string
nullable: true
slug:
type: string
nullable: true
forceShow:
type: boolean
nullable: true
publishedAt:
type: string
nullable: true
createdBy:
type: integer
nullable: true
updatedBy:
type: integer
nullable: true
createdAt:
type: string
format: date-time
nullable: true
updatedAt:
type: string
format: date-time
nullable: true
forceHide:
type: boolean
nullable: true
isCarousel:
type: boolean
nullable: true
````
+109
View File
@@ -0,0 +1,109 @@
> ## 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.
# Get tag by slug
## OpenAPI
````yaml api-reference/gamma-openapi.json get /tags/slug/{slug}
openapi: 3.0.3
info:
title: Markets API
version: 1.0.0
description: REST API specification for public endpoints used by the Markets service.
servers:
- url: https://gamma-api.polymarket.com
description: Polymarket Gamma API Production Server
security: []
tags:
- name: Gamma Status
description: Gamma API status and health check
- name: Sports
description: Sports-related endpoints including teams and game data
- name: Tags
description: Tag management and related tag operations
- name: Events
description: Event management and event-related operations
- name: Markets
description: Market data and market-related operations
- name: Comments
description: Comment system and user interactions
- name: Series
description: Series management and related operations
- name: Profiles
description: User profile management
- name: Search
description: Search functionality across different entity types
paths:
/tags/slug/{slug}:
get:
tags:
- Tags
summary: Get tag by slug
operationId: getTagBySlug
parameters:
- $ref: '#/components/parameters/pathSlug'
- name: include_template
in: query
schema:
type: boolean
responses:
'200':
description: Tag
content:
application/json:
schema:
$ref: '#/components/schemas/Tag'
'404':
description: Not found
components:
parameters:
pathSlug:
name: slug
in: path
required: true
schema:
type: string
schemas:
Tag:
type: object
properties:
id:
type: string
label:
type: string
nullable: true
slug:
type: string
nullable: true
forceShow:
type: boolean
nullable: true
publishedAt:
type: string
nullable: true
createdBy:
type: integer
nullable: true
updatedBy:
type: integer
nullable: true
createdAt:
type: string
format: date-time
nullable: true
updatedAt:
type: string
format: date-time
nullable: true
forceHide:
type: boolean
nullable: true
isCarousel:
type: boolean
nullable: true
````
@@ -0,0 +1,117 @@
> ## 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.
# Get tags related to a tag id
## OpenAPI
````yaml api-reference/gamma-openapi.json get /tags/{id}/related-tags/tags
openapi: 3.0.3
info:
title: Markets API
version: 1.0.0
description: REST API specification for public endpoints used by the Markets service.
servers:
- url: https://gamma-api.polymarket.com
description: Polymarket Gamma API Production Server
security: []
tags:
- name: Gamma Status
description: Gamma API status and health check
- name: Sports
description: Sports-related endpoints including teams and game data
- name: Tags
description: Tag management and related tag operations
- name: Events
description: Event management and event-related operations
- name: Markets
description: Market data and market-related operations
- name: Comments
description: Comment system and user interactions
- name: Series
description: Series management and related operations
- name: Profiles
description: User profile management
- name: Search
description: Search functionality across different entity types
paths:
/tags/{id}/related-tags/tags:
get:
tags:
- Tags
summary: Get tags related to a tag id
operationId: getTagsRelatedToATagById
parameters:
- $ref: '#/components/parameters/pathId'
- name: omit_empty
in: query
schema:
type: boolean
- name: status
in: query
schema:
type: string
enum:
- active
- closed
- all
responses:
'200':
description: Related tags
content:
application/json:
schema:
type: array
items:
$ref: '#/components/schemas/Tag'
components:
parameters:
pathId:
name: id
in: path
required: true
schema:
type: integer
schemas:
Tag:
type: object
properties:
id:
type: string
label:
type: string
nullable: true
slug:
type: string
nullable: true
forceShow:
type: boolean
nullable: true
publishedAt:
type: string
nullable: true
createdBy:
type: integer
nullable: true
updatedBy:
type: integer
nullable: true
createdAt:
type: string
format: date-time
nullable: true
updatedAt:
type: string
format: date-time
nullable: true
forceHide:
type: boolean
nullable: true
isCarousel:
type: boolean
nullable: true
````
@@ -0,0 +1,117 @@
> ## 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.
# Get tags related to a tag slug
## OpenAPI
````yaml api-reference/gamma-openapi.json get /tags/slug/{slug}/related-tags/tags
openapi: 3.0.3
info:
title: Markets API
version: 1.0.0
description: REST API specification for public endpoints used by the Markets service.
servers:
- url: https://gamma-api.polymarket.com
description: Polymarket Gamma API Production Server
security: []
tags:
- name: Gamma Status
description: Gamma API status and health check
- name: Sports
description: Sports-related endpoints including teams and game data
- name: Tags
description: Tag management and related tag operations
- name: Events
description: Event management and event-related operations
- name: Markets
description: Market data and market-related operations
- name: Comments
description: Comment system and user interactions
- name: Series
description: Series management and related operations
- name: Profiles
description: User profile management
- name: Search
description: Search functionality across different entity types
paths:
/tags/slug/{slug}/related-tags/tags:
get:
tags:
- Tags
summary: Get tags related to a tag slug
operationId: getTagsRelatedToATagBySlug
parameters:
- $ref: '#/components/parameters/pathSlug'
- name: omit_empty
in: query
schema:
type: boolean
- name: status
in: query
schema:
type: string
enum:
- active
- closed
- all
responses:
'200':
description: Related tags
content:
application/json:
schema:
type: array
items:
$ref: '#/components/schemas/Tag'
components:
parameters:
pathSlug:
name: slug
in: path
required: true
schema:
type: string
schemas:
Tag:
type: object
properties:
id:
type: string
label:
type: string
nullable: true
slug:
type: string
nullable: true
forceShow:
type: boolean
nullable: true
publishedAt:
type: string
nullable: true
createdBy:
type: integer
nullable: true
updatedBy:
type: integer
nullable: true
createdAt:
type: string
format: date-time
nullable: true
updatedAt:
type: string
format: date-time
nullable: true
forceHide:
type: boolean
nullable: true
isCarousel:
type: boolean
nullable: true
````
+133
View File
@@ -0,0 +1,133 @@
> ## 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.
# List tags
## OpenAPI
````yaml api-reference/gamma-openapi.json get /tags
openapi: 3.0.3
info:
title: Markets API
version: 1.0.0
description: REST API specification for public endpoints used by the Markets service.
servers:
- url: https://gamma-api.polymarket.com
description: Polymarket Gamma API Production Server
security: []
tags:
- name: Gamma Status
description: Gamma API status and health check
- name: Sports
description: Sports-related endpoints including teams and game data
- name: Tags
description: Tag management and related tag operations
- name: Events
description: Event management and event-related operations
- name: Markets
description: Market data and market-related operations
- name: Comments
description: Comment system and user interactions
- name: Series
description: Series management and related operations
- name: Profiles
description: User profile management
- name: Search
description: Search functionality across different entity types
paths:
/tags:
get:
tags:
- Tags
summary: List tags
operationId: listTags
parameters:
- $ref: '#/components/parameters/limit'
- $ref: '#/components/parameters/offset'
- $ref: '#/components/parameters/order'
- $ref: '#/components/parameters/ascending'
- name: include_template
in: query
schema:
type: boolean
- name: is_carousel
in: query
schema:
type: boolean
responses:
'200':
description: List of tags
content:
application/json:
schema:
type: array
items:
$ref: '#/components/schemas/Tag'
components:
parameters:
limit:
name: limit
in: query
schema:
type: integer
minimum: 0
offset:
name: offset
in: query
schema:
type: integer
minimum: 0
order:
name: order
in: query
schema:
type: string
description: Comma-separated list of fields to order by
ascending:
name: ascending
in: query
schema:
type: boolean
schemas:
Tag:
type: object
properties:
id:
type: string
label:
type: string
nullable: true
slug:
type: string
nullable: true
forceShow:
type: boolean
nullable: true
publishedAt:
type: string
nullable: true
createdBy:
type: integer
nullable: true
updatedBy:
type: integer
nullable: true
createdAt:
type: string
format: date-time
nullable: true
updatedAt:
type: string
format: date-time
nullable: true
forceHide:
type: boolean
nullable: true
isCarousel:
type: boolean
nullable: true
````
+408
View File
@@ -0,0 +1,408 @@
> ## 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.
# Authentication
> Understanding authentication using Polymarket's CLOB
The CLOB uses two levels of authentication: **L1 (Private Key)** and **L2 (API Key)**.
Either can be accomplished using the CLOB client or REST API. Authentication is not
required to access client public methods and public endpoints.
## Authentication Levels
<CardGroup cols={2}>
<Card title="L1 Authentication" icon="key" href="#l1-authentication">
Use the private key of the users account to sign messages
</Card>
<Card title="L2 Authentication" icon="lock" href="#l2-authentication">
Use API credentials (key, secret, passphrase) to authenticate requests to the CLOB
</Card>
</CardGroup>
***
## L1 Authentication
### What is L1?
L1 authentication uses the wallet's private key to sign an EIP-712 message used in the
request header. It proves ownership and control over the private key. The private key
stays in control of the user and all trading activity remains non-custodial.
### What This Enables
Access to L1 methods that create or derive L2 authentication headers.
* Create user API credentials
* Derive existing user API credentials
* Sign/create user's orders locally
### CLOB 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);
const client = new ClobClient(
HOST,
CHAIN_ID,
signer // Signer enables L1 methods
);
// Gets API key, or else creates
const apiCreds = await client.createOrDeriveApiKey();
/*
apiCreds = {
"apiKey": "550e8400-e29b-41d4-a716-446655440000",
"secret": "base64EncodedSecretString",
"passphrase": "randomPassphraseString"
}
*/
```
</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")
client = ClobClient(
host=host,
chain_id=chaind_id,
key=private_key # Signer enables L1 methods
)
# Gets API key, or else creates
api_creds = await client.create_or_derive_api_key()
# api_creds = {
# "apiKey": "550e8400-e29b-41d4-a716-446655440000",
# "secret": "base64EncodedSecretString",
# "passphrase": "randomPassphraseString"
# }
```
</Tab>
</Tabs>
<Warning>
**Never commit private keys to version control.** Always use environment
variables or secure key management systems.
</Warning>
***
### REST API
While we highly recommend using our provided clients to handle signing
and authentication, the following is for developers who choose NOT to
use our [Python](https://github.com/Polymarket/py-clob-client) or
[TypeScript](https://github.com/Polymarket/clob-client) clients.
When making direct REST API calls with L1 authentication, include these headers:
| Header | Required? | Description |
| ---------------- | --------- | ---------------------- |
| `POLY_ADDRESS` | yes | Polygon signer address |
| `POLY_SIGNATURE` | yes | CLOB EIP 712 signature |
| `POLY_TIMESTAMP` | yes | Current UNIX timestamp |
| `POLY_NONCE` | yes | Nonce. Default 0 |
The `POLY_SIGNATURE` is generated by signing the following EIP-712 struct.
<Accordion title="EIP-712 Signing Example">
<CodeGroup>
```typescript Typescript theme={null}
const domain = {
name: "ClobAuthDomain",
version: "1",
chainId: chainId, // Polygon Chain ID 137
};
const types = {
ClobAuth: [
{ name: "address", type: "address" },
{ name: "timestamp", type: "string" },
{ name: "nonce", type: "uint256" },
{ name: "message", type: "string" },
],
};
const value = {
address: signingAddress, // The Signing address
timestamp: ts, // The CLOB API server timestamp
nonce: nonce, // The nonce used
message: "This message attests that I control the given wallet",
};
const sig = await signer._signTypedData(domain, types, value);
```
```python Python theme={null}
domain = {
"name": "ClobAuthDomain",
"version": "1",
"chainId": chainId, # Polygon Chain ID 137
}
types = {
"ClobAuth": [
{"name": "address", "type": "address"},
{"name": "timestamp", "type": "string"},
{"name": "nonce", "type": "uint256"},
{"name": "message", "type": "string"},
]
}
value = {
"address": signingAddress, # The signing address
"timestamp": ts, # The CLOB API server timestamp
"nonce": nonce, # The nonce used
"message": "This message attests that I control the given wallet",
}
sig = await signer._signTypedData(domain, types, value)
```
</CodeGroup>
</Accordion>
Reference implementations:
* [TypeScript](https://github.com/Polymarket/clob-client/blob/main/src/signing/eip712.ts)
* [Python](https://github.com/Polymarket/py-clob-client/blob/main/py_clob_client/signing/eip712.py)
***
**Create API Credentials**
Create new API credentials for user.
```bash theme={null}
POST {clob-endpoint}/auth/api-key
```
**Derive API Credentials**
Derive API credentials for user.
```bash theme={null}
GET {clob-endpoint}/auth/derive-api-key
```
**Response**
```json theme={null}
{
"apiKey": "550e8400-e29b-41d4-a716-446655440000",
"secret": "base64EncodedSecretString",
"passphrase": "randomPassphraseString"
}
```
**You'll need all three values for L2 authentication.**
***
## L2 Authentication
### What is L2?
The next level of authentication is called L2, and it consists of the
user's API credentials (apiKey, secret, passphrase) generated from L1
authentication. These are used solely to authenticate requests made to
the CLOB API. Requests are signed using HMAC-SHA256.
### What This Enables
Access to L2 methods such as posting signed/created orders, viewing open
orders, cancelling open orders, getting trades
* Cancel or get user's open orders
* Check user's balances and allowances
* Post user's signed orders
### CLOB 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);
const client = new ClobClient(
HOST,
CHAIN_ID,
signer,
apiCreds, // Generated from L1 auth, API credentials enable L2 methods
1, // signatureType explained below
FUNDER // funder explained below
);
// Now you can trade!*
const order = await client.createAndPostOrder(
{ tokenID: "123456", price: 0.65, size: 100, side: "BUY" },
{ tickSize: "0.01", negRisk: false }
);
```
</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")
client = ClobClient(
host="https://clob.polymarket.com",
chain_id=137,
key=os.getenv("PRIVATE_KEY"),
creds=api_creds, # Generated from L1 auth, API credentials enable L2 methods
signature_type=1, # signatureType explained below
funder=os.getenv("FUNDER_ADDRESS") # funder explained below
)
# Now you can trade!*
order = await client.create_and_post_order(
{"token_id": "123456", "price": 0.65, "size": 100, "side": "BUY"},
{"tick_size": "0.01", "neg_risk": False}
)
```
</Tab>
</Tabs>
<Info>
Even with L2 authentication headers, methods that create user orders still require the user to sign the order payload.
</Info>
***
### REST API
While we highly recommend using our provided clients to handle signing
and authentication, the following is for developers who choose NOT to
use our [Python](https://github.com/Polymarket/py-clob-client) or
[TypeScript](https://github.com/Polymarket/clob-client) clients.
When making direct REST API calls with L2 authentication, include these headers:
| Header | Required? | Description |
| ----------------- | --------- | ----------------------------- |
| `POLY_ADDRESS` | yes | Polygon signer address |
| `POLY_SIGNATURE` | yes | HMAC signature for request |
| `POLY_TIMESTAMP` | yes | Current UNIX timestamp |
| `POLY_API_KEY` | yes | User's API `apiKey` value |
| `POLY_PASSPHRASE` | yes | User's API `passphrase` value |
The `POLY_SIGNATURE` for L2 is an HMAC-SHA256 signature created using the user's API credentials `secret` value.
Reference implementations can be found in the [Typescript](https://github.com/Polymarket/clob-client/blob/main/src/signing/hmac.ts)
and [Python](https://github.com/Polymarket/py-clob-client/blob/main/py_clob_client/signing/hmac.py) clients.
***
## Signature Types and Funder
When initializing the L2 client, you must specify your wallet **signatureType** and the **funder** address which holds the funds:
| Signature Type | Value | Description |
| -------------- | ----- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| EOA | 0 | Standard Ethereum wallet (MetaMask). Funder is the EOA address and will need POL to pay gas on transactions. |
| POLY\_PROXY | 1 | A custom proxy wallet only used with users who logged in via Magic Link email/Google. Using this requires the user to have exported their PK from Polymarket.com and imported into your app. |
| GNOSIS\_SAFE | 2 | Gnosis Safe multisig proxy wallet (most common). Use this for any new or returning user who does not fit the other 2 types. |
<Tip>
The wallet addresses displayed to the user on Polymarket.com is the proxy wallet and should be used as the funder.
These can be deterministically derived or you can deploy them on behalf of the user.
These proxy wallets are automatically deployed for the user on their first login to Polymarket.com.
</Tip>
***
## Troubleshooting
<AccordionGroup>
<Accordion title="Error: INVALID_SIGNATURE">
Your wallet's private key is incorrect or improperly formatted.
**Solution:**
* Verify your private key is a valid hex string (starts with "0x")
* Ensure you're using the correct key for the intended address
* Check that the key has proper permissions
</Accordion>
<Accordion title="Error: NONCE_ALREADY_USED">
The nonce you provided has already been used to create an API key.
**Solution:**
* Use `deriveApiKey()` with the same nonce to retrieve existing credentials
* Or use a different nonce with `createApiKey()`
</Accordion>
<Accordion title="Error: Invalid Funder Address">
Your funder address is incorrect or doesn't match your wallet.
**Solution:** Check your Polymarket profile address at [polymarket.com/settings](https://polymarket.com/settings).
If it does not exist or user has never logged into Polymarket.com, deploy it first before creating L2 authentication.
</Accordion>
<Accordion title="Lost API credentials but have nonce">
```typescript theme={null}
// Use deriveApiKey with the original nonce
const recovered = await client.deriveApiKey(originalNonce);
```
</Accordion>
<Accordion title="Lost both credentials and nonce">
Unfortunately, there's no way to recover lost API credentials without the nonce. You'll need to create new credentials:
```typescript theme={null}
// Create fresh credentials with a new nonce
const newCreds = await client.createApiKey();
// Save the nonce this time!
```
</Accordion>
</AccordionGroup>
***
## See Client Methods
<CardGroup cols={2}>
<Card title="Public Methods" icon="globe" href="/developers/CLOB/clients/methods-public">
Access market data, orderbooks, and prices.
</Card>
<Card title="L1 Methods" icon="key" href="/developers/CLOB/clients/methods-l1">
Private key authentication to create or derive API keys (L2 headers).
</Card>
<Card title="L2 Methods" icon="lock" href="/developers/CLOB/clients/methods-l2">
Manage and close orders. Creating orders requires signer.
</Card>
<Card title="Builder Program Methods" icon="hammer" href="/developers/CLOB/clients/methods-builder">
Builder-specific operations for those in the Builders Program.
</Card>
</CardGroup>
@@ -0,0 +1,215 @@
> ## 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.
# Builder Methods
> These methods require builder API credentials and are only relevant for Builders Program order attribution.
## Client Initialization
Builder methods require the client to initialize with a separate authentication setup using
builder configs acquired from [Polymarket.com](https://polymarket.com/settings?tab=builder)
and the `@polymarket/builder-signing-sdk` package.
<Tabs>
<Tab title="Local Builder Credentials">
<CodeGroup>
```typescript TypeScript theme={null}
import { ClobClient } from "@polymarket/clob-client";
import { BuilderConfig, BuilderApiKeyCreds } from "@polymarket/builder-signing-sdk";
const builderConfig = new BuilderConfig({
localBuilderCreds: new BuilderApiKeyCreds({
key: process.env.BUILDER_API_KEY,
secret: process.env.BUILDER_SECRET,
passphrase: process.env.BUILDER_PASS_PHRASE,
}),
});
const clobClient = new ClobClient(
"https://clob.polymarket.com",
137,
signer,
apiCreds, // The user's API credentials generated from L1 authentication
signatureType,
funderAddress,
undefined,
false,
builderConfig
);
```
```python Python theme={null}
from py_clob_client.client import ClobClient
from py_builder_signing_sdk.config import BuilderConfig, BuilderApiKeyCreds
import os
builder_config = BuilderConfig(
local_builder_creds=BuilderApiKeyCreds(
key=os.getenv("BUILDER_API_KEY"),
secret=os.getenv("BUILDER_SECRET"),
passphrase=os.getenv("BUILDER_PASS_PHRASE"),
)
)
clob_client = ClobClient(
host="https://clob.polymarket.com",
chain_id=137,
key=os.getenv("PRIVATE_KEY"),
creds=creds, # The user's API credentials generated from L1 authentication
signature_type=signature_type,
funder=funder,
builder_config=builder_config
)
```
</CodeGroup>
</Tab>
<Tab title="Remote Builder Signing">
<CodeGroup>
```typescript TypeScript theme={null}
import { ClobClient } from "@polymarket/clob-client";
import { BuilderConfig } from "@polymarket/builder-signing-sdk";
const builderConfig = new BuilderConfig({
remoteBuilderConfig: {url: "http://localhost:3000/sign"}
});
const clobClient = new ClobClient(
"https://clob.polymarket.com",
137,
signer,
apiCreds, // The user's API credentials generated from L1 authentication
signatureType,
funder,
undefined,
false,
builderConfig
);
```
```typescript Python theme={null}
from py_clob_client.client import ClobClient
from py_builder_signing_sdk.config import BuilderConfig, RemoteBuilderConfig
import os
builder_config = BuilderConfig(
remote_builder_config=RemoteBuilderConfig(
url="http://localhost:3000/sign"
)
)
clob_client = ClobClient(
host="https://clob.polymarket.com",
chain_id=137,
key=os.getenv("PRIVATE_KEY"),
creds=creds, # The user's API credentials generated from L1 authentication
signature_type=signature_type,
funder=funder,
builder_config=builder_config
)
```
</CodeGroup>
</Tab>
</Tabs>
<Info>
[More information on builder signing](/developers/builders/order-attribution)
</Info>
***
## Methods
***
### getBuilderTrades()
Retrieves all trades attributed to your builder account.
This method allows builders to track which trades were routed through your platform.
```typescript Signature theme={null}
async getBuilderTrades(
params?: TradeParams,
): Promise<BuilderTradesPaginatedResponse>
```
```typescript Params theme={null}
interface TradeParams {
id?: string;
maker_address?: string;
market?: string;
asset_id?: string;
before?: string;
after?: string;
}
```
```typescript Response theme={null}
interface BuilderTradesPaginatedResponse {
trades: BuilderTrade[];
next_cursor: string;
limit: number;
count: number;
}
interface BuilderTrade {
id: string;
tradeType: string;
takerOrderHash: string;
builder: string;
market: string;
assetId: string;
side: string;
size: string;
sizeUsdc: string;
price: string;
status: string;
outcome: string;
outcomeIndex: number;
owner: string;
maker: string;
transactionHash: string;
matchTime: string;
bucketIndex: number;
fee: string;
feeUsdc: string;
err_msg?: string | null;
createdAt: string | null;
updatedAt: string | null;
}
```
***
### revokeBuilderApiKey()
Revokes the builder API key used to authenticate the current request.
After revocation, the key can no longer be used to make builder-authenticated requests.
```typescript Signature theme={null}
async revokeBuilderApiKey(): Promise<any>
```
***
## See Also
<CardGroup cols={2}>
<Card title="Builders Program Introduction" icon="hammer" href="/developers/builders/builder-intro">
Learn the benefits, how to implement, and more.
</Card>
<Card title="Implement Builders Signing" icon="key" href="/developers/builders/order-attribution">
Attribute orders to you, and pre-requisite to using the Relayer Client.
</Card>
<Card title="Relayer Client" icon="globe" href="/developers/builders/relayer-client">
The relayer executes other gasless transactions for your users, on your app.
</Card>
<Card title="Full Example Implementations" icon="puzzle" href="/developers/builders/examples">
Complete Next.js examples integrated with embedded wallets (Privy, Magic, Turnkey, wagmi)
</Card>
</CardGroup>
+295
View File
@@ -0,0 +1,295 @@
> ## 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.
# L1 Methods
> These methods require a wallet signer (private key) but do not require user API credentials. Use these for initial setup.
## Client Initialization
L1 methods require the client to initialize with a signer.
<Tabs>
<Tab title="TypeScript">
```typescript theme={null}
import { ClobClient } from "@polymarket/clob-client";
import { Wallet } from "ethers";
const signer = new Wallet(process.env.PRIVATE_KEY);
const client = new ClobClient(
"https://clob.polymarket.com",
137,
signer // Signer required for L1 methods
);
// Ready to create user API credentials
const apiKey = await client.createApiKey();
```
</Tab>
<Tab title="Python">
```python theme={null}
from py_clob_client.client import ClobClient
import os
private_key = os.getenv("PRIVATE_KEY")
client = ClobClient(
host="https://clob.polymarket.com",
chain_id=137,
key=private_key # Signer required for L1 methods
)
# Ready to create user API credentials
api_key = await client.create_api_key()
```
</Tab>
</Tabs>
<Warning>
**Security:** Never commit private keys to version control. Always use environment variables or secure key management systems.
</Warning>
***
## API Key Management
***
### createApiKey()
Creates a new API key (L2 credentials) for the wallet signer. This generates a new set of credentials that can be used for L2 authenticated requests.
Each wallet can only have one active API key at a time. Creating a new key invalidates the previous one.
```typescript Signature theme={null}
async createApiKey(nonce?: number): Promise<ApiKeyCreds>
```
```typescript Params theme={null}
`nonce` (optional): Custom nonce for deterministic key generation. If not provided, a default derivation is used.
```
```typescript Response theme={null}
interface ApiKeyCreds {
apiKey: string;
secret: string;
passphrase: string;
}
```
***
### deriveApiKey()
Derives an existing API key (L2 credentials) using a specific nonce. If you've already created API credentials with a particular nonce, this method will return the same credentials again.
```typescript Signature theme={null}
async deriveApiKey(nonce?: number): Promise<ApiKeyCreds>
```
```typescript Params theme={null}
`nonce` (optional): Custom nonce for deterministic key generation. If not provided, a default derivation is used.
```
```typescript Response theme={null}
interface ApiKeyCreds {
apiKey: string;
secret: string;
passphrase: string;
}
```
***
### createOrDeriveApiKey()
Convenience method that attempts to derive an API key with the default nonce, or creates a new one if it doesn't exist. This is the recommended method for initial setup if you're unsure if credentials already exist.
```typescript Signature theme={null}
async createOrDeriveApiKey(nonce?: number): Promise<ApiKeyCreds>
```
```typescript Params theme={null}
`nonce` (optional): Custom nonce for deterministic key generation. If not provided, a default derivation is used.
```
```typescript Response theme={null}
interface ApiKeyCreds {
apiKey: string;
secret: string;
passphrase: string;
}
```
***
## Order Signing
### createOrder()
Create and sign a limit order locally without posting it to the CLOB.
Use this when you want to sign orders in advance or implement custom order submission logic.
Place order via L2 methods postOrder or postOrders.
```typescript Signature theme={null}
async createOrder(
userOrder: UserOrder,
options?: Partial<CreateOrderOptions>
): Promise<SignedOrder>
```
```typescript Params theme={null}
interface UserOrder {
tokenID: string;
price: number;
size: number;
side: Side;
feeRateBps?: number;
nonce?: number;
expiration?: number;
taker?: string;
}
interface CreateOrderOptions {
tickSize: TickSize;
negRisk?: boolean;
}
```
```typescript Response theme={null}
interface SignedOrder {
salt: string;
maker: string;
signer: string;
taker: string;
tokenId: string;
makerAmount: string;
takerAmount: string;
side: number; // 0 = BUY, 1 = SELL
expiration: string;
nonce: string;
feeRateBps: string;
signatureType: number;
signature: string;
}
```
***
### createMarketOrder()
Create and sign a market order locally without posting it to the CLOB.
Use this when you want to sign orders in advance or implement custom order submission logic.
Place orders via L2 methods postOrder or postOrders.
```typescript Signature theme={null}
async createMarketOrder(
userMarketOrder: UserMarketOrder,
options?: Partial<CreateOrderOptions>
): Promise<SignedOrder>
```
```typescript Params theme={null}
interface UserMarketOrder {
tokenID: string;
amount: number; // BUY: dollar amount, SELL: number of shares
side: Side;
price?: number; // Optional price limit
feeRateBps?: number;
nonce?: number;
taker?: string;
orderType?: OrderType.FOK | OrderType.FAK;
}
```
```typescript Response theme={null}
interface SignedOrder {
salt: string;
maker: string;
signer: string;
taker: string;
tokenId: string;
makerAmount: string;
takerAmount: string;
side: number; // 0 = BUY, 1 = SELL
expiration: string;
nonce: string;
feeRateBps: string;
signatureType: number;
signature: string;
}
```
***
## Troubleshooting
<AccordionGroup>
<Accordion title="Error: INVALID_SIGNATURE">
Your wallet's private key is incorrect or improperly formatted.
**Solution:**
* Verify your private key is a valid hex string (starts with "0x")
* Ensure you're using the correct key for the intended address
* Check that the key has proper permissions
</Accordion>
<Accordion title="Error: NONCE_ALREADY_USED">
The nonce you provided has already been used to create an API key.
**Solution:**
* Use `deriveApiKey()` with the same nonce to retrieve existing credentials
* Or use a different nonce with `createApiKey()`
</Accordion>
<Accordion title="Error: Invalid Funder Address">
Your funder address is incorrect or doesn't match your wallet.
**Solution:** Check your Polymarket profile address at [polymarket.com/settings](https://polymarket.com/settings).
If it does not exist or user has never logged into Polymarket.com, deploy it first before creating L2 authentication.
</Accordion>
<Accordion title="Lost API credentials but have nonce">
```typescript theme={null}
// Use deriveApiKey with the original nonce
const recovered = await client.deriveApiKey(originalNonce);
```
</Accordion>
<Accordion title="Lost both credentials and nonce">
Unfortunately, there's no way to recover lost API credentials without the nonce. You'll need to create new credentials:
```typescript theme={null}
// Create fresh credentials with a new nonce
const newCreds = await client.createApiKey();
// Save the nonce this time!
```
</Accordion>
</AccordionGroup>
***
## See Also
<CardGroup cols={2}>
<Card title="Understand CLOB Authentication" icon="shield" href="/developers/CLOB/authentication">
Deep dive into L1 and L2 authentication
</Card>
<Card title="CLOB Quickstart Guide" icon="hammer" href="/developers/CLOB/quickstart">
Initialize the CLOB quickly and place your first order.
</Card>
<Card title="Public Methods" icon="globe" href="/developers/CLOB/clients/methods-l2">
Access market data, orderbooks, and prices.
</Card>
<Card title="L2 Methods" icon="lock" href="/developers/CLOB/clients/methods-l2">
Manage and close orders. Creating orders requires signer.
</Card>
</CardGroup>
+650
View File
@@ -0,0 +1,650 @@
> ## 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.
# L2 Methods
> These methods require user API credentials (L2 headers). Use these for placing trades and managing user's positions.
***
## Client Initialization
L2 methods require the client to initialize with the signer, signatureType, user API credentials, and funder.
<Tabs>
<Tab title="TypeScript">
```typescript theme={null}
import { ClobClient } from "@polymarket/clob-client";
import { Wallet } from "ethers";
const signer = new Wallet(process.env.PRIVATE_KEY)
const apiCreds = {
apiKey: process.env.API_KEY,
secret: process.env.SECRET,
passphrase: process.env.PASSPHRASE,
};
const client = new ClobClient(
"https://clob.polymarket.com",
137,
signer,
apiCreds,
2, // Deployed Safe proxy wallet
process.env.FUNDER_ADDRESS // Address of deployed Safe proxy wallet
);
// Ready to send authenticated requests to the CLOB API!
const order = await client.postOrder(signedOrder);
```
</Tab>
<Tab title="Python">
```python theme={null}
from py_clob_client.client import ClobClient
from py_clob_client.clob_types import ApiCreds
import os
api_creds = ApiCreds(
api_key=os.getenv("API_KEY"),
api_secret=os.getenv("SECRET"),
api_passphrase=os.getenv("PASSPHRASE")
)
client = ClobClient(
host="https://clob.polymarket.com",
chain_id=137,
key=os.getenv("PRIVATE_KEY"),
creds=api_creds,
signature_type=2, # Deployed Safe proxy wallet
funder=os.getenv("FUNDER_ADDRESS") # Address of deployed Safe proxy wallet
)
# Ready to send authenticated requests to the CLOB API!
order = await client.post_order(signed_order)
```
</Tab>
</Tabs>
***
## Order Creation and Management
***
### createAndPostOrder()
A convenience method that creates, prompts signature, and posts an order in a single call.
Use when you want to buy/sell at a specific price and can wait.
```typescript Signature theme={null}
async createAndPostOrder(
userOrder: UserOrder,
options?: Partial<CreateOrderOptions>,
orderType?: OrderType.GTC | OrderType.GTD, // Defaults to GTC
): Promise<OrderResponse>
```
```typescript Params theme={null}
interface UserOrder {
tokenID: string;
price: number;
size: number;
side: Side;
feeRateBps?: number;
nonce?: number;
expiration?: number;
taker?: string;
}
type CreateOrderOptions = {
tickSize: TickSize;
negRisk?: boolean;
}
type TickSize = "0.1" | "0.01" | "0.001" | "0.0001";
```
```typescript Response theme={null}
interface OrderResponse {
success: boolean;
errorMsg: string;
orderID: string;
transactionsHashes: string[];
status: string;
takingAmount: string;
makingAmount: string;
}
```
***
### createAndPostMarketOrder()
A convenience method that creates, prompts signature, and posts an order in a single call.
Use when you want to buy/sell right now at whatever the market price is.
```typescript Signature theme={null}
async createAndPostMarketOrder(
userMarketOrder: UserMarketOrder,
options?: Partial<CreateOrderOptions>,
orderType?: OrderType.FOK | OrderType.FAK, // Defaults to FOK
): Promise<OrderResponse>
```
```typescript Params theme={null}
interface UserMarketOrder {
tokenID: string;
amount: number;
side: Side;
price?: number;
feeRateBps?: number;
nonce?: number;
taker?: string;
orderType?: OrderType.FOK | OrderType.FAK;
}
type CreateOrderOptions = {
tickSize: TickSize;
negRisk?: boolean;
}
type TickSize = "0.1" | "0.01" | "0.001" | "0.0001";
```
```typescript Response theme={null}
interface OrderResponse {
success: boolean;
errorMsg: string;
orderID: string;
transactionsHashes: string[];
status: string;
takingAmount: string;
makingAmount: string;
}
```
***
### postOrder()
Posts a pre-signed and created order to the CLOB.
```typescript Signature theme={null}
async postOrder(
order: SignedOrder,
orderType?: OrderType, // Defaults to GTC
postOnly?: boolean, // Defaults to false
): Promise<OrderResponse>
```
```typescript Params theme={null}
order: SignedOrder // Pre-signed order from createOrder() or createMarketOrder()
orderType?: OrderType // Optional, defaults to GTC
postOnly?: boolean // Optional, defaults to false
```
```typescript Response theme={null}
interface OrderResponse {
success: boolean;
errorMsg: string;
orderID: string;
transactionsHashes: string[];
status: string;
takingAmount: string;
makingAmount: string;
}
```
***
### postOrders()
Posts up to 15 pre-signed and created orders in a single batch.
```typescript theme={null}
async postOrders(
args: PostOrdersArgs[],
): Promise<OrderResponse[]>
```
```typescript Params theme={null}
interface PostOrdersArgs {
order: SignedOrder;
orderType: OrderType;
postOnly?: boolean; // Defaults to false
}
```
```typescript Response theme={null}
OrderResponse[] // Array of OrderResponse objects
interface OrderResponse {
success: boolean;
errorMsg: string;
orderID: string;
transactionsHashes: string[];
status: string;
takingAmount: string;
makingAmount: string;
}
```
***
### cancelOrder()
Cancels a single open order.
```typescript Signature theme={null}
async cancelOrder(orderID: string): Promise<CancelOrdersResponse>
```
```typescript Response theme={null}
interface CancelOrdersResponse {
canceled: string[];
not_canceled: Record<string, any>;
}
```
***
### cancelOrders()
Cancels multiple orders in a single batch.
```typescript Signature theme={null}
async cancelOrders(orderIDs: string[]): Promise<CancelOrdersResponse>
```
```typescript Params theme={null}
orderIDs: string[];
```
```typescript Response theme={null}
interface CancelOrdersResponse {
canceled: string[];
not_canceled: Record<string, any>;
}
```
***
### cancelAll()
Cancels all open orders.
```typescript Signature theme={null}
async cancelAll(): Promise<CancelResponse>
```
```typescript Response theme={null}
interface CancelOrdersResponse {
canceled: string[];
not_canceled: Record<string, any>;
}
```
***
### cancelMarketOrders()
Cancels all open orders for a specific market.
```typescript Signature theme={null}
async cancelMarketOrders(
payload: OrderMarketCancelParams
): Promise<CancelOrdersResponse>
```
```typescript Parameters theme={null}
interface OrderMarketCancelParams {
market?: string;
asset_id?: string;
}
```
```typescript Response theme={null}
interface CancelOrdersResponse {
canceled: string[];
not_canceled: Record<string, any>;
}
```
***
## Order and Trade Queries
***
### getOrder()
Get details for a specific order.
```typescript Signature theme={null}
async getOrder(orderID: string): Promise<OpenOrder>
```
```typescript Response theme={null}
interface OpenOrder {
id: string;
status: string;
owner: string;
maker_address: string;
market: string;
asset_id: string;
side: string;
original_size: string;
size_matched: string;
price: string;
associate_trades: string[];
outcome: string;
created_at: number;
expiration: string;
order_type: string;
}
```
***
### getOpenOrders()
Get all your open orders.
```typescript Signature theme={null}
async getOpenOrders(
params?: OpenOrderParams,
only_first_page?: boolean,
): Promise<OpenOrdersResponse>
```
```typescript Params theme={null}
interface OpenOrderParams {
id?: string; // Order ID
market?: string; // Market condition ID
asset_id?: string; // Token ID
}
only_first_page?: boolean // Defaults to false
```
```typescript Response theme={null}
type OpenOrdersResponse = OpenOrder[];
interface OpenOrder {
id: string;
status: string;
owner: string;
maker_address: string;
market: string;
asset_id: string;
side: string;
original_size: string;
size_matched: string;
price: string;
associate_trades: string[];
outcome: string;
created_at: number;
expiration: string;
order_type: string;
}
```
***
### getTrades()
Get your trade history (filled orders).
```typescript Signature theme={null}
async getTrades(
params?: TradeParams,
only_first_page?: boolean,
): Promise<Trade[]>
```
```typescript Params theme={null}
interface TradeParams {
id?: string;
maker_address?: string;
market?: string;
asset_id?: string;
before?: string;
after?: string;
}
only_first_page?: boolean // Defaults to false
```
```typescript Response theme={null}
interface Trade {
id: string;
taker_order_id: string;
market: string;
asset_id: string;
side: Side;
size: string;
fee_rate_bps: string;
price: string;
status: string;
match_time: string;
last_update: string;
outcome: string;
bucket_index: number;
owner: string;
maker_address: string;
maker_orders: MakerOrder[];
transaction_hash: string;
trader_side: "TAKER" | "MAKER";
}
interface MakerOrder {
order_id: string;
owner: string;
maker_address: string;
matched_amount: string;
price: string;
fee_rate_bps: string;
asset_id: string;
outcome: string;
side: Side;
}
```
***
### getTradesPaginated()
Get trade history with pagination for large result sets.
```typescript Signature theme={null}
async getTradesPaginated(
params?: TradeParams,
): Promise<TradesPaginatedResponse>
```
```typescript Params theme={null}
interface TradeParams {
id?: string;
maker_address?: string;
market?: string;
asset_id?: string;
before?: string;
after?: string;
}
```
```typescript Response theme={null}
interface TradesPaginatedResponse {
trades: Trade[];
limit: number;
count: number;
}
```
***
## Balance and Allowances
***
### getBalanceAllowance()
Get your balance and allowance for specific tokens.
```typescript Signature theme={null}
async getBalanceAllowance(
params?: BalanceAllowanceParams
): Promise<BalanceAllowanceResponse>
```
```typescript Params theme={null}
interface BalanceAllowanceParams {
asset_type: AssetType;
token_id?: string;
}
enum AssetType {
COLLATERAL = "COLLATERAL",
CONDITIONAL = "CONDITIONAL",
}
```
```typescript Response theme={null}
interface BalanceAllowanceResponse {
balance: string;
allowance: string;
}
```
***
### updateBalanceAllowance()
Updates the cached balance and allowance for specific tokens.
```typescript Signature theme={null}
async updateBalanceAllowance(
params?: BalanceAllowanceParams
): Promise<void>
```
```typescript Params theme={null}
interface BalanceAllowanceParams {
asset_type: AssetType;
token_id?: string;
}
enum AssetType {
COLLATERAL = "COLLATERAL",
CONDITIONAL = "CONDITIONAL",
}
```
***
## API Key Management (L2)
### getApiKeys()
Get all API keys associated with your account.
```typescript Signature theme={null}
async getApiKeys(): Promise<ApiKeysResponse>
```
```typescript Response theme={null}
interface ApiKeysResponse {
apiKeys: ApiKeyCreds[];
}
interface ApiKeyCreds {
key: string;
secret: string;
passphrase: string;
}
```
***
### deleteApiKey()
Deletes (revokes) the currently authenticated API key.
**TypeScript Signature:**
```typescript theme={null}
async deleteApiKey(): Promise<any>
```
***
## Notifications
***
### getNotifications()
Retrieves all event notifications for the L2 authenticated user.
Records are removed automatically after 48 hours or if manually removed via dropNotifications().
```typescript Signature theme={null}
public async getNotifications(): Promise<Notification[]>
```
```typescript Response theme={null}
interface Notification {
id: number; // Unique notification ID
owner: string; // User's L2 credential apiKey or empty string for global notifications
payload: any; // Type-specific payload data
timestamp?: number; // Unix timestamp
type: number; // Notification type (see type mapping below)
}
```
**Notification Type Mapping**
| Name | Value | Description |
| ------------------ | ----- | ---------------------------------------- |
| Order Cancellation | 1 | User's order was canceled |
| Order Fill | 2 | User's order was filled (maker or taker) |
| Market Resolved | 4 | Market was resolved |
***
### dropNotifications()
Mark notifications as read/dismissed.
```typescript Signature theme={null}
public async dropNotifications(params?: DropNotificationParams): Promise<void>
```
```typescript Params theme={null}
interface DropNotificationParams {
ids: string[]; // Array of notification IDs to mark as read
}
```
***
## See Also
<CardGroup cols={2}>
<Card title="Understand CLOB Authentication" icon="shield" href="/developers/CLOB/authentication">
Deep dive into L1 and L2 authentication
</Card>
<Card title="Public Methods" icon="globe" href="/developers/CLOB/clients/methods-l2">
Access market data, orderbooks, and prices.
</Card>
<Card title="L1 Methods" icon="lock" href="/developers/CLOB/clients/methods-l2">
Private key authentication to create or derive API keys (L2 headers)
</Card>
<Card title="Web Socket API" icon="hammer" href="/developers/CLOB/websocket/wss-overview">
Real-time market data streaming
</Card>
</CardGroup>
@@ -0,0 +1,235 @@
> ## 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.
# Methods Overview
> CLOB client methods require different levels of authentication. This reference is organized by what credentials you need to call each method.
<CardGroup cols={2}>
<Card title="Public Methods" icon="globe" href="/developers/CLOB/clients/methods-public">
Access market data, orderbooks, and prices.
</Card>
<Card title="L1 Methods" icon="key" href="/developers/CLOB/clients/methods-l1">
Private key authentication to create or derive API keys (L2 headers).
</Card>
<Card title="L2 Methods" icon="lock" href="/developers/CLOB/clients/methods-l2">
Manage and close orders. Creating orders requires signer.
</Card>
<Card title="Builder Program Methods" icon="hammer" href="/developers/CLOB/clients/methods-builder">
Builder-specific operations for those in the Builders Program.
</Card>
</CardGroup>
***
## Client Initialization by Use Case
<Tabs>
<Tab title="Get Market Data">
<CodeGroup>
```typescript TypeScript theme={null}
// No signer or credentials needed
const client = new ClobClient(
"https://clob.polymarket.com",
137
);
// All public methods available
const markets = await client.getMarkets();
const book = await client.getOrderBook(tokenId);
const price = await client.getPrice(tokenId, "BUY");
```
```python Python theme={null}
# No signer or credentials needed
client = new ClobClient(
host="https://clob.polymarket.com",
chain_id=137
)
# All public methods available
markets = client.get_markets()
book = client.get_order_book()
price = client.get_price()
```
</CodeGroup>
</Tab>
<Tab title="Generate User API Credentials">
<CodeGroup>
```typescript TypeScript theme={null}
// Create client with signer
const client = new ClobClient(
"https://clob.polymarket.com",
137,
signer
);
// All public and L1 methods available
const newCreds = createApiKey();
const derivedCreds = deriveApiKey();
const creds = createOrDeriveApiKey();
```
```python Python theme={null}
# Create client with signer
client = new ClobClient(
host="https://clob.polymarket.com",
chain_id=137
key="private_key"
)
# All public and L1 methods available
new_creds = client.create_api_key()
derived_creds = client.derive_api_key()
creds = client.create_or_derive_api_key()
```
</CodeGroup>
</Tab>
<Tab title="Create and Post Order">
<CodeGroup>
```typescript TypeScript theme={null}
// Create client with signer and creds
const client = new ClobClient(
"https://clob.polymarket.com",
137,
signer,
creds,
2, // Indicates Gnosis Safe proxy
funder // Safe wallet address holding funds
);
// All public, L1, and L2 methods available
const order = await client.createOrder({ /* ... */ });
const result = await client.postOrder(order);
const trades = await client.getTrades();
```
```python Python theme={null}
# Create client with signer and creds
const client = new ClobClient(
host="https://clob.polymarket.com",
chain_id=137,
key="private_key",
creds=creds,
signature_type=2, // Indicates Gnosis Safe proxy
funder="funder_address" // Safe wallet address holding funds
)
# All public, L1, and L2 methods available
order = client.create_order({ /* ... */ })
result = client.post_order(order)
trades = client.get_trades()
```
</CodeGroup>
</Tab>
<Tab title="Get Builders Orders">
<CodeGroup>
```typescript TypeScript theme={null}
// Create client with builder's authentication headers
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: BuilderConfig = {
localBuilderCreds: builderCreds
};
const client = new ClobClient(
"https://clob.polymarket.com",
137,
signer,
creds, // User's API credentials
2,
funder,
undefined,
false,
builderConfig // Builder's API credentials
);
// You can call all methods including builder methods
const builderTrades = await client.getBuilderTrades();
```
```python Python theme={null}
# Create client with builder's authentication headers
from py_clob_client.client import ClobClient
from py_clob_client.clob_types import ApiCreds
from py_builder_signing_sdk.config import BuilderConfig, BuilderApiKeyCreds
builder_creds = BuilderApiKeyCreds(
key="POLY_BUILDER_API_KEY",
secret="POLY_BUILDER_SECRET,
passphrase="POLY_BUILDER_PASSPHRASE"
)
builder_config = BuilderConfig(
local_builder_creds=builder_creds
)
client = ClobClient(
host="https://clob.polymarket.com",
chain_id=137,
key="private_key",
creds=creds, # User's API credentials
signature_type=2,
funder=funder_address,
builder_config=builder_config # Builder's API credentials
)
# You can call all methods including builder methods
builder_trades = client.get_builder_trades()
```
</CodeGroup>
Learn more about the Builders Program and Relay Client here
</Tab>
</Tabs>
***
## Resources
<CardGroup cols={3}>
<Card title="TypeScript Client" icon="github" href="https://github.com/Polymarket/clob-client">
Open source TypeScript client on GitHub
</Card>
<Card title="Python Client" icon="github" href="https://github.com/Polymarket/py-clob-client">
Open source Python client for GitHub
</Card>
<Card title="Rust Client" icon="github" href="https://github.com/Polymarket/rs-clob-client">
Open source Rust client on GitHub
</Card>
<Card title="TypeScript Examples" icon="code" href="https://github.com/Polymarket/clob-client/tree/main/examples">
TypeScript client method examples
</Card>
<Card title="Python Examples" icon="python" href="https://github.com/Polymarket/py-clob-client/tree/main/examples">
Python client method examples
</Card>
<Card title="Rust Examples" icon="rust" href="https://github.com/Polymarket/rs-clob-client/tree/main/examples">
Rust client method examples
</Card>
<Card title="CLOB Rest API Reference" icon="hammer" href="/api-reference/orderbook/get-order-book-summary">
Complete REST endpoint documentation
</Card>
<Card title="Web Socket API" icon="hammer" href="/developers/CLOB/websocket/wss-overview">
Real-time market data streaming
</Card>
</CardGroup>
@@ -0,0 +1,717 @@
> ## 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.
# Public Methods
> These methods can be called without a signer or user credentials. Use these for reading market data, prices, and order books.
## Client Initialization
Public methods require the client to initialize with the host URL and Polygon chain ID.
<Tabs>
<Tab title="TypeScript">
```typescript theme={null}
import { ClobClient } from "@polymarket/clob-client";
const client = new ClobClient(
"https://clob.polymarket.com",
137
);
// Ready to call public methods
const markets = await client.getMarkets();
```
</Tab>
<Tab title="Python">
```python theme={null}
from py_clob_client.client import ClobClient
client = ClobClient(
host="https://clob.polymarket.com",
chain_id=137
)
# Ready to call public methods
markets = await client.get_markets()
```
</Tab>
</Tabs>
***
## Health Check
***
### getOk()
Health check endpoint to verify the CLOB service is operational.
```typescript Signature theme={null}
async getOk(): Promise<any>
```
***
## Markets
***
### getMarket()
Get details for a single market by condition ID.
```typescript Signature theme={null}
async getMarket(conditionId: string): Promise<Market>
```
```typescript Response theme={null}
interface MarketToken {
outcome: string;
price: number;
token_id: string;
winner: boolean;
}
interface Market {
accepting_order_timestamp: string | null;
accepting_orders: boolean;
active: boolean;
archived: boolean;
closed: boolean;
condition_id: string;
description: string;
enable_order_book: boolean;
end_date_iso: string;
fpmm: string;
game_start_time: string;
icon: string;
image: string;
is_50_50_outcome: boolean;
maker_base_fee: number;
market_slug: string;
minimum_order_size: number;
minimum_tick_size: number;
neg_risk: boolean;
neg_risk_market_id: string;
neg_risk_request_id: string;
notifications_enabled: boolean;
question: string;
question_id: string;
rewards: {
max_spread: number;
min_size: number;
rates: any | null;
};
seconds_delay: number;
tags: string[];
taker_base_fee: number;
tokens: MarketToken[];
}
```
***
### getMarkets()
Get details for multiple markets paginated.
```typescript Signature theme={null}
async getMarkets(): Promise<PaginationPayload>
```
```typescript Response theme={null}
interface PaginationPayload {
limit: number;
count: number;
data: Market[];
}
interface Market {
accepting_order_timestamp: string | null;
accepting_orders: boolean;
active: boolean;
archived: boolean;
closed: boolean;
condition_id: string;
description: string;
enable_order_book: boolean;
end_date_iso: string;
fpmm: string;
game_start_time: string;
icon: string;
image: string;
is_50_50_outcome: boolean;
maker_base_fee: number;
market_slug: string;
minimum_order_size: number;
minimum_tick_size: number;
neg_risk: boolean;
neg_risk_market_id: string;
neg_risk_request_id: string;
notifications_enabled: boolean;
question: string;
question_id: string;
rewards: {
max_spread: number;
min_size: number;
rates: any | null;
};
seconds_delay: number;
tags: string[];
taker_base_fee: number;
tokens: MarketToken[];
}
interface MarketToken {
outcome: string;
price: number;
token_id: string;
winner: boolean;
}
```
***
### getSimplifiedMarkets()
Get simplified market data paginated for faster loading.
```typescript Signature theme={null}
async getSimplifiedMarkets(): Promise<PaginationPayload>
```
```typescript Response theme={null}
interface PaginationPayload {
limit: number;
count: number;
data: SimplifiedMarket[];
}
interface SimplifiedMarket {
accepting_orders: boolean;
active: boolean;
archived: boolean;
closed: boolean;
condition_id: string;
rewards: {
rates: any | null;
min_size: number;
max_spread: number;
};
tokens: SimplifiedToken[];
}
interface SimplifiedToken {
outcome: string;
price: number;
token_id: string;
}
```
***
### getSamplingMarkets()
```typescript Signature theme={null}
async getSamplingMarkets(): Promise<PaginationPayload>
```
```typescript Response theme={null}
interface PaginationPayload {
limit: number;
count: number;
data: Market[];
}
interface Market {
accepting_order_timestamp: string | null;
accepting_orders: boolean;
active: boolean;
archived: boolean;
closed: boolean;
condition_id: string;
description: string;
enable_order_book: boolean;
end_date_iso: string;
fpmm: string;
game_start_time: string;
icon: string;
image: string;
is_50_50_outcome: boolean;
maker_base_fee: number;
market_slug: string;
minimum_order_size: number;
minimum_tick_size: number;
neg_risk: boolean;
neg_risk_market_id: string;
neg_risk_request_id: string;
notifications_enabled: boolean;
question: string;
question_id: string;
rewards: {
max_spread: number;
min_size: number;
rates: any | null;
};
seconds_delay: number;
tags: string[];
taker_base_fee: number;
tokens: MarketToken[];
}
interface MarketToken {
outcome: string;
price: number;
token_id: string;
winner: boolean;
}
```
***
### getSamplingSimplifiedMarkets()
```typescript Signature theme={null}
async getSamplingSimplifiedMarkets(): Promise<PaginationPayload>
```
```typescript Response theme={null}
interface PaginationPayload {
limit: number;
count: number;
data: SimplifiedMarket[];
}
interface SimplifiedMarket {
accepting_orders: boolean;
active: boolean;
archived: boolean;
closed: boolean;
condition_id: string;
rewards: {
rates: any | null;
min_size: number;
max_spread: number;
};
tokens: SimplifiedToken[];
}
interface SimplifiedToken {
outcome: string;
price: number;
token_id: string;
}
```
***
## Order Books and Prices
***
### calculateMarketPrice()
```typescript Signature theme={null}
async calculateMarketPrice(
tokenID: string,
side: Side,
amount: number,
orderType: OrderType = OrderType.FOK
): Promise<number>
```
```typescript Params theme={null}
enum OrderType {
GTC = "GTC", // Good Till Cancelled
FOK = "FOK", // Fill or Kill
GTD = "GTD", // Good Till Date
FAK = "FAK", // Fill and Kill
}
enum Side {
BUY = "BUY",
SELL = "SELL",
}
```
```typescript Response theme={null}
number // calculated market price
```
***
### getOrderBook()
Get the order book for a specific token ID.
```typescript Signature theme={null}
async getOrderBook(tokenID: string): Promise<OrderBookSummary>
```
```typescript Response theme={null}
interface OrderBookSummary {
market: string;
asset_id: string;
timestamp: string;
bids: OrderSummary[];
asks: OrderSummary[];
min_order_size: string;
tick_size: string;
neg_risk: boolean;
hash: string;
}
interface OrderSummary {
price: string;
size: string;
}
```
***
### getOrderBooks()
Get order books for multiple token IDs.
```typescript Signature theme={null}
async getOrderBooks(params: BookParams[]): Promise<OrderBookSummary[]>
```
```typescript Params theme={null}
interface BookParams {
token_id: string;
side: Side; // Side.BUY or Side.SELL
}
```
```typescript Response theme={null}
OrderBookSummary[]
```
***
### getPrice()
Get the current best price for buying or selling a token ID.
```typescript Signature theme={null}
async getPrice(
tokenID: string,
side: "BUY" | "SELL"
): Promise<any>
```
```typescript Response theme={null}
{
price: string;
}
```
***
### getPrices()
Get the current best prices for multiple token IDs.
```typescript Signature theme={null}
async getPrices(params: BookParams[]): Promise<PricesResponse>
```
```typescript Params theme={null}
interface BookParams {
token_id: string;
side: Side; // Side.BUY or Side.SELL
}
```
```typescript Response theme={null}
interface TokenPrices {
BUY?: string;
SELL?: string;
}
type PricesResponse = {
[tokenId: string]: TokenPrices;
}
```
***
### getMidpoint()
Get the midpoint price (average of best bid and best ask) for a token ID.
```typescript Signature theme={null}
async getMidpoint(tokenID: string): Promise<any>
```
```typescript Response theme={null}
{
mid: string;
}
```
***
### getMidpoints()
Get the midpoint prices (average of best bid and best ask) for multiple token IDs.
```typescript Signature theme={null}
async getMidpoints(params: BookParams[]): Promise<any>
```
```typescript Params theme={null}
interface BookParams {
token_id: string;
side: Side; // Side is ignored
}
```
```typescript Response theme={null}
{
[tokenId: string]: string;
}
```
***
### getSpread()
Get the spread (difference between best ask and best bid) for a token ID.
```typescript Signature theme={null}
async getSpread(tokenID: string): Promise<SpreadResponse>
```
```typescript Response theme={null}
interface SpreadResponse {
spread: string;
}
```
***
### getSpreads()
Get the spreads (difference between best ask and best bid) for multiple token IDs.
```typescript Signature theme={null}
async getSpreads(params: BookParams[]): Promise<SpreadsResponse>
```
```typescript Params theme={null}
interface BookParams {
token_id: string;
side: Side;
}
```
```typescript Response theme={null}
type SpreadsResponse = {
[tokenId: string]: string;
}
```
***
### getPricesHistory()
Get historical price data for a token.
```typescript Signature theme={null}
async getPricesHistory(params: PriceHistoryFilterParams): Promise<MarketPrice[]>
```
```typescript Params theme={null}
interface PriceHistoryFilterParams {
market: string; // tokenID
startTs?: number;
endTs?: number;
fidelity?: number;
interval: PriceHistoryInterval;
}
enum PriceHistoryInterval {
MAX = "max",
ONE_WEEK = "1w",
ONE_DAY = "1d",
SIX_HOURS = "6h",
ONE_HOUR = "1h",
}
```
```typescript Response theme={null}
interface MarketPrice {
t: number; // timestamp
p: number; // price
}
```
***
## Trades
***
### getLastTradePrice()
Get the price of the most recent trade for a token.
```typescript Signature theme={null}
async getLastTradePrice(tokenID: string): Promise<LastTradePrice>
```
```typescript Response theme={null}
interface LastTradePrice {
price: string;
side: string;
}
```
***
### getLastTradesPrices()
Get the price of the most recent trade for a token.
```typescript Signature theme={null}
async getLastTradesPrices(params: BookParams[]): Promise<LastTradePriceWithToken[]>
```
```typescript Params theme={null}
interface BookParams {
token_id: string;
side: Side;
}
```
```typescript Response theme={null}
interface LastTradePriceWithToken {
price: string;
side: string;
token_id: string;
}
```
***
### getMarketTradesEvents
```typescript Signature theme={null}
async getMarketTradesEvents(conditionID: string): Promise<MarketTradeEvent[]>
```
```typescript Response theme={null}
interface MarketTradeEvent {
event_type: string;
market: {
condition_id: string;
asset_id: string;
question: string;
icon: string;
slug: string;
};
user: {
address: string;
username: string;
profile_picture: string;
optimized_profile_picture: string;
pseudonym: string;
};
side: Side;
size: string;
fee_rate_bps: string;
price: string;
outcome: string;
outcome_index: number;
transaction_hash: string;
timestamp: string;
}
```
## Market Parameters
***
### getFeeRateBps()
Get the fee rate in basis points for a token.
```typescript Signature theme={null}
async getFeeRateBps(tokenID: string): Promise<number>
```
```typescript Response theme={null}
number
```
***
### getTickSize()
Get the tick size (minimum price increment) for a market.
```typescript Signature theme={null}
async getTickSize(tokenID: string): Promise<TickSize>
```
```typescript Response theme={null}
type TickSize = "0.1" | "0.01" | "0.001" | "0.0001";
```
***
### getNegRisk()
Check if a market uses negative risk (binary complementary tokens).
```typescript Signature theme={null}
async getNegRisk(tokenID: string): Promise<boolean>
```
```typescript Response theme={null}
boolean
```
***
## Time & Server Info
### getServerTime()
Get the current server timestamp.
```typescript Signature theme={null}
async getServerTime(): Promise<number>
```
```typescript Response theme={null}
number // Unix timestamp in seconds
```
***
## See Also
<CardGroup cols={2}>
<Card title="L1 Methods" icon="key" href="/developers/CLOB/clients/methods-l1">
Private key authentication to create or derive API keys (L2 headers).
</Card>
<Card title="L2 Methods" icon="lock" href="/developers/CLOB/clients/methods-l2">
Manage and close orders. Creating orders requires signer.
</Card>
<Card title="CLOB Rest API Reference" icon="hammer" href="/api-reference/orderbook/get-order-book-summary">
Complete REST endpoint documentation
</Card>
<Card title="Web Socket API" icon="hammer" href="/developers/CLOB/websocket/wss-overview">
Real-time market data streaming
</Card>
</CardGroup>
+156
View File
@@ -0,0 +1,156 @@
> ## 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.
# Geographic Restrictions
> Check geographic restrictions before placing orders on Polymarket's CLOB
## Overview
Polymarket restricts order placement from certain geographic locations due to regulatory requirements and compliance with international sanctions.
Before placing orders, builders should verify the location.
<Warning>
Orders submitted from blocked regions will be rejected. Implement geoblock checks
in your application to provide users with appropriate feedback before they attempt to trade.
</Warning>
***
## Server Infrastructure
* **Primary Servers**: eu-west-2
* **Closest Non-Georestricted Region**: eu-west-1
***
## Geoblock Endpoint
Check the geographic eligibility of the requesting IP address:
```bash theme={null}
GET https://polymarket.com/api/geoblock
```
### Response
```typescript theme={null}
{
"blocked": boolean;
"ip": string;
"country": string;
"region": string;
}
```
| Field | Type | Description |
| --------- | ------- | ----------------------------------------------- |
| `blocked` | boolean | Whether the user is blocked from placing orders |
| `ip` | string | Detected IP address |
| `country` | string | ISO 3166-1 alpha-2 country code |
| `region` | string | Region/state code |
***
## Blocked Countries
The following **33 countries** are completely restricted from placing orders on Polymarket:
| Country Code | Country Name |
| ------------ | ------------------------------------ |
| AU | Australia |
| BE | Belgium |
| BY | Belarus |
| BI | Burundi |
| CF | Central African Republic |
| CD | Congo (Kinshasa) |
| CU | Cuba |
| DE | Germany |
| ET | Ethiopia |
| FR | France |
| GB | United Kingdom |
| IR | Iran |
| IQ | Iraq |
| IT | Italy |
| KP | North Korea |
| LB | Lebanon |
| LY | Libya |
| MM | Myanmar |
| NI | Nicaragua |
| PL | Poland |
| RU | Russia |
| SG | Singapore |
| SO | Somalia |
| SS | South Sudan |
| SD | Sudan |
| SY | Syria |
| TH | Thailand |
| TW | Taiwan |
| UM | United States Minor Outlying Islands |
| US | United States |
| VE | Venezuela |
| YE | Yemen |
| ZW | Zimbabwe |
***
## Blocked Regions
In addition to fully blocked countries, the following specific regions within otherwise accessible countries are also restricted:
| Country | Region | Region Code |
| ------------ | ------- | ----------- |
| Canada (CA) | Ontario | ON |
| Ukraine (UA) | Crimea | 43 |
| Ukraine (UA) | Donetsk | 14 |
| Ukraine (UA) | Luhansk | 09 |
***
## Usage Examples
<Tabs>
<Tab title="TypeScript">
```typescript theme={null}
interface GeoblockResponse {
blocked: boolean;
ip: string;
country: string;
region: string;
}
async function checkGeoblock(): Promise<GeoblockResponse> {
const response = await fetch("https://polymarket.com/api/geoblock");
return response.json();
}
// Usage
const geo = await checkGeoblock();
if (geo.blocked) {
console.log(`Trading not available in ${geo.country}`);
} else {
console.log("Trading available");
}
```
</Tab>
<Tab title="Python">
```python theme={null}
import requests
def check_geoblock() -> dict:
response = requests.get("https://polymarket.com/api/geoblock")
return response.json()
# Usage
geo = check_geoblock()
if geo["blocked"]:
print(f"Trading not available in {geo['country']}")
else:
print("Trading available")
```
</Tab>
</Tabs>
+56
View File
@@ -0,0 +1,56 @@
> ## 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.
# CLOB Introduction
Welcome to the Polymarket Order Book API! This documentation provides overviews, explanations, examples, and annotations to simplify interaction with the order book. The following sections detail the Polymarket Order Book and the API usage.
## System
Polymarket's Order Book, or CLOB (Central Limit Order Book), is hybrid-decentralized. It includes an operator for off-chain matching/ordering, with settlement executed on-chain, non-custodially, via signed order messages.
The exchange uses a custom Exchange contract facilitating atomic swaps between binary Outcome Tokens (CTF ERC1155 assets and ERC20 PToken assets) and collateral assets (ERC20), following signed limit orders. Designed for binary markets, the contract enables complementary tokens to match across a unified order book.
Orders are EIP712-signed structured data. Matched orders have one maker and one or more takers, with price improvements benefiting the taker. The operator handles off-chain order management and submits matched trades to the blockchain for on-chain execution.
## API
The Polymarket Order Book API enables market makers and traders to programmatically manage market orders. Orders of any amount can be created, listed, fetched, or read from the market order books. Data includes all available markets, market prices, and order history via REST and WebSocket endpoints.
## Security
Polymarket's Exchange contract has been audited by Chainsecurity ([View Audit](https://github.com/Polymarket/ctf-exchange/blob/main/audit/ChainSecurity_Polymarket_Exchange_audit.pdf)).
The operator's privileges are limited to order matching, non-censorship, and ensuring correct ordering. Operators can't set prices or execute unauthorized trades. Users can cancel orders on-chain independently if trust issues arise.
## Fees
### Schedule
> Subject to change
| Volume Level | Maker Fee Base Rate (bps) | Taker Fee Base Rate (bps) |
| ------------ | ------------------------- | ------------------------- |
| >0 USDC | 0 | 0 |
### Overview
Fees apply symmetrically in output assets (proceeds). This symmetry ensures fairness and market integrity. Fees are calculated differently depending on whether you are buying or selling:
* **Selling outcome tokens (base) for collateral (quote):**
$$
feeQuote = baseRate \times \min(price, 1 - price) \times size
$$
* **Buying outcome tokens (base) with collateral (quote):**
$$
feeBase = baseRate \times \min(price, 1 - price) \times \frac{size}{price}
$$
## Additional Resources
* [Exchange contract source code](https://github.com/Polymarket/ctf-exchange/tree/main/src)
* [Exchange contract documentation](https://github.com/Polymarket/ctf-exchange/blob/main/docs/Overview.md)
@@ -0,0 +1,173 @@
> ## 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.
# Cancel Orders(s)
> Multiple endpoints to cancel a single order, multiple orders, all orders or all orders from a single market.
# Cancel an single Order
<Tip> This endpoint requires a L2 Header. </Tip>
Cancel an order.
**HTTP REQUEST**
`DELETE /<clob-endpoint>/order`
### Request Payload Parameters
| Name | Required | Type | Description |
| ------- | -------- | ------ | --------------------- |
| orderID | yes | string | ID of order to cancel |
### Response Format
| Name | Type | Description |
| ------------- | --------- | -------------------------------------------------------------------------- |
| canceled | string\[] | list of canceled orders |
| not\_canceled | {} | a order id -> reason map that explains why that order couldn't be canceled |
<CodeGroup>
```python Python theme={null}
resp = client.cancel(order_id="0x38a73eed1e6d177545e9ab027abddfb7e08dbe975fa777123b1752d203d6ac88")
print(resp)
```
```javascript Typescript theme={null}
async function main() {
// Send it to the server
const resp = await clobClient.cancelOrder({
orderID:
"0x38a73eed1e6d177545e9ab027abddfb7e08dbe975fa777123b1752d203d6ac88",
});
console.log(resp);
console.log(`Done!`);
}
main();
```
</CodeGroup>
# Cancel Multiple Orders
<Tip> This endpoint requires a L2 Header. </Tip>
**HTTP REQUEST**
`DELETE /<clob-endpoint>/orders`
### Request Payload Parameters
| Name | Required | Type | Description |
| ---- | -------- | --------- | --------------------------- |
| null | yes | string\[] | IDs of the orders to cancel |
### Response Format
| Name | Type | Description |
| ------------- | --------- | -------------------------------------------------------------------------- |
| canceled | string\[] | list of canceled orders |
| not\_canceled | {} | a order id -> reason map that explains why that order couldn't be canceled |
<CodeGroup>
```python Python theme={null}
resp = client.cancel_orders(["0x38a73eed1e6d177545e9ab027abddfb7e08dbe975fa777123b1752d203d6ac88", "0xaaaa..."])
print(resp)
```
```javascript Typescript theme={null}
async function main() {
// Send it to the server
const resp = await clobClient.cancelOrders([
"0x38a73eed1e6d177545e9ab027abddfb7e08dbe975fa777123b1752d203d6ac88",
"0xaaaa...",
]);
console.log(resp);
console.log(`Done!`);
}
main();
```
</CodeGroup>
# Cancel ALL Orders
<Tip> This endpoint requires a L2 Header. </Tip>
Cancel all open orders posted by a user.
**HTTP REQUEST**
`DELETE /<clob-endpoint>/cancel-all`
### Response Format
| Name | Type | Description |
| ------------- | --------- | -------------------------------------------------------------------------- |
| canceled | string\[] | list of canceled orders |
| not\_canceled | {} | a order id -> reason map that explains why that order couldn't be canceled |
<CodeGroup>
```python Python theme={null}
resp = client.cancel_all()
print(resp)
print("Done!")
```
```javascript Typescript theme={null}
async function main() {
const resp = await clobClient.cancelAll();
console.log(resp);
console.log(`Done!`);
}
main();
```
</CodeGroup>
# Cancel orders from market
<Tip> This endpoint requires a L2 Header. </Tip>
Cancel orders from market.
**HTTP REQUEST**
`DELETE /<clob-endpoint>/cancel-market-orders`
### Request Payload Parameters
| Name | Required | Type | Description |
| --------- | -------- | ------ | -------------------------- |
| market | no | string | condition id of the market |
| asset\_id | no | string | id of the asset/token |
### Response Format
| Name | Type | Description |
| ------------- | --------- | -------------------------------------------------------------------------- |
| canceled | string\[] | list of canceled orders |
| not\_canceled | {} | a order id -> reason map that explains why that order couldn't be canceled |
<CodeGroup>
```python Python theme={null}
resp = client.cancel_market_orders(market="0xbd31dc8a20211944f6b70f31557f1001557b59905b7738480ca09bd4532f84af", asset_id="52114319501245915516055106046884209969926127482827954674443846427813813222426")
print(resp)
```
```javascript Typescript theme={null}
async function main() {
// Send it to the server
const resp = await clobClient.cancelMarketOrders({
market:
"0xbd31dc8a20211944f6b70f31557f1001557b59905b7738480ca09bd4532f84af",
asset_id:
"52114319501245915516055106046884209969926127482827954674443846427813813222426",
});
console.log(resp);
console.log(`Done!`);
}
main();
```
</CodeGroup>
@@ -0,0 +1,96 @@
> ## 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.
# Check Order Reward Scoring
> Check if an order is eligble or scoring for Rewards purposes
<Tip> This endpoint requires a L2 Header. </Tip>
Returns a boolean value where it is indicated if an order is scoring or not.
**HTTP REQUEST**
`GET /<clob-endpoint>/order-scoring?order_id={...}`
### Request Parameters
| Name | Required | Type | Description |
| ------- | -------- | ------ | ------------------------------------ |
| orderId | yes | string | id of order to get information about |
### Response Format
| Name | Type | Description |
| ---- | ------------- | ------------------ |
| null | OrdersScoring | order scoring data |
An `OrdersScoring` object is of the form:
| Name | Type | Description |
| ------- | ------- | ---------------------------------------- |
| scoring | boolean | indicates if the order is scoring or not |
# Check if some orders are scoring
> This endpoint requires a L2 Header.
Returns to a dictionary with boolean value where it is indicated if an order is scoring or not.
**HTTP REQUEST**
`POST /<clob-endpoint>/orders-scoring`
### Request Parameters
| Name | Required | Type | Description |
| -------- | -------- | --------- | ------------------------------------------ |
| orderIds | yes | string\[] | ids of the orders to get information about |
### Response Format
| Name | Type | Description |
| ---- | ------------- | ------------------- |
| null | OrdersScoring | orders scoring data |
An `OrdersScoring` object is a dictionary that indicates the order by if it score.
<RequestExample>
```python Python theme={null}
scoring = client.is_order_scoring(
OrderScoringParams(
orderId="0x..."
)
)
print(scoring)
scoring = client.are_orders_scoring(
OrdersScoringParams(
orderIds=["0x..."]
)
)
print(scoring)
```
```javascript Typescript theme={null}
async function main() {
const scoring = await clobClient.isOrderScoring({
orderId: "0x...",
});
console.log(scoring);
}
main();
async function main() {
const scoring = await clobClient.areOrdersScoring({
orderIds: ["0x..."],
});
console.log(scoring);
}
main();
```
</RequestExample>
@@ -0,0 +1,234 @@
> ## 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.
# Place Multiple Orders (Batching)
> Instructions for placing multiple orders(Batch)
<Tip> This endpoint requires a L2 Header </Tip>
Polymarkets CLOB supports batch orders, allowing you to place up to `15` orders in a single request. Before using this feature, make sure you're comfortable placing a single order first. You can find the documentation for that [here.](/developers/CLOB/orders/create-order)
**HTTP REQUEST**
`POST /<clob-endpoint>/orders`
### Request Payload Parameters
| Name | Required | Type | Description |
| --------- | -------- | ------------- | ---------------------------------------------------------------- |
| PostOrder | yes | PostOrders\[] | list of signed order objects (Signed Order + Order Type + Owner) |
A `PostOrder` object is the form:
| Name | Required | Type | Description |
| --------- | -------- | ------- | -------------------------------------------------------------------------------------------- |
| order | yes | order | See below table for details on crafting this object |
| orderType | yes | string | order type ("FOK", "GTC", "GTD", "FAK") |
| owner | yes | string | api key of order owner |
| postOnly | no | boolean | if `true`, the order will only rest on the book and not match immediately (default: `false`) |
An `order` object is the form:
| Name | Required | Type | Description |
| ------------- | -------- | ------- | -------------------------------------------------- |
| salt | yes | integer | random salt used to create unique order |
| maker | yes | string | maker address (funder) |
| signer | yes | string | signing address |
| taker | yes | string | taker address (operator) |
| tokenId | yes | string | ERC1155 token ID of conditional token being traded |
| makerAmount | yes | string | maximum amount maker is willing to spend |
| takerAmount | yes | string | minimum amount taker will pay the maker in return |
| expiration | yes | string | unix expiration timestamp |
| nonce | yes | string | maker's exchange nonce of the order is associated |
| feeRateBps | yes | string | fee rate basis points as required by the operator |
| side | yes | string | buy or sell enum index |
| signatureType | yes | integer | signature type enum index |
| signature | yes | string | hex encoded signature |
### Order types
* **FOK**: A Fill-Or-Kill order is an market order to buy (in dollars) or sell (in shares) shares that must be executed immediately in its entirety; otherwise, the entire order will be cancelled.
* **FAK**: A Fill-And-Kill order is a market order to buy (in dollars) or sell (in shares) that will be executed immediately for as many shares as are available; any portion not filled at once is cancelled.
* **GTC**: A Good-Til-Cancelled order is a limit order that is active until it is fulfilled or cancelled.
* **GTD**: A Good-Til-Date order is a type of order that is active until its specified date (UTC seconds timestamp), unless it has already been fulfilled or cancelled. There is a security threshold of one minute. If the order needs to expire in 90 seconds the correct expiration value is: now + 1 minute + 30 seconds
### Response Format
| Name | Type | Description |
| ----------- | --------- | ---------------------------------------------------------------------------------------------------------------------------------- |
| success | boolean | boolean indicating if server-side err (`success = false`) -> server-side error |
| errorMsg | string | error message in case of unsuccessful placement (in case `success = false`, e.g. `client-side error`, the reason is in `errorMsg`) |
| orderId | string | id of order |
| orderHashes | string\[] | hash of settlement transaction order was marketable and triggered a match |
### Insert Error Messages
If the `errorMsg` field of the response object from placement is not an empty string, the order was not able to be immediately placed. This might be because of a delay or because of a failure. If the `success` is not `true`, then there was an issue placing the order. The following `errorMessages` are possible:
#### Error
| Error | Success | Message | Description |
| ------------------------------------ | ------- | --------------------------------------------------------------------------------------- | --------------------------------------------------------------------- |
| INVALID\_ORDER\_MIN\_TICK\_SIZE | yes | order is invalid. Price breaks minimum tick size rules | order price isn't accurate to correct tick sizing |
| INVALID\_ORDER\_MIN\_SIZE | yes | order is invalid. Size lower than the minimum | order size must meet min size threshold requirement |
| INVALID\_ORDER\_DUPLICATED | yes | order is invalid. Duplicated. Same order has already been placed, can't be placed again | |
| INVALID\_ORDER\_NOT\_ENOUGH\_BALANCE | yes | not enough balance / allowance | funder address doesn't have sufficient balance or allowance for order |
| INVALID\_ORDER\_EXPIRATION | yes | invalid expiration | expiration field expresses a time before now |
| INVALID\_ORDER\_ERROR | yes | could not insert order | system error while inserting order |
| INVALID\_POST\_ONLY\_ORDER\_TYPE | yes | invalid post-only order: only GTC and GTD order types are allowed | post only flag attached to a market order |
| INVALID\_POST\_ONLY\_ORDER | yes | invalid post-only order: order crosses book | post only order would match |
| EXECUTION\_ERROR | yes | could not run the execution | system error while attempting to execute trade |
| ORDER\_DELAYED | no | order match delayed due to market conditions | order placement delayed |
| DELAYING\_ORDER\_ERROR | yes | error delaying the order | system error while delaying order |
| FOK\_ORDER\_NOT\_FILLED\_ERROR | yes | order couldn't be fully filled, FOK orders are fully filled/killed | FOK order not fully filled so can't be placed |
| MARKET\_NOT\_READY | no | the market is not yet ready to process new orders | system not accepting orders for market yet |
### Insert Statuses
When placing an order, a status field is included. The status field provides additional information regarding the order's state as a result of the placement. Possible values include:
#### Status
| Status | Description |
| --------- | ------------------------------------------------------------ |
| matched | order placed and matched with an existing resting order |
| live | order placed and resting on the book |
| delayed | order marketable, but subject to matching delay |
| unmatched | order marketable, but failure delaying, placement successful |
<RequestExample>
```python Python theme={null}
from py_clob_client.client import ClobClient
from py_clob_client.clob_types import OrderArgs, OrderType, PostOrdersArgs
from py_clob_client.order_builder.constants import BUY
host: str = "https://clob.polymarket.com"
key: str = "" ##This is your Private Key. Export from https://reveal.magic.link/polymarket or from your Web3 Application
chain_id: int = 137 #No need to adjust this
POLYMARKET_PROXY_ADDRESS: str = '' #This is the address listed below your profile picture when using the Polymarket site.
#Select from the following 3 initialization options to matches your login method, and remove any unused lines so only one client is initialized.
### 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)
### 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)
### Initialization of a client that trades directly from an EOA.
client = ClobClient(host, key=key, chain_id=chain_id)
## Create and sign a limit order buying 100 YES tokens for 0.50c each
#Refer to the Markets API documentation to locate a tokenID: https://docs.polymarket.com/developers/gamma-markets-api/get-markets
client.set_api_creds(client.create_or_derive_api_creds())
resp = client.post_orders([
PostOrdersArgs(
# Create and sign a limit order buying 100 YES tokens for 0.50 each
order=client.create_order(OrderArgs(
price=0.01,
size=5,
side=BUY,
token_id="88613172803544318200496156596909968959424174365708473463931555296257475886634",
)),
orderType=OrderType.GTC, # Good 'Til Cancelled
),
PostOrdersArgs(
# Create and sign a limit order selling 200 NO tokens for 0.25 each
order=client.create_order(OrderArgs(
price=0.01,
size=5,
side=BUY,
token_id="93025177978745967226369398316375153283719303181694312089956059680730874301533",
)),
orderType=OrderType.GTC, # Good 'Til Cancelled
)
])
print(resp)
print("Done!")
```
```javascript typescript theme={null}
import { ethers } from "ethers";
import { config as dotenvConfig } from "dotenv";
import { resolve } from "path";
import { ApiKeyCreds, Chain, ClobClient, OrderType, PostOrdersArgs, Side } from "../src";
dotenvConfig({ path: resolve(__dirname, "../.env") });
async function main() {
const wallet = new ethers.Wallet(`${process.env.PK}`);
const chainId = parseInt(`${process.env.CHAIN_ID || Chain.AMOY}`) as Chain;
console.log(`Address: ${await wallet.getAddress()}, chainId: ${chainId}`);
const host = process.env.CLOB_API_URL || "https://clob.polymarket.com";
const creds: ApiKeyCreds = {
key: `${process.env.CLOB_API_KEY}`,
secret: `${process.env.CLOB_SECRET}`,
passphrase: `${process.env.CLOB_PASS_PHRASE}`,
};
const clobClient = new ClobClient(host, chainId, wallet, creds);
await clobClient.cancelAll();
const YES = "71321045679252212594626385532706912750332728571942532289631379312455583992563";
const orders: PostOrdersArgs[] = [
{
order: await clobClient.createOrder({
tokenID: YES,
price: 0.4,
side: Side.BUY,
size: 100,
}),
orderType: OrderType.GTC,
},
{
order: await clobClient.createOrder({
tokenID: YES,
price: 0.45,
side: Side.BUY,
size: 100,
}),
orderType: OrderType.GTC,
},
{
order: await clobClient.createOrder({
tokenID: YES,
price: 0.55,
side: Side.SELL,
size: 100,
}),
orderType: OrderType.GTC,
},
{
order: await clobClient.createOrder({
tokenID: YES,
price: 0.6,
side: Side.SELL,
size: 100,
}),
orderType: OrderType.GTC,
},
];
// Send it to the server
const resp = await clobClient.postOrders(orders);
console.log(resp);
}
main();
```
```REQUEST Example Payload theme={null}
[
{'order': {'salt': 660377097, 'maker': '0x17A9568474b5fc84B1D1C44f081A0a3aDE750B2b', 'signer': '0x17A9568474b5fc84B1D1C44f081A0a3aDE750B2b', 'taker': '0x0000000000000000000000000000000000000000', 'tokenId': '88613172803544318200496156596909968959424174365708473463931555296257475886634', 'makerAmount': '50000', 'takerAmount': '5000000', 'expiration': '0', 'nonce': '0', 'feeRateBps': '0', 'side': 'BUY', 'signatureType': 0, 'signature': '0xccb8d1298d698ebc0859e6a26044c848ac4a4b0e20a391a4574e42b9c9bf237e5fa09fc00743e3e2d2f8e909a21d60f276ce083cc35c6661410b892f5bcbe2291c'}, 'owner': 'PRIVATEKEY', 'orderType': 'GTC'},
{'order': {'salt': 1207111323, 'maker': '0x17A9568474b5fc84B1D1C44f081A0a3aDE750B2b', 'signer': '0x17A9568474b5fc84B1D1C44f081A0a3aDE750B2b', 'taker': '0x0000000000000000000000000000000000000000', 'tokenId': '93025177978745967226369398316375153283719303181694312089956059680730874301533', 'makerAmount': '50000', 'takerAmount': '5000000', 'expiration': '0', 'nonce': '0', 'feeRateBps': '0', 'side': 'BUY', 'signatureType': 0, 'signature': '0x0feca28666283824c27d7bead0bc441dde6df20dd71ef5ff7c84d3d1d5bf8aa4296fa382769dc11a92abe05b6f731d6c32556e9b4fb29e6eb50131af23a9ac941c'}, 'owner': 'PRIVATEKEY', 'orderType': 'GTC'}
]
```
</RequestExample>
+264
View File
@@ -0,0 +1,264 @@
> ## 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.
# Place Single Order
> Detailed instructions for creating, placing, and managing orders using Polymarket's CLOB API.
# Create and Place an Order
<Tip> This endpoint requires a L2 Header </Tip>
Create and place an order using the Polymarket CLOB API clients. All orders are represented as "limit" orders, but "market" orders are also supported. To place a market order, simply ensure your price is marketable against current resting limit orders, which are executed on input at the best price.
**HTTP REQUEST**
`POST /<clob-endpoint>/order`
### Request Payload Parameters
| Name | Required | Type | Description |
| --------- | -------- | ------- | -------------------------------------------------------------------------------------------- |
| order | yes | Order | signed object |
| owner | yes | string | api key of order owner |
| orderType | yes | string | order type ("FOK", "GTC", "GTD") |
| postOnly | no | boolean | if `true`, the order will only rest on the book and not match immediately (default: `false`) |
### Post-only orders
* postOnly submits a limit order that will not match resting liquidity upon entry.
* If a postOnly order would cross the spread (i.e., it is marketable), it will be rejected rather than executed.
* postOnly cannot be combined with market order types (e.g., FOK or FAK). If `postOnly = true` is sent with a market order type, the order will be rejected.
An `order` object is the form:
| Name | Required | Type | Description |
| ------------- | -------- | ------- | -------------------------------------------------- |
| salt | yes | integer | random salt used to create unique order |
| maker | yes | string | maker address (funder) |
| signer | yes | string | signing address |
| taker | yes | string | taker address (operator) |
| tokenId | yes | string | ERC1155 token ID of conditional token being traded |
| makerAmount | yes | string | maximum amount maker is willing to spend |
| takerAmount | yes | string | minimum amount taker will pay the maker in return |
| expiration | yes | string | unix expiration timestamp |
| nonce | yes | string | maker's exchange nonce of the order is associated |
| feeRateBps | yes | string | fee rate basis points as required by the operator |
| side | yes | string | buy or sell enum index |
| signatureType | yes | integer | signature type enum index |
| signature | yes | string | hex encoded signature |
### Order types
* **FOK**: A Fill-Or-Kill order is an market order to buy (in dollars) or sell (in shares) shares that must be executed immediately in its entirety; otherwise, the entire order will be cancelled.
* **FAK**: A Fill-And-Kill order is a market order to buy (in dollars) or sell (in shares) that will be executed immediately for as many shares as are available; any portion not filled at once is cancelled.
* **GTC**: A Good-Til-Cancelled order is a limit order that is active until it is fulfilled or cancelled.
* **GTD**: A Good-Til-Date order is a type of order that is active until its specified date (UTC seconds timestamp), unless it has already been fulfilled or cancelled. There is a security threshold of one minute. If the order needs to expire in 90 seconds the correct expiration value is: now + 1 minute + 30 seconds
### Response Format
| Name | Type | Description |
| ----------- | --------- | ---------------------------------------------------------------------------------------------------------------------------------- |
| success | boolean | boolean indicating if server-side err (`success = false`) -> server-side error |
| errorMsg | string | error message in case of unsuccessful placement (in case `success = false`, e.g. `client-side error`, the reason is in `errorMsg`) |
| orderId | string | id of order |
| orderHashes | string\[] | hash of settlement transaction order was marketable and triggered a match |
### Insert Error Messages
If the `errorMsg` field of the response object from placement is not an empty string, the order was not able to be immediately placed. This might be because of a delay or because of a failure. If the `success` is not `true`, then there was an issue placing the order. The following `errorMessages` are possible:
#### Error
| Error | Success | Message | Description |
| ------------------------------------ | ------- | --------------------------------------------------------------------------------------- | --------------------------------------------------------------------- |
| INVALID\_ORDER\_MIN\_TICK\_SIZE | yes | order is invalid. Price breaks minimum tick size rules | order price isn't accurate to correct tick sizing |
| INVALID\_ORDER\_MIN\_SIZE | yes | order is invalid. Size lower than the minimum | order size must meet min size threshold requirement |
| INVALID\_ORDER\_DUPLICATED | yes | order is invalid. Duplicated. Same order has already been placed, can't be placed again | |
| INVALID\_ORDER\_NOT\_ENOUGH\_BALANCE | yes | not enough balance / allowance | funder address doesn't have sufficient balance or allowance for order |
| INVALID\_ORDER\_EXPIRATION | yes | invalid expiration | expiration field expresses a time before now |
| INVALID\_ORDER\_ERROR | yes | could not insert order | system error while inserting order |
| INVALID\_POST\_ONLY\_ORDER\_TYPE | yes | invalid post-only order: only GTC and GTD order types are allowed | post only flag attached to a market order |
| INVALID\_POST\_ONLY\_ORDER | yes | invalid post-only order: order crosses book | post only order would match |
| EXECUTION\_ERROR | yes | could not run the execution | system error while attempting to execute trade |
| ORDER\_DELAYED | no | order match delayed due to market conditions | order placement delayed |
| DELAYING\_ORDER\_ERROR | yes | error delaying the order | system error while delaying order |
| FOK\_ORDER\_NOT\_FILLED\_ERROR | yes | order couldn't be fully filled, FOK orders are fully filled/killed | FOK order not fully filled so can't be placed |
| MARKET\_NOT\_READY | no | the market is not yet ready to process new orders | system not accepting orders for market yet |
### Insert Statuses
When placing an order, a status field is included. The status field provides additional information regarding the order's state as a result of the placement. Possible values include:
#### Status
| Status | Description |
| --------- | ------------------------------------------------------------ |
| matched | order placed and matched with an existing resting order |
| live | order placed and resting on the book |
| delayed | order marketable, but subject to matching delay |
| unmatched | order marketable, but failure delaying, placement successful |
<RequestExample>
```python Python theme={null}
from py_clob_client.client import ClobClient
from py_clob_client.clob_types import OrderArgs, OrderType
from py_clob_client.order_builder.constants import BUY
host: str = "https://clob.polymarket.com"
key: str = "" #This is your Private Key. Export from reveal.polymarket.com or 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.
#Select from the following 3 initialization options to matches your login method, and remove any unused lines so only one client is initialized.
### 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)
### 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)
### Initialization of a client that trades directly from an EOA.
client = ClobClient(host, key=key, chain_id=chain_id)
## Create and sign a limit order buying 100 YES tokens for 0.50c each
#Refer to the Markets API documentation to locate a tokenID: https://docs.polymarket.com/developers/gamma-markets-api/get-markets
client.set_api_creds(client.create_or_derive_api_creds())
order_args = OrderArgs(
price=0.01,
size=5.0,
side=BUY,
token_id="", #Token ID you want to purchase goes here.
)
signed_order = client.create_order(order_args)
## GTC(Good-Till-Cancelled) Order
resp = client.post_order(signed_order, OrderType.GTC)
print(resp)
```
```javascript typescript theme={null}
// GTC Order example
//
import { Side, OrderType } from "@polymarket/clob-client";
async function main() {
// Create a buy order for 100 YES for 0.50c
// YES: 71321045679252212594626385532706912750332728571942532289631379312455583992563
const order = await clobClient.createOrder({
tokenID:
"71321045679252212594626385532706912750332728571942532289631379312455583992563",
price: 0.5,
side: Side.BUY,
size: 100,
feeRateBps: 0,
nonce: 1,
});
console.log("Created Order", order);
// Send it to the server
// GTC Order
const resp = await clobClient.postOrder(order, OrderType.GTC);
console.log(resp);
}
main();
// GTD Order example
//
import { Side, OrderType } from "@polymarket/clob-client";
async function main() {
// Create a buy order for 100 YES for 0.50c that expires in 1 minute
// YES: 71321045679252212594626385532706912750332728571942532289631379312455583992563
// There is a 1 minute of security threshold for the expiration field.
// If we need the order to expire in 30 seconds the correct expiration value is:
// now + 1 miute + 30 seconds
const oneMinute = 60 * 1000;
const seconds = 30 * 1000;
const expiration = parseInt(
((new Date().getTime() + oneMinute + seconds) / 1000).toString()
);
const order = await clobClient.createOrder({
tokenID:
"71321045679252212594626385532706912750332728571942532289631379312455583992563",
price: 0.5,
side: Side.BUY,
size: 100,
feeRateBps: 0,
nonce: 1,
// There is a 1 minute of security threshold for the expiration field.
// If we need the order to expire in 30 seconds the correct expiration value is:
// now + 1 miute + 30 seconds
expiration: expiration,
});
console.log("Created Order", order);
// Send it to the server
// GTD Order
const resp = await clobClient.postOrder(order, OrderType.GTD);
console.log(resp);
}
main();
// FOK BUY Order example
//
import { Side, OrderType } from "@polymarket/clob-client";
async function main() {
// Create a market buy order for $100
// YES: 71321045679252212594626385532706912750332728571942532289631379312455583992563
const marketOrder = await clobClient.createMarketOrder({
side: Side.BUY,
tokenID:
"71321045679252212594626385532706912750332728571942532289631379312455583992563",
amount: 100, // $$$
feeRateBps: 0,
nonce: 0,
price: 0.5,
});
console.log("Created Order", order);
// Send it to the server
// FOK Order
const resp = await clobClient.postOrder(order, OrderType.FOK);
console.log(resp);
}
main();
// FOK SELL Order example
//
import { Side, OrderType } from "@polymarket/clob-client";
async function main() {
// Create a market sell order for 100 shares
// YES: 71321045679252212594626385532706912750332728571942532289631379312455583992563
const marketOrder = await clobClient.createMarketOrder({
side: Side.SELL,
tokenID:
"71321045679252212594626385532706912750332728571942532289631379312455583992563",
amount: 100, // shares
feeRateBps: 0,
nonce: 0,
price: 0.5,
});
console.log("Created Order", order);
// Send it to the server
// FOK Order
const resp = await clobClient.postOrder(order, OrderType.FOK);
console.log(resp);
}
main();
```
</RequestExample>
@@ -0,0 +1,53 @@
> ## 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.
# Get Active Orders
<Tip> This endpoint requires a L2 Header. </Tip>
Get active order(s) for a specific market.
**HTTP REQUEST**
`GET /<clob-endpoint>/data/orders`
### Request Parameters
| Name | Required | Type | Description |
| --------- | -------- | ------ | ------------------------------------ |
| id | no | string | id of order to get information about |
| market | no | string | condition id of market |
| asset\_id | no | string | id of the asset/token |
### Response Format
| Name | Type | Description |
| ---- | ------------ | ---------------------------------------------------- |
| null | OpenOrder\[] | list of open orders filtered by the query parameters |
<RequestExample>
```python Python theme={null}
from py_clob_client.clob_types import OpenOrderParams
resp = client.get_orders(
OpenOrderParams(
market="0xbd31dc8a20211944f6b70f31557f1001557b59905b7738480ca09bd4532f84af",
)
)
print(resp)
print("Done!")
```
```javascript Typescript theme={null}
async function main() {
const resp = await clobClient.getOpenOrders({
market:
"0xbd31dc8a20211944f6b70f31557f1001557b59905b7738480ca09bd4532f84af",
});
console.log(resp);
console.log(`Done!`);
}
main();
```
</RequestExample>
+66
View File
@@ -0,0 +1,66 @@
> ## 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.
# Get Order
> Get information about an existing order
<Tip>This endpoint requires a L2 Header. </Tip>
Get single order by id.
**HTTP REQUEST**
`GET /<clob-endpoint>/data/order/<order_hash>`
### Request Parameters
| Name | Required | Type | Description |
| ---- | -------- | ------ | ------------------------------------ |
| id | no | string | id of order to get information about |
### Response Format
| Name | Type | Description |
| ----- | --------- | ------------------ |
| order | OpenOrder | order if it exists |
An `OpenOrder` object is of the form:
| Name | Type | Description |
| ----------------- | --------- | -------------------------------------------------------------- |
| associate\_trades | string\[] | any Trade id the order has been partially included in |
| id | string | order id |
| status | string | order current status |
| market | string | market id (condition id) |
| original\_size | string | original order size at placement |
| outcome | string | human readable outcome the order is for |
| maker\_address | string | maker address (funder) |
| owner | string | api key |
| price | string | price |
| side | string | buy or sell |
| size\_matched | string | size of order that has been matched/filled |
| asset\_id | string | token id |
| expiration | string | unix timestamp when the order expired, 0 if it does not expire |
| type | string | order type (GTC, FOK, GTD) |
| created\_at | string | unix timestamp when the order was created |
<RequestExample>
```python Python theme={null}
order = clob_client.get_order("0xb816482a5187a3d3db49cbaf6fe3ddf24f53e6c712b5a4bf5e01d0ec7b11dabc")
print(order)
```
```javascript Typescript theme={null}
async function main() {
const order = await clobClient.getOrder(
"0xb816482a5187a3d3db49cbaf6fe3ddf24f53e6c712b5a4bf5e01d0ec7b11dabc"
);
console.log(order);
}
main();
```
</RequestExample>
@@ -0,0 +1,18 @@
> ## 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.
# Onchain Order Info
## How do I interpret the OrderFilled onchain event?
Given an OrderFilled event:
* `orderHash`: a unique hash for the Order being filled
* `maker`: the user generating the order and the source of funds for the order
* `taker`: the user filling the order OR the Exchange contract if the order fills multiple limit orders
* `makerAssetId`: id of the asset that is given out. If 0, indicates that the Order is a BUY, giving USDC in exchange for Outcome tokens. Else, indicates that the Order is a SELL, giving Outcome tokens in exchange for USDC.
* `takerAssetId`: id of the asset that is received. If 0, indicates that the Order is a SELL, receiving USDC in exchange for Outcome tokens. Else, indicates that the Order is a BUY, receiving Outcome tokens in exchange for USDC.
* `makerAmountFilled`: the amount of the asset that is given out.
* `takerAmountFilled`: the amount of the asset that is received.
* `fee`: the fees paid by the order maker
+33
View File
@@ -0,0 +1,33 @@
> ## 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.
# Orders Overview
> Detailed instructions for creating, placing, and managing orders using Polymarket's CLOB API.
All orders are expressed as limit orders (can be marketable). The underlying order primitive must be in the form expected and executable by the on-chain binary limit order protocol contract. Preparing such an order is quite involved (structuring, hashing, signing), thus Polymarket suggests using the open source typescript, python and golang libraries.
## Allowances
To place an order, allowances must be set by the funder address for the specified `maker` asset for the Exchange contract. When buying, this means the funder must have set a USDC allowance greater than or equal to the spending amount. When selling, the funder must have set an allowance for the conditional token that is greater than or equal to the selling amount. This allows the Exchange contract to execute settlement according to the signed order instructions created by a user and matched by the operator.
## Signature Types
Polymarkets CLOB supports 3 signature types. Orders must identify what signature type they use. The available typescript and python clients abstract the complexity of signing and preparing orders with the following signature types by allowing a funder address and signer type to be specified on initialization. The supported signature types are:
| Type | ID | Description |
| ------------------ | -- | ------------------------------------------------------------------------------------------ |
| EOA | 0 | EIP712 signature signed by an EOA |
| POLY\_PROXY | 1 | EIP712 signatures signed by a signer associated with funding Polymarket proxy wallet |
| POLY\_GNOSIS\_SAFE | 2 | EIP712 signatures signed by a signer associated with funding Polymarket gnosis safe wallet |
## Validity Checks
Orders are continually monitored to make sure they remain valid. Specifically, this includes continually tracking underlying balances, allowances and on-chain order cancellations. Any maker that is caught intentionally abusing these checks (which are essentially real time) will be blacklisted.
Additionally, there are rails on order placement in a market. Specifically, you can only place orders that sum to less than or equal to your available balance for each market. For example if you have 500 USDC in your funding wallet, you can place one order to buy 1000 YES in marketA @ \$.50, then any additional buy orders to that market will be rejected since your entire balance is reserved for the first (and only) buy order. More explicitly the max size you can place for an order is:
$$
\text{maxOrderSize} = \text{underlyingAssetBalance} - \sum(\text{orderSize} - \text{orderFillAmount})
$$
+305
View File
@@ -0,0 +1,305 @@
> ## 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.
# Quickstart
> Initialize the CLOB and place your first order.
## Installation
<CodeGroup>
```bash TypeScript theme={null}
npm install @polymarket/clob-client ethers
```
```bash Python theme={null}
pip install py-clob-client
```
```bash Rust theme={null}
cargo add polymarket-client-sdk
```
</CodeGroup>
***
## Quick Start
### 1. Setup Client
<CodeGroup>
```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);
// Create or derive user API credentials
const tempClient = new ClobClient(HOST, CHAIN_ID, signer);
const apiCreds = await tempClient.createOrDeriveApiKey();
// See 'Signature Types' note below
const signatureType = 0;
// Initialize trading client
const client = new ClobClient(
HOST,
CHAIN_ID,
signer,
apiCreds,
signatureType
);
```
```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")
# Create or derive user API credentials
temp_client = ClobClient(host, key=private_key, chain_id=chain_id)
api_creds = await temp_client.create_or_derive_api_key()
# See 'Signature Types' note below
signature_type = 0
# Initialize trading client
client = ClobClient(
host,
key=private_key,
chain_id=chain_id,
creds=api_creds,
signature_type=signature_type
)
```
</CodeGroup>
<Note>
This quick start sets your EOA as the trading account. You'll need to fund this
wallet to trade and pay for gas on transactions. Gas-less transactions are only
available by deploying a proxy wallet and using Polymarket's Polygon relayer
infrastructure.
</Note>
<Accordion title="Signature Types">
| Wallet Type | ID | When to Use |
| ------------ | --- | ------------------------------------------------------ |
| EOA | `0` | Standard Ethereum wallet (MetaMask) |
| Custom Proxy | `1` | Specific to Magic Link users from Polymarket only |
| Gnosis Safe | `2` | Injected providers (Metamask, Rabby, embedded wallets) |
</Accordion>
***
### 2. Place an Order
<CodeGroup>
```typescript TypeScript theme={null}
import { Side } from "@polymarket/clob-client";
// Place a limit order in one step
const response = await client.createAndPostOrder({
tokenID: "YOUR_TOKEN_ID", // Get from Gamma API
price: 0.65, // Price per share
size: 10, // Number of shares
side: Side.BUY, // or SELL
});
console.log(`Order placed! ID: ${response.orderID}`);
```
```python Python theme={null}
from py_clob_client.clob_types import OrderArgs
from py_clob_client.order_builder.constants import BUY
# Place a limit order in one step
response = await client.create_and_post_order(
OrderArgs(
token_id="YOUR_TOKEN_ID", # Get from Gamma API
price=0.65, # Price per share
size=10, # Number of shares
side=BUY, # or SELL
)
)
print(f"Order placed! ID: {response['orderID']}")
```
</CodeGroup>
***
### 3. 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`);
```
```python Python theme={null}
# View all open orders
open_orders = await client.get_open_orders()
print(f"You have {len(open_orders)} open orders")
# View your trade history
trades = await client.get_trades()
print(f"You've made {len(trades)} trades")
```
</CodeGroup>
***
## Complete Example
<CodeGroup>
```typescript TypeScript theme={null}
import { ClobClient, Side } from "@polymarket/clob-client";
import { Wallet } from "ethers";
async function trade() {
const HOST = "https://clob.polymarket.com";
const CHAIN_ID = 137; // Polygon mainnet
const signer = new Wallet(process.env.PRIVATE_KEY);
const tempClient = new ClobClient(HOST, CHAIN_ID, signer);
const apiCreds = await tempClient.createOrDeriveApiKey();
const signatureType = 0;
const client = new ClobClient(
HOST,
CHAIN_ID,
signer,
apiCreds,
signatureType
);
const response = await client.createAndPostOrder({
tokenID: "YOUR_TOKEN_ID",
price: 0.65,
size: 10,
side: Side.BUY,
});
console.log(`Order placed! ID: ${response.orderID}`);
}
trade();
```
```python Python theme={null}
from py_clob_client.client import ClobClient
from py_clob_client.clob_types import OrderArgs
from py_clob_client.order_builder.constants import BUY
import asyncio
import os
async def trade():
host = "https://clob.polymarket.com"
chain_id = 137 # Polygon mainnet
private_key = os.getenv("PRIVATE_KEY")
temp_client = ClobClient(host, key=private_key, chain_id=chain_id)
creds = await temp_client.create_or_derive_api_key()
signature_type=0
client = ClobClient(
host,
chain_id=chain_id,
key=private_key,
creds=creds,
signature_type=signature_type
)
response = await client.create_and_post_order(
OrderArgs(
token_id="YOUR_TOKEN_ID",
price=0.65,
size=10,
side=BUY
)
)
print(f"Order placed! ID: {response['orderID']}")
if __name__ == "__main__":
asyncio.run(trade())
```
</CodeGroup>
***
## Troubleshooting
<AccordionGroup>
<Accordion title="Error: L2_AUTH_NOT_AVAILABLE">
You forgot to call `createOrDeriveApiKey()`. Make sure you initialize the client with API credentials:
```typescript theme={null}
const creds = await clobClient.createOrDeriveApiKey();
const client = new ClobClient(host, chainId, wallet, creds);
```
</Accordion>
<Accordion title="Order rejected: insufficient balance">
Ensure you have:
* **USDC** in your funder address for BUY orders
* **Outcome tokens** in your funder address for SELL orders
Check your balance at [polymarket.com/portfolio](https://polymarket.com/portfolio).
</Accordion>
<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 use the CTF contract's `setApprovalForAll()` method.
</Accordion>
<Accordion title="What's my funder address?">
Your funder address is the Polymarket proxy wallet where you deposit funds. Find it:
1. Go to [polymarket.com/settings](https://polymarket.com/settings)
2. Look for "Wallet Address" or "Profile Address"
3. This is your `FUNDER_ADDRESS`
</Accordion>
</AccordionGroup>
***
## Next Steps
<CardGroup cols={1}>
<Card title="Full Example Implementations" icon="puzzle" href="/developers/builders/examples">
Complete Next.js examples demonstrating integration of embedded wallets
(Privy, Magic, Turnkey, wagmi) and the CLOB and Builder Relay clients
</Card>
</CardGroup>
<CardGroup cols={2}>
<Card title="Understand CLOB Authentication" icon="shield" href="/developers/CLOB/authentication">
Deep dive into L1 and L2 authentication
</Card>
<Card title="Browse Client Methods" icon="book" href="/developers/CLOB/clients/methods-overview">
Explore the complete client reference
</Card>
<Card title="Find Markets to Trade" icon="chart-line" href="/developers/gamma-markets-api/get-markets">
Use Gamma API to discover markets
</Card>
<Card title="Monitor with WebSocket" icon="signal-stream" href="/developers/CLOB/websocket/wss-overview">
Get real-time order updates
</Card>
</CardGroup>
+9
View File
@@ -0,0 +1,9 @@
> ## 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.
# null
Check the status of the Polymarket Order Book:
[Status Page](https://status-clob.polymarket.com/)
+154
View File
@@ -0,0 +1,154 @@
> ## 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.
# Historical Timeseries Data
> Fetches historical price data for a specified market token.
The CLOB provides detailed price history for each traded token.
**HTTP REQUEST**
`GET /<clob-endpoint>/prices-history`
<Tip>We also have a Interactive Notebook to visualize the data from this endpoint available [here](https://colab.research.google.com/drive/1s4TCOR4K7fRP7EwAH1YmOactMakx24Cs?usp=sharing#scrollTo=mYCJBcfB9Zu4).</Tip>
## OpenAPI
````yaml GET /prices-history
openapi: 3.0.3
info:
title: CLOB (Central Limit Order Book) API
description: >-
API for interacting with the Central Limit Order Book system, providing
orderbook data, prices, midpoints, and spreads
version: 1.0.0
contact:
name: CLOB API Team
license:
name: MIT
servers:
- url: https://clob.polymarket.com/
description: Production server
security: []
tags:
- name: Orderbook
description: Order book related operations
- name: Pricing
description: Price and midpoint operations
- name: Spreads
description: Spread calculation operations
paths:
/prices-history:
get:
tags:
- Pricing
summary: Get price history for a traded token
description: Fetches historical price data for a specified market token
parameters:
- name: market
in: query
required: true
schema:
type: string
description: The CLOB token ID for which to fetch price history
example: '1234567890'
- name: startTs
in: query
required: false
schema:
type: number
description: The start time, a Unix timestamp in UTC
example: 1697875200
- name: endTs
in: query
required: false
schema:
type: number
description: The end time, a Unix timestamp in UTC
example: 1697961600
- name: interval
in: query
required: false
schema:
type: string
enum:
- 1m
- 1w
- 1d
- 6h
- 1h
- max
description: >-
A string representing a duration ending at the current time.
Mutually exclusive with startTs and endTs
example: 1d
- name: fidelity
in: query
required: false
schema:
type: number
description: The resolution of the data, in minutes
example: 60
responses:
'200':
description: A list of timestamp/price pairs
content:
application/json:
schema:
$ref: '#/components/schemas/PriceHistoryResponse'
'400':
description: Bad request
content:
application/json:
schema:
$ref: '#/components/schemas/Error'
'404':
description: Market not found
content:
application/json:
schema:
$ref: '#/components/schemas/Error'
'500':
description: Internal server error
content:
application/json:
schema:
$ref: '#/components/schemas/Error'
components:
schemas:
PriceHistoryResponse:
type: object
required:
- history
properties:
history:
type: array
items:
type: object
required:
- t
- p
properties:
t:
type: number
description: UTC timestamp
example: 1697875200
p:
type: number
description: Price
example: 1800.75
Error:
type: object
required:
- error
properties:
error:
type: string
description: Error message describing what went wrong
example: Invalid token id
````
@@ -0,0 +1,19 @@
> ## 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.
# Trades Overview
## Overview
All historical trades can be fetched via the Polymarket CLOB REST API. A trade is initiated by a "taker" who creates a marketable limit order. This limit order can be matched against one or more resting limit orders on the associated book. A trade can be in various states as described below. Note: in some cases (due to gas limitations) the execution of a "trade" must be broken into multiple transactions which case separate trade entities will be returned. To associate trade entities, there is a bucket\_index field and a match\_time field. Trades that have been broken into multiple trade objects can be reconciled by combining trade objects with the same market\_order\_id, match\_time and incrementing bucket\_index's into a top level "trade" client side.
## Statuses
| Status | Terminal? | Description |
| --------- | --------- | --------------------------------------------------------------------------------------------------------------------------------------------------------- |
| MATCHED | no | trade has been matched and sent to the executor service by the operator, the executor service submits the trade as a transaction to the Exchange contract |
| MINED | no | trade is observed to be mined into the chain, no finality threshold established |
| CONFIRMED | yes | trade has achieved strong probabilistic finality and was successful |
| RETRYING | no | trade transaction has failed (revert or reorg) and is being retried/resubmitted by the operator |
| FAILED | yes | trade has failed and is not being retried |
+96
View File
@@ -0,0 +1,96 @@
> ## 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.
# Get Trades
<Tip> This endpoint requires a L2 Header. </Tip>
Get trades for the authenticated user based on the provided filters.
**HTTP REQUEST**
`GET /<clob-endpoint>/data/trades`
### Request Parameters
| Name | Required | Type | Description |
| ------ | -------- | ------ | --------------------------------------------------------------------------------------------------- |
| id | no | string | id of trade to fetch |
| taker | no | string | address to get trades for where it is included as a taker |
| maker | no | string | address to get trades for where it is included as a maker |
| market | no | string | market for which to get the trades (condition ID) |
| before | no | string | unix timestamp representing the cutoff up to which trades that happened before then can be included |
| after | no | string | unix timestamp representing the cutoff for which trades that happened after can be included |
### Response Format
| Name | Type | Description |
| ---- | -------- | ------------------------------------------- |
| null | Trade\[] | list of trades filtered by query parameters |
A `Trade` object is of the form:
| Name | Type | Description |
| ----------------- | ------------- | ---------------------------------------------------------------------------- |
| id | string | trade id |
| taker\_order\_id | string | hash of taker order (market order) that catalyzed the trade |
| market | string | market id (condition id) |
| asset\_id | string | asset id (token id) of taker order (market order) |
| side | string | buy or sell |
| size | string | size |
| fee\_rate\_bps | string | the fees paid for the taker order expressed in basic points |
| price | string | limit price of taker order |
| status | string | trade status (see above) |
| match\_time | string | time at which the trade was matched |
| last\_update | string | timestamp of last status update |
| outcome | string | human readable outcome of the trade |
| maker\_address | string | funder address of the taker of the trade |
| owner | string | api key of taker of the trade |
| transaction\_hash | string | hash of the transaction where the trade was executed |
| bucket\_index | integer | index of bucket for trade in case trade is executed in multiple transactions |
| maker\_orders | MakerOrder\[] | list of the maker trades the taker trade was filled against |
| type | string | side of the trade: TAKER or MAKER |
A `MakerOrder` object is of the form:
| Name | Type | Description |
| --------------- | ------ | ----------------------------------------------------------- |
| order\_id | string | id of maker order |
| maker\_address | string | maker address of the order |
| owner | string | api key of the owner of the order |
| matched\_amount | string | size of maker order consumed with this trade |
| fee\_rate\_bps | string | the fees paid for the taker order expressed in basic points |
| price | string | price of maker order |
| asset\_id | string | token/asset id |
| outcome | string | human readable outcome of the maker order |
| side | string | the side of the maker order. Can be `buy` or `sell` |
<RequestExample>
```python Python theme={null}
from py_clob_client.clob_types import TradeParams
resp = client.get_trades(
TradeParams(
maker_address=client.get_address(),
market="0xbd31dc8a20211944f6b70f31557f1001557b59905b7738480ca09bd4532f84af",
),
)
print(resp)
print("Done!")
```
```typescript Typescript theme={null}
async function main() {
const trades = await clobClient.getTrades({
market:
"0xbd31dc8a20211944f6b70f31557f1001557b59905b7738480ca09bd4532f84af",
maker_address: await wallet.getAddress(),
});
console.log(`trades: `);
console.log(trades);
}
main();
```
</RequestExample>
@@ -0,0 +1,323 @@
> ## 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.
# Market Channel
Public channel for updates related to market updates (level 2 price data).
**SUBSCRIBE**
`<wss-channel> market`
## book Message
Emitted When:
* First subscribed to a market
* When there is a trade that affects the book
### Structure
| Name | Type | Description |
| ----------- | --------------- | --------------------------------------------------------------------------- |
| event\_type | string | "book" |
| asset\_id | string | asset ID (token ID) |
| market | string | condition ID of market |
| timestamp | string | unix timestamp the current book generation in milliseconds (1/1,000 second) |
| hash | string | hash summary of the orderbook content |
| buys | OrderSummary\[] | list of type (size, price) aggregate book levels for buys |
| sells | OrderSummary\[] | list of type (size, price) aggregate book levels for sells |
Where a `OrderSummary` object is of the form:
| Name | Type | Description |
| ----- | ------ | ---------------------------------- |
| price | string | price of the orderbook level |
| size | string | size available at that price level |
```json Response theme={null}
{
"event_type": "book",
"asset_id": "65818619657568813474341868652308942079804919287380422192892211131408793125422",
"market": "0xbd31dc8a20211944f6b70f31557f1001557b59905b7738480ca09bd4532f84af",
"bids": [
{ "price": ".48", "size": "30" },
{ "price": ".49", "size": "20" },
{ "price": ".50", "size": "15" }
],
"asks": [
{ "price": ".52", "size": "25" },
{ "price": ".53", "size": "60" },
{ "price": ".54", "size": "10" }
],
"timestamp": "123456789000",
"hash": "0x0...."
}
```
## price\_change Message
<div style={{backgroundColor: '#fff3cd', border: '1px solid #ffeaa7', borderRadius: '4px', padding: '12px', marginBottom: '16px'}}>
<strong>⚠️ Breaking Change Notice:</strong> The price\_change message schema will be updated on September 15, 2025 at 11 PM UTC. Please see the [migration guide](/developers/CLOB/websocket/market-channel-migration-guide) for details.
</div>
Emitted When:
* A new order is placed
* An order is cancelled
### Structure
| Name | Type | Description |
| -------------- | -------------- | ------------------------------ |
| event\_type | string | "price\_change" |
| market | string | condition ID of market |
| price\_changes | PriceChange\[] | array of price change objects |
| timestamp | string | unix timestamp in milliseconds |
Where a `PriceChange` object is of the form:
| Name | Type | Description |
| --------- | ------ | ---------------------------------- |
| asset\_id | string | asset ID (token ID) |
| price | string | price level affected |
| size | string | new aggregate size for price level |
| side | string | "BUY" or "SELL" |
| hash | string | hash of the order |
| best\_bid | string | current best bid price |
| best\_ask | string | current best ask price |
```json Response theme={null}
{
"market": "0x5f65177b394277fd294cd75650044e32ba009a95022d88a0c1d565897d72f8f1",
"price_changes": [
{
"asset_id": "71321045679252212594626385532706912750332728571942532289631379312455583992563",
"price": "0.5",
"size": "200",
"side": "BUY",
"hash": "56621a121a47ed9333273e21c83b660cff37ae50",
"best_bid": "0.5",
"best_ask": "1"
},
{
"asset_id": "52114319501245915516055106046884209969926127482827954674443846427813813222426",
"price": "0.5",
"size": "200",
"side": "SELL",
"hash": "1895759e4df7a796bf4f1c5a5950b748306923e2",
"best_bid": "0",
"best_ask": "0.5"
}
],
"timestamp": "1757908892351",
"event_type": "price_change"
}
```
## tick\_size\_change Message
Emitted When:
* The minimum tick size of the market changes. This happens when the book's price reaches the limits: price > 0.96 or price \< 0.04
### Structure
| Name | Type | Description |
| --------------- | ------ | -------------------------- |
| event\_type | string | "price\_change" |
| asset\_id | string | asset ID (token ID) |
| market | string | condition ID of market |
| old\_tick\_size | string | previous minimum tick size |
| new\_tick\_size | string | current minimum tick size |
| side | string | buy/sell |
| timestamp | string | time of event |
```json Response theme={null}
{
"event_type": "tick_size_change",
"asset_id": "65818619657568813474341868652308942079804919287380422192892211131408793125422",\
"market": "0xbd31dc8a20211944f6b70f31557f1001557b59905b7738480ca09bd4532f84af",
"old_tick_size": "0.01",
"new_tick_size": "0.001",
"timestamp": "100000000"
}
```
## last\_trade\_price Message
Emitted When:
* When a maker and taker order is matched creating a trade event.
```json Response theme={null}
{
"asset_id":"114122071509644379678018727908709560226618148003371446110114509806601493071694",
"event_type":"last_trade_price",
"fee_rate_bps":"0",
"market":"0x6a67b9d828d53862160e470329ffea5246f338ecfffdf2cab45211ec578b0347",
"price":"0.456",
"side":"BUY",
"size":"219.217767",
"timestamp":"1750428146322"
}
```
## best\_bid\_ask Message
Emitted When:
* The best bid and ask prices for a market change.
(This message is behind the `custom_feature_enabled` flag)
### Structure
| Name | Type | Description |
| ----------- | ------ | ------------------------------- |
| event\_type | string | "best\_bid\_ask" |
| market | string | condition ID of market |
| asset\_id | string | asset ID (token ID) |
| best\_bid | string | current best bid price |
| best\_ask | string | current best ask price |
| spread | string | spread between best bid and ask |
| timestamp | string | unix timestamp in milliseconds |
### Example
```json Response theme={null}
{
"event_type": "best_bid_ask",
"market": "0x0005c0d312de0be897668695bae9f32b624b4a1ae8b140c49f08447fcc74f442",
"asset_id": "85354956062430465315924116860125388538595433819574542752031640332592237464430",
"best_bid": "0.73",
"best_ask": "0.77",
"spread": "0.04",
"timestamp": "1766789469958"
}
```
## new\_market Message
Emitted When:
* A new market is created.
(This message is behind the `custom_feature_enabled` flag)
### Structure
| Name | Type | Description |
| -------------- | --------- | ------------------------------ |
| id | string | market ID |
| question | string | market question |
| market | string | condition ID of market |
| slug | string | market slug |
| description | string | market description |
| assets\_ids | string\[] | list of asset IDs |
| outcomes | string\[] | list of outcomes |
| event\_message | object | event message object |
| timestamp | string | unix timestamp in milliseconds |
| event\_type | string | "new\_market" |
Where a `EventMessage` object is of the form:
| Name | Type | Description |
| ----------- | ------ | ------------------------- |
| id | string | event message ID |
| ticker | string | event message ticker |
| slug | string | event message slug |
| title | string | event message title |
| description | string | event message description |
### Example
```json Response theme={null}
{
"id": "1031769",
"question": "Will NVIDIA (NVDA) close above $240 end of January?",
"market": "0x311d0c4b6671ab54af4970c06fcf58662516f5168997bdda209ec3db5aa6b0c1",
"slug": "nvda-above-240-on-january-30-2026",
"description": "This market will resolve to \"Yes\" if the official closing price for NVIDIA (NVDA) on the final trading day of January 2026 is higher than the listed price. Otherwise, this market will resolve to \"No\".\n\nIf the final trading day of the month is shortened (for example, due to a market-holiday schedule), the official closing price published for that shortened session will still be used for resolution.\n\nIf no official closing price is published for that session (for example, due to a trading halt into the close, system issue, or other disruption), the market will use the last valid on-exchange trade price of the regular session as the effective closing price.\n\nThe resolution source for this market is Yahoo Finance — specifically, the NVIDIA (NVDA) \"Close\" prices available at https://finance.yahoo.com/quote/NVDA/history, published under \"Historical Prices.\"\n\nIn the event of a stock split, reverse stock split, or similar corporate action affecting the listed company during the listed time frame, this market will resolve based on split-adjusted prices as displayed on Yahoo Finance.",
"assets_ids": [
"76043073756653678226373981964075571318267289248134717369284518995922789326425",
"31690934263385727664202099278545688007799199447969475608906331829650099442770"
],
"outcomes": [
"Yes",
"No"
],
"event_message": {
"id": "125819",
"ticker": "nvda-above-in-january-2026",
"slug": "nvda-above-in-january-2026",
"title": "Will NVIDIA (NVDA) close above ___ end of January?",
"description": "This market will resolve to \"Yes\" if the official closing price for NVIDIA (NVDA) on the final trading day of January 2026 is higher than the listed price. Otherwise, this market will resolve to \"No\".\n\nIf the final trading day of the month is shortened (for example, due to a market-holiday schedule), the official closing price published for that shortened session will still be used for resolution.\n\nIf no official closing price is published for that session (for example, due to a trading halt into the close, system issue, or other disruption), the market will use the last valid on-exchange trade price of the regular session as the effective closing price.\n\nThe resolution source for this market is Yahoo Finance — specifically, the NVIDIA (NVDA) \"Close\" prices available at https://finance.yahoo.com/quote/NVDA/history, published under \"Historical Prices.\"\n\nIn the event of a stock split, reverse stock split, or similar corporate action affecting the listed company during the listed time frame, this market will resolve based on split-adjusted prices as displayed on Yahoo Finance."
},
"timestamp": "1766790415550",
"event_type": "new_market"
}
```
## market\_resolved Message
Emitted When:
* A market is resolved.
(This message is behind the `custom_feature_enabled` flag)
### Structure
| Name | Type | Description |
| ------------------ | --------- | ------------------------------ |
| id | string | market ID |
| question | string | market question |
| market | string | condition ID of market |
| slug | string | market slug |
| description | string | market description |
| assets\_ids | string\[] | list of asset IDs |
| outcomes | string\[] | list of outcomes |
| winning\_asset\_id | string | winning asset ID |
| winning\_outcome | string | winning outcome |
| event\_message | object | event message object |
| timestamp | string | unix timestamp in milliseconds |
| event\_type | string | "market\_resolved" |
Where a `EventMessage` object is of the form:
| Name | Type | Description |
| ----------- | ------ | ------------------------- |
| id | string | event message ID |
| ticker | string | event message ticker |
| slug | string | event message slug |
| title | string | event message title |
| description | string | event message description |
### Example
```json Response theme={null}
{
"id": "1031769",
"question": "Will NVIDIA (NVDA) close above $240 end of January?",
"market": "0x311d0c4b6671ab54af4970c06fcf58662516f5168997bdda209ec3db5aa6b0c1",
"slug": "nvda-above-240-on-january-30-2026",
"description": "This market will resolve to \"Yes\" if the official closing price for NVIDIA (NVDA) on the final trading day of January 2026 is higher than the listed price. Otherwise, this market will resolve to \"No\".\n\nIf the final trading day of the month is shortened (for example, due to a market-holiday schedule), the official closing price published for that shortened session will still be used for resolution.\n\nIf no official closing price is published for that session (for example, due to a trading halt into the close, system issue, or other disruption), the market will use the last valid on-exchange trade price of the regular session as the effective closing price.\n\nThe resolution source for this market is Yahoo Finance — specifically, the NVIDIA (NVDA) \"Close\" prices available at https://finance.yahoo.com/quote/NVDA/history, published under \"Historical Prices.\"\n\nIn the event of a stock split, reverse stock split, or similar corporate action affecting the listed company during the listed time frame, this market will resolve based on split-adjusted prices as displayed on Yahoo Finance.",
"assets_ids": [
"76043073756653678226373981964075571318267289248134717369284518995922789326425",
"31690934263385727664202099278545688007799199447969475608906331829650099442770"
],
"winning_asset_id": "76043073756653678226373981964075571318267289248134717369284518995922789326425",
"winning_outcome": "Yes",
"event_message": {
"id": "125819",
"ticker": "nvda-above-in-january-2026",
"slug": "nvda-above-in-january-2026",
"title": "Will NVIDIA (NVDA) close above ___ end of January?",
"description": "This market will resolve to \"Yes\" if the official closing price for NVIDIA (NVDA) on the final trading day of January 2026 is higher than the listed price. Otherwise, this market will resolve to \"No\".\n\nIf the final trading day of the month is shortened (for example, due to a market-holiday schedule), the official closing price published for that shortened session will still be used for resolution.\n\nIf no official closing price is published for that session (for example, due to a trading halt into the close, system issue, or other disruption), the market will use the last valid on-exchange trade price of the regular session as the effective closing price.\n\nThe resolution source for this market is Yahoo Finance — specifically, the NVIDIA (NVDA) \"Close\" prices available at https://finance.yahoo.com/quote/NVDA/history, published under \"Historical Prices.\"\n\nIn the event of a stock split, reverse stock split, or similar corporate action affecting the listed company during the listed time frame, this market will resolve based on split-adjusted prices as displayed on Yahoo Finance."
},
"timestamp": "1766790415550",
"event_type": "new_market"
}
```
@@ -0,0 +1,129 @@
> ## 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.
# User Channel
Authenticated channel for updates related to user activities (orders, trades), filtered for authenticated user by apikey.
**SUBSCRIBE**
`<wss-channel> user`
## Trade Message
Emitted when:
* when a market order is matched ("MATCHED")
* when a limit order for the user is included in a trade ("MATCHED")
* subsequent status changes for trade ("MINED", "CONFIRMED", "RETRYING", "FAILED")
### Structure
| Name | Type | Description |
| ---------------- | ------------- | ------------------------------------------- |
| asset\_id | string | asset id (token ID) of order (market order) |
| event\_type | string | "trade" |
| id | string | trade id |
| last\_update | string | time of last update to trade |
| maker\_orders | MakerOrder\[] | array of maker order details |
| market | string | market identifier (condition ID) |
| matchtime | string | time trade was matched |
| outcome | string | outcome |
| owner | string | api key of event owner |
| price | string | price |
| side | string | BUY/SELL |
| size | string | size |
| status | string | trade status |
| taker\_order\_id | string | id of taker order |
| timestamp | string | time of event |
| trade\_owner | string | api key of trade owner |
| type | string | "TRADE" |
Where a `MakerOrder` object is of the form:
| Name | Type | Description |
| --------------- | ------ | -------------------------------------- |
| asset\_id | string | asset of the maker order |
| matched\_amount | string | amount of maker order matched in trade |
| order\_id | string | maker order ID |
| outcome | string | outcome |
| owner | string | owner of maker order |
| price | string | price of maker order |
```json Response theme={null}
{
"asset_id": "52114319501245915516055106046884209969926127482827954674443846427813813222426",
"event_type": "trade",
"id": "28c4d2eb-bbea-40e7-a9f0-b2fdb56b2c2e",
"last_update": "1672290701",
"maker_orders": [
{
"asset_id": "52114319501245915516055106046884209969926127482827954674443846427813813222426",
"matched_amount": "10",
"order_id": "0xff354cd7ca7539dfa9c28d90943ab5779a4eac34b9b37a757d7b32bdfb11790b",
"outcome": "YES",
"owner": "9180014b-33c8-9240-a14b-bdca11c0a465",
"price": "0.57"
}
],
"market": "0xbd31dc8a20211944f6b70f31557f1001557b59905b7738480ca09bd4532f84af",
"matchtime": "1672290701",
"outcome": "YES",
"owner": "9180014b-33c8-9240-a14b-bdca11c0a465",
"price": "0.57",
"side": "BUY",
"size": "10",
"status": "MATCHED",
"taker_order_id": "0x06bc63e346ed4ceddce9efd6b3af37c8f8f440c92fe7da6b2d0f9e4ccbc50c42",
"timestamp": "1672290701",
"trade_owner": "9180014b-33c8-9240-a14b-bdca11c0a465",
"type": "TRADE"
}
```
## Order Message
Emitted when:
* When an order is placed (PLACEMENT)
* When an order is updated (some of it is matched) (UPDATE)
* When an order is canceled (CANCELLATION)
### Structure
| Name | Type | Description |
| ----------------- | --------- | ------------------------------------------------------------------- |
| asset\_id | string | asset ID (token ID) of order |
| associate\_trades | string\[] | array of ids referencing trades that the order has been included in |
| event\_type | string | "order" |
| id | string | order id |
| market | string | condition ID of market |
| order\_owner | string | owner of order |
| original\_size | string | original order size |
| outcome | string | outcome |
| owner | string | owner of orders |
| price | string | price of order |
| side | string | BUY/SELL |
| size\_matched | string | size of order that has been matched |
| timestamp | string | time of event |
| type | string | PLACEMENT/UPDATE/CANCELLATION |
```json Response theme={null}
{
"asset_id": "52114319501245915516055106046884209969926127482827954674443846427813813222426",
"associate_trades": null,
"event_type": "order",
"id": "0xff354cd7ca7539dfa9c28d90943ab5779a4eac34b9b37a757d7b32bdfb11790b",
"market": "0xbd31dc8a20211944f6b70f31557f1001557b59905b7738480ca09bd4532f84af",
"order_owner": "9180014b-33c8-9240-a14b-bdca11c0a465",
"original_size": "10",
"outcome": "YES",
"owner": "9180014b-33c8-9240-a14b-bdca11c0a465",
"price": "0.57",
"side": "SELL",
"size_matched": "0",
"timestamp": "1672290687",
"type": "PLACEMENT"
}
```
@@ -0,0 +1,13 @@
> ## 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.
# WSS Authentication
<Tip> Only connections to `user` channel require authentication. </Tip>
| Field | Optional | Description |
| ---------- | -------- | ------------------------------------- |
| apikey | yes | Polygon account's CLOB api key |
| secret | yes | Polygon account's CLOB api secret |
| passphrase | yes | Polygon account's CLOB api passphrase |
@@ -0,0 +1,36 @@
> ## 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.
# WSS Overview
> Overview and general information about the Polymarket Websocket
## Overview
The Polymarket CLOB API provides websocket (wss) channels through which clients can get pushed updates. These endpoints allow clients to maintain almost real-time views of their orders, their trades and markets in general. There are two available channels `user` and `market`.
## Subscription
To subscribe send a message including the following authentication and intent information upon opening the connection.
| Field | Type | Description |
| ------------------------ | --------- | --------------------------------------------------------------------------- |
| auth | Auth | see next page for auth information |
| markets | string\[] | array of markets (condition IDs) to receive events for (for `user` channel) |
| assets\_ids | string\[] | array of asset ids (token IDs) to receive events for (for `market` channel) |
| type | string | id of channel to subscribe to (USER or MARKET) |
| custom\_feature\_enabled | bool | enabling / disabling custom features |
Where the `auth` field is of type `Auth` which has the form described in the WSS Authentication section below.
### Subscribe to more assets
Once connected, the client can subscribe and unsubscribe to `asset_ids` by sending the following message:
| Field | Type | Description |
| ------------------------ | --------- | ------------------------------------------------------------------------------ |
| assets\_ids | string\[] | array of asset ids (token IDs) to receive events for (for `market` channel) |
| markets | string\[] | array of market ids (condition IDs) to receive events for (for `user` channel) |
| operation | string | "subscribe" or "unsubscribe" |
| custom\_feature\_enabled | bool | enabling / disabling custom features |
@@ -0,0 +1,28 @@
> ## 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.
# Deployment and Additional Information
## Deployment
The CTF contract is deployed (and verified) at the following addresses:
| Network | Deployed Address |
| --------------- | ------------------------------------------------------------------------------------------------------------------------ |
| Polygon Mainnet | [0x4D97DCd97eC945f40cF65F87097ACe5EA0476045](https://polygonscan.com/address/0x4D97DCd97eC945f40cF65F87097ACe5EA0476045) |
| Polygon Mainnet | [0x4bFb41d5B3570DeFd03C39a9A4D8dE6Bd8B8982E](https://polygonscan.com/address/0x4bFb41d5B3570DeFd03C39a9A4D8dE6Bd8B8982E) |
Polymarket provides code samples in both Python and TypeScript for interacting
with our smart chain contracts. You will need an RPC endpoint to access the
blockchain, and you'll be responsible for paying gas fees when executing these
RPC/function calls. Please ensure you're using the correct example for your wallet
type (Safe Wallet vs Proxy Wallet) when implementing.
## Resources
* [On-Chain Code Samples](https://github.com/Polymarket/examples/tree/main/examples)
* [Polygon RPC List](https://chainlist.org/chain/137)
* [CTF Source Code](https://github.com/gnosis/conditional-tokens-contracts)
* [Audits](https://github.com/gnosis/conditional-tokens-contracts/tree/master/docs/audit)
* [Gist For positionId Calculation](https://gist.github.com/L-Kov/950bce141a9d1aa1ed3b1cfce6d30217)
+13
View File
@@ -0,0 +1,13 @@
> ## 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.
# Merging Tokens
In addition to splitting collateral for a full set, the inverse can also happen; a full set can be "merged" for collateral. This operation can again happen at any time after a condition has been prepared on the CTF contract. One unit of each position in a full set is burned in return for 1 collateral unit. This operation happens via the `mergePositions()` function on the CTF contract with the following parameters:
* `collateralToken`: IERC20 - The address of the positions' backing collateral token.
* `parentCollectionId`: bytes32 - The ID of the outcome collections common to the position being merged and the merge target positions. Null in Polymarket case.
* `conditionId`: bytes32 - The ID of the condition to merge on.
* `partition`: uint\[] - An array of disjoint index sets representing a nontrivial partition of the outcome slots of the given condition. E.G. A|B and C but not A|B and B|C (is not disjoint). Each element's a number which, together with the condition, represents the outcome collection. E.G. 0b110 is A|B, 0b010 is B, etc. In the Polymarket case 1|2.
* `amount` - The number of full sets to merge. Also the amount of collateral to receive.
+34
View File
@@ -0,0 +1,34 @@
> ## 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.
# Overview
All outcomes on Polymarket are tokenized on the Polygon network. Specifically, Polymarket outcomes shares are binary outcomes (ie "YES" and "NO") using Gnosis' Conditional Token Framework (CTF). They are distinct ERC1155 tokens related to a parent condition and backed by the same collateral. More technically, the binary outcome tokens are referred to as "positionIds" in Gnosis's documentation. "PositionIds" are derived from a collateral token and distinct "collectionIds". "CollectionIds" are derived from a "parentCollectionId", (always bytes32(0) in our case) a "conditionId", and a unique "indexSet".
The "indexSet" is a 256 bit array denoting which outcome slots are in an outcome collection; it MUST be a nonempty proper subset of a condition's outcome slots. In the binary case, which we are interested in, there are two "indexSets", one for the first outcome and one for the second. The first outcome's "indexSet" is 0b01 = 1 and the second's is 0b10 = 2. The parent "conditionId" (shared by both "collectionIds" and therefore "positionIds") is derived from a "questionId" (a hash of the UMA ancillary data), an "oracle" (the UMA adapter V2), and an "outcomeSlotCount" (always 2 in the binary case). The steps for calculating the ERC1155 token ids (positionIds) is as follows:
1. Get the conditionId
1. Function:
1. `getConditionId(oracle, questionId, outcomeSlotCount)`
2. Inputs:
1. `oracle`: address - UMA adapter V2
2. `questionId`: bytes32 - hash of the UMA ancillary data
3. `outcomeSlotCount`: uint - 2 for binary markets
2. Get the two collectionIds
1. Function:
1. `getCollectionId(parentCollectionId, conditionId, indexSet)`
2. Inputs:
1. `parentCollectionId`: bytes32 - bytes32(0)
2. `conditionId`: bytes32 - the conditionId derived from (1)
3. `indexSet`: uint - 1 (0b01) for the first and 2 (0b10) for the second.
3. Get the two positionIds
1. Function:
1. `getPositionId(collateralToken, collectionId)`
2. Inputs:
1. `collateralToken`: IERC20 - address of ERC20 token collateral (USDC)
2. `collectionId`: bytes32 - the two collectionIds derived from (3)
Leveraging the relations above, specifically "conditionIds" -> "positionIds" the Gnosis CTF contract allows for "splitting" and "merging" full outcome sets. We explore these actions and provide code examples below.
+12
View File
@@ -0,0 +1,12 @@
> ## 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.
# Reedeeming Tokens
Once a condition has had it's payouts reported (ie by the UMACTFAdapter calling `reportPayouts` on the CTF contract), users with shares in the winning outcome can redeem them for the underlying collateral. Specifically, users can call the `redeemPositions` function on the CTF contract which will burn all valuable conditional tokens in return for collateral according to the reported payout vector. This function has the following parameters:
* `collateralToken`: IERC20 - The address of the positions' backing collateral token.
* `parentCollectionId`: bytes32 - The ID of the outcome collections common to the position being redeemed. Null in Polymarket case.
* `indexSets`: uint\[] - The ID of the condition to redeem.
* `indexSets`: uint\[] - An array of disjoint index sets representing a nontrivial partition of the outcome slots of the given condition. E.G. A|B and C but not A|B and B|C (is not disjoint). Each element's a number which, together with the condition, represents the outcome collection. E.G. 0b110 is A|B, 0b010 is B, etc. In the Polymarket case 1|2.
+13
View File
@@ -0,0 +1,13 @@
> ## 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.
# Splitting USDC
At any time, after a condition has been prepared on the CTF contract (via `prepareCondition`), it is possible to "split" collateral into a full (position) set. In other words, one unit USDC can be split into 1 YES unit and 1 NO unit. If splitting from the collateral, the CTF contract will attempt to transfer `amount` collateral from the message sender to itself. If successful, `amount` stake will be minted in the split target positions. If any of the transfers, mints, or burns fail, the transaction will revert. The transaction will also revert if the given partition is trivial, invalid, or refers to more slots than the condition is prepared with. This operation happens via the `splitPosition()` function on the CTF contract with the following parameters:
* `collateralToken`: IERC20 - The address of the positions' backing collateral token.
* `parentCollectionId`: bytes32 - The ID of the outcome collections common to the position being split and the split target positions. Null in Polymarket case.
* `conditionId`: bytes32 - The ID of the condition to split on.
* `partition`: uint\[] - An array of disjoint index sets representing a nontrivial partition of the outcome slots of the given condition. E.G. A|B and C but not A|B and B|C (is not disjoint). Each element's a number which, together with the condition, represents the outcome collection. E.G. 0b110 is A|B, 0b010 is B, etc. In the Polymarket case 1|2.
* `amount` - The amount of collateral or stake to split. Also the number of full sets to receive.
+202
View File
@@ -0,0 +1,202 @@
> ## 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.
# RTDS Comments
<Card title="TypeScript client" icon="github" href="https://github.com/Polymarket/real-time-data-client">
Official RTDS TypeScript client (`real-time-data-client`).
</Card>
## Overview
The comments subscription provides real-time updates for comment-related events on the Polymarket platform. This includes new comments being created, as well as other comment interactions like reactions and replies.
## Subscription Details
* **Topic**: `comments`
* **Type**: `comment_created` (and potentially other comment event types like `reaction_created`)
* **Authentication**: May require Gamma authentication for user-specific data
* **Filters**: Optional (can filter by specific comment IDs, users, or events)
## Subscription Message
```json theme={null}
{
"action": "subscribe",
"subscriptions": [
{
"topic": "comments",
"type": "comment_created"
}
]
}
```
## Message Format
When subscribed to comments, you'll receive messages with the following structure:
```json theme={null}
{
"topic": "comments",
"type": "comment_created",
"timestamp": 1753454975808,
"payload": {
"body": "do you know what the term encircle means? it means to surround from all sides, Russia has present on only 1 side, that's the opposite of an encirclement",
"createdAt": "2025-07-25T14:49:35.801298Z",
"id": "1763355",
"parentCommentID": "1763325",
"parentEntityID": 18396,
"parentEntityType": "Event",
"profile": {
"baseAddress": "0xce533188d53a16ed580fd5121dedf166d3482677",
"displayUsernamePublic": true,
"name": "salted.caramel",
"proxyWallet": "0x4ca749dcfa93c87e5ee23e2d21ff4422c7a4c1ee",
"pseudonym": "Adored-Disparity"
},
"reactionCount": 0,
"replyAddress": "0x0bda5d16f76cd1d3485bcc7a44bc6fa7db004cdd",
"reportCount": 0,
"userAddress": "0xce533188d53a16ed580fd5121dedf166d3482677"
}
}
```
## Message Types
### comment\_created
Triggered when a user creates a new comment on an event or in reply to another comment.
### comment\_removed
Triggered when a comment is removed or deleted.
### reaction\_created
Triggered when a user adds a reaction to an existing comment.
### reaction\_removed
Triggered when a reaction is removed from a comment.
## Payload Fields
| Field | Type | Description |
| ------------------ | ------ | ------------------------------------------------------------------------- |
| `body` | string | The text content of the comment |
| `createdAt` | string | ISO 8601 timestamp when the comment was created |
| `id` | string | Unique identifier for this comment |
| `parentCommentID` | string | ID of the parent comment if this is a reply (null for top-level comments) |
| `parentEntityID` | number | ID of the parent entity (event, market, etc.) |
| `parentEntityType` | string | Type of parent entity (e.g., "Event", "Market") |
| `profile` | object | Profile information of the user who created the comment |
| `reactionCount` | number | Current number of reactions on this comment |
| `replyAddress` | string | Polygon address for replies (may be different from userAddress) |
| `reportCount` | number | Current number of reports on this comment |
| `userAddress` | string | Polygon address of the user who created the comment |
### Profile Object Fields
| Field | Type | Description |
| ----------------------- | ------- | ------------------------------------------------- |
| `baseAddress` | string | User profile address |
| `displayUsernamePublic` | boolean | Whether the username should be displayed publicly |
| `name` | string | User's display name |
| `proxyWallet` | string | Proxy wallet address used for transactions |
| `pseudonym` | string | Generated pseudonym for the user |
## Parent Entity Types
The following parent entity types are supported:
* `Event` - Comments on prediction events
* `Market` - Comments on specific markets
* Additional entity types may be available
## Example Messages
### New Comment Created
```json theme={null}
{
"topic": "comments",
"type": "comment_created",
"timestamp": 1753454975808,
"payload": {
"body": "do you know what the term encircle means? it means to surround from all sides, Russia has present on only 1 side, that's the opposite of an encirclement",
"createdAt": "2025-07-25T14:49:35.801298Z",
"id": "1763355",
"parentCommentID": "1763325",
"parentEntityID": 18396,
"parentEntityType": "Event",
"profile": {
"baseAddress": "0xce533188d53a16ed580fd5121dedf166d3482677",
"displayUsernamePublic": true,
"name": "salted.caramel",
"proxyWallet": "0x4ca749dcfa93c87e5ee23e2d21ff4422c7a4c1ee",
"pseudonym": "Adored-Disparity"
},
"reactionCount": 0,
"replyAddress": "0x0bda5d16f76cd1d3485bcc7a44bc6fa7db004cdd",
"reportCount": 0,
"userAddress": "0xce533188d53a16ed580fd5121dedf166d3482677"
}
}
```
### Reply to Existing Comment
```json theme={null}
{
"topic": "comments",
"type": "comment_created",
"timestamp": 1753454985123,
"payload": {
"body": "That's a good point about the definition of encirclement.",
"createdAt": "2025-07-25T14:49:45.120000Z",
"id": "1763356",
"parentCommentID": "1763355",
"parentEntityID": 18396,
"parentEntityType": "Event",
"profile": {
"baseAddress": "0x1234567890abcdef1234567890abcdef12345678",
"displayUsernamePublic": true,
"name": "trader",
"proxyWallet": "0x9876543210fedcba9876543210fedcba98765432",
"pseudonym": "Bright-Analysis"
},
"reactionCount": 0,
"replyAddress": "0x0bda5d16f76cd1d3485bcc7a44bc6fa7db004cdd",
"reportCount": 0,
"userAddress": "0x1234567890abcdef1234567890abcdef12345678"
}
}
```
## Comment Hierarchy
Comments support nested threading:
* **Top-level comments**: `parentCommentID` is null or empty
* **Reply comments**: `parentCommentID` contains the ID of the parent comment
* All comments are associated with a `parentEntityID` and `parentEntityType`
## Use Cases
* Real-time comment feed displays
* Discussion thread monitoring
* Community sentiment analysis
## Content
* Comments include `reactionCount` and `reportCount`
* Comment body contains the full text content
## Notes
* The `createdAt` timestamp uses ISO 8601 format with timezone information
* The outer `timestamp` field represents when the WebSocket message was sent
* User profiles include both primary addresses and proxy wallet addresses
+244
View File
@@ -0,0 +1,244 @@
> ## 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.
# RTDS Crypto Prices
<Card title="TypeScript client" icon="github" href="https://github.com/Polymarket/real-time-data-client">
Official RTDS TypeScript client (`real-time-data-client`).
</Card>
## Overview
The crypto prices subscription provides real-time updates for cryptocurrency price data from two different sources:
* **Binance Source** (`crypto_prices`): Real-time price data from Binance exchange
* **Chainlink Source** (`crypto_prices_chainlink`): Price data from Chainlink oracle networks
Both streams deliver current market prices for various cryptocurrency trading pairs, but use different symbol formats and subscription structures.
## Binance Source (`crypto_prices`)
### Subscription Details
* **Topic**: `crypto_prices`
* **Type**: `update`
* **Authentication**: Not required
* **Filters**: Optional (specific symbols can be filtered)
* **Symbol Format**: Lowercase concatenated pairs (e.g., `solusdt`, `btcusdt`)
### Subscription Message
```json theme={null}
{
"action": "subscribe",
"subscriptions": [
{
"topic": "crypto_prices",
"type": "update"
}
]
}
```
### With Symbol Filter
To subscribe to specific cryptocurrency symbols, include a filters parameter:
```json theme={null}
{
"action": "subscribe",
"subscriptions": [
{
"topic": "crypto_prices",
"type": "update",
"filters": "solusdt,btcusdt,ethusdt"
}
]
}
```
## Chainlink Source (`crypto_prices_chainlink`)
<Tip>
**Trading 15m Crypto Markets?** Get a sponsored Chainlink API key with onboarding support from Chainlink. Fill out [this form](https://pm-ds-request.streams.chain.link/).
</Tip>
### Subscription Details
* **Topic**: `crypto_prices_chainlink`
* **Type**: `*` (all types)
* **Authentication**: Not required
* **Filters**: Optional (JSON object with symbol specification)
* **Symbol Format**: Slash-separated pairs (e.g., `eth/usd`, `btc/usd`)
### Subscription Message
```json theme={null}
{
"action": "subscribe",
"subscriptions": [
{
"topic": "crypto_prices_chainlink",
"type": "*",
"filters": ""
}
]
}
```
### With Symbol Filter
To subscribe to specific cryptocurrency symbols, include a JSON filters parameter:
```json theme={null}
{
"action": "subscribe",
"subscriptions": [
{
"topic": "crypto_prices_chainlink",
"type": "*",
"filters": "{\"symbol\":\"eth/usd\"}"
}
]
}
```
## Message Format
### Binance Source Message Format
When subscribed to Binance crypto prices (`crypto_prices`), you'll receive messages with the following structure:
```json theme={null}
{
"topic": "crypto_prices",
"type": "update",
"timestamp": 1753314064237,
"payload": {
"symbol": "solusdt",
"timestamp": 1753314064213,
"value": 189.55
}
}
```
### Chainlink Source Message Format
When subscribed to Chainlink crypto prices (`crypto_prices_chainlink`), you'll receive messages with the following structure:
```json theme={null}
{
"topic": "crypto_prices_chainlink",
"type": "update",
"timestamp": 1753314064237,
"payload": {
"symbol": "eth/usd",
"timestamp": 1753314064213,
"value": 3456.78
}
}
```
## Payload Fields
| Field | Type | Description |
| ----------- | ------ | ---------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `symbol` | string | Trading pair symbol<br />**Binance**: lowercase concatenated (e.g., "solusdt", "btcusdt")<br />**Chainlink**: slash-separated (e.g., "eth/usd", "btc/usd") |
| `timestamp` | number | Price timestamp in Unix milliseconds |
| `value` | number | Current price value in the quote currency |
## Example Messages
### Binance Source Examples
#### Solana Price Update (Binance)
```json theme={null}
{
"topic": "crypto_prices",
"type": "update",
"timestamp": 1753314064237,
"payload": {
"symbol": "solusdt",
"timestamp": 1753314064213,
"value": 189.55
}
}
```
#### Bitcoin Price Update (Binance)
```json theme={null}
{
"topic": "crypto_prices",
"type": "update",
"timestamp": 1753314088421,
"payload": {
"symbol": "btcusdt",
"timestamp": 1753314088395,
"value": 67234.50
}
}
```
### Chainlink Source Examples
#### Ethereum Price Update (Chainlink)
```json theme={null}
{
"topic": "crypto_prices_chainlink",
"type": "update",
"timestamp": 1753314064237,
"payload": {
"symbol": "eth/usd",
"timestamp": 1753314064213,
"value": 3456.78
}
}
```
#### Bitcoin Price Update (Chainlink)
```json theme={null}
{
"topic": "crypto_prices_chainlink",
"type": "update",
"timestamp": 1753314088421,
"payload": {
"symbol": "btc/usd",
"timestamp": 1753314088395,
"value": 67234.50
}
}
```
## Supported Symbols
### Binance Source Symbols
The Binance source supports various cryptocurrency trading pairs using lowercase concatenated format:
* `btcusdt` - Bitcoin to USDT
* `ethusdt` - Ethereum to USDT
* `solusdt` - Solana to USDT
* `xrpusdt` - XRP to USDT
### Chainlink Source Symbols
The Chainlink source supports cryptocurrency trading pairs using slash-separated format:
* `btc/usd` - Bitcoin to USD
* `eth/usd` - Ethereum to USD
* `sol/usd` - Solana to USD
* `xrp/usd` - XRP to USD
## Notes
### General
* Price updates are sent as market prices change
* The timestamp in the payload represents when the price was recorded
* The outer timestamp represents when the message was sent via WebSocket
* No authentication is required for crypto price data
+91
View File
@@ -0,0 +1,91 @@
> ## 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.
# Real Time Data Socket
## Overview
The Polymarket Real-Time Data Socket (RTDS) is a WebSocket-based streaming service that provides real-time updates for **comments** and **crypto prices**.
<Card title="TypeScript client" icon="github" href="https://github.com/Polymarket/real-time-data-client">
Official RTDS TypeScript client (`real-time-data-client`).
</Card>
### Connection Details
* **WebSocket URL**: `wss://ws-live-data.polymarket.com`
* **Protocol**: WebSocket
* **Data Format**: JSON
### Authentication
Some user-specific streams may require `gamma_auth`:
* `address`: User wallet address
### Connection Management
The WebSocket connection supports:
* **Dynamic Subscriptions**: Without disconnecting from the socket users can add, remove and modify topics and filters they are subscribed to.
* **Ping/Pong**: You should send PING messages (every 5 seconds ideally) to maintain connection
## Available Subscription Types
<Note>Only the subscription types documented below are supported.</Note>
The RTDS currently supports the following subscription types:
1. **[Crypto Prices](/developers/RTDS/RTDS-crypto-prices)** - Real-time cryptocurrency price updates
2. **[Comments](/developers/RTDS/RTDS-comments)** - Comment-related events including reactions
## Message Structure
All messages received from the WebSocket follow this structure:
```json theme={null}
{
"topic": "string",
"type": "string",
"timestamp": "number",
"payload": "object"
}
```
* `topic`: The subscription topic (e.g., "crypto\_prices", "comments")
* `type`: The message type/event (e.g., "update", "reaction\_created")
* `timestamp`: Unix timestamp in milliseconds
* `payload`: Event-specific data object
## Subscription Management
### Subscribe to Topics
To subscribe to data streams, send a JSON message with this structure:
```json theme={null}
{
"action": "subscribe",
"subscriptions": [
{
"topic": "topic_name",
"type": "message_type",
"filters": "optional_filter_string",
"gamma_auth": {
"address": "wallet_address"
}
}
]
}
```
### Unsubscribe from Topics
To unsubscribe from data streams, send a similar message with `"action": "unsubscribe"`.
## Error Handling
* Connection errors will trigger automatic reconnection attempts
* Invalid subscription messages may result in connection closure
* Authentication failures will prevent successful subscription to protected topics
@@ -0,0 +1,70 @@
> ## 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.
# Blockchain Data Resources
> Access Polymarket on-chain activity for data & analytics
Polymarket data that lands on the blockchain, such as trades, balances, positions, and redeems, is available through various on-chain analytics platforms and blockchain data providers. Polymarket also provides its own APIs and WebSockets. See the [API Endpoints reference](/quickstart/reference/endpoints) for more information.
The purpose of this page is to serve as a public good for Polymarket builders, researches, and analysts alike.
***
## Data
### Goldsky
[Goldsky](https://docs.goldsky.com/chains/polymarket) provides real-time streaming pipelines for Polymarket on-chain activity (i.e. trades, balances, positions, etc...) into your own database/data warehouse.
Goldsky also partnered with [ClickHouse](https://clickhouse.com) to create [CryptoHouse](https://crypto.clickhouse.com), where you can query Polymarket on-chain data using SQL.
### Dune
[Dune](https://dune.com) is a blockchain analytics platform that has Polymarket on-chain activity (i.e. trades, balances, positions, etc...). Query Polymarket data using SQL, create custom dashboards, and more.
Here are a few simple queries to get started:
| Query | Description | Link |
| ------------- | --------------------------------------------- | --------------------------------------------------- |
| Volume | Notional Volume and Maker & Taker USDC Volume | [View Dune Query](https://dune.com/queries/6545441) |
| TVL | USDC locked in Polymarket smart contracts | [View Dune Query](https://dune.com/queries/6588784) |
| Open Interest | Estimated market open interest, and over time | [View Dune Query](https://dune.com/queries/6555478) |
### Allium
[Allium](https://docs.allium.so/historical-data/predictions) is a blockchain analytics platform that has Polymarket on-chain activity (i.e. trades, balances, positions, etc...). Query Polymarket data using SQL, create custom dashboards, and more.
\--
## Dashboards
Third-party blockchain analytics platforms that aggregate and visualize Polymarket data:
<CardGroup cols={4}>
<Card title="Blockworks" img="https://pbs.twimg.com/profile_images/1651677302634483712/7s2FxV2K_400x400.jpg" href="https://blockworks.com/analytics/polymarket" />
<Card title="Artemis" img="https://pbs.twimg.com/profile_images/1896982195723546624/2XeO9mPb_400x400.png" href="https://app.artemisanalytics.com/asset/polymarket?from=assets" />
<Card title="Dune" img="https://pbs.twimg.com/profile_images/1986458079248986112/qq80s3hx_400x400.jpg" href="https://dune.com/discover/content/popular?q=polymarket&resource-type=dashboards" />
<Card title="DeFiLlama" img="https://pbs.twimg.com/profile_images/1915756547705036800/rAeLzZqs_400x400.jpg" href="https://defillama.com/protocol/polymarket" />
<Card title="The Block" img="https://pbs.twimg.com/profile_images/1944749695525425152/9babG7Df_400x400.jpg" href="https://www.theblock.co/data/decentralized-finance/prediction-markets-and-betting" />
<Card title="Token Terminal" img="https://pbs.twimg.com/profile_images/1594678659222306817/SMum_RcQ_400x400.jpg" href="https://tokenterminal.com/explorer/projects/polymarket" />
<Card title="Allium" img="https://pbs.twimg.com/profile_images/1778926940407132160/UEwR3lHt_400x400.jpg" href="https://predictions.allium.so" />
</CardGroup>
### Community Dashboards
Community-created Dune dashboards of Polymarket on-chain analytics:
| Dashboard | Created By | Link |
| ------------------------------------------------- | ----------------------------------------------- | ---------------------------------------------------------------------------- |
| Polymarket Overview | [@datadashboards](https://x.com/datadashboards) | [View Dashboard](https://dune.com/datadashboards/polymarket-overview) |
| Polymarket Volume, OI, Markets, Addresses and TVL | [@hildobby](https://x.com/hildobby) | [View Dashboard](https://dune.com/hildobby/polymarket) |
| Polymarket Historical Accuracy | [@alexmccullaaa](https://x.com/alexmccullaaa) | [View Dashboard](https://dune.com/alexmccullough/how-accurate-is-polymarket) |
| Polymarket Builders Dashboard | [@defioasis](https://x.com/defioasis) | [View Dashboard](https://dune.com/gateresearch/pmbuilders) |
+102
View File
@@ -0,0 +1,102 @@
> ## 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.
# Builder Program Introduction
> Learn about Polymarket's Builder Program and how to integrate
## What is a Builder?
A "builder" is a person, group, or organization that routes orders from their users to Polymarket.
If you've created a platform that allows users to trade on Polymarket via your system, this program is for you.
***
## Program Benefits
<CardGroup cols={3}>
<Card title="Relayer Access" icon="gas-pump">
All onchain operations are gasless through our relayer
</Card>
<Card title="Order Attribution" icon="tag">
Get credited for orders and compete for weekly rewards on the Builder Leaderboard
</Card>
<Card title="Fee Share" icon="percent">
Earn a share of fees on routed orders
</Card>
</CardGroup>
### Relayer Access
We expose our relayer to builders, providing gasless transactions for users with
Polymarket's Proxy Wallets deployed via [Relayer Client](/developers/builders/relayer-client).
When transactions are routed through proxy wallets, Polymarket pays all gas fees for:
* Deploying Gnosis Safe Wallets or Custom Proxy (Magic Link users) Wallets
* Token approvals (USDC, outcome tokens)
* CTF operations (split, merge, redeem)
* Order execution (via [CLOB API](/developers/CLOB/introduction))
<Warning>
EOA wallets do not have relayer access. Users trading directly from an EOA pay their own gas fees.
</Warning>
### Trading Attribution
Attach custom headers to orders to identify your builder account:
* Orders attributed to your builder account
* Compete on the [Builder Leaderboard](https://builders.polymarket.com/) for weekly rewards
* Track performance via the Data API
* [Leaderboard API](/api-reference/builders/get-aggregated-builder-leaderboard): Get aggregated builder rankings for a time period
* [Volume API](/api-reference/builders/get-daily-builder-volume-time-series): Get daily time-series volume data for trend analysis
***
## Getting Started
1. **Get Builder Credentials**: Generate API keys from your [Builder Profile](/developers/builders/builder-profile)
2. **Configure Order Attribution**: Set up CLOB client to credit trades to your account ([guide](/developers/builders/order-attribution))
3. **Enable Gasless Transactions**: Use the Relayer for gas-free wallet deployment and trading ([guide](/developers/builders/relayer-client))
<Tip>
See [Example Apps](/developers/builders/examples) for complete Next.js reference implementations.
</Tip>
***
## SDKs & Libraries
<CardGroup cols={3}>
<Card title="CLOB Client (TypeScript)" icon="github" href="https://github.com/Polymarket/clob-client">
Place orders with builder attribution
</Card>
<Card title="CLOB Client (Python)" icon="github" href="https://github.com/Polymarket/py-clob-client">
Place orders with builder attribution
</Card>
<Card title="CLOB Client (Rust)" icon="github" href="https://github.com/Polymarket/rs-clob-client">
Place orders with builder attribution
</Card>
<Card title="Relayer Client (TypeScript)" icon="github" href="https://github.com/Polymarket/builder-relayer-client">
Gasless onchain transactions for your users
</Card>
<Card title="Relayer Client (Python)" icon="github" href="https://github.com/Polymarket/py-builder-relayer-client">
Gasless onchain transactions for your users
</Card>
<Card title="Signing SDK (TypeScript)" icon="github" href="https://github.com/Polymarket/builder-signing-sdk">
Sign builder authentication headers
</Card>
<Card title="Signing SDK (Python)" icon="github" href="https://github.com/Polymarket/py-builder-signing-sdk">
Sign builder authentication headers
</Card>
</CardGroup>
@@ -0,0 +1,76 @@
> ## 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.
# Builder Profile & Keys
> Learn how to access your builder profile and obtain API credentials
## Accessing Your Builder Profile
<CardGroup cols={2}>
<Card title="Direct Link" icon="link">
Go to [polymarket.com/settings?tab=builder](https://polymarket.com/settings?tab=builder)
</Card>
<Card title="From Profile Menu" icon="user">
Click your profile image and Select "Builders"
</Card>
</CardGroup>
***
## Builder Profile Settings
<img src="https://mintcdn.com/polymarket-292d1b1b/Quu9lXyXHL-5rjVX/images/builder-profile-image.png?fit=max&auto=format&n=Quu9lXyXHL-5rjVX&q=85&s=67176050b411016e3bfea47bc6fd8fbb" alt="Builder Settings Page" data-og-width="1854" width="1854" data-og-height="1056" height="1056" data-path="images/builder-profile-image.png" data-optimize="true" data-opv="3" srcset="https://mintcdn.com/polymarket-292d1b1b/Quu9lXyXHL-5rjVX/images/builder-profile-image.png?w=280&fit=max&auto=format&n=Quu9lXyXHL-5rjVX&q=85&s=539b92c0a46959d583d603849459e8df 280w, https://mintcdn.com/polymarket-292d1b1b/Quu9lXyXHL-5rjVX/images/builder-profile-image.png?w=560&fit=max&auto=format&n=Quu9lXyXHL-5rjVX&q=85&s=e7141165754009d3942946b53817feb8 560w, https://mintcdn.com/polymarket-292d1b1b/Quu9lXyXHL-5rjVX/images/builder-profile-image.png?w=840&fit=max&auto=format&n=Quu9lXyXHL-5rjVX&q=85&s=1ec3abc842204033dc99acc2a1fdd9bf 840w, https://mintcdn.com/polymarket-292d1b1b/Quu9lXyXHL-5rjVX/images/builder-profile-image.png?w=1100&fit=max&auto=format&n=Quu9lXyXHL-5rjVX&q=85&s=33d5ca2e18a9267289c1075a0b6d2413 1100w, https://mintcdn.com/polymarket-292d1b1b/Quu9lXyXHL-5rjVX/images/builder-profile-image.png?w=1650&fit=max&auto=format&n=Quu9lXyXHL-5rjVX&q=85&s=5ee84537ae2c108a23f01a19581f2783 1650w, https://mintcdn.com/polymarket-292d1b1b/Quu9lXyXHL-5rjVX/images/builder-profile-image.png?w=2500&fit=max&auto=format&n=Quu9lXyXHL-5rjVX&q=85&s=ed471a4141f2e55fba0f16ad0b70aa38 2500w" />
### Customize Your Builder Identity
* **Profile Picture**: Upload a custom image for the [Builder Leaderboard](https://builders.polymarket.com/)
* **Builder Name**: Set the name displayed publicly on the leaderboard
### View Your Builder Information
* **Builder Address**: Your unique builder address for identification
* **Creation Date**: When your builder account was created
* **Current Tier**: Your rate limit tier (Unverified or Verified)
***
## Builder API Keys
Builder API keys are required to access the relayer and for CLOB order attribution.
### Creating API Keys
In the **Builder Keys** section of your profile's **Builder Settings**:
1. View existing API keys with their creation dates and status
2. Click **"+ Create New"** to generate a new API key
Each API key includes:
| Credential | Description |
| ------------ | ------------------------------------ |
| `apiKey` | Your builder API key identifier |
| `secret` | Secret key for signing requests |
| `passphrase` | Additional authentication passphrase |
### Managing API Keys
* **Multiple Keys**: Create separate keys for different environments
* **Active Status**: Keys show "ACTIVE" when operational
***
## Next Steps
<CardGroup cols={2}>
<Card title="Order Attribution" icon="tag" href="/developers/builders/order-attribution">
Start attributing customer orders to your account
</Card>
<Card title="Builder Leaderboard" icon="trophy" href="https://builders.polymarket.com/">
View your public profile and stats
</Card>
</CardGroup>
+151
View File
@@ -0,0 +1,151 @@
> ## 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.
# Builder Tiers
> Permissionless integration with tiered rate limits, rewards, and revenue generating opportunities as you scale
## Overview
Polymarket Builders lets anyone integrate without approval.
Tiers exist to manage rate limits while rewarding high performing integrations with weekly rewards and revenue sharing opportunities. Higher tiers also unlock engineering support, marketing promotion, and priority access.
## Feature Definitions
| Feature | Description |
| --------------------------- | -------------------------------------------------------------------------- |
| **Daily Relayer Txn Limit** | Maximum Relayer transactions per day for Safe/Proxy wallet operations |
| **API Rate Limits** | Rate limits for non-relayer endpoints (CLOB, Gamma, etc.) |
| **Subsidized Transactions** | Gas fees subsidized for Relayer and CLOB operations via Safe/Proxy wallets |
| **Order Attribution** | Orders tracked and attributed to your Builder profile |
| **RevShare Protocol** | Infrastructure allowing Builders to charge fees |
| **Leaderboard Visibility** | Visibility on the [Builder leaderboard](https://builders.polymarket.com/) |
| **Weekly Rewards** | Weekly USDC rewards program for visible builders based on volume |
| **Telegram Channel** | Private Builders channel for announcements and support |
| **Badge** | Verified Builder affiliate badge on your Builder profile |
| **Engineering Support** | Direct access to engineering team |
| **Marketing Support** | Promotion via official Polymarket social accounts |
| **Weekly Rewards Boost** | Multiplier on the weekly USDC rewards program for visible builders |
| **Priority Access** | Early access to new features and products |
## Tier Comparison
| Feature | Unverified | Verified | Partner |
| --------------------------- | :--------: | :-------: | :-------: |
| **Daily Relayer Txn Limit** | 100/day | 3,000/day | Unlimited |
| **API Rate Limits** | Standard | Standard | Highest |
| **Subsidized Transactions** | ✅ | ✅ | ✅ |
| **Order Attribution** | ✅ | ✅ | ✅ |
| **RevShare Protocol** | ❌ | ✅ | ✅ |
| **Leaderboard Visibility** | ❌ | ✅ | ✅ |
| **Weekly Rewards** | ❌ | ✅ | ✅ |
| **Telegram Channel** | ❌ | ✅ | ✅ |
| **Badge** | ❌ | ✅ | ✅ |
| **Engineering Support** | ❌ | Standard | Elevated |
| **Marketing Support** | ❌ | Standard | Elevated |
| **Weekly Reward Boosts** | ❌ | ❌ | ✅ |
| **Priority Access** | ❌ | ❌ | ✅ |
***
### Unverified
<Card title="100 transactions/day" icon="seedling">
The default tier for all new builders. Create Builder API keys instantly from your Polymarket profile.
</Card>
**How to get started:**
1. Go to [polymarket.com/settings?tab=builder](https://polymarket.com/settings?tab=builder)
2. Create a builder profile and click **"+ Create New"** to generate builder API keys
3. Implement [builder signing](/developers/builders/order-attribution); required for Relayer access and CLOB order attribution
**Included:**
* Gasless trading on all CLOB orders through Safe/Proxy wallets
* Gas subsidized on all Relayer transactions through Safe/Proxy wallets up to daily limit
* Order attribution credit to your Builder profile
* Access to all client libraries and documentation
***
### Verified
<Card title="3,000 transactions/day" icon="badge-check">
For builders who need higher throughput. Requires manual approval by Polymarket.
</Card>
**How to upgrade:**
Contact us with your Builder API Key, use case, expected volume, and relevant info (app, docs, X profile).
**Unlocks over Unverified:**
* 15x daily Relayer transaction limit
* RevShare Protocol Access
* Telegram channel
* Leaderboard visibility
* Eligible for Weekly Rewards Program
* Promotion and verified affiliate badge from @PolymarketBuild
***
### Partner
<Card title="Unlimited transactions/day" icon="handshake">
Enterprise tier for high-volume integrations and strategic partners.
</Card>
**How to apply:**
Reach out to discuss partnership opportunities.
**Unlocks over Verified:**
* Unlimited Relayer transactions
* Highest API rate limits
* Elevated engineering support
* Elevated and coordinated marketing support
* Priority access to new features and products
* Multiplier on the Weekly Rewards Program
***
## Contact
Ready to upgrade or have questions?
* [builder@polymarket.com](mailto:builder@polymarket.com)
***
## FAQ
<AccordionGroup>
<Accordion title="How do I know if I'm verified?">
Verification is displayed in your [Builder Profile](https://polymarket.com/settings?tab=builder) settings.
</Accordion>
<Accordion title="What happens if I exceed my daily limit?">
Relayer requests beyond your daily limit will be rate-limited and return an error. Consider upgrading to Verified or Partner tier if you're hitting limits.
</Accordion>
<Accordion title="Can I get a temporary limit increase?">
For special events or product launches, contact [builder@polymarket.com](mailto:builder@polymarket.com)
</Accordion>
</AccordionGroup>
***
## Next Steps
<CardGroup cols={2}>
<Card title="Get Your Builder Keys" icon="key" href="/developers/builders/builder-profile">
Create Builder API credentials to get started
</Card>
<Card title="Use Your Builder Keys" icon="server" href="/developers/builders/relayer-client">
Configure Builder API credentials to attribute orders
</Card>
</CardGroup>
@@ -0,0 +1,358 @@
> ## 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.
# Order Attribution
> Learn how to attribute orders to your builder account
## Overview
The [CLOB (Central Limit Order Book)](/developers/CLOB/introduction) is Polymarket's order matching system. Order attribution adds builder authentication headers when placing orders through the CLOB Client, enabling Polymarket to credit trades to your builder account. This allows you to:
* Track volume on the [Builder Leaderboard](https://builders.polymarket.com/)
* Monitor performance via the Data API
***
## Builder API Credentials
Each builder receives API credentials from their [Builder Profile](/developers/builders/builder-profile):
| Credential | Description |
| ------------ | ------------------------------------ |
| `key` | Your builder API key identifier |
| `secret` | Secret key for signing requests |
| `passphrase` | Additional authentication passphrase |
<Warning>
**Security Notice**: Your Builder API keys must be kept secure. Never expose them in client-side code.
</Warning>
***
## Signing Methods
<Tabs>
<Tab title="Remote Signing (Recommended)">
Remote signing keeps your credentials secure on a server you control.
**How it works:**
1. User signs an order payload
2. Payload is sent to your builder signing server
3. Your server adds builder authentication headers
4. Complete order is sent to the CLOB
### Server Implementation
Your signing server receives request details and returns the authentication headers. Use the `buildHmacSignature` function from the SDK:
<CodeGroup>
```typescript TypeScript theme={null}
import {
buildHmacSignature,
BuilderApiKeyCreds
} from "@polymarket/builder-signing-sdk";
const BUILDER_CREDENTIALS: BuilderApiKeyCreds = {
key: process.env.POLY_BUILDER_API_KEY!,
secret: process.env.POLY_BUILDER_SECRET!,
passphrase: process.env.POLY_BUILDER_PASSPHRASE!,
};
// POST /sign - receives { method, path, body } from the client SDK
export async function handleSignRequest(request) {
const { method, path, body } = await request.json();
const timestamp = Date.now().toString();
const signature = buildHmacSignature(
BUILDER_CREDENTIALS.secret,
parseInt(timestamp),
method,
path,
body
);
return {
POLY_BUILDER_SIGNATURE: signature,
POLY_BUILDER_TIMESTAMP: timestamp,
POLY_BUILDER_API_KEY: BUILDER_CREDENTIALS.key,
POLY_BUILDER_PASSPHRASE: BUILDER_CREDENTIALS.passphrase,
};
}
```
```python Python theme={null}
import os
import time
from py_builder_signing_sdk.signing.hmac import build_hmac_signature
from py_builder_signing_sdk import BuilderApiKeyCreds
BUILDER_CREDENTIALS = BuilderApiKeyCreds(
key=os.environ["POLY_BUILDER_API_KEY"],
secret=os.environ["POLY_BUILDER_SECRET"],
passphrase=os.environ["POLY_BUILDER_PASSPHRASE"],
)
# POST /sign - receives { method, path, body } from the client SDK
def handle_sign_request(method: str, path: str, body: str):
timestamp = str(int(time.time()))
signature = build_hmac_signature(
BUILDER_CREDENTIALS.secret,
timestamp,
method,
path,
body
)
return {
"POLY_BUILDER_SIGNATURE": signature,
"POLY_BUILDER_TIMESTAMP": timestamp,
"POLY_BUILDER_API_KEY": BUILDER_CREDENTIALS.key,
"POLY_BUILDER_PASSPHRASE": BUILDER_CREDENTIALS.passphrase,
}
```
</CodeGroup>
<Warning>
Never commit credentials to version control. Use environment variables or a secrets manager.
</Warning>
### Client Configuration
Point your client to your signing server:
<CodeGroup>
```typescript TypeScript theme={null}
import { ClobClient } from "@polymarket/clob-client";
import { BuilderConfig } from "@polymarket/builder-signing-sdk";
// Point to your signing server
const builderConfig = new BuilderConfig({
remoteBuilderConfig: {
url: "https://your-server.com/sign"
}
});
// Or with optional authorization token
const builderConfigWithAuth = new BuilderConfig({
remoteBuilderConfig: {
url: "https://your-server.com/sign",
token: "your-auth-token"
}
});
const client = new ClobClient(
"https://clob.polymarket.com",
137,
signer, // ethers v5.x EOA signer
creds, // User's API Credentials
2, // signatureType for the Safe proxy wallet
funderAddress, // Safe proxy wallet address
undefined,
false,
builderConfig
);
// Orders automatically use the signing server
const order = await client.createOrder({
price: 0.40,
side: Side.BUY,
size: 5,
tokenID: "YOUR_TOKEN_ID"
});
const response = await client.postOrder(order);
```
```python Python theme={null}
from py_clob_client.client import ClobClient
from py_builder_signing_sdk import BuilderConfig, RemoteBuilderConfig
# Point to your signing server
builder_config = BuilderConfig(
remote_builder_config=RemoteBuilderConfig(
url="https://your-server.com/sign"
)
)
# Or with optional authorization token
builder_config_with_auth = BuilderConfig(
remote_builder_config=RemoteBuilderConfig(
url="https://your-server.com/sign",
token="your-auth-token"
)
)
client = ClobClient(
host="https://clob.polymarket.com",
chain_id=137,
key=private_key,
creds=creds, # User's API Credentials
signature_type=2, # signatureType for the Safe proxy wallet
funder=funder_address, # Safe proxy wallet address
builder_config=builder_config
)
# Orders automatically use the signing server
order = client.create_order({
"price": 0.40,
"side": "BUY",
"size": 5,
"token_id": "YOUR_TOKEN_ID"
})
response = client.post_order(order)
```
</CodeGroup>
### Troubleshooting
<AccordionGroup>
<Accordion title="Invalid Signature Errors">
**Error:** Client receives invalid signature errors
**Solution:**
1. Verify the request body is passed correctly as JSON
2. Check that `path`, `body`, and `method` match what the client sends
3. Ensure your server and client use the same Builder API credentials
</Accordion>
<Accordion title="Missing Credentials">
**Error:** `Builder credentials not configured` or undefined values
**Solution:** Ensure your environment variables are set:
* `POLY_BUILDER_API_KEY`
* `POLY_BUILDER_SECRET`
* `POLY_BUILDER_PASSPHRASE`
</Accordion>
</AccordionGroup>
</Tab>
<Tab title="Local Signing">
Sign orders locally when you control the entire order placement flow.
**How it works:**
1. Your system creates and signs orders on behalf of users
2. Your system uses Builder API credentials locally to add headers
3. Complete signed order is sent directly to the CLOB
<CodeGroup>
```typescript TypeScript theme={null}
import { ClobClient } from "@polymarket/clob-client";
import { BuilderConfig, BuilderApiKeyCreds } from "@polymarket/builder-signing-sdk";
// Configure with local builder credentials
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
});
const client = new ClobClient(
"https://clob.polymarket.com",
137,
signer, // ethers v5.x EOA signer
creds, // User's API Credentials
2, // signatureType for the Safe proxy wallet
funderAddress, // Safe proxy wallet address
undefined,
false,
builderConfig
);
// Orders automatically include builder headers
const order = await client.createOrder({
price: 0.40,
side: Side.BUY,
size: 5,
tokenID: "YOUR_TOKEN_ID"
});
const response = await client.postOrder(order);
```
```python Python theme={null}
import os
from py_clob_client.client import ClobClient
from py_builder_signing_sdk import BuilderConfig, BuilderApiKeyCreds
# Configure with local builder credentials
builder_creds = BuilderApiKeyCreds(
key=os.environ["POLY_BUILDER_API_KEY"],
secret=os.environ["POLY_BUILDER_SECRET"],
passphrase=os.environ["POLY_BUILDER_PASSPHRASE"]
)
builder_config = BuilderConfig(
local_builder_creds=builder_creds
)
client = ClobClient(
host="https://clob.polymarket.com",
chain_id=137,
key=private_key,
creds=creds, # User's API Credentials
signature_type=2, # signatureType for the Safe proxy wallet
funder=funder_address, # Safe proxy wallet address
builder_config=builder_config
)
# Orders automatically include builder headers
order = client.create_order({
"price": 0.40,
"side": "BUY",
"size": 5,
"token_id": "YOUR_TOKEN_ID"
})
response = client.post_order(order)
```
</CodeGroup>
<Warning>
Never commit credentials to version control. Use environment variables or a secrets manager.
</Warning>
</Tab>
</Tabs>
***
## Authentication Headers
The SDK automatically generates and attaches these headers to each request:
| Header | Description |
| ------------------------- | ------------------------------------ |
| `POLY_BUILDER_API_KEY` | Your builder API key |
| `POLY_BUILDER_TIMESTAMP` | Unix timestamp of signature creation |
| `POLY_BUILDER_PASSPHRASE` | Your builder passphrase |
| `POLY_BUILDER_SIGNATURE` | HMAC signature of the request |
<Info>
With **local signing**, the SDK constructs and attaches these headers automatically. With **remote signing**, your server must return these headers (see Server Implementation above), and the SDK attaches them to the request.
</Info>
***
## Next Steps
<CardGroup cols={2}>
<Card title="Relayer Client" icon="bolt" href="/developers/builders/relayer-client">
Learn how to configure and use the Relay Client too!
</Card>
<Card title="CLOB Client Methods" icon="book" href="/developers/CLOB/clients/methods-overview">
Explore the complete CLOB client reference
</Card>
</CardGroup>
+917
View File
@@ -0,0 +1,917 @@
> ## 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.
# Relayer Client
> Use Polymarket's Polygon relayer to execute gasless transactions for your users
## Overview
The Relayer Client routes onchain transactions through Polymarket's infrastructure, providing gasless transactions for your users. Builder authentication is required to access the relayer.
<CardGroup cols={3}>
<Card title="Gasless Transactions" icon="gas-pump">
Polymarket pays all gas fees
</Card>
<Card title="Wallet Deployment" icon="wallet">
Deploy Safe or Proxy wallets
</Card>
<Card title="CTF Operations" icon="arrows-split-up-and-left">
Split, merge, and redeem positions
</Card>
</CardGroup>
***
## Builder API Credentials
Each builder receives API credentials from their [Builder Profile](/developers/builders/builder-profile):
| Credential | Description |
| ------------ | ------------------------------------ |
| `key` | Your builder API key identifier |
| `secret` | Secret key for signing requests |
| `passphrase` | Additional authentication passphrase |
<Warning>
**Security Notice**: Your Builder API keys must be kept secure. Never expose them in client-side code.
</Warning>
***
## Installation
<CodeGroup>
```bash TypeScript theme={null}
npm install @polymarket/builder-relayer-client
```
```bash Python theme={null}
pip install py-builder-relayer-client
```
</CodeGroup>
***
## Relayer Endpoint
All relayer requests are sent to Polymarket's relayer service on Polygon:
```
https://relayer-v2.polymarket.com/
```
***
## Signing Methods
<Tabs>
<Tab title="Remote Signing (Recommended)">
Remote signing keeps your credentials secure on a server you control.
**How it works:**
1. Client sends request details to your signing server
2. Your server generates the HMAC signature
3. Client attaches headers and sends to relayer
### Server Implementation
Your signing server receives request details and returns the authentication headers:
<CodeGroup>
```typescript TypeScript theme={null}
import {
buildHmacSignature,
BuilderApiKeyCreds
} from "@polymarket/builder-signing-sdk";
const BUILDER_CREDENTIALS: BuilderApiKeyCreds = {
key: process.env.POLY_BUILDER_API_KEY!,
secret: process.env.POLY_BUILDER_SECRET!,
passphrase: process.env.POLY_BUILDER_PASSPHRASE!,
};
// POST /sign - receives { method, path, body } from the client SDK
export async function handleSignRequest(request) {
const { method, path, body } = await request.json();
const timestamp = Date.now().toString();
const signature = buildHmacSignature(
BUILDER_CREDENTIALS.secret,
parseInt(timestamp),
method,
path,
body
);
return {
POLY_BUILDER_SIGNATURE: signature,
POLY_BUILDER_TIMESTAMP: timestamp,
POLY_BUILDER_API_KEY: BUILDER_CREDENTIALS.key,
POLY_BUILDER_PASSPHRASE: BUILDER_CREDENTIALS.passphrase,
};
}
```
```python Python theme={null}
import os
import time
from py_builder_signing_sdk.signing.hmac import build_hmac_signature
from py_builder_signing_sdk import BuilderApiKeyCreds
BUILDER_CREDENTIALS = BuilderApiKeyCreds(
key=os.environ["POLY_BUILDER_API_KEY"],
secret=os.environ["POLY_BUILDER_SECRET"],
passphrase=os.environ["POLY_BUILDER_PASSPHRASE"],
)
# POST /sign - receives { method, path, body } from the client SDK
def handle_sign_request(method: str, path: str, body: str):
timestamp = str(int(time.time()))
signature = build_hmac_signature(
BUILDER_CREDENTIALS.secret,
timestamp,
method,
path,
body
)
return {
"POLY_BUILDER_SIGNATURE": signature,
"POLY_BUILDER_TIMESTAMP": timestamp,
"POLY_BUILDER_API_KEY": BUILDER_CREDENTIALS.key,
"POLY_BUILDER_PASSPHRASE": BUILDER_CREDENTIALS.passphrase,
}
```
</CodeGroup>
<Warning>
Never commit credentials to version control. Use environment variables or a secrets manager.
</Warning>
### Client Configuration
Point your client to your signing server:
<CodeGroup>
```typescript TypeScript theme={null}
import { createWalletClient, http, Hex } from "viem";
import { privateKeyToAccount } from "viem/accounts";
import { polygon } from "viem/chains";
import { RelayClient } from "@polymarket/builder-relayer-client";
import { BuilderConfig } from "@polymarket/builder-signing-sdk";
// Create wallet
const account = privateKeyToAccount(process.env.PRIVATE_KEY as Hex);
const wallet = createWalletClient({
account,
chain: polygon,
transport: http(process.env.RPC_URL)
});
// Configure remote signing
const builderConfig = new BuilderConfig({
remoteBuilderConfig: {
url: "https://your-server.com/sign"
}
});
const RELAYER_URL = "https://relayer-v2.polymarket.com/";
const CHAIN_ID = 137;
const client = new RelayClient(
RELAYER_URL,
CHAIN_ID,
wallet,
builderConfig
);
```
```python Python theme={null}
import os
from py_builder_relayer_client.client import RelayClient
from py_builder_signing_sdk import BuilderConfig, RemoteBuilderConfig
private_key = os.getenv("PRIVATE_KEY")
# Configure remote signing
builder_config = BuilderConfig(
remote_builder_config=RemoteBuilderConfig(
url="https://your-server.com/sign"
)
)
client = RelayClient(
"https://relayer-v2.polymarket.com",
137,
private_key,
builder_config
)
```
</CodeGroup>
</Tab>
<Tab title="Local Signing">
Sign locally when your backend handles all transactions.
**How it works:**
1. Your system creates transactions on behalf of users
2. Your system uses Builder API credentials locally to add headers
3. Complete signed request is sent directly to the relayer
<CodeGroup>
```typescript TypeScript theme={null}
import { createWalletClient, http, Hex } from "viem";
import { privateKeyToAccount } from "viem/accounts";
import { polygon } from "viem/chains";
import { RelayClient } from "@polymarket/builder-relayer-client";
import { BuilderConfig } from "@polymarket/builder-signing-sdk";
// Create wallet
const account = privateKeyToAccount(process.env.PRIVATE_KEY as Hex);
const wallet = createWalletClient({
account,
chain: polygon,
transport: http(process.env.RPC_URL)
});
// Configure local signing
const builderConfig = new BuilderConfig({
localBuilderCreds: {
key: process.env.POLY_BUILDER_API_KEY!,
secret: process.env.POLY_BUILDER_SECRET!,
passphrase: process.env.POLY_BUILDER_PASSPHRASE!
}
});
const RELAYER_URL = "https://relayer-v2.polymarket.com/";
const CHAIN_ID = 137;
const client = new RelayClient(
RELAYER_URL,
CHAIN_ID,
wallet,
builderConfig
);
```
```python Python theme={null}
import os
from py_builder_relayer_client.client import RelayClient
from py_builder_signing_sdk import BuilderConfig, BuilderApiKeyCreds
private_key = os.getenv("PRIVATE_KEY")
# Configure local signing
builder_config = BuilderConfig(
local_builder_creds=BuilderApiKeyCreds(
key=os.getenv("POLY_BUILDER_API_KEY"),
secret=os.getenv("POLY_BUILDER_SECRET"),
passphrase=os.getenv("POLY_BUILDER_PASSPHRASE"),
)
)
client = RelayClient(
"https://relayer-v2.polymarket.com",
137,
private_key,
builder_config
)
```
</CodeGroup>
<Warning>
Never commit credentials to version control. Use environment variables or a secrets manager.
</Warning>
</Tab>
</Tabs>
***
## Authentication Headers
The SDK automatically generates and attaches these headers to each request:
| Header | Description |
| ------------------------- | ------------------------------------ |
| `POLY_BUILDER_API_KEY` | Your builder API key |
| `POLY_BUILDER_TIMESTAMP` | Unix timestamp of signature creation |
| `POLY_BUILDER_PASSPHRASE` | Your builder passphrase |
| `POLY_BUILDER_SIGNATURE` | HMAC signature of the request |
<Info>
With **local signing**, the SDK constructs and attaches these headers automatically. With **remote signing**, your server must return these headers (see Server Implementation above), and the SDK attaches them to the request.
</Info>
***
## Wallet Types
Choose your wallet type before using the relayer:
<Tabs>
<Tab title="Safe Wallets">
Gnosis Safe-based proxy wallets that require explicit deployment before use.
* **Best for:** Most builder integrations
* **Deployment:** Call `client.deploy()` before first transaction
* **Gas fees:** Paid by Polymarket
<CodeGroup>
```typescript TypeScript theme={null}
const client = new RelayClient(
"https://relayer-v2.polymarket.com",
137,
eoaSigner,
builderConfig,
RelayerTxType.SAFE // Default
);
// Deploy before first use
const response = await client.deploy();
const result = await response.wait();
console.log("Safe Address:", result?.proxyAddress);
```
```python Python theme={null}
from py_builder_relayer_client.client import RelayClient, RelayerTxType
client = RelayClient(
"https://relayer-v2.polymarket.com",
137,
private_key,
builder_config,
RelayerTxType.SAFE # Default
)
# Deploy before first use
response = client.deploy()
result = response.wait()
print(f"Safe Address: {result.proxy_address}")
```
</CodeGroup>
</Tab>
<Tab title="Proxy Wallets">
Custom Polymarket proxy wallets that auto-deploy on first transaction.
* **Used for:** Magic Link users from Polymarket.com
* **Deployment:** Automatic on first transaction
* **Gas fees:** Paid by Polymarket
<CodeGroup>
```typescript TypeScript theme={null}
const client = new RelayClient(
"https://relayer-v2.polymarket.com",
137,
eoaSigner,
builderConfig,
RelayerTxType.PROXY
);
// No deploy() needed - auto-deploys on first tx
await client.execute([transaction], "First transaction");
```
```python Python theme={null}
from py_builder_relayer_client.client import RelayClient, RelayerTxType
client = RelayClient(
"https://relayer-v2.polymarket.com",
137,
private_key,
builder_config,
RelayerTxType.PROXY
)
# No deploy() needed - auto-deploys on first tx
client.execute([transaction], "First transaction")
```
</CodeGroup>
</Tab>
</Tabs>
<Accordion title="Wallet Comparison Table">
| Feature | Safe Wallets | Proxy Wallets |
| ----------------- | :-----------------: | :---------------------: |
| Deployment | Explicit `deploy()` | Auto-deploy on first tx |
| Gas Fees | Polymarket pays | Polymarket pays |
| ERC20 Approvals | ✅ | ✅ |
| CTF Operations | ✅ | ✅ |
| Send Transactions | ✅ | ✅ |
</Accordion>
***
## Usage
### Deploy a Wallet
For Safe wallets, deploy before executing transactions:
<CodeGroup>
```typescript TypeScript theme={null}
const response = await client.deploy();
const result = await response.wait();
if (result) {
console.log("Safe deployed successfully!");
console.log("Transaction Hash:", result.transactionHash);
console.log("Safe Address:", result.proxyAddress);
}
```
```python Python theme={null}
response = client.deploy()
result = response.wait()
if result:
print("Safe deployed successfully!")
print(f"Transaction Hash: {result.transaction_hash}")
print(f"Safe Address: {result.proxy_address}")
```
</CodeGroup>
### Execute Transactions
The `execute` method sends transactions through the relayer. Pass an array of transactions to batch multiple operations in a single call.
<CodeGroup>
```typescript TypeScript theme={null}
interface Transaction {
to: string; // Target contract or wallet address
data: string; // Encoded function call (use "0x" for simple transfers)
value: string; // Amount of MATIC to send (usually "0")
}
const response = await client.execute(transactions, "Description");
const result = await response.wait();
if (result) {
console.log("Transaction confirmed:", result.transactionHash);
}
```
```python Python theme={null}
# Transaction dict format:
# { "to": str, "data": str, "value": str }
response = client.execute(transactions, "Description")
result = response.wait()
if result:
print(f"Transaction confirmed: {result.transaction_hash}")
```
</CodeGroup>
### Transaction Examples
<Tabs>
<Tab title="Transfer">
Transfer tokens to any address (e.g., withdrawals):
<CodeGroup>
```typescript TypeScript theme={null}
import { encodeFunctionData, parseUnits } from "viem";
const transferTx = {
to: "0x2791Bca1f2de4661ED88A30C99A7a9449Aa84174", // USDCe
data: encodeFunctionData({
abi: [{
name: "transfer",
type: "function",
inputs: [
{ name: "to", type: "address" },
{ name: "amount", type: "uint256" }
],
outputs: [{ type: "bool" }]
}],
functionName: "transfer",
args: [
"0xRecipientAddressHere",
parseUnits("100", 6) // 100 USDCe (6 decimals)
]
}),
value: "0"
};
const response = await client.execute([transferTx], "Transfer USDCe");
await response.wait();
```
```python Python theme={null}
from web3 import Web3
USDC_E = "0x2791Bca1f2de4661ED88A30C99A7a9449Aa84174"
transfer_tx = {
"to": USDC_E,
"data": Web3().eth.contract(
address=USDC_E,
abi=[{"name": "transfer", "type": "function", "inputs": [{"name": "to", "type": "address"}, {"name": "amount", "type": "uint256"}], "outputs": [{"type": "bool"}]}]
).encode_abi(abi_element_identifier="transfer", args=["0xRecipientAddressHere", 100 * 10**6]),
"value": "0"
}
response = client.execute([transfer_tx], "Transfer USDCe")
response.wait()
```
</CodeGroup>
</Tab>
<Tab title="Approve">
Set token allowances to enable trading:
<CodeGroup>
```typescript TypeScript theme={null}
import { encodeFunctionData, maxUint256 } from "viem";
const approveTx = {
to: "0x2791Bca1f2de4661ED88A30C99A7a9449Aa84174", // USDCe
data: encodeFunctionData({
abi: [{
name: "approve",
type: "function",
inputs: [
{ name: "spender", type: "address" },
{ name: "amount", type: "uint256" }
],
outputs: [{ type: "bool" }]
}],
functionName: "approve",
args: [
"0x4d97dcd97ec945f40cf65f87097ace5ea0476045", // CTF
maxUint256
]
}),
value: "0"
};
const response = await client.execute([approveTx], "Approve USDCe for CTF");
await response.wait();
```
```python Python theme={null}
from web3 import Web3
USDC_E = "0x2791Bca1f2de4661ED88A30C99A7a9449Aa84174"
CTF = "0x4d97dcd97ec945f40cf65f87097ace5ea0476045"
MAX_UINT256 = 2**256 - 1
approve_tx = {
"to": USDC_E,
"data": Web3().eth.contract(
address=USDC_E,
abi=[{"name": "approve", "type": "function", "inputs": [{"name": "spender", "type": "address"}, {"name": "amount", "type": "uint256"}], "outputs": [{"type": "bool"}]}]
).encode_abi(abi_element_identifier="approve", args=[CTF, MAX_UINT256]),
"value": "0"
}
response = client.execute([approve_tx], "Approve USDCe for CTF")
response.wait()
```
</CodeGroup>
</Tab>
<Tab title="Redeem Positions">
Redeem winning conditional tokens after market resolution:
<CodeGroup>
```typescript TypeScript theme={null}
import { encodeFunctionData } from "viem";
const redeemTx = {
to: ctfAddress,
data: encodeFunctionData({
abi: [{
name: "redeemPositions",
type: "function",
inputs: [
{ name: "collateralToken", type: "address" },
{ name: "parentCollectionId", type: "bytes32" },
{ name: "conditionId", type: "bytes32" },
{ name: "indexSets", type: "uint256[]" }
],
outputs: []
}],
functionName: "redeemPositions",
args: [collateralToken, parentCollectionId, conditionId, indexSets]
}),
value: "0"
};
const response = await client.execute([redeemTx], "Redeem positions");
await response.wait();
```
```python Python theme={null}
from web3 import Web3
CTF = "0x4d97dcd97ec945f40cf65f87097ace5ea0476045"
redeem_tx = {
"to": CTF,
"data": Web3().eth.contract(
address=CTF,
abi=[{"name": "redeemPositions", "type": "function", "inputs": [{"name": "collateralToken", "type": "address"}, {"name": "parentCollectionId", "type": "bytes32"}, {"name": "conditionId", "type": "bytes32"}, {"name": "indexSets", "type": "uint256[]"}], "outputs": []}]
).encode_abi(abi_element_identifier="redeemPositions", args=[collateral_token, parent_collection_id, condition_id, index_sets]),
"value": "0"
}
response = client.execute([redeem_tx], "Redeem positions")
response.wait()
```
</CodeGroup>
</Tab>
<Tab title="Split Positions">
Split collateral tokens into conditional outcome tokens:
<CodeGroup>
```typescript TypeScript theme={null}
import { encodeFunctionData } from "viem";
const splitTx = {
to: ctfAddress,
data: encodeFunctionData({
abi: [{
name: "splitPosition",
type: "function",
inputs: [
{ name: "collateralToken", type: "address" },
{ name: "parentCollectionId", type: "bytes32" },
{ name: "conditionId", type: "bytes32" },
{ name: "partition", type: "uint256[]" },
{ name: "amount", type: "uint256" }
],
outputs: []
}],
functionName: "splitPosition",
args: [collateralToken, parentCollectionId, conditionId, partition, amount]
}),
value: "0"
};
const response = await client.execute([splitTx], "Split positions");
await response.wait();
```
```python Python theme={null}
from web3 import Web3
CTF = "0x4d97dcd97ec945f40cf65f87097ace5ea0476045"
split_tx = {
"to": CTF,
"data": Web3().eth.contract(
address=CTF,
abi=[{"name": "splitPosition", "type": "function", "inputs": [{"name": "collateralToken", "type": "address"}, {"name": "parentCollectionId", "type": "bytes32"}, {"name": "conditionId", "type": "bytes32"}, {"name": "partition", "type": "uint256[]"}, {"name": "amount", "type": "uint256"}], "outputs": []}]
).encode_abi(abi_element_identifier="splitPosition", args=[collateral_token, parent_collection_id, condition_id, partition, amount]),
"value": "0"
}
response = client.execute([split_tx], "Split positions")
response.wait()
```
</CodeGroup>
</Tab>
<Tab title="Merge Positions">
Merge conditional tokens back into collateral:
<CodeGroup>
```typescript TypeScript theme={null}
import { encodeFunctionData } from "viem";
const mergeTx = {
to: ctfAddress,
data: encodeFunctionData({
abi: [{
name: "mergePositions",
type: "function",
inputs: [
{ name: "collateralToken", type: "address" },
{ name: "parentCollectionId", type: "bytes32" },
{ name: "conditionId", type: "bytes32" },
{ name: "partition", type: "uint256[]" },
{ name: "amount", type: "uint256" }
],
outputs: []
}],
functionName: "mergePositions",
args: [collateralToken, parentCollectionId, conditionId, partition, amount]
}),
value: "0"
};
const response = await client.execute([mergeTx], "Merge positions");
await response.wait();
```
```python Python theme={null}
from web3 import Web3
CTF = "0x4d97dcd97ec945f40cf65f87097ace5ea0476045"
merge_tx = {
"to": CTF,
"data": Web3().eth.contract(
address=CTF,
abi=[{"name": "mergePositions", "type": "function", "inputs": [{"name": "collateralToken", "type": "address"}, {"name": "parentCollectionId", "type": "bytes32"}, {"name": "conditionId", "type": "bytes32"}, {"name": "partition", "type": "uint256[]"}, {"name": "amount", "type": "uint256"}], "outputs": []}]
).encode_abi(abi_element_identifier="mergePositions", args=[collateral_token, parent_collection_id, condition_id, partition, amount]),
"value": "0"
}
response = client.execute([merge_tx], "Merge positions")
response.wait()
```
</CodeGroup>
</Tab>
<Tab title="Batch Transactions">
Execute multiple transactions atomically in a single call:
<CodeGroup>
```typescript TypeScript theme={null}
import { encodeFunctionData, parseUnits, maxUint256 } from "viem";
const erc20Abi = [
{
name: "approve",
type: "function",
inputs: [
{ name: "spender", type: "address" },
{ name: "amount", type: "uint256" }
],
outputs: [{ type: "bool" }]
},
{
name: "transfer",
type: "function",
inputs: [
{ name: "to", type: "address" },
{ name: "amount", type: "uint256" }
],
outputs: [{ type: "bool" }]
}
] as const;
// Approve CTF to spend USDCe
const approveTx = {
to: "0x2791Bca1f2de4661ED88A30C99A7a9449Aa84174",
data: encodeFunctionData({
abi: erc20Abi,
functionName: "approve",
args: ["0x4d97dcd97ec945f40cf65f87097ace5ea0476045", maxUint256]
}),
value: "0"
};
// Transfer some USDCe to another wallet
const transferTx = {
to: "0x2791Bca1f2de4661ED88A30C99A7a9449Aa84174",
data: encodeFunctionData({
abi: erc20Abi,
functionName: "transfer",
args: ["0xRecipientAddressHere", parseUnits("50", 6)]
}),
value: "0"
};
// Both transactions execute in one call
const response = await client.execute(
[approveTx, transferTx],
"Approve and transfer"
);
await response.wait();
```
```python Python theme={null}
from web3 import Web3
USDC_E = "0x2791Bca1f2de4661ED88A30C99A7a9449Aa84174"
CTF = "0x4d97dcd97ec945f40cf65f87097ace5ea0476045"
MAX_UINT256 = 2**256 - 1
erc20_abi = [
{"name": "approve", "type": "function", "inputs": [{"name": "spender", "type": "address"}, {"name": "amount", "type": "uint256"}], "outputs": [{"type": "bool"}]},
{"name": "transfer", "type": "function", "inputs": [{"name": "to", "type": "address"}, {"name": "amount", "type": "uint256"}], "outputs": [{"type": "bool"}]}
]
contract = Web3().eth.contract(address=USDC_E, abi=erc20_abi)
# Approve CTF to spend USDCe
approve_tx = {
"to": USDC_E,
"data": contract.encode_abi(abi_element_identifier="approve", args=[CTF, MAX_UINT256]),
"value": "0"
}
# Transfer some USDCe to another wallet
transfer_tx = {
"to": USDC_E,
"data": contract.encode_abi(abi_element_identifier="transfer", args=["0xRecipientAddressHere", 50 * 10**6]),
"value": "0"
}
# Both transactions execute in one call
response = client.execute([approve_tx, transfer_tx], "Approve and transfer")
response.wait()
```
</CodeGroup>
<Info>
Batching reduces latency and ensures all transactions succeed or fail together.
</Info>
</Tab>
</Tabs>
***
## Reference
### Contracts & Approvals
| Contract | Address | USDCe | Outcome Tokens |
| --------------------- | -------------------------------------------- | :---: | :------------: |
| USDCe | `0x2791Bca1f2de4661ED88A30C99A7a9449Aa84174` | — | — |
| CTF | `0x4d97dcd97ec945f40cf65f87097ace5ea0476045` | ✅ | — |
| CTF Exchange | `0x4bFb41d5B3570DeFd03C39a9A4D8dE6Bd8B8982E` | ✅ | ✅ |
| Neg Risk CTF Exchange | `0xC5d563A36AE78145C45a50134d48A1215220f80a` | ✅ | ✅ |
| Neg Risk Adapter | `0xd91E80cF2E7be2e162c6513ceD06f1dD0dA35296` | — | ✅ |
### Transaction States
| State | Description |
| ----------------- | -------------------------------------------- |
| `STATE_NEW` | Transaction received by relayer |
| `STATE_EXECUTED` | Transaction executed onchain |
| `STATE_MINED` | Transaction included in a block |
| `STATE_CONFIRMED` | Transaction confirmed (final ✅) |
| `STATE_FAILED` | Transaction failed (terminal ❌) |
| `STATE_INVALID` | Transaction rejected as invalid (terminal ❌) |
### TypeScript Types
<Accordion title="View Type Definitions">
```typescript theme={null}
// Transaction type used in all examples
interface Transaction {
to: string;
data: string;
value: string;
}
// Wallet type selector
enum RelayerTxType {
SAFE = "SAFE",
PROXY = "PROXY"
}
// Transaction states
enum RelayerTransactionState {
STATE_NEW = "STATE_NEW",
STATE_EXECUTED = "STATE_EXECUTED",
STATE_MINED = "STATE_MINED",
STATE_CONFIRMED = "STATE_CONFIRMED",
STATE_FAILED = "STATE_FAILED",
STATE_INVALID = "STATE_INVALID"
}
// Response from relayer
interface RelayerTransaction {
transactionID: string;
transactionHash: string;
from: string;
to: string;
proxyAddress: string;
data: string;
state: string;
type: string;
metadata: string;
createdAt: Date;
updatedAt: Date;
}
```
</Accordion>
***
## Next Steps
<CardGroup cols={2}>
<Card title="Order Attribution" icon="tag" href="/developers/builders/order-attribution">
Attribute orders to your builder account
</Card>
<Card title="Example Apps" icon="code" href="/developers/builders/examples">
Complete integration examples
</Card>
</CardGroup>
@@ -0,0 +1,160 @@
> ## 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.
# How to Fetch Markets
<Tip>Both the getEvents and getMarkets are paginated. See [pagination section](#pagination) for details.</Tip>
This guide covers the three recommended approaches for fetching market data from the Gamma API, each optimized for different use cases.
## Overview
There are three main strategies for retrieving market data:
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
***
## 1. Fetch by Slug
**Use Case:** When you need to retrieve a specific market or event that you already know about.
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/` or `/market/`:
```
https://polymarket.com/event/fed-decision-in-october?tid=1758818660485
Slug: fed-decision-in-october
```
### API Endpoints
**For Events:** [GET /events/slug/{slug}](/api-reference/events/list-events)
**For Markets:** [GET /markets/slug/{slug}](/api-reference/markets/list-markets)
### Examples
```bash theme={null}
curl "https://gamma-api.polymarket.com/events/slug/fed-decision-in-october"
```
***
## 2. Fetch by Tags
**Use Case:** When you want to filter markets by category, sport, or topic.
Tags provide a powerful way to categorize and filter markets. You can discover available tags and then use them to filter your market requests.
### Discover Available Tags
**General Tags:** [GET /tags](/api-reference/tags/list-tags)
**Sports Tags & Metadata:** [GET /sports](/api-reference/sports/get-sports-metadata-information)
The `/sports` endpoint returns comprehensive metadata for sports including tag IDs, images, resolution sources, and series information.
### Using Tags in Market Requests
Once you have tag IDs, you can use them with the `tag_id` parameter in both markets and events endpoints.
**Markets with Tags:** [GET /markets](/api-reference/markets/list-markets)
**Events with Tags:** [GET /events](/api-reference/events/list-events)
```bash theme={null}
curl "https://gamma-api.polymarket.com/events?tag_id=100381&limit=1&closed=false"
```
### Additional Tag Filtering
You can also:
* Use `related_tags=true` to include related tag markets
* Exclude specific tags with `exclude_tag_id`
***
## 3. Fetch All Active Markets
**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 and work backwards, as events contain their associated markets.
**Events Endpoint:** [GET /events](/api-reference/events/list-events)
**Markets Endpoint:** [GET /markets](/api-reference/markets/list-markets)
### Key Parameters
* `order=id` - Order by event ID
* `ascending=false` - Get newest events first
* `closed=false` - Only active markets
* `limit` - Control response size
* `offset` - For pagination
### Examples
```bash theme={null}
curl "https://gamma-api.polymarket.com/events?order=id&ascending=false&closed=false&limit=100"
```
This approach gives you all active markets ordered from newest to oldest, allowing you to systematically process all available trading opportunities.
### Pagination
For large datasets, use pagination with `limit` and `offset` parameters:
* `limit=50` - Return 50 results per page
* `offset=0` - Start from the beginning (increment by limit for subsequent pages)
**Pagination Examples:**
```bash theme={null}
# Page 1: First 50 results (offset=0)
curl "https://gamma-api.polymarket.com/events?order=id&ascending=false&closed=false&limit=50&offset=0"
```
```bash theme={null}
# Page 2: Next 50 results (offset=50)
curl "https://gamma-api.polymarket.com/events?order=id&ascending=false&closed=false&limit=50&offset=50"
```
```bash theme={null}
# Page 3: Next 50 results (offset=100)
curl "https://gamma-api.polymarket.com/events?order=id&ascending=false&closed=false&limit=50&offset=100"
```
```bash theme={null}
# Paginating through markets with tag filtering
curl "https://gamma-api.polymarket.com/markets?tag_id=100381&closed=false&limit=25&offset=0"
```
```bash theme={null}
# Next page of markets with tag filtering
curl "https://gamma-api.polymarket.com/markets?tag_id=100381&closed=false&limit=25&offset=25"
```
***
## Best Practices
1. **For Individual Markets:** Always use the slug method for best performance
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 `closed=false`:** Unless you specifically need historical data
5. **Implement Rate Limiting:** Respect API limits for production applications
## Related Endpoints
* [Get Markets](/developers/gamma-markets-api/get-markets) - Full markets endpoint documentation
* [Get Events](/developers/gamma-markets-api/get-events) - Full events endpoint documentation
* [Search Markets](/developers/gamma-markets-api/get-public-search) - Search functionality
@@ -0,0 +1,27 @@
> ## 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.
# Gamma Structure
Gamma provides some organizational models. These include events, and markets. The most fundamental element is always markets and the other models simply provide additional organization.
# Detail
1. **Market**
1. Contains data related to a market that is traded on. Maps onto a pair of clob token ids, a market address, a question id and a condition id
2. **Event**
1. Contains a set of markets
2. Variants:
1. Event with 1 market (i.e., resulting in an SMP)
2. Event with 2 or more markets (i.e., resulting in an GMP)
# Example
* **\[Event]** Where will Barron Trump attend College?
* **\[Market]** Will Barron attend Georgetown?
* **\[Market]** Will Barron attend NYU?
* **\[Market]** Will Barron attend UPenn?
* **\[Market]** Will Barron attend Harvard?
* **\[Market]** Will Barron attend another college?
@@ -0,0 +1,11 @@
> ## 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.
# null
All market data necessary for market resolution is available on-chain (ie ancillaryData in UMA 00 request), but Polymarket also provides a hosted service, Gamma, that indexes this data and provides additional market metadata (ie categorization, indexed volume, etc). This service is made available through a REST API. For public users, this resource read only and can be used to fetch useful information about markets for things like non-profit research projects, alternative trading interfaces, automated trading systems etc.
# Endpoint
[https://gamma-api.polymarket.com](https://gamma-api.polymarket.com)
+166
View File
@@ -0,0 +1,166 @@
> ## 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.
# Data Feeds
> Real-time and historical data sources for market makers
## Overview
Market makers need fast, reliable data to price markets and manage inventory. Polymarket provides several data feeds at different latency and detail levels.
| Feed | Latency | Use Case | Access |
| --------- | ---------- | ------------------------- | ------ |
| WebSocket | \~100ms | Standard MM operations | Public |
| Gamma API | \~1s | Market metadata, indexing | Public |
| Onchain | Block time | Settlement, resolution | Public |
## WebSocket Feeds
The WebSocket API provides real-time market data with low latency. This is sufficient for most market making strategies.
### Connecting
```typescript theme={null}
const ws = new WebSocket("wss://ws-subscriptions-clob.polymarket.com/ws/market");
ws.onopen = () => {
// Subscribe to orderbook updates
ws.send(JSON.stringify({
type: "market",
assets_ids: [tokenId]
}));
};
ws.onmessage = (event) => {
const data = JSON.parse(event.data);
// Handle orderbook update
};
```
### Available Channels
| Channel | Message Types | Documentation |
| -------- | ------------------------------------------ | ----------------------------------------------------------- |
| `market` | `book`, `price_change`, `last_trade_price` | [Market Channel](/developers/CLOB/websocket/market-channel) |
| `user` | Order fills, cancellations | [User Channel](/developers/CLOB/websocket/user-channel) |
### User Channel (Authenticated)
Monitor your order activity in real-time:
```typescript theme={null}
// Requires authentication
const userWs = new WebSocket("wss://ws-subscriptions-clob.polymarket.com/ws/user");
userWs.onopen = () => {
userWs.send(JSON.stringify({
type: "user",
auth: {
apiKey: "your-api-key",
secret: "your-secret",
passphrase: "your-passphrase"
},
markets: [conditionId] // Optional: filter to specific markets
}));
};
userWs.onmessage = (event) => {
const data = JSON.parse(event.data);
// Handle order fills, cancellations, etc.
};
```
See [WebSocket Authentication](/developers/CLOB/websocket/wss-auth) for auth details.
### Best Practices
1. **Reconnection logic** - Implement automatic reconnection with exponential backoff
2. **Heartbeats** - Respond to ping messages to maintain connection
3. **Local orderbook** - Maintain a local copy and apply incremental updates
4. **Sequence numbers** - Track sequence to detect missed messages
See [WebSocket Overview](/developers/CLOB/websocket/wss-overview) for complete documentation.
## Gamma API
The Gamma API provides market metadata and indexing. Use it for:
* Market titles, slugs, categories
* Event/condition mapping
* Volume and liquidity data
* Outcome token metadata
### Get Markets
```typescript theme={null}
const response = await fetch(
"https://gamma-api.polymarket.com/markets?active=true"
);
const markets = await response.json();
```
### Get Events
```typescript theme={null}
const response = await fetch(
"https://gamma-api.polymarket.com/events?slug=us-presidential-election"
);
const event = await response.json();
```
### Key Fields for MMs
| Field | Description |
| --------------- | ------------------------ |
| `conditionId` | Unique market identifier |
| `clobTokenIds` | Outcome token IDs |
| `outcomes` | Outcome names |
| `outcomePrices` | Current outcome prices |
| `volume` | Trading volume |
| `liquidity` | Current liquidity |
See [Gamma API Overview](/developers/gamma-markets-api/overview) for complete documentation.
## Onchain Data
For settlement, resolution, and position tracking, market makers may query onchain data directly.
### Data Sources
| Data | Source | Use Case |
| -------------------- | ------------------- | ---------------------------- |
| Token balances | ERC1155 `balanceOf` | Position tracking |
| Resolution | UMA Oracle events | Pre-resolution risk modeling |
| Condition resolution | CTF contract | Post-resolution redemption |
### RPC Providers
Common providers for Polygon:
* Alchemy
* QuickNode
* Infura
### UMA Oracle
Markets are resolved via UMA's Optimistic Oracle. Monitor resolution events for risk management.
See [Resolution](/developers/resolution/UMA) for details on the resolution process.
## Related Documentation
<CardGroup cols={3}>
<Card title="WebSocket Overview" icon="plug" href="/developers/CLOB/websocket/wss-overview">
Complete WebSocket documentation
</Card>
<Card title="Gamma API" icon="database" href="/developers/gamma-markets-api/overview">
Market metadata and indexing
</Card>
<Card title="Resolution" icon="gavel" href="/developers/resolution/UMA">
UMA Oracle resolution process
</Card>
</CardGroup>
@@ -0,0 +1,76 @@
> ## 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.
# Market Maker Introduction
> Overview of market making on Polymarket and available tools for liquidity providers
## What is a Market Maker?
A Market Maker (MM) on Polymarket is a sophisticated trader who provides liquidity to prediction markets by continuously posting bid and ask orders. By "laying the spread," market makers enable other users to trade efficiently while earning the spread as compensation for the risk they take.
Market makers are essential to Polymarket's ecosystem:
* **Provide liquidity** across all markets
* **Tighten spreads** for better user experience
* **Enable price discovery** through continuous quoting
* **Absorb trading flow** from retail and institutional users
**Not a Market Maker?** If you're building an application that routes orders for your
users, see the [Builders Program](/developers/builders/builder-intro) instead. Builders
get access to gasless transactions via the Relayer Client.
## Getting Started
To become a market maker on Polymarket:
1. **Complete setup** - Deploy wallets, fund with USDCe, set token approvals
2. **Connect to data feeds** - WebSocket for orderbook, RTDS for low-latency data
3. **Start quoting** - Post orders via CLOB REST API
## Available Tools
### By Action Type
<CardGroup cols={2}>
<Card title="Setup" icon="gear" href="/developers/market-makers/setup">
Deposits, token approvals, wallet deployment, API keys
</Card>
<Card title="Trading" icon="chart-line" href="/developers/market-makers/trading">
CLOB order entry, order types, quoting best practices
</Card>
<Card title="Data Feeds" icon="database" href="/developers/market-makers/data-feeds">
WebSocket, RTDS, Gamma API, on-chain data
</Card>
<Card title="Inventory Management" icon="boxes-stacked" href="/developers/market-makers/inventory">
Split, merge, and redeem outcome tokens
</Card>
<Card title="Liquidity Rewards" icon="gift" href="/developers/market-makers/liquidity-rewards">
Earn rewards for providing liquidity
</Card>
<Card title="Maker Rebates Program" icon="gift" href="/developers/market-makers/maker-rebates-program">
Earn rebates for providing liquidity
</Card>
</CardGroup>
## Quick Reference
| Action | Tool | Documentation |
| --------------------- | -------------- | ------------------------------------------------------------- |
| Deposit USDCe | Bridge API | [Bridge Overview](/developers/misc-endpoints/bridge-overview) |
| Approve tokens | Relayer Client | [Setup Guide](/developers/market-makers/setup) |
| Post limit orders | CLOB REST API | [CLOB Client](/developers/CLOB/clients/methods-l2) |
| Monitor orderbook | WebSocket | [WebSocket Overview](/developers/CLOB/websocket/wss-overview) |
| Low-latency data | RTDS | [Data Feeds](/developers/market-makers/data-feeds) |
| Split USDCe to tokens | CTF / Relayer | [Inventory](/developers/market-makers/inventory) |
| Merge tokens to USDCe | CTF / Relayer | [Inventory](/developers/market-makers/inventory) |
## Support
For market maker onboarding and support, contact [support@polymarket.com](mailto:support@polymarket.com).
+247
View File
@@ -0,0 +1,247 @@
> ## 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.
# Inventory Management
> Split, merge, and redeem outcome tokens for market making
## Overview
Market makers need to manage their inventory of outcome tokens. This involves:
1. **Splitting** USDCe into YES/NO tokens to have inventory to quote
2. **Merging** tokens back to USDCe to reduce exposure
3. **Redeeming** winning tokens after market resolution
All these operations use the Conditional Token Framework (CTF) contract, typically via the Relayer Client for gasless execution.
<Note>
These examples assume you have initialized a RelayClient. See [Setup](/developers/market-makers/setup) for client initialization.
</Note>
## Splitting USDCe into Tokens
Split 1 USDCe into 1 YES + 1 NO token. This creates inventory for quoting both sides.
### Via Relayer Client (Recommended)
```typescript theme={null}
import { ethers } from "ethers";
import { Interface } from "ethers/lib/utils";
import { RelayClient, Transaction } from "@polymarket/builder-relayer-client";
const CTF_ADDRESS = "0x4d97dcd97ec945f40cf65f87097ace5ea0476045";
const USDCe_ADDRESS = "0x2791Bca1f2de4661ED88A30C99A7a9449Aa84174";
const ctfInterface = new Interface([
"function splitPosition(address collateralToken, bytes32 parentCollectionId, bytes32 conditionId, uint[] partition, uint amount)"
]);
// Split $1000 USDCe into YES/NO tokens
const amount = ethers.utils.parseUnits("1000", 6); // USDCe has 6 decimals
const splitTx: Transaction = {
to: CTF_ADDRESS,
data: ctfInterface.encodeFunctionData("splitPosition", [
USDCe_ADDRESS, // collateralToken
ethers.constants.HashZero, // parentCollectionId (null for Polymarket)
conditionId, // conditionId from market
[1, 2], // partition: [YES, NO]
amount
]),
value: "0"
};
const response = await client.execute([splitTx], "Split USDCe into tokens");
const result = await response.wait();
console.log("Split completed:", result?.transactionHash);
```
### Result
After splitting 1000 USDCe:
* Receive 1000 YES tokens
* Receive 1000 NO tokens
* USDCe balance decreases by 1000
## Merging Tokens to USDCe
Merge equal amounts of YES + NO tokens back into USDCe. Useful for:
* Reducing inventory
* Exiting a market
* Converting profits to USDCe
### Via Relayer Client
```typescript theme={null}
const ctfInterface = new Interface([
"function mergePositions(address collateralToken, bytes32 parentCollectionId, bytes32 conditionId, uint[] partition, uint amount)"
]);
// Merge 500 YES + 500 NO back to 500 USDCe
const amount = ethers.utils.parseUnits("500", 6);
const mergeTx: Transaction = {
to: CTF_ADDRESS,
data: ctfInterface.encodeFunctionData("mergePositions", [
USDCe_ADDRESS,
ethers.constants.HashZero,
conditionId,
[1, 2],
amount
]),
value: "0"
};
const response = await client.execute([mergeTx], "Merge tokens to USDCe");
await response.wait();
```
### Result
After merging 500 of each:
* YES tokens decrease by 500
* NO tokens decrease by 500
* USDCe balance increases by 500
## Redeeming After Resolution
After a market resolves, redeem winning tokens for USDCe.
### Check Resolution Status
```typescript theme={null}
// Via CLOB API
const market = await clobClient.getMarket(conditionId);
if (market.closed) {
// Market is resolved
const winningToken = market.tokens.find(t => t.winner);
console.log("Winning outcome:", winningToken?.outcome);
}
```
### Redeem Winning Tokens
```typescript theme={null}
const ctfInterface = new Interface([
"function redeemPositions(address collateralToken, bytes32 parentCollectionId, bytes32 conditionId, uint[] indexSets)"
]);
const redeemTx: Transaction = {
to: CTF_ADDRESS,
data: ctfInterface.encodeFunctionData("redeemPositions", [
USDCe_ADDRESS,
ethers.constants.HashZero,
conditionId,
[1, 2] // Redeem both YES and NO (only winners pay out)
]),
value: "0"
};
const response = await client.execute([redeemTx], "Redeem winning tokens");
await response.wait();
```
### Payout
* If YES wins: Each YES token redeems for \$1 USDCe
* If NO wins: Each NO token redeems for \$1 USDCe
* Losing tokens are worthless (redeem for \$0)
## Negative Risk Markets
Multi-outcome markets use the Negative Risk CTF Exchange. The split/merge process is similar but uses different contract addresses.
```typescript theme={null}
const NEG_RISK_ADAPTER = "0xd91E80cF2E7be2e162c6513ceD06f1dD0dA35296";
const NEG_RISK_CTF_EXCHANGE = "0xC5d563A36AE78145C45a50134d48A1215220f80a";
```
See [Negative Risk Overview](/developers/neg-risk/overview) for details.
## Inventory Strategies
### Pre-market Preparation
Before quoting a market:
1. Check market metadata via Gamma API
2. Split sufficient USDCe to cover expected quoting size
3. Set token approvals if not already done
### During Trading
Monitor inventory and adjust:
* Skew quotes when inventory is imbalanced
* Merge excess tokens to free up capital
* Split more when inventory runs low
### Post-Resolution
After market closes:
1. Cancel all open orders
2. Wait for resolution
3. Redeem winning tokens
4. Merge any remaining pairs
## Batch Operations
For efficiency, batch multiple operations:
```typescript theme={null}
const transactions: Transaction[] = [
// Split on Market A
{
to: CTF_ADDRESS,
data: ctfInterface.encodeFunctionData("splitPosition", [
USDCe_ADDRESS,
ethers.constants.HashZero,
conditionIdA,
[1, 2],
ethers.utils.parseUnits("1000", 6)
]),
value: "0"
},
// Split on Market B
{
to: CTF_ADDRESS,
data: ctfInterface.encodeFunctionData("splitPosition", [
USDCe_ADDRESS,
ethers.constants.HashZero,
conditionIdB,
[1, 2],
ethers.utils.parseUnits("1000", 6)
]),
value: "0"
}
];
const response = await client.execute(transactions, "Batch inventory setup");
await response.wait();
```
## Related Documentation
<CardGroup cols={2}>
<Card title="CTF Overview" icon="coins" href="/developers/CTF/overview">
Conditional Token Framework basics
</Card>
<Card title="Split Positions" icon="code-branch" href="/developers/CTF/split">
Detailed split documentation
</Card>
<Card title="Merge Positions" icon="code-merge" href="/developers/CTF/merge">
Detailed merge documentation
</Card>
<Card title="Relayer Client" icon="paper-plane" href="/developers/builders/relayer-client">
Gasless transaction execution
</Card>
</CardGroup>

Some files were not shown because too many files have changed in this diff Show More