Skip to content

OsvoDev/polymarket-go-clob

 
 

Repository files navigation

Polymarket Go CLOB Client

A Golang port of the official Polymarket CLOB Client (TypeScript). This library brings all the functionality of the original client to Go, enabling you to trade prediction market outcomes programmatically.

What is this?

Polymarket is a decentralized prediction market platform where you can trade on the outcomes of real-world events. This client library allows you to:

  • Place buy and sell orders programmatically
  • Query market data and orderbooks
  • Manage your API keys and credentials
  • Trade using your Polymarket account funds (Gnosis Safe wallet)

Features

  • Market Orders: Buy and sell at market price with FOK (Fill or Kill) or FAK (Fill and Kill) execution
  • Limit Orders: Place orders at specific prices
  • Proxy Wallet Support: Trade using funds in your Polymarket account
  • EIP-712 Signing: Secure authentication using typed data signatures
  • Order Management: Cancel orders, view open orders, and track trades

Prerequisites

  • Go 1.21 or later
  • A Polygon wallet with a private key
  • Funds in your Polymarket account or wallet

Installation

go get github.com/tolu0x/polymarket-go-clob-client

Or clone the repository:

git clone https://github.com/tolu0x/polymarket-go-clob-client.git
cd polymarket-go-clob-client
go mod tidy

Quick Start

1. Set up your environment

Create a .env file in the project root:

# Your wallet private key (without 0x prefix)
PK=your_private_key_here

# Polygon Mainnet
CHAIN_ID=137
CLOB_API_URL=https://clob.polymarket.com

# Wallet type: 0=EOA, 1=Poly Proxy, 2=Gnosis Safe
SIGNATURE_TYPE=2

2. Find your wallet addresses

If you've used Polymarket through their web interface, your funds are likely in a Gnosis Safe proxy wallet. Run this to find your wallet addresses:

cd examples
go run check_proxy_wallet.go

Output:

EOA Address: 0xYourEOAAddress
Polymarket Proxy Wallet (MagicLink): 0x...
Gnosis Safe Wallet (Browser): 0x...

=== USDC Balances ===
EOA: 0.000000 USDC
Proxy Wallet: 0.000000 USDC
Safe Wallet: 4.966266 USDC

=== Recommendation ===
Your funds are in the Gnosis Safe wallet.
Use SignatureType = 2 (GnosisSafe)

Usage Examples

Creating a Client

package main

import (
    clobclient "polymarket-go-clob-client"
    "polymarket-go-clob-client/types"
)

func main() {
    // Set up signature type for Gnosis Safe
    signatureType := int64(2)

    // Your Safe wallet address (or use auto-derivation)
    funderAddress := "0xYourSafeWalletAddress"

    client, err := clobclient.NewClobClient(
        "https://clob.polymarket.com",
        types.POLYGON,           // Chain ID 137
        signer,                  // Your wallet signer
        nil,                     // API credentials (will be derived)
        &signatureType,          // 2 = Gnosis Safe
        &funderAddress,          // Safe wallet address
        nil, nil, nil, nil,
        orderBuilder,
    )
    if err != nil {
        log.Fatal(err)
    }

    // Derive API credentials
    creds, _ := client.CreateOrDeriveApiKey(nil)
    client.Creds = creds
}

Placing a Market Buy Order

// Buy $1 worth of YES tokens
order, err := client.CreateMarketOrder(
    types.UserMarketOrder{
        TokenID:   "your_token_id",
        Amount:    1.0,           // Amount in USDC
        Side:      types.BUY,
        OrderType: &types.FOK,    // Fill or Kill
    },
    &types.CreateOrderOptions{
        TickSize: types.TickSize0_01,
    },
)

result, err := client.PostOrder(order, types.FOK, false)

Placing a Market Sell Order

// Sell 5 tokens at market price
result, err := client.CreateAndPostMarketOrder(
    types.UserMarketOrder{
        TokenID:   "your_token_id",
        Amount:    5.0,           // Number of tokens
        Side:      types.SELL,
        OrderType: &types.FOK,
    },
    &types.CreateOrderOptions{
        TickSize: types.TickSize0_01,
    },
    types.FOK,
    false,
)

Checking Balances

// Check USDC balance
params := &types.BalanceAllowanceParams{
    AssetType: types.COLLATERAL,
}
resp, err := client.GetBalanceAllowance(params)
fmt.Printf("USDC Balance: %s\n", resp.Balance)

// Check token balance
tokenID := "your_token_id"
params := &types.BalanceAllowanceParams{
    AssetType: types.CONDITIONAL,
    TokenID:   &tokenID,
}
resp, err := client.GetBalanceAllowance(params)
fmt.Printf("Token Balance: %s\n", resp.Balance)

Getting Market Data

// Get orderbook
orderbook, err := client.GetOrderBook(tokenID)
fmt.Printf("Best Bid: %s, Best Ask: %s\n",
    orderbook.Bids[0].Price,
    orderbook.Asks[0].Price)

// Get midpoint price
midpoint, err := client.GetMidpoint(tokenID)

Wallet Types

Type Value Description
EOA 0 Direct wallet trading (funds in your own wallet)
Poly Proxy 1 Polymarket proxy wallet (MagicLink/email users)
Gnosis Safe 2 Browser wallet users (MetaMask, etc.)

Most users who deposited through the Polymarket web interface will have funds in a Gnosis Safe wallet (type 2).

Project Structure

polymarket-go-clob-client/
├── client.go           # Main ClobClient implementation
├── types/              # API types and constants
├── headers/            # Authentication header generation
├── orderbuilder/       # Order building and signing
├── signing/            # EIP-712 signing utilities
├── httphelper/         # HTTP request helpers
├── config/             # Chain and contract configuration
└── examples/           # Usage examples

Environment Variables

Variable Required Description
PK Yes Private key (hex, without 0x prefix)
CHAIN_ID No Chain ID (default: 137 for Polygon)
CLOB_API_URL No API URL (default: https://clob.polymarket.com)
SIGNATURE_TYPE No Wallet type: 0, 1, or 2 (default: 0)
FUNDER_ADDRESS No Proxy wallet address (auto-derived if not set)

Running Tests

go test -v ./...

Building

go build ./...

Common Issues

"Could not create api key"

This warning can be ignored if you already have API keys. The client will derive existing keys automatically.

API Documentation

For full API documentation, see the Polymarket CLOB API docs.

Credits

This project is a Go port of the official Polymarket CLOB Client by the Polymarket team. Full credit to them for the original TypeScript implementation and API design.

License

MIT

Disclaimer

This software is provided as-is. Trading on prediction markets involves risk. Always test with small amounts first and never trade more than you can afford to lose.

About

A Golang library that allows you to use the Polymarket API programmatically.

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

 
 
 

Contributors

Languages

  • Go 100.0%