jpskill.com
🛠️ 開発・MCP コミュニティ

polymarket-api

PolymarketのCLOB API、Gamma API、オンチェーンデータを活用し、取引機能の構築、市場データの取得、注文執行の実装などをスムーズに行えるように支援するSkill。

📜 元の英語説明(参考)

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.

🇯🇵 日本人クリエイター向け解説

一言でいうと

PolymarketのCLOB API、Gamma API、オンチェーンデータを活用し、取引機能の構築、市場データの取得、注文執行の実装などをスムーズに行えるように支援するSkill。

※ jpskill.com 編集部が日本のビジネス現場向けに補足した解説です。Skill本体の挙動とは独立した参考情報です。

⚡ おすすめ: コマンド1行でインストール(60秒)

下記のコマンドをコピーしてターミナル(Mac/Linux)または PowerShell(Windows)に貼り付けてください。 ダウンロード → 解凍 → 配置まで全自動。

🍎 Mac / 🐧 Linux
mkdir -p ~/.claude/skills && cd ~/.claude/skills && curl -L -o polymarket-api.zip https://jpskill.com/download/10200.zip && unzip -o polymarket-api.zip && rm polymarket-api.zip
🪟 Windows (PowerShell)
$d = "$env:USERPROFILE\.claude\skills"; ni -Force -ItemType Directory $d | Out-Null; iwr https://jpskill.com/download/10200.zip -OutFile "$d\polymarket-api.zip"; Expand-Archive "$d\polymarket-api.zip" -DestinationPath $d -Force; ri "$d\polymarket-api.zip"

完了後、Claude Code を再起動 → 普通に「動画プロンプト作って」のように話しかけるだけで自動発動します。

💾 手動でダウンロードしたい(コマンドが難しい人向け)
  1. 1. 下の青いボタンを押して polymarket-api.zip をダウンロード
  2. 2. ZIPファイルをダブルクリックで解凍 → polymarket-api フォルダができる
  3. 3. そのフォルダを C:\Users\あなたの名前\.claude\skills\(Win)または ~/.claude/skills/(Mac)へ移動
  4. 4. Claude Code を再起動

⚠️ ダウンロード・利用は自己責任でお願いします。当サイトは内容・動作・安全性について責任を負いません。

🎯 このSkillでできること

下記の説明文を読むと、このSkillがあなたに何をしてくれるかが分かります。Claudeにこの分野の依頼をすると、自動で発動します。

📦 インストール方法 (3ステップ)

  1. 1. 上の「ダウンロード」ボタンを押して .skill ファイルを取得
  2. 2. ファイル名の拡張子を .skill から .zip に変えて展開(macは自動展開可)
  3. 3. 展開してできたフォルダを、ホームフォルダの .claude/skills/ に置く
    • · macOS / Linux: ~/.claude/skills/
    • · Windows: %USERPROFILE%\.claude\skills\

Claude Code を再起動すれば完了。「このSkillを使って…」と話しかけなくても、関連する依頼で自動的に呼び出されます。

詳しい使い方ガイドを見る →
最終更新
2026-05-18
取得日時
2026-05-18
同梱ファイル
1

📖 Skill本文(日本語訳)

※ 原文(英語/中国語)を Gemini で日本語化したものです。Claude 自身は原文を読みます。誤訳がある場合は原文をご確認ください。

Polymarket API 連携スキル

概要

このスキルは、Polymarket の API およびスマートコントラクトとの連携に関する包括的なガイダンスを提供します。

API エンドポイント

CLOB API (Central Limit Order Book)

ベース URL: https://clob.polymarket.com

認証レベル

  • レベル 0 (Public): マーケットデータ、オーダーブック、価格
  • レベル 1 (Signer): API キーの作成/派生
  • レベル 2 (Authenticated): 取引、注文、ポジション

主要なエンドポイント

GET  /markets              # すべてのマーケットをリスト表示
GET  /markets/{token_id}   # 特定のマーケットを取得
GET  /price?token_id=X     # 現在の価格を取得
GET  /midpoint?token_id=X  # 中間価格を取得
GET  /book?token_id=X      # オーダーブックを取得
GET  /trades               # ユーザーの取引を取得
POST /order                # 注文を出す
DELETE /order/{id}         # 注文をキャンセル
GET  /positions            # ポジションを取得

Gamma API (マーケットメタデータ)

ベース URL: https://gamma-api.polymarket.com

GET /events              # イベントをリスト表示
GET /events/{slug}       # イベントの詳細を取得
GET /markets             # マーケットをリスト表示
GET /markets/{id}        # マーケットの詳細を取得

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:
        """包括的なマーケットデータを取得します。"""
        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:
        """指値注文を出します。"""
        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 サブスクリプション

import asyncio
import websockets
import json

async def subscribe_market_updates(token_ids: list[str]):
    """リアルタイムのマーケットアップデートをサブスクライブします。"""
    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 クライアント

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]:
        """すべてのアクティブなマーケットを取得します。"""
        response = await self.client.get("/markets", params={"active": True})
        return response.json()

    async def get_event(self, slug: str) -> dict:
        """すべてのマーケットを含むイベントを取得します。"""
        response = await self.client.get(f"/events/{slug}")
        return response.json()

注文タイプ

  • GTC (Good Till Cancelled): 約定またはキャンセルされるまで有効
  • GTD (Good Till Date): 指定された時間に失効
  • FOK (Fill or Kill): 全量を約定させるか、キャンセルする必要がある
  • IOC (Immediate or Cancel): 約定可能な量を約定させ、残りをキャンセル

価格計算

def calculate_implied_probability(price: float) -> float:
    """価格をインプライド・プロバビリティに変換します。"""
    return price  # 価格は確率 (0-1) です

def calculate_cost(price: float, shares: float) -> float:
    """株式を購入するためのコストを計算します。"""
    return price * shares

def calculate_pnl(
    entry_price: float,
    current_price: float,
    shares: float,
    side: str
) -> float:
    """未実現の P&L を計算します。"""
    if side == "BUY":
        return (current_price - entry_price) * shares
    return (entry_price - current_price) * shares

エラー処理

from py_clob_client.exceptions import PolymarketException

try:
    result = client.post_order(order)
except PolymarketException as e:
    if "INSUFFICIENT_BALANCE" in str(e):
        # 資金不足を処理
        pass
    elif "INVALID_PRICE" in str(e):
        # 価格が範囲外の場合を処理
        pass
    raise

レート制限

  • パブリックエンドポイント: ~100 リクエスト/分
  • 認証済みエンドポイント: ~1000 リクエスト/分
  • WebSocket: サブスクリプションタイプによって異なります

常に指数バックオフとリクエストキューイングを実装してください。

主要なコントラクトアドレス (Polygon)

CONTRACTS = {
    "CTF_EXCHANGE": "0x4bFb41d5B3570DeFd03C39a9A4D8dE6Bd8B8982E",
    "NEG_RISK_CTF_EXCHANGE": "0xC5d563A36AE78145C45a50134d48A1215220f80a",
    "CONDITIONAL_TOKENS": "0x4D97DCd97eC945f40cF65F87097ACe5EA0476045",
    "USDC": "0x2791Bca1f2de4661ED88A30C99A7a9449Aa84174",
}
📜 原文 SKILL.md(Claudeが読む英語/中国語)を展開

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": "0xC5d563A36AE78145C45a50134d48A1215220f80a",
    "CONDITIONAL_TOKENS": "0x4D97DCd97eC945f40cF65F87097ACe5EA0476045",
    "USDC": "0x2791Bca1f2de4661ED88A30C99A7a9449Aa84174",
}