Documentation Index Fetch the complete documentation index at: https://docs.polymarket.us/llms.txt
Use this file to discover all available pages before exploring further.
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
Variable Description 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
Variable Default Description 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)
Example Description 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:
Example Description 11_grpc_market_data_streamReal-time order book updates - Subscribe to bid/ask changes12_grpc_order_subscriptionOrder status notifications - Get live updates on your orders13_grpc_position_subscriptionPosition change updates - Track position changes in real-time14_grpc_funding_subscriptionFunding notifications - Monitor deposits and withdrawals15_grpc_dropcopy_subscriptionExecution reports (drop copy) - Receive trade confirmations16_connect_streamingConnect protocol - Streaming via HTTP/2 (alternative to gRPC)
Advanced Examples (17-20)
Example Description 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