polymarket-api

agentmc15/polymarket-trader · updated May 19, 2026

MDX-style export adds YAML metadata + attribution linking explainx.ai and this canonical listing URL.

$npx skills add https://github.com/agentmc15/polymarket-trader --skill polymarket-api
0 commentsdiscussion
summary

Complete integration guide for Polymarket's CLOB and Gamma APIs with order execution and market data.

  • Covers three authentication levels (public market data, signer key derivation, authenticated trading) with endpoints for orderbooks, pricing, positions, and order management
  • Includes Python client patterns for market data fetching, limit order placement, WebSocket subscriptions, and real-time updates via py_clob_client library
  • Supports four order types (GTC, GTD, FOK, IOC) with price
skill.md

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

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

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

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

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

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)

CONTRACTS = {
    "CTF_EXCHANGE": "0x4bFb41d5B3570DeFd03C39a9A4D8dE6Bd8B8982E",
    "NEG_RISK_CTF_EXCHANGE": "0xC5d563A36AE7814
how to use polymarket-api

How to use polymarket-api on Cursor

AI-first code editor with Composer

1

Prerequisites

Before installing skills in Cursor, ensure your development environment meets these requirements:

  • Cursor installed and configured on your development machine
  • Node.js version 16.0+ with npm package manager (verify with node --version)
  • Active project directory or workspace where you want to add polymarket-api
2

Execute installation command

Execute the skills CLI command in your project's root directory to begin installation:

$npx skills add https://github.com/agentmc15/polymarket-trader --skill polymarket-api

The skills CLI fetches polymarket-api from GitHub repository agentmc15/polymarket-trader and configures it for Cursor.

3

Select Cursor when prompted

The CLI will show a list of available agents. Use arrow keys to navigate and space to select Cursor:

◆ Which agents do you want to install to?
│ ── Universal (.agents/skills) ── always included ────
│ • Amp
│ • Antigravity
│ • Cline
│ • Codex
│ ●Cursor(selected)
│ • Cursor
│ • Windsurf
4

Verify installation

Confirm successful installation by checking the skill directory location:

.cursor/skills/polymarket-api

Reload or restart Cursor to activate polymarket-api. Access the skill through slash commands (e.g., /polymarket-api) or your agent's skill management interface.

Security & Verification Notice

We perform automated surface-level scans (Gen AI Scanner, Socket, Snyk) during installation. These checks detect common vulnerabilities but do not guarantee complete security. Always review skill source code and verify the publisher's reputation before production use.

Skills execute code in your development environment. Always verify the publisher's identity, review recent commits, and test in isolated environments before production deployment.

List & Monetize Your Skill

Submit your Claude Code skill and start earning

GET_STARTED →

Use Cases

Task Automation & Efficiency

Automate repetitive workflows and reduce manual effort

Example

Generate reports, summarize documents, draft communications

Save 3-5 hours per week on routine tasks

Knowledge Enhancement

Learn new skills, understand complex topics, get expert guidance

Example

Explain concepts, provide examples, suggest learning resources

Accelerate learning and skill development by 2x

Quality Improvement

Enhance output quality through reviews, suggestions, and refinements

Example

Review drafts, suggest improvements, catch errors

Improve work quality by 30-40% with less effort

Implementation Guide

Prerequisites

  • Claude Desktop or compatible AI client with skill support
  • Clear understanding of task or problem to solve
  • Willingness to iterate and refine outputs

Time Estimate

15-45 minutes depending on use case complexity

Installation Steps

  1. 1.Install skill using provided installation command
  2. 2.Test with simple use case relevant to your work
  3. 3.Evaluate output quality and relevance
  4. 4.Iterate on prompts to improve results
  5. 5.Integrate into regular workflow if valuable

Common Pitfalls

  • Expecting perfect results without iteration
  • Not providing enough context in prompts
  • Using skill for tasks outside its intended scope
  • Accepting outputs without review and validation

Best Practices

✓ Do

  • +Start with clear, specific prompts
  • +Provide relevant context and constraints
  • +Review and refine all outputs before using
  • +Iterate to improve output quality
  • +Document successful prompt patterns

✗ Don't

  • Don't use without understanding skill limitations
  • Don't skip validation of outputs
  • Don't share sensitive information in prompts
  • Don't expect skill to replace human judgment

💡 Pro Tips

  • Be specific about desired format and style
  • Ask for multiple options to choose from
  • Request explanations to understand reasoning
  • Combine AI efficiency with human expertise

When to Use This

✓ Use When

Use when skill capabilities match your task, clear ROI on time saved, and you can validate outputs. Best for repetitive tasks, learning, and quality improvement.

✗ Avoid When

Avoid when task requires deep expertise you can't validate, involves sensitive decisions, or when learning process is more valuable than speed of completion.

Learning Path

  1. 1Familiarize yourself with skill capabilities and limitations
  2. 2Start with low-risk, non-critical tasks
  3. 3Progress to more complex and valuable use cases
  4. 4Build expertise through regular use and experimentation

Discussion

Product Hunt–style comments (not star reviews)
  • No comments yet — start the thread.
general reviews

Ratings

4.649 reviews
  • Yusuf Sanchez· Dec 24, 2024

    polymarket-api fits our agent workflows well — practical, well scoped, and easy to wire into existing repos.

  • Arya Torres· Dec 8, 2024

    Registry listing for polymarket-api matched our evaluation — installs cleanly and behaves as described in the markdown.

  • Ganesh Mohane· Dec 4, 2024

    Useful defaults in polymarket-api — fewer surprises than typical one-off scripts, and it plays nicely with `npx skills` flows.

  • Yusuf Perez· Dec 4, 2024

    I recommend polymarket-api for anyone iterating fast on agent tooling; clear intent and a small, reviewable surface area.

  • Sakshi Patil· Nov 23, 2024

    polymarket-api is among the better-maintained entries we tried; worth keeping pinned for repeat workflows.

  • Naina Mensah· Nov 23, 2024

    Keeps context tight: polymarket-api is the kind of skill you can hand to a new teammate without a long onboarding doc.

  • Evelyn Kim· Nov 15, 2024

    polymarket-api has been reliable in day-to-day use. Documentation quality is above average for community skills.

  • James Johnson· Nov 11, 2024

    Registry listing for polymarket-api matched our evaluation — installs cleanly and behaves as described in the markdown.

  • Yash Thakker· Nov 3, 2024

    Registry listing for polymarket-api matched our evaluation — installs cleanly and behaves as described in the markdown.

  • Dhruvi Jain· Oct 22, 2024

    polymarket-api reduced setup friction for our internal harness; good balance of opinion and flexibility.

showing 1-10 of 49

1 / 5