A fully typed SDK and proxy server built with Elysia for Polymarket APIs. This package provides standalone SDK clients, WebSocket real-time streaming, and a proxy server with type-safe endpoints for CLOB and Gamma APIs, featuring comprehensive validation and automatic OpenAPI schema generation. Available in TypeScript, Python, and Go.
any typesunknown/any.This package provides two ways to use Polymarket APIs:
PolymarketSDK: For CLOB operations (requires credentials) — TypeScriptGammaSDK: For Gamma API operations (no credentials required) — TypeScriptDataSDK: For user positions, trades, and activity data — TypeScriptPolymarketWebSocketClient: For real-time market data streaming — TypeScriptGammaClient: Gamma API client — PythonClobClient: CLOB price history client — PythonTradingClient: Order placement and management — PythonPolymarketWebSocket: Async WebSocket for market and user channels — PythonWebSocketClient: For real-time market data streaming — GoRedundantWSPool: Redundant parallel connections with message deduplication — Go/gamma/*) - Market and event data from gamma-api.polymarket.com/clob/*) - Trading and price history from Polymarket CLOB client/data/*) - User positions, trades, and activity datasrc/
├── mod.ts # Main SDK exports (JSR entry point)
├── index.ts # Elysia server entry point
├── client.ts # Proxy client (referenced in JSR)
├── run.ts # Server runner for development
├── sdk/ # Standalone SDK clients
│ ├── index.ts # SDK exports
│ ├── client.ts # PolymarketSDK (CLOB client)
│ ├── gamma-client.ts # GammaSDK (Gamma API client)
│ ├── data-client.ts # DataSDK (Data API client)
│ └── websocket-client.ts # WebSocket client for real-time data
├── routes/ # Elysia server routes
│ ├── gamma.ts # Gamma API endpoints
│ ├── clob.ts # CLOB API endpoints
│ └── data.ts # Data API endpoints
├── types/
│ ├── elysia-schemas.ts # Unified TypeBox schema definitions
│ └── websocket-schemas.ts # WebSocket message schemas (Zod)
└── utils/ # Utility functions
py-src/
└── polymarket_kit/
├── __init__.py # Package exports
├── profile.py # Wallet address extraction from usernames
├── gamma/ # Gamma API client (GammaClient, GammaSDK)
├── clob/ # CLOB client (ClobClient, TradingClient)
├── data/ # Data API client (DataSDK)
└── ws/ # Async WebSocket client (PolymarketWebSocket)
go-client/
├── auth/ # Ethereum wallet & signing
├── client/ # CLOB client implementation
│ ├── clob_client.go # Main API client
│ ├── websocket_client.go # Market WebSocket
│ ├── user_ws.go # User channel WebSocket
│ ├── orders.go # Order building & placement
│ ├── ws_pool.go # Redundant WebSocket pool
│ └── aggregator.go # Message deduplication
├── order/ # Order building utilities
├── realtime/ # Real-time data client
├── data/ # Data API client
├── gamma/ # Gamma API client
└── examples/ # Comprehensive usage examples
. → ./src/mod.ts - Main SDK exports./proxy → ./src/client.ts - Proxy client./sdk → ./src/sdk/index.ts - Direct SDK accessimport { GammaSDK } from "@hk/polymarket";
const gammaSDK = new GammaSDK();
// Get all active markets
const markets = await gammaSDK.getActiveMarkets();
// Get markets with filtering
const filteredMarkets = await gammaSDK.getMarkets({
limit: "10",
active: "true",
volume_num_min: "1000",
});
// Get specific market by slug
const market = await gammaSDK.getMarketBySlug("bitcoin-above-100k");
// Get events with filtering
const events = await gammaSDK.getEvents({
limit: "5",
active: "true",
end_date_min: "2024-01-01",
});
import { PolymarketSDK } from "@hk/polymarket";
const polymarketSDK = new PolymarketSDK({
privateKey: "your_private_key",
funderAddress: "your_funder_address",
});
// Get price history for a market
const priceHistory = await polymarketSDK.getPriceHistory({
market: "0x123...", // CLOB token ID
interval: "1h",
startDate: "2024-01-01",
endDate: "2024-01-31",
});
// Check CLOB connection health
const health = await polymarketSDK.healthCheck();
# Using uv (recommended)
uv add polymarket-kit
# Using pip
pip install polymarket-kit
from polymarket_kit import GammaSDK
gamma = GammaSDK()
# Get markets
markets = gamma.get_markets(limit=10, active=True)
# Get events
events = gamma.get_events(limit=5, active=True)
# Get market by slug
market = gamma.get_market_by_slug("bitcoin-above-100k")
import asyncio
from polymarket_kit import TradingClient
async def main():
client = TradingClient(
private_key="your_private_key",
funder="your_funder_address",
)
# Initialize and derive API credentials
creds = await client.initialize()
# Place a GTC limit buy order
resp = await client.place_limit_order(
token_id="60487116984468020978247225474488676749601001829886755968952521846780452448915",
price=0.45,
size=10.0,
side="BUY",
)
print(f"Order placed: {resp.order_id}, status={resp.status}")
# Query open orders
open_orders = await client.get_open_orders()
# Cancel an order
await client.cancel_order(resp.order_id)
asyncio.run(main())
import asyncio
from polymarket_kit import PolymarketWebSocket
from polymarket_kit.ws import BookMessage, PriceChangeMessage, LastTradePriceMessage
async def main():
ws = PolymarketWebSocket("market")
ws.on_book = lambda msg: print(f"Book: bids={len(msg.bids)} asks={len(msg.asks)}")
ws.on_price_change = lambda msg: print(f"Price change: {len(msg.price_changes)} changes")
ws.on_last_trade = lambda msg: print(f"Trade: {msg.side} @ {msg.price}")
ws.on_connect = lambda: print("Connected!")
await ws.connect()
await ws.subscribe([
"60487116984468020978247225474488676749601001829886755968952521846780452448915"
])
await asyncio.Event().wait() # run forever
asyncio.run(main())
import asyncio
from polymarket_kit import PolymarketWebSocket, ApiCreds
async def main():
creds = ApiCreds(
api_key="your_api_key",
secret="your_secret",
passphrase="your_passphrase",
)
ws = PolymarketWebSocket("user", api_creds=creds)
ws.on_order = lambda evt: print(f"Order event: {evt}")
ws.on_trade = lambda evt: print(f"Trade event: {evt}")
await ws.connect()
await asyncio.Event().wait()
asyncio.run(main())
Stream real-time market data with automatic authentication, reconnection, and type-safe message handling.
import { ClobClient } from "@polymarket/clob-client";
import { Wallet } from "@ethersproject/wallet";
import { PolymarketWebSocketClient } from "@hk/polymarket";
const signer = new Wallet(process.env.POLYMARKET_KEY!);
const clobClient = new ClobClient("https://clob.polymarket.com", 137, signer);
// Create WebSocket client with asset IDs to subscribe to
const ws = new PolymarketWebSocketClient(clobClient, {
assetIds: ["60487116984468020978247225474488676749601001829886755968952521846780452448915"],
autoReconnect: true,
debug: true,
});
// Register event handlers
ws.on({
onBook: (msg) => {
console.log(`Book Update - Bids: ${msg.bids.length}, Asks: ${msg.asks.length}`);
},
onPriceChange: (msg) => {
console.log(`Price Change - ${msg.price_changes.length} changes`);
},
onLastTradePrice: (msg) => {
console.log(`Trade: ${msg.side} @ ${msg.price}`);
},
onError: (error) => console.error("Error:", error),
onConnect: () => console.log("Connected!"),
});
await ws.connect();
import (
"github.com/HuakunShen/polymarket-kit/go-client/client"
"github.com/HuakunShen/polymarket-kit/go-client/types"
)
config := &client.ClientConfig{
Host: "https://clob.polymarket.com",
ChainID: types.ChainPolygon,
PrivateKey: os.Getenv("POLYMARKET_KEY"),
}
clobClient, _ := client.NewClobClient(config)
wsClient := client.NewWebSocketClient(clobClient, &client.WebSocketClientOptions{
AssetIDs: []string{
"60487116984468020978247225474488676749601001829886755968952521846780452448915",
},
AutoReconnect: true,
Debug: true,
})
wsClient.On(&client.WebSocketCallbacks{
OnBook: func(msg *types.BookMessage) {
fmt.Printf("Book Update - Bids: %d, Asks: %d\n", len(msg.Bids), len(msg.Asks))
},
OnLastTradePrice: func(msg *types.LastTradePriceMessage) {
fmt.Printf("Trade: %s @ %s\n", msg.Side, msg.Price)
},
OnError: func(err error) {
fmt.Printf("Error: %v\n", err)
},
})
wsClient.Connect()
For high-availability scenarios, use RedundantWSPool which maintains N parallel connections with automatic message deduplication:
pool := client.NewRedundantWSPool(&client.PoolConfig{
Redundancy: 3, // 3 parallel connections
DedupTTL: 60 * time.Second,
OnMessage: func(msg []byte) {
// deduplicated message callback
fmt.Println(string(msg))
},
})
ctx := context.Background()
pool.Start(ctx)
pool.Subscribe([]string{"asset_id_1", "asset_id_2"})
The WebSocket client handles these message types:
See WebSocket Client Documentation for detailed API reference and examples.
All types are exported from the unified schema:
import type {
// Market & Event Types
MarketType,
EventType,
MarketQueryType,
EventQueryType,
PriceHistoryQueryType,
PriceHistoryResponseType,
// WebSocket Types
MarketChannelMessage,
BookMessage,
PriceChangeMessage,
TickSizeChangeMessage,
LastTradePriceMessage,
WebSocketClientOptions,
WebSocketClientCallbacks,
} from "@hk/polymarket";
GET / - API information and available endpointsGET /health - Global health checkGET /docs - Swagger/OpenAPI documentationGET /gamma/markets - Get markets with comprehensive filteringlimit, offset, order, ascending, id, slug, archived, active, closed, clob_token_ids, condition_ids, liquidity_num_min, liquidity_num_max, volume_num_min, volume_num_max, start_date_min, start_date_max, end_date_min, end_date_max, tag_id, related_tagsGET /gamma/events - Get events with comprehensive filteringlimit, offset, order, ascending, id, slug, archived, active, closed, liquidity_min, liquidity_max, volume_min, volume_max, start_date_min, start_date_max, end_date_min, end_date_max, tag, tag_id, related_tags, tag_slug$ claude mcp add polymarket-kit \
-- python -m otcore.mcp_server <graph>