polymarket-api
Deep integration guide for Polymarket's CLOB API, Gamma API, and on-chain data. Use when building trading functionality, fetching market data, or implementing order execution.
Best use case
polymarket-api is best used when you need a repeatable AI agent workflow instead of a one-off prompt.
Deep integration guide for Polymarket's CLOB API, Gamma API, and on-chain data. Use when building trading functionality, fetching market data, or implementing order execution.
Teams using polymarket-api should expect a more consistent output, faster repeated execution, less prompt rewriting.
When to use this skill
- You want a reusable workflow that can be run more than once with consistent structure.
When not to use this skill
- You only need a quick one-off answer and do not need a reusable workflow.
- You cannot install or maintain the underlying files, dependencies, or repository context.
Installation
Claude Code / Cursor / Codex
Manual Installation
- Download SKILL.md from GitHub
- Place it in
.claude/skills/polymarket-api/SKILL.mdinside your project - Restart your AI agent — it will auto-discover the skill
How polymarket-api Compares
| Feature / Agent | polymarket-api | Standard Approach |
|---|---|---|
| Platform Support | Not specified | Limited / Varies |
| Context Awareness | High | Baseline |
| Installation Complexity | Unknown | N/A |
Frequently Asked Questions
What does this skill do?
Deep integration guide for Polymarket's CLOB API, Gamma API, and on-chain data. Use when building trading functionality, fetching market data, or implementing order execution.
Where can I find the source code?
You can find the source code on GitHub using the link provided at the top of the page.
SKILL.md Source
# Polymarket API Integration Skill
## Overview
This skill provides comprehensive guidance for integrating with Polymarket's APIs and smart contracts.
## API Endpoints
### CLOB API (Central Limit Order Book)
Base URL: `https://clob.polymarket.com`
#### Authentication Levels
- **Level 0 (Public)**: Market data, orderbooks, prices
- **Level 1 (Signer)**: Create/derive API keys
- **Level 2 (Authenticated)**: Trading, orders, positions
#### 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 positions
```
### Gamma API (Market Metadata)
Base URL: `https://gamma-api.polymarket.com`
```
GET /events # List events
GET /events/{slug} # Get event details
GET /markets # List markets
GET /markets/{id} # Get market details
```
## Python Implementation Patterns
### 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)
```
### WebSocket Subscription
```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 data
```
### Gamma API Client
```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
## 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) * shares
```
## Error 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
raise
```
## Rate Limits
- Public endpoints: ~100 requests/minute
- Authenticated endpoints: ~1000 requests/minute
- WebSocket: Varies by subscription type
Always implement exponential backoff and request queuing.
## Key Contract Addresses (Polygon)
```python
CONTRACTS = {
"CTF_EXCHANGE": "0x4bFb41d5B3570DeFd03C39a9A4D8dE6Bd8B8982E",
"NEG_RISK_CTF_EXCHANGE": "0xC5d563A36AE78145C45a50134d48A1215220f80a",
"CONDITIONAL_TOKENS": "0x4D97DCd97eC945f40cF65F87097ACe5EA0476045",
"USDC": "0x2791Bca1f2de4661ED88A30C99A7a9449Aa84174",
}
```Related Skills
polymarket-skill
> Polymarket 预测市场交易——预测市场数据分析与交易策略
polymarket-profit
围绕 Polymarket 预测市场执行小资金量化交易与收益跟踪策略。
polymarket-copy-tracker
Analyze top Polymarket traders for copy trading. Use when asked to find best traders to copy, analyze trader performance/history, evaluate wallet PnL, discover high-ROI wallets, or research trader win rates on Polymarket. Supports Dune analytics, Polymarket Data API, and automated scoring.
wemp-operator
> 微信公众号全功能运营——草稿/发布/评论/用户/素材/群发/统计/菜单/二维码 API 封装
zsxq-smart-publish
Publish and manage content on 知识星球 (zsxq.com). Supports talk posts, Q&A, long articles, file sharing, digest/bookmark, homework tasks, and tag management. Use when publishing content to 知识星球, creating/editing posts, uploading files/images/audio, managing digests, batch publishing, or formatting content for 知识星球.
zoom-automation
Automate Zoom meeting creation, management, recordings, webinars, and participant tracking via Rube MCP (Composio). Always search tools first for current schemas.
zoho-crm-automation
Automate Zoho CRM tasks via Rube MCP (Composio): create/update records, search contacts, manage leads, and convert leads. Always search tools first for current schemas.
ziliu-publisher
字流(Ziliu) - AI驱动的多平台内容分发工具。用于一次创作、智能适配排版、一键分发到16+平台(公众号/知乎/小红书/B站/抖音/微博/X等)。当用户需要多平台发布、内容排版、格式适配时使用。触发词:字流、ziliu、多平台发布、一键分发、内容分发、排版发布。
zhihu-post-skill
> 知乎文章发布——知乎平台内容创作与发布自动化
zendesk-automation
Automate Zendesk tasks via Rube MCP (Composio): tickets, users, organizations, replies. Always search tools first for current schemas.
youtube-knowledge-extractor
This skill performs deep analysis of YouTube videos through **both information channels** Multimodal YouTube video analysis through both audio (transcript) and visual (frame extraction + image analysis) channels. Especially powerful for HowTo videos, tutorials, demos, and explainer videos where what is SHOWN (screenshots, UI demos, diagrams, code, physical actions) is just as important as what is SAID. Use this skill whenever a user wants to analyze, summarize, or create step-by-step guides from YouTube videos, or when they share a YouTube URL and want to understand what happens in the video. Triggers on requests like "Analyze this YouTube video", "Create a step-by-step guide from this video", "What does this video show?", "Summarize this tutorial", or any YouTube URL shared with analysis intent.
youtube-factory
Generate complete YouTube videos from a single prompt - script, voiceover, stock footage, captions, thumbnail. Self-contained, no external modules. 100% free tools.