Skip to main content

Overview

The Go sample code demonstrates how to authenticate and use the Polymarket Exchange API, including REST endpoints, real-time gRPC streaming, and advanced features. It includes 20 example programs covering REST, gRPC streaming, Connect protocol, pagination, and historical data.

Download Sample Code

Download the complete sample code package including Python and Go examples.

What’s Included

  • REST API Client - Complete client for all REST endpoints
  • gRPC Client - Streaming client for real-time market data and order updates
  • Connect Protocol - HTTP/2 alternative to native gRPC
  • 20 Example Programs - Covering REST, gRPC streaming, Connect protocol, pagination, and advanced features
  • Authentication - Private key JWT authentication flow
  • Generated Protos - Pre-generated protocol buffer bindings

Prerequisites

  • Go 1.21 or higher
  • Credentials (Client ID and private key) provided by Polymarket
  • A registered trading account

Installation

# Extract the download
unzip polymarket-us-client-sample-code.zip
cd client_sample_code/go

# Download dependencies
make deps

Configuration

Copy the sample environment file and fill in your credentials:
cp sample_env.sh my_env.sh
nano my_env.sh  # Edit with your credentials
source my_env.sh

Required Environment Variables

VariableDescription
POLYMARKET_CLIENT_IDYour Client ID (provided by Polymarket)
POLYMARKET_PRIVATE_KEY_PATHPath to your RSA private key (PEM format)
POLYMARKET_API_URLAPI base URL (e.g., https://api.preprod.polymarketexchange.com)
POLYMARKET_AUTH_DOMAINAuthentication domain (e.g., pmx-preprod.us.auth0.com)
POLYMARKET_AUTH_AUDIENCEAuthentication audience (matches API URL)
POLYMARKET_PARTICIPANT_IDYour participant ID (e.g., firms/Your-Firm/users/your-user)
POLYMARKET_ACCOUNTYour trading account (e.g., firms/Your-Firm/accounts/your-account)

Optional Environment Variables

VariableDefaultDescription
POLYMARKET_TEST_SYMBOLSBLIX-KC-YESSymbol for order placement demo
POLYMARKET_GRPC_ADDR(derived from API URL)gRPC endpoint address
POLYMARKET_VERBOSEfalseEnable verbose logging
POLYMARKET_TIMEOUT30Request timeout (seconds)

Running Examples

Using Make

# Run all REST examples
make run-all

# Run all examples with gRPC streaming
make run-streaming

# Run a specific example
make run EXAMPLE=01_health_check
make run EXAMPLE=11_grpc_market_data_stream

# Build all examples
make build

# Check environment configuration
make check-env

Using Go Directly

# Run all REST examples
cd cmd/run_all && go run .

# Run with streaming
cd cmd/run_all && go run . -streaming

# Run individual examples
go run ./examples/01_health_check
go run ./examples/11_grpc_market_data_stream

REST API Examples (01-10)

ExampleDescription
01_health_checkHealth check (no authentication required)
02_whoamiGet current user info
03_list_accountsList trading accounts
04_get_balanceGet account balance
05_list_positionsList positions
06_list_instrumentsList tradeable instruments
07_list_symbolsList all symbols
08_search_ordersSearch order history
09_list_usersList users in firm
10_place_and_cancel_orderPlace and cancel order (safe demo)

gRPC Streaming Examples (11-16)

These examples demonstrate real-time streaming connections for live market data and trading updates:
ExampleDescription
11_grpc_market_data_streamReal-time order book updates - Subscribe to bid/ask changes
12_grpc_order_subscriptionOrder status notifications - Get live updates on your orders
13_grpc_position_subscriptionPosition change updates - Track position changes in real-time
14_grpc_funding_subscriptionFunding notifications - Monitor deposits and withdrawals
15_grpc_dropcopy_subscriptionExecution reports (drop copy) - Receive trade confirmations
16_connect_streamingConnect protocol - Streaming via HTTP/2 (alternative to gRPC)

Advanced Examples (17-20)

ExampleDescription
17_paginationPaginating through large result sets
18_historical_positionsQuerying historical position data
19_instrument_filtersFiltering instruments by criteria
20_grpc_bidi_market_dataBidirectional streaming market data

Code Examples

REST API Client

package main

import (
    "fmt"
    "github.com/polymarket/client-sample-code/go/config"
    "github.com/polymarket/client-sample-code/go/rest"
)

func main() {
    // Load configuration from environment
    cfg := config.MustLoad()

    // Create REST client
    client := rest.NewClient(cfg)

    // Health check (no auth)
    health, _ := client.Health()
    fmt.Printf("Health: %s\n", health.Status)

    // Get current user
    whoami, _ := client.WhoAmI()
    fmt.Printf("User: %s\n", whoami.User)

    // Get balance
    balance, _ := client.GetBalance(cfg.Account, "USD")
    fmt.Printf("Balance: %s\n", balance.Balance)
}

gRPC Streaming - Market Data

package main

import (
    "context"
    "fmt"
    "time"
    "github.com/polymarket/client-sample-code/go/config"
    grpcclient "github.com/polymarket/client-sample-code/go/grpc"
)

func main() {
    cfg := config.MustLoad()

    // Create gRPC client
    client, _ := grpcclient.NewClient(cfg)
    defer client.Close()

    ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
    defer cancel()

    // Subscribe to market data for specific symbols
    sub, _ := client.SubscribeMarketData(ctx, []string{"SBLIX-KC-YES"}, 5)
    defer sub.Close()

    // Receive real-time order book updates
    for i := 0; i < 10; i++ {
        select {
        case update := <-sub.Updates():
            fmt.Printf("Symbol: %s, Bids: %d, Offers: %d\n",
                update.Symbol, len(update.Bids), len(update.Offers))
        case <-sub.Done():
            return
        }
    }
}

gRPC Streaming - Order Subscription

// Subscribe to order status updates
sub, _ := client.SubscribeOrders(ctx, []string{cfg.Account})
defer sub.Close()

for update := range sub.Updates() {
    if order := update.GetOrder(); order != nil {
        fmt.Printf("Order %s: Status=%s, Filled=%d\n",
            order.OrderId, order.Status, order.FilledQty)
    }
}

Authentication Flow

import (
    "github.com/golang-jwt/jwt/v4"
    "time"
)

func createClientAssertion(cfg *config.Config) string {
    now := time.Now()
    claims := jwt.MapClaims{
        "iss": cfg.ClientID,
        "sub": cfg.ClientID,
        "aud": fmt.Sprintf("https://%s/oauth/token", cfg.AuthDomain),
        "iat": now.Unix(),
        "exp": now.Add(5 * time.Minute).Unix(),
        "jti": uuid.New().String(),
    }

    token := jwt.NewWithClaims(jwt.SigningMethodRS256, claims)
    signedToken, _ := token.SignedString(cfg.PrivateKey)
    return signedToken
}

File Structure

client_sample_code/go/
├── Makefile                 # Build and run commands
├── README.md                # Go-specific documentation
├── go.mod                   # Go module definition
├── go.sum                   # Dependencies checksum
├── sample_env.sh            # Sample environment configuration
├── config/
│   └── config.go            # Configuration loading and validation
├── auth/
│   └── auth.go              # JWT authentication
├── rest/
│   └── client.go            # REST API client
├── grpc/
│   ├── client.go            # gRPC client setup
│   └── streams.go           # Streaming subscription helpers
├── gen/
│   ├── README.md            # Explains auto-generated files
│   └── polymarket/v1/       # Pre-generated proto files
├── examples/
│   ├── 01_health_check/     # Health check (no auth)
│   ├── 02_whoami/           # Get current user
│   ├── 03_list_accounts/    # List accounts
│   ├── 04_get_balance/      # Get balance
│   ├── 05_list_positions/   # List positions
│   ├── 06_list_instruments/ # List instruments
│   ├── 07_list_symbols/     # List symbols
│   ├── 08_search_orders/    # Search orders
│   ├── 09_list_users/       # List users
│   ├── 10_place_and_cancel_order/  # Place and cancel order
│   ├── 11_grpc_market_data_stream/  # Real-time market data
│   ├── 12_grpc_order_subscription/  # Order updates
│   ├── 13_grpc_position_subscription/  # Position updates
│   ├── 14_grpc_funding_subscription/  # Funding notifications
│   ├── 15_grpc_dropcopy_subscription/  # Execution reports
│   ├── 16_connect_streaming/  # Connect protocol streaming
│   ├── 17_pagination/       # Pagination examples
│   ├── 18_historical_positions/  # Historical data
│   ├── 19_instrument_filters/  # Filtering instruments
│   └── 20_grpc_bidi_market_data/  # Bidirectional streaming
└── cmd/
    └── run_all/             # Run all examples

Troubleshooting

”Private key file not found”

Ensure POLYMARKET_PRIVATE_KEY_PATH points to a valid PEM file:
ls -la $POLYMARKET_PRIVATE_KEY_PATH
openssl rsa -in $POLYMARKET_PRIVATE_KEY_PATH -check -noout

“Missing required environment variables”

Source your environment file before running:
source my_env.sh
make run-all

“Authentication server returned 401”

  • Verify your Client ID is correct
  • Ensure your private key matches the public key registered with Polymarket
  • Check that your credentials haven’t expired

gRPC Connection Issues

  • Verify the gRPC address is correct (default derived from API URL)
  • Check that port 443 is not blocked by a firewall
  • Try setting POLYMARKET_GRPC_ADDR explicitly