polymarket-api
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
ChinesePolymarket API Integration Skill
Polymarket API集成指南
Overview
概述
This skill provides comprehensive guidance for integrating with Polymarket's APIs and smart contracts.
本技能提供了与Polymarket的API及智能合约集成的全面指导。
API Endpoints
API端点
CLOB API (Central Limit Order Book)
CLOB API(中央限价订单簿)
Base URL:
https://clob.polymarket.com基础URL:
https://clob.polymarket.comAuthentication Levels
认证级别
- Level 0 (Public): Market data, orderbooks, prices
- Level 1 (Signer): Create/derive API keys
- Level 2 (Authenticated): Trading, orders, positions
- Level 0(公开):市场数据、订单簿、价格
- Level 1(签名者):创建/派生API密钥
- Level 2(已认证):交易、订单、持仓
Key Endpoints
核心端点
GET /markets # List all markets
GET /markets/{token_id} # Get specific market
GET /price?token_id=X # Get current price
GET /midpoint?token_id=X # Get midpoint price
GET /book?token_id=X # Get orderbook
GET /trades # Get user trades
POST /order # Place order
DELETE /order/{id} # Cancel order
GET /positions # Get positionsGET /markets # List all markets
GET /markets/{token_id} # Get specific market
GET /price?token_id=X # Get current price
GET /midpoint?token_id=X # Get midpoint price
GET /book?token_id=X # Get orderbook
GET /trades # Get user trades
POST /order # Place order
DELETE /order/{id} # Cancel order
GET /positions # Get positionsGamma API (Market Metadata)
Gamma API(市场元数据)
Base URL:
https://gamma-api.polymarket.comGET /events # List events
GET /events/{slug} # Get event details
GET /markets # List markets
GET /markets/{id} # Get market details基础URL:
https://gamma-api.polymarket.comGET /events # List events
GET /events/{slug} # Get event details
GET /markets # List markets
GET /markets/{id} # Get market detailsPython Implementation Patterns
Python实现模式
Initialize Client
初始化客户端
python
from py_clob_client.client import ClobClient
from py_clob_client.clob_types import OrderArgs, OrderType
import os
class PolymarketService:
def __init__(self):
self.client = ClobClient(
host="https://clob.polymarket.com",
key=os.getenv("POLYMARKET_PRIVATE_KEY"),
chain_id=137,
signature_type=1,
funder=os.getenv("POLYMARKET_FUNDER_ADDRESS")
)
self.client.set_api_creds(
self.client.create_or_derive_api_creds()
)
async def get_market_data(self, token_id: str) -> dict:
"""Fetch comprehensive market data."""
return {
"price": self.client.get_price(token_id, "BUY"),
"midpoint": self.client.get_midpoint(token_id),
"book": self.client.get_order_book(token_id),
"spread": self.client.get_spread(token_id),
}
async def place_order(
self,
token_id: str,
side: str,
price: float,
size: float,
order_type: str = "GTC"
) -> dict:
"""Place a limit order."""
order = self.client.create_order(
OrderArgs(
token_id=token_id,
price=price,
size=size,
side=side,
)
)
return self.client.post_order(order, order_type)python
from py_clob_client.client import ClobClient
from py_clob_client.clob_types import OrderArgs, OrderType
import os
class PolymarketService:
def __init__(self):
self.client = ClobClient(
host="https://clob.polymarket.com",
key=os.getenv("POLYMARKET_PRIVATE_KEY"),
chain_id=137,
signature_type=1,
funder=os.getenv("POLYMARKET_FUNDER_ADDRESS")
)
self.client.set_api_creds(
self.client.create_or_derive_api_creds()
)
async def get_market_data(self, token_id: str) -> dict:
"""Fetch comprehensive market data."""
return {
"price": self.client.get_price(token_id, "BUY"),
"midpoint": self.client.get_midpoint(token_id),
"book": self.client.get_order_book(token_id),
"spread": self.client.get_spread(token_id),
}
async def place_order(
self,
token_id: str,
side: str,
price: float,
size: float,
order_type: str = "GTC"
) -> dict:
"""Place a limit order."""
order = self.client.create_order(
OrderArgs(
token_id=token_id,
price=price,
size=size,
side=side,
)
)
return self.client.post_order(order, order_type)WebSocket Subscription
WebSocket订阅
python
import asyncio
import websockets
import json
async def subscribe_market_updates(token_ids: list[str]):
"""Subscribe to real-time market updates."""
uri = "wss://ws-subscriptions-clob.polymarket.com/ws/market"
async with websockets.connect(uri) as ws:
await ws.send(json.dumps({
"type": "subscribe",
"markets": token_ids
}))
async for message in ws:
data = json.loads(message)
yield datapython
import asyncio
import websockets
import json
async def subscribe_market_updates(token_ids: list[str]):
"""Subscribe to real-time market updates."""
uri = "wss://ws-subscriptions-clob.polymarket.com/ws/market"
async with websockets.connect(uri) as ws:
await ws.send(json.dumps({
"type": "subscribe",
"markets": token_ids
}))
async for message in ws:
data = json.loads(message)
yield dataGamma API Client
Gamma API客户端
python
import httpx
class GammaClient:
BASE_URL = "https://gamma-api.polymarket.com"
def __init__(self):
self.client = httpx.AsyncClient(base_url=self.BASE_URL)
async def get_active_markets(self) -> list[dict]:
"""Fetch all active markets."""
response = await self.client.get("/markets", params={"active": True})
return response.json()
async def get_event(self, slug: str) -> dict:
"""Fetch event with all markets."""
response = await self.client.get(f"/events/{slug}")
return response.json()python
import httpx
class GammaClient:
BASE_URL = "https://gamma-api.polymarket.com"
def __init__(self):
self.client = httpx.AsyncClient(base_url=self.BASE_URL)
async def get_active_markets(self) -> list[dict]:
"""Fetch all active markets."""
response = await self.client.get("/markets", params={"active": True})
return response.json()
async def get_event(self, slug: str) -> dict:
"""Fetch event with all markets."""
response = await self.client.get(f"/events/{slug}")
return response.json()Order Types
订单类型
- GTC (Good Till Cancelled): Stays until filled or cancelled
- GTD (Good Till Date): Expires at specified time
- FOK (Fill or Kill): Must fill entirely or cancel
- IOC (Immediate or Cancel): Fill what's available, cancel rest
- GTC(取消前有效):订单保持有效直至成交或主动取消
- GTD(指定日期前有效):订单在指定时间到期
- FOK(全部成交否则取消):订单必须完全成交,否则立即取消
- IOC(立即成交否则取消):成交当前可用份额,剩余部分取消
Price Calculations
价格计算
python
def calculate_implied_probability(price: float) -> float:
"""Convert price to implied probability."""
return price # Prices ARE probabilities (0-1)
def calculate_cost(price: float, shares: float) -> float:
"""Calculate cost to buy shares."""
return price * shares
def calculate_pnl(
entry_price: float,
current_price: float,
shares: float,
side: str
) -> float:
"""Calculate unrealized P&L."""
if side == "BUY":
return (current_price - entry_price) * shares
return (entry_price - current_price) * sharespython
def calculate_implied_probability(price: float) -> float:
"""Convert price to implied probability."""
return price # Prices ARE probabilities (0-1)
def calculate_cost(price: float, shares: float) -> float:
"""Calculate cost to buy shares."""
return price * shares
def calculate_pnl(
entry_price: float,
current_price: float,
shares: float,
side: str
) -> float:
"""Calculate unrealized P&L."""
if side == "BUY":
return (current_price - entry_price) * shares
return (entry_price - current_price) * sharesError Handling
错误处理
python
from py_clob_client.exceptions import PolymarketException
try:
result = client.post_order(order)
except PolymarketException as e:
if "INSUFFICIENT_BALANCE" in str(e):
# Handle insufficient funds
pass
elif "INVALID_PRICE" in str(e):
# Handle price out of range
pass
raisepython
from py_clob_client.exceptions import PolymarketException
try:
result = client.post_order(order)
except PolymarketException as e:
if "INSUFFICIENT_BALANCE" in str(e):
# Handle insufficient funds
pass
elif "INVALID_PRICE" in str(e):
# Handle price out of range
pass
raiseRate Limits
速率限制
- Public endpoints: ~100 requests/minute
- Authenticated endpoints: ~1000 requests/minute
- WebSocket: Varies by subscription type
Always implement exponential backoff and request queuing.
- 公开端点:约100次请求/分钟
- 已认证端点:约1000次请求/分钟
- WebSocket:根据订阅类型有所不同
请务必实现指数退避和请求排队机制。
Key Contract Addresses (Polygon)
关键合约地址(Polygon链)
python
CONTRACTS = {
"CTF_EXCHANGE": "0x4bFb41d5B3570DeFd03C39a9A4D8dE6Bd8B8982E",
"NEG_RISK_CTF_EXCHANGE": "0xC5d563A36AE78145C45a50134d48A1215220f80a",
"CONDITIONAL_TOKENS": "0x4D97DCd97eC945f40cF65F87097ACe5EA0476045",
"USDC": "0x2791Bca1f2de4661ED88A30C99A7a9449Aa84174",
}python
CONTRACTS = {
"CTF_EXCHANGE": "0x4bFb41d5B3570DeFd03C39a9A4D8dE6Bd8B8982E",
"NEG_RISK_CTF_EXCHANGE": "0xC5d563A36AE78145C45a50134d48A1215220f80a",
"CONDITIONAL_TOKENS": "0x4D97DCd97eC945f40cF65F87097ACe5EA0476045",
"USDC": "0x2791Bca1f2de4661ED88A30C99A7a9449Aa84174",
}