Skip to content

Latest commit

 

History

151 Commits

Folders and files

NameName
Last commit message
Last commit date
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

Polymarket Go SDK

A complete Go SDK for interacting with the Polymarket prediction markets, covering real-time quotes, market data, trade execution, and on-chain operations.

Project Structure

polymarket-sdk/
├── sdk.go              # Unified SDK entry point
├── go.mod              # Go module definition
├── go.sum              # Dependency lock file
├── Makefile            # Build scripts
├── internal/           # Internal implementation packages
│   ├── auth/           # Authentication module (L1 EIP-712 / L2 HMAC)
│   ├── config/         # Configuration management
│   ├── market/         # Market data module (Public API)
│   ├── orderbook/      # Order book module (WebSocket)
│   ├── polygon/        # On-chain operations module (USDC/CTF)
│   ├── trading/        # Trading module (CLOB API)
│   └── websocket/      # WebSocket module (order book / orders / trades)
├── pkg/                # Public utility packages
│   ├── aws/            # AWS service integration (Secrets Manager)
│   ├── common/         # Common constants and endpoints
│   ├── errors/         # Error definitions
│   ├── http/           # HTTP client
│   ├── logger/         # Logging utilities
│   └── utils/          # General utility functions
├── apps/               # Applications
│   ├── makerladder/    # MakerLadder market-making strategy
│   └── examples/       # Usage example code
└── docs/               # Documentation

Architecture Overview

The SDK follows a modular design. The unified entry point NewSDK automatically initializes each sub-module:

sdk, _ := polymarket.NewSDK(config, privateKey)
// sdk.Markets   - Market data (Public Gamma API)
// sdk.OrderBook - Real-time quotes (Public WebSocket)
// sdk.Trading   - Trade execution (L2 Auth CLOB API)
// sdk.Polygon   - On-chain operations (L1 Auth / Gasless)
// The Auth module is mainly invoked internally by Trading, but can also be used
// standalone for signing and credential management.

// The WebSocket module can be used independently:
// websocket.MarketManager - Real-time order book data (Public)
// websocket.UserManager   - Order/trade events (Private, requires API Key)

Module Reference

1. Markets Module

Provides market metadata queries via the Gamma API. No authentication required.

Feature Example Methods Description
Market lists GetActiveMarkets, GetFeaturedMarkets Fetch active or featured markets
Market details GetMarket, GetMarketBySlug, GetMarketByConditionID Fetch details for a single market
Filter & search SearchMarkets, GetMarketsByTag, GetMarketsByCategory Search by keyword, tag, or category
Special markets GetNegRiskMarkets, GetTopVolumeMarkets, GetEndingSoonMarkets Fetch NegRisk, high-volume, or soon-to-close markets
Paginated queries GetMarkets, GetAllMarkets Basic list queries with pagination and custom parameters

Interface definition: market/types.go - MarketAPI

2. OrderBook Module

Maintains a local real-time order book. No authentication required.

Feature Example Methods Description
Subscribe Subscribe([]string{tokenID}) Subscribe to real-time updates for a token
Best price GetBestBid, GetBestAsk, GetBBO Get best bid/ask price and size
Calculations GetMidPrice, GetSpread Compute mid price and spread
Depth GetDepth(tokenID, depth) Get bid/ask levels at a given depth
Simulation SimulateBuyAsks, ScanAsksBelow Simulate order fill cost calculation

Interface definition: orderbook/types.go - ClientAPI

3. WebSocket Module

Provides real-time WebSocket subscriptions, including public order book data and private order/trade events.

Market Channel (Public)

Subscribe to real-time order book updates. No authentication required.

Feature Example Methods Description
Subscribe Subscribe(tokenIDs) Subscribe to order books for multiple tokens
Order book GetOrderBook(tokenID) Get the order book for a given token
State IsInitialized(tokenID) Check whether the order book is initialized
Updates Updates() Get the update notification channel
manager := websocket.NewMarketManager(config)
manager.Subscribe([]string{tokenID1, tokenID2})

for update := range manager.Updates() {
    ob := manager.GetOrderBook(update.TokenID)
    bbo := ob.GetBBO()
    logger.Info("BBO", "bid", bbo.Bid, "ask", bbo.Ask)
}

User Channel (Private)

Subscribe to order status and trade events. Requires API Key authentication.

Feature Example Methods Description
Subscribe Subscribe(conditionIDs) Subscribe to order/trade events for markets
Order updates OrderUpdates() Get the order event channel
Trade updates TradeUpdates() Get the trade event channel
Callbacks OnOrder, OnTrade Set event callbacks
auth := &websocket.WSAuthPayload{
    APIKey:     creds.APIKey,
    Secret:     creds.Secret,
    Passphrase: creds.Passphrase,
}
manager := websocket.NewUserManager(config, auth)
manager.Subscribe([]string{conditionID})

// Order events: PLACEMENT, UPDATE, CANCELLATION
for order := range manager.OrderUpdates() {
    logger.Info("order", "type", order.Type, "id", order.ID, "price", order.Price)
}

// Trade events: MATCHED, MINED, CONFIRMED
for trade := range manager.TradeUpdates() {
    logger.Info("trade", "status", trade.Status, "price", trade.Price, "size", trade.Size)
}

Logging

The WebSocket module uses a global logger; logs are written to ws.log:

// Initialize the global logger
cleanup := logger.Init("info", "logs")
defer cleanup()

// WebSocket logs are automatically written to logs/ws.log

Interface definitions: websocket/types.go, websocket/market_manager.go, websocket/user_manager.go

4. Trading Module

Core trading functionality. Requires L2 (API Key) authentication. The SDK handles signing automatically.

Feature Example Methods Description
Place order CreateOrder Create and submit an order (GTC/FOK/GTD)
Cancel order CancelOrder, CancelAllOrders Cancel a specific order or all orders
Account GetBalanceAllowance Query USDC/token balance
History GetTrades Query historical trade records

Interface definition: trading/types.go - Client (interface)

5. Polygon Module

On-chain contract interactions. Requires L1 (private key) authentication. Supports Gasless mode.

Feature Example Methods Description
Mint SplitPosition USDC → YES + NO
Burn MergePosition YES + NO → USDC
Redeem RedeemPosition Exchange the winning token after settlement
Config EnableGasless Uses a relayer to cover gas by default

Interface definition: polygon/types.go - Client (interface)

6. Auth Module

Base authentication service responsible for signing and credential management. Typically handled automatically by the SDK, but can also be used standalone.

Feature Example Methods Description
L1 signing NewL1Signer Create an EIP-712 signer (private key operations)
L2 signing NewL2Signer Create an HMAC signer (API request authentication)
Credential management CreateAPIKey, DeriveAPIKey Generate random or deterministic API credentials
Struct definitions Credentials Defines the API Key, Secret, and Passphrase structure

Interface definitions: auth/signer.go, auth/credentials.go


Quick Start

Installation

go get github.com/polymarket/go-sdk

Initialization

1. Public mode (query only) No private key required; only the Markets and OrderBook modules are available.

config := polymarket.DefaultConfig()
sdk := polymarket.NewPublicSDK(config)
defer sdk.Close()

// Query markets
markets, _ := sdk.Markets.GetActiveMarkets(ctx, 10)

2. Full mode (trading + on-chain) Requires a private key; all modules are available.

privateKey := os.Getenv("PRIVATE_KEY")
sdk, err := polymarket.NewSDK(nil, privateKey)
if err != nil {
    log.Fatal(err)
}
defer sdk.Close()

// Automatically creates/derives API credentials on first use
creds, _ := sdk.Trading.CreateOrDeriveAPICredentials(ctx)

Configuration (Config)

type Config struct {
    // API endpoints
    GammaEndpoint string // Gamma API (market data)
    CLOBEndpoint  string // CLOB API (trading)
    WSEndpoint    string // WebSocket (real-time order book data)

    // Strategy configuration
    HTTPTimeout  time.Duration
    MaxRetries   int
    
    // Polygon / Gasless
    RPCEndpoint     string
    UseGasless      bool // Default true (no Matic needed)
    DisablePolygon  bool // Set to true in test environments to skip on-chain initialization
}

Development & Debugging

Common Commands

# Run all tests
go test ./...

# Run tests for a specific module (e.g. trading)
go test ./trading/...

# Format code
go fmt ./...

# Run examples
go run examples/main.go
go run examples/trading/main.go

Documentation

About

A complete Go SDK for interacting with Polymarket prediction markets — market data, real-time quotes, trading, and on-chain operations.

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages