clobclient

package module
v0.0.0-...-45e54d0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Feb 15, 2026 License: Apache-2.0 Imports: 19 Imported by: 0

README

Polymarket CLOB Client - Go Implementation

A Go client for the Polymarket Central Limit Order Book (CLOB) API. This is a port of the official TypeScript @polymarket/clob-client.

Features

  • ✅ Full API coverage for Polymarket CLOB
  • ✅ EIP712 signature support for order signing
  • ✅ L1 (wallet) and L2 (API key) authentication
  • ✅ Order creation, posting, and cancellation
  • ✅ Market data queries (order books, prices, trades)
  • ✅ Automatic retry logic with exponential backoff
  • ✅ Type-safe API with Go structs

Installation

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

Quick Start

package main

import (
    "fmt"
    "log"
    
    clob "github.com/Cyvadra/polymarket-clob-client"
)

func main() {
    // Configuration
    host := "https://clob.polymarket.com"
    chainID := 137 // Polygon mainnet
    privateKey := "0x..." // Your private key
    funder := "0x..." // Your Polymarket profile address (optional)
    
    // Create client without credentials first
    client := clob.NewClobClient(
        host,
        chainID,
        privateKey,
        nil, // No credentials yet
        clob.SignatureTypePOLYPROXY, // or SignatureTypeEOA
        &funder,
    )
    
    // Create or derive API key
    nonce := "12345"
    creds, err := client.CreateOrDeriveAPIKey(nonce)
    if err != nil {
        log.Fatalf("Failed to get API key: %v", err)
    }
    
    // Update client with credentials
    client.Creds = creds
    
    // Create and post an order
    order := &clob.UserOrder{
        TokenID: "your-token-id",
        Price:   0.52,
        Size:    10.0,
        Side:    clob.SideBuy,
    }
    
    options := &clob.CreateOrderOptions{
        TickSize: clob.TickSize0001,
        NegRisk:  boolPtr(false),
    }
    
    response, err := client.CreateAndPostOrder(
        order,
        options,
        clob.OrderTypeGTC,
    )
    if err != nil {
        log.Fatalf("Failed to post order: %v", err)
    }
    
    fmt.Printf("Order posted! ID: %s\n", response.OrderID)
}

func boolPtr(b bool) *bool {
    return &b
}

Core Components

ClobClient

The main client for interacting with the Polymarket CLOB API.

client := clob.NewClobClient(
    host,        // API endpoint
    chainID,     // Blockchain network (137 for Polygon, 80002 for Amoy)
    privateKey,  // Your private key
    creds,       // API credentials (can be nil initially)
    signatureType, // Signature type (EOA, POLYPROXY, etc.)
    funderAddress, // Optional funder address
)
Authentication

L1 Authentication (Wallet-based):

  • Used for creating/deriving API keys
  • Uses EIP712 signatures
creds, err := client.CreateAPIKey(nonce)
// or
creds, err := client.DeriveAPIKey(nonce)
// or
creds, err := client.CreateOrDeriveAPIKey(nonce)

L2 Authentication (API Key-based):

  • Used for trading operations
  • Uses HMAC-SHA256 signatures
  • Automatically handled by the client when credentials are set
Order Management

Create and Post Order:

userOrder := &clob.UserOrder{
    TokenID: "token-id",
    Price:   0.52,
    Size:    10.0,
    Side:    clob.SideBuy,
}

options := &clob.CreateOrderOptions{
    TickSize: clob.TickSize0001,
}

response, err := client.CreateAndPostOrder(
    userOrder,
    options,
    clob.OrderTypeGTC,
)

Cancel Order:

response, err := client.CancelOrder(orderID)

Cancel All Orders:

err := client.CancelAll()
Market Data

Get Order Book:

book, err := client.GetOrderBook(tokenID)

Get Price:

price, err := client.GetPrice(tokenID, nil)
// or with side
side := clob.SideBuy
price, err := client.GetPrice(tokenID, &side)

Get Midpoint:

mid, err := client.GetMidpoint(tokenID)

Get Open Orders:

params := &clob.OpenOrderParams{
    Market: &marketID,
}
orders, err := client.GetOpenOrders(params)

Get Trades:

params := &clob.TradeParams{
    Market: &marketID,
}
trades, err := client.GetTrades(params)
Balance & Allowance
params := &clob.BalanceAllowanceParams{
    AssetType: clob.AssetTypeCollateral,
}
balance, err := client.GetBalanceAllowance(params)

Types

Order Types
  • OrderTypeGTC - Good Till Cancel
  • OrderTypeFOK - Fill or Kill
  • OrderTypeGTD - Good Till Date
  • OrderTypeFAK - Fill and Kill
Sides
  • SideBuy - Buy order
  • SideSell - Sell order
Chains
  • ChainPolygon - Polygon mainnet (137)
  • ChainAmoy - Amoy testnet (80002)
Signature Types
  • SignatureTypeEOA - Externally Owned Account
  • SignatureTypePOLYPROXY - Polymarket Proxy Wallet
  • SignatureTypePOLYGNOSISSAFE - Gnosis Safe
Tick Sizes
  • TickSize01 - 0.1
  • TickSize001 - 0.01
  • TickSize0001 - 0.001
  • TickSize00001 - 0.0001

Error Handling

The client returns standard Go errors. Always check for errors:

response, err := client.CreateAndPostOrder(order, options, orderType)
if err != nil {
    log.Printf("Error: %v", err)
    return
}

Examples

See the examples directory for more detailed examples:

Architecture

The Go implementation follows the same architecture as the TypeScript client:

  • Client Layer: Main ClobClient handles API interactions
  • Order Builder: Creates and signs orders using EIP712
  • Headers: Manages L1/L2 authentication headers
  • Signing: EIP712 and HMAC-SHA256 signature generation
  • HTTP Client: Handles requests with retry logic

Differences from TypeScript Client

While maintaining feature parity, the Go implementation has some differences:

  1. Error Handling: Uses Go's explicit error returns instead of exceptions
  2. Type System: Uses Go structs with JSON tags instead of TypeScript interfaces
  3. Async: Synchronous by default (Go doesn't have async/await)
  4. Naming: Follows Go conventions (PascalCase for exports)

Testing

go test ./...

Contributing

Contributions are welcome! Please feel free to submit issues and pull requests.

License

MIT License - see LICENSE file for details.

Disclaimer

This is an unofficial implementation. Use at your own risk. Always test thoroughly in a testnet environment before using with real funds.

Documentation

Index

Constants

View Source
const (
	EndpointTime                   = "/time"
	EndpointCreateAPIKey           = "/auth/api-key"
	EndpointDeriveAPIKey           = "/auth/derive-api-key"
	EndpointDeleteAPIKey           = "/auth/api-key"
	EndpointGetAPIKeys             = "/auth/api-keys"
	EndpointCreateReadonlyAPIKey   = "/auth/readonly-api-key"
	EndpointPostOrder              = "/order"
	EndpointCancelOrder            = "/order"
	EndpointCancelAll              = "/cancel-all"
	EndpointCancelMarketOrders     = "/cancel-market-orders"
	EndpointCancelOrders           = "/cancel-orders"
	EndpointGetOrder               = "/data/order"
	EndpointGetOpenOrders          = "/data/orders"
	EndpointGetTrades              = "/data/trades"
	EndpointGetOrderBook           = "/book"
	EndpointGetOrderBooks          = "/books"
	EndpointGetMidpoint            = "/midpoint"
	EndpointGetPrice               = "/price"
	EndpointGetLastTradePrice      = "/last-trade-price"
	EndpointGetMarket              = "/market"
	EndpointGetMarkets             = "/markets"
	EndpointGetPricesHistory       = "/prices-history"
	EndpointGetNotifications       = "/notifications"
	EndpointDropNotifications      = "/notifications"
	EndpointGetBalanceAllowance    = "/balance-allowance"
	EndpointUpdateBalanceAllowance = "/balance-allowance"
	EndpointGetOrderScoring        = "/order-scoring"
	EndpointGetOrdersScoring       = "/orders-scoring"
	EndpointClosedOnly             = "/closed-only"
)

API Endpoints

View Source
const (
	ClobAuthDomain = "ClobAuthDomain"
	ClobVersion    = "1"
)

Variables

This section is empty.

Functions

func BuildClobEip712Signature

func BuildClobEip712Signature(
	chainID int,
	privateKey string,
	timestamp int64,
	nonce string,
) (string, error)

BuildClobEip712Signature creates an EIP712 signature for CLOB authentication

func BuildOrderSignature

func BuildOrderSignature(
	chainID int,
	privateKey string,
	order *SignedOrder,
	signatureType SignatureType,
) (string, error)

BuildOrderSignature creates an EIP712 signature for an order

func BuildPolyHmacSignature

func BuildPolyHmacSignature(
	secret string,
	timestamp int64,
	method string,
	requestPath string,
	body string,
) (string, error)

BuildPolyHmacSignature creates an HMAC signature for API authentication

func CreateL1Headers

func CreateL1Headers(
	chainID int,
	privateKey string,
	nonce string,
) (map[string]string, error)

CreateL1Headers creates headers for L1 authentication (wallet signature)

func CreateL2Headers

func CreateL2Headers(
	privateKey string,
	creds *ApiKeyCreds,
	method string,
	requestPath string,
	body string,
) (map[string]string, error)

CreateL2Headers creates headers for L2 authentication (API key)

func CreateL2HeadersWithTimestamp

func CreateL2HeadersWithTimestamp(
	privateKey string,
	creds *ApiKeyCreds,
	method string,
	requestPath string,
	body string,
	timestamp int64,
) (map[string]string, error)

CreateL2HeadersWithTimestamp creates L2 headers with a specific timestamp

func GetAddressFromPrivateKey

func GetAddressFromPrivateKey(privateKey string) (string, error)

GetAddressFromPrivateKey returns the Ethereum address from a private key

func InjectBuilderHeaders

func InjectBuilderHeaders(
	headers map[string]string,
	builderCreds *BuilderApiKey,
	method string,
	requestPath string,
	body string,
	timestamp int64,
) (map[string]string, error)

InjectBuilderHeaders injects builder API key headers into existing L2 headers

func IsValidAddress

func IsValidAddress(address string) bool

IsValidAddress checks if a string is a valid Ethereum address

func ValidatePrice

func ValidatePrice(price float64, tickSize TickSize) error

ValidatePrice validates that a price is within valid range and tick size

Types

type ApiKeyCreds

type ApiKeyCreds struct {
	Key        string `json:"key"`
	Secret     string `json:"secret"`
	Passphrase string `json:"passphrase"`
}

ApiKeyCreds represents API key credentials

type ApiKeyRaw

type ApiKeyRaw struct {
	ApiKey     string `json:"apiKey"`
	Secret     string `json:"secret"`
	Passphrase string `json:"passphrase"`
}

ApiKeyRaw represents raw API key

type ApiKeysResponse

type ApiKeysResponse struct {
	ApiKeys []ApiKeyCreds `json:"apiKeys"`
}

ApiKeysResponse represents API keys response

type AssetType

type AssetType string

AssetType represents the type of asset

const (
	AssetTypeCollateral  AssetType = "COLLATERAL"
	AssetTypeConditional AssetType = "CONDITIONAL"
)

type BalanceAllowanceParams

type BalanceAllowanceParams struct {
	AssetType AssetType `json:"asset_type"`
	TokenID   *string   `json:"token_id,omitempty"`
}

BalanceAllowanceParams represents parameters for balance/allowance queries

type BalanceAllowanceResponse

type BalanceAllowanceResponse struct {
	Balance   string `json:"balance"`
	Allowance string `json:"allowance"`
}

BalanceAllowanceResponse represents balance and allowance

type BanStatus

type BanStatus struct {
	ClosedOnly bool `json:"closed_only"`
}

BanStatus represents ban status

type BookParams

type BookParams struct {
	TokenID string `json:"token_id"`
	Side    Side   `json:"side"`
}

BookParams represents parameters for order book queries

type BuilderApiKey

type BuilderApiKey struct {
	Key        string `json:"key"`
	Secret     string `json:"secret"`
	Passphrase string `json:"passphrase"`
}

BuilderApiKey represents builder API key credentials

type BuilderApiKeyResponse

type BuilderApiKeyResponse struct {
	Key       string     `json:"key"`
	CreatedAt *time.Time `json:"createdAt,omitempty"`
	RevokedAt *time.Time `json:"revokedAt,omitempty"`
}

BuilderApiKeyResponse represents builder API key response

type BuilderTrade

type BuilderTrade struct {
	ID              string  `json:"id"`
	TradeType       string  `json:"tradeType"`
	TakerOrderHash  string  `json:"takerOrderHash"`
	Builder         string  `json:"builder"`
	Market          string  `json:"market"`
	AssetID         string  `json:"assetId"`
	Side            string  `json:"side"`
	Size            string  `json:"size"`
	SizeUsdc        string  `json:"sizeUsdc"`
	Price           string  `json:"price"`
	Status          string  `json:"status"`
	Outcome         string  `json:"outcome"`
	OutcomeIndex    int     `json:"outcomeIndex"`
	Owner           string  `json:"owner"`
	Maker           string  `json:"maker"`
	TransactionHash string  `json:"transactionHash"`
	MatchTime       string  `json:"matchTime"`
	BucketIndex     int     `json:"bucketIndex"`
	Fee             string  `json:"fee"`
	FeeUsdc         string  `json:"feeUsdc"`
	ErrMsg          *string `json:"err_msg,omitempty"`
	CreatedAt       *string `json:"createdAt,omitempty"`
	UpdatedAt       *string `json:"updatedAt,omitempty"`
}

BuilderTrade represents a builder trade

type Chain

type Chain int

Chain represents the blockchain network

const (
	ChainPolygon Chain = 137
	ChainAmoy    Chain = 80002
)

type ClobClient

type ClobClient struct {
	Host          string
	ChainID       int
	PrivateKey    string
	Creds         *ApiKeyCreds
	SignatureType SignatureType
	FunderAddress *string
	OrderBuilder  *OrderBuilder
	HTTPClient    *HTTPClient
	UseServerTime bool
	BuilderCreds  *BuilderApiKey
	// contains filtered or unexported fields
}

ClobClient is the main client for interacting with the Polymarket CLOB API

func NewClobClient

func NewClobClient(
	host string,
	chainID int,
	privateKey string,
	creds *ApiKeyCreds,
	signatureType SignatureType,
	funderAddress *string,
) *ClobClient

NewClobClient creates a new CLOB client

func (*ClobClient) CancelAll

func (c *ClobClient) CancelAll() error

CancelAll cancels all open orders

func (*ClobClient) CancelMarketOrders

func (c *ClobClient) CancelMarketOrders(params *OrderMarketCancelParams) error

CancelMarketOrders cancels all orders for a specific market or asset

func (*ClobClient) CancelOrder

func (c *ClobClient) CancelOrder(orderID string) (*OrderResponse, error)

CancelOrder cancels an order by ID

func (*ClobClient) CreateAPIKey

func (c *ClobClient) CreateAPIKey(nonce string) (*ApiKeyCreds, error)

CreateAPIKey creates a new API key using L1 authentication

func (*ClobClient) CreateAndPostOrder

func (c *ClobClient) CreateAndPostOrder(
	userOrder *UserOrder,
	options *CreateOrderOptions,
	orderType OrderType,
) (*OrderResponse, error)

CreateAndPostOrder creates and posts an order in one call

func (*ClobClient) CreateOrDeriveAPIKey

func (c *ClobClient) CreateOrDeriveAPIKey(nonce string) (*ApiKeyCreds, error)

CreateOrDeriveAPIKey creates or derives an API key

func (*ClobClient) CreateOrder

func (c *ClobClient) CreateOrder(
	userOrder *UserOrder,
	options *CreateOrderOptions,
) (*SignedOrder, error)

CreateOrder creates an order from user input

func (*ClobClient) DeriveAPIKey

func (c *ClobClient) DeriveAPIKey(nonce string) (*ApiKeyCreds, error)

DeriveAPIKey derives an API key using L1 authentication

func (*ClobClient) GetBalanceAllowance

func (c *ClobClient) GetBalanceAllowance(params *BalanceAllowanceParams) (*BalanceAllowanceResponse, error)

GetBalanceAllowance retrieves balance and allowance for an asset

func (*ClobClient) GetMidpoint

func (c *ClobClient) GetMidpoint(tokenID string) (float64, error)

GetMidpoint retrieves the midpoint price for a token

func (*ClobClient) GetOpenOrders

func (c *ClobClient) GetOpenOrders(params *OpenOrderParams) ([]OpenOrder, error)

GetOpenOrders retrieves open orders

func (*ClobClient) GetOrderBook

func (c *ClobClient) GetOrderBook(tokenID string) (*OrderBookSummary, error)

GetOrderBook retrieves the order book for a token

func (*ClobClient) GetPrice

func (c *ClobClient) GetPrice(tokenID string, side *Side) (float64, error)

GetPrice retrieves the mid price for a token

func (*ClobClient) GetServerTime

func (c *ClobClient) GetServerTime() (int64, error)

GetServerTime returns the server time

func (*ClobClient) GetTrades

func (c *ClobClient) GetTrades(params *TradeParams) ([]Trade, error)

GetTrades retrieves trades

func (*ClobClient) PostOrder

func (c *ClobClient) PostOrder(args *PostOrderArgs) (*OrderResponse, error)

PostOrder posts a signed order to the exchange

type CreateOrderOptions

type CreateOrderOptions struct {
	TickSize TickSize `json:"tickSize"`
	NegRisk  *bool    `json:"negRisk,omitempty"`
}

CreateOrderOptions represents options for creating an order

type DropNotificationParams

type DropNotificationParams struct {
	IDs []string `json:"ids"`
}

DropNotificationParams represents parameters for dropping notifications

type HTTPClient

type HTTPClient struct {
	// contains filtered or unexported fields
}

HTTPClient handles HTTP requests with retry logic

func NewHTTPClient

func NewHTTPClient(timeout time.Duration, retryEnabled bool) *HTTPClient

NewHTTPClient creates a new HTTP client

func (*HTTPClient) Delete

func (c *HTTPClient) Delete(url string, headers map[string]string, body interface{}) ([]byte, error)

Delete performs a DELETE request

func (*HTTPClient) Get

func (c *HTTPClient) Get(url string, headers map[string]string) ([]byte, error)

Get performs a GET request

func (*HTTPClient) Post

func (c *HTTPClient) Post(url string, headers map[string]string, body interface{}) ([]byte, error)

Post performs a POST request

func (*HTTPClient) Put

func (c *HTTPClient) Put(url string, headers map[string]string, body interface{}) ([]byte, error)

Put performs a PUT request

func (*HTTPClient) Request

func (c *HTTPClient) Request(
	method string,
	url string,
	headers map[string]string,
	body interface{},
) ([]byte, error)

Request performs an HTTP request with optional retry logic

type HeartbeatResponse

type HeartbeatResponse struct {
	HeartbeatID string  `json:"heartbeat_id"`
	Error       *string `json:"error,omitempty"`
}

HeartbeatResponse represents a heartbeat response

type L2HeaderArgs

type L2HeaderArgs struct {
	Method      string
	RequestPath string
	Body        string
}

L2HeaderArgs represents arguments for L2 headers

type MakerOrder

type MakerOrder struct {
	OrderID       string `json:"order_id"`
	Owner         string `json:"owner"`
	MakerAddress  string `json:"maker_address"`
	MatchedAmount string `json:"matched_amount"`
	Price         string `json:"price"`
	FeeRateBps    string `json:"fee_rate_bps"`
	AssetID       string `json:"asset_id"`
	Outcome       string `json:"outcome"`
	Side          Side   `json:"side"`
}

MakerOrder represents a maker order in a trade

type MarketPrice

type MarketPrice struct {
	Timestamp int64   `json:"t"`
	Price     float64 `json:"p"`
}

MarketPrice represents a market price at a timestamp

type MarketTradeEvent

type MarketTradeEvent struct {
	EventType string `json:"event_type"`
	Market    struct {
		ConditionID string `json:"condition_id"`
		AssetID     string `json:"asset_id"`
		Question    string `json:"question"`
		Icon        string `json:"icon"`
		Slug        string `json:"slug"`
	} `json:"market"`
	User struct {
		Address                 string `json:"address"`
		Username                string `json:"username"`
		ProfilePicture          string `json:"profile_picture"`
		OptimizedProfilePicture string `json:"optimized_profile_picture"`
		Pseudonym               string `json:"pseudonym"`
	} `json:"user"`
	Side            Side   `json:"side"`
	Size            string `json:"size"`
	FeeRateBps      string `json:"fee_rate_bps"`
	Price           string `json:"price"`
	Outcome         string `json:"outcome"`
	OutcomeIndex    int    `json:"outcome_index"`
	TransactionHash string `json:"transaction_hash"`
	Timestamp       string `json:"timestamp"`
}

MarketTradeEvent represents a market trade event

type Notification

type Notification struct {
	Type    int         `json:"type"`
	Owner   string      `json:"owner"`
	Payload interface{} `json:"payload"`
}

Notification represents a notification

type OpenOrder

type OpenOrder struct {
	ID              string   `json:"id"`
	Status          string   `json:"status"`
	Owner           string   `json:"owner"`
	MakerAddress    string   `json:"maker_address"`
	Market          string   `json:"market"`
	AssetID         string   `json:"asset_id"`
	Side            string   `json:"side"`
	OriginalSize    string   `json:"original_size"`
	SizeMatched     string   `json:"size_matched"`
	Price           string   `json:"price"`
	AssociateTrades []string `json:"associate_trades"`
	Outcome         string   `json:"outcome"`
	CreatedAt       int64    `json:"created_at"`
	Expiration      string   `json:"expiration"`
	OrderType       string   `json:"order_type"`
}

OpenOrder represents an open order

type OpenOrderParams

type OpenOrderParams struct {
	ID      *string `json:"id,omitempty"`
	Market  *string `json:"market,omitempty"`
	AssetID *string `json:"asset_id,omitempty"`
}

OpenOrderParams represents parameters for open order queries

type OrderBookSummary

type OrderBookSummary struct {
	Market         string         `json:"market"`
	AssetID        string         `json:"asset_id"`
	Timestamp      string         `json:"timestamp"`
	Bids           []OrderSummary `json:"bids"`
	Asks           []OrderSummary `json:"asks"`
	MinOrderSize   string         `json:"min_order_size"`
	TickSize       string         `json:"tick_size"`
	NegRisk        bool           `json:"neg_risk"`
	LastTradePrice string         `json:"last_trade_price"`
	Hash           string         `json:"hash"`
}

OrderBookSummary represents an order book summary

type OrderBuilder

type OrderBuilder struct {
	PrivateKey    string
	ChainID       int
	SignatureType SignatureType
	FunderAddress *string
}

OrderBuilder handles order creation and signing

func NewOrderBuilder

func NewOrderBuilder(
	privateKey string,
	chainID int,
	signatureType SignatureType,
	funderAddress *string,
) *OrderBuilder

NewOrderBuilder creates a new OrderBuilder

func (*OrderBuilder) BuildMarketOrder

func (b *OrderBuilder) BuildMarketOrder(
	userMarketOrder *UserMarketOrder,
	options *CreateOrderOptions,
) (*SignedOrder, error)

BuildMarketOrder creates and signs a market order

func (*OrderBuilder) BuildOrder

func (b *OrderBuilder) BuildOrder(
	userOrder *UserOrder,
	options *CreateOrderOptions,
) (*SignedOrder, error)

BuildOrder creates and signs an order

type OrderMarketCancelParams

type OrderMarketCancelParams struct {
	Market  *string `json:"market,omitempty"`
	AssetID *string `json:"asset_id,omitempty"`
}

OrderMarketCancelParams represents parameters for canceling market orders

type OrderPayload

type OrderPayload struct {
	OrderID string `json:"orderID"`
}

OrderPayload represents the order ID payload

type OrderResponse

type OrderResponse struct {
	Success            bool     `json:"success"`
	ErrorMsg           string   `json:"errorMsg"`
	OrderID            string   `json:"orderID"`
	TransactionsHashes []string `json:"transactionsHashes"`
	Status             string   `json:"status"`
	TakingAmount       string   `json:"takingAmount"`
	MakingAmount       string   `json:"makingAmount"`
}

OrderResponse represents the response from posting an order

type OrderScoring

type OrderScoring struct {
	Scoring bool `json:"scoring"`
}

OrderScoring represents order scoring

type OrderScoringParams

type OrderScoringParams struct {
	OrderID string `json:"order_id"`
}

OrderScoringParams represents parameters for order scoring

type OrderSummary

type OrderSummary struct {
	Price string `json:"price"`
	Size  string `json:"size"`
}

OrderSummary represents a price level in the order book

type OrderType

type OrderType string

OrderType represents the type of order

const (
	OrderTypeGTC OrderType = "GTC" // Good Till Cancel
	OrderTypeFOK OrderType = "FOK" // Fill or Kill
	OrderTypeGTD OrderType = "GTD" // Good Till Date
	OrderTypeFAK OrderType = "FAK" // Fill and Kill
)

type OrdersScoring

type OrdersScoring map[string]bool

OrdersScoring represents scoring for multiple orders

type OrdersScoringParams

type OrdersScoringParams struct {
	OrderIDs []string `json:"orderIds"`
}

OrdersScoringParams represents parameters for multiple order scoring

type PaginationPayload

type PaginationPayload struct {
	Limit      int           `json:"limit"`
	Count      int           `json:"count"`
	NextCursor string        `json:"next_cursor"`
	Data       []interface{} `json:"data"`
}

PaginationPayload represents a paginated response

type PostOrderArgs

type PostOrderArgs struct {
	Order     SignedOrder `json:"order"`
	OrderType OrderType   `json:"orderType"`
	PostOnly  *bool       `json:"postOnly,omitempty"`
}

PostOrderArgs represents arguments for posting an order

type PriceHistoryFilterParams

type PriceHistoryFilterParams struct {
	Market   *string               `json:"market,omitempty"`
	StartTs  *int64                `json:"startTs,omitempty"`
	EndTs    *int64                `json:"endTs,omitempty"`
	Fidelity *int                  `json:"fidelity,omitempty"`
	Interval *PriceHistoryInterval `json:"interval,omitempty"`
}

PriceHistoryFilterParams represents parameters for price history queries

type PriceHistoryInterval

type PriceHistoryInterval string

PriceHistoryInterval represents the interval for price history

const (
	PriceHistoryIntervalMax      PriceHistoryInterval = "max"
	PriceHistoryIntervalOneWeek  PriceHistoryInterval = "1w"
	PriceHistoryIntervalOneDay   PriceHistoryInterval = "1d"
	PriceHistoryIntervalSixHours PriceHistoryInterval = "6h"
	PriceHistoryIntervalOneHour  PriceHistoryInterval = "1h"
)

type ReadonlyApiKeyResponse

type ReadonlyApiKeyResponse struct {
	ApiKey string `json:"apiKey"`
}

ReadonlyApiKeyResponse represents readonly API key response

type RoundConfig

type RoundConfig struct {
	Price  int `json:"price"`
	Size   int `json:"size"`
	Amount int `json:"amount"`
}

RoundConfig represents rounding configuration

type Side

type Side string

Side represents the order side

const (
	SideBuy  Side = "BUY"
	SideSell Side = "SELL"
)

type SignatureType

type SignatureType int

SignatureType represents the signature type for orders

const (
	SignatureTypeEOA            SignatureType = 0
	SignatureTypePOLYPROXY      SignatureType = 1
	SignatureTypePOLYGNOSISSAFE SignatureType = 2
)

type SignedOrder

type SignedOrder struct {
	Salt          int64         `json:"salt"`
	Maker         string        `json:"maker"`
	Signer        string        `json:"signer"`
	Taker         string        `json:"taker"`
	TokenID       string        `json:"tokenId"`
	MakerAmount   string        `json:"makerAmount"`
	TakerAmount   string        `json:"takerAmount"`
	Expiration    string        `json:"expiration"`
	Nonce         string        `json:"nonce"`
	FeeRateBps    string        `json:"feeRateBps"`
	Side          Side          `json:"side"`
	SignatureType SignatureType `json:"signatureType"`
	Signature     string        `json:"signature"`
}

SignedOrder represents a signed order

type TickSize

type TickSize string

TickSize represents the minimum price increment

const (
	TickSize01    TickSize = "0.1"
	TickSize001   TickSize = "0.01"
	TickSize0001  TickSize = "0.001"
	TickSize00001 TickSize = "0.0001"
)

type Trade

type Trade struct {
	ID              string       `json:"id"`
	TakerOrderID    string       `json:"taker_order_id"`
	Market          string       `json:"market"`
	AssetID         string       `json:"asset_id"`
	Side            Side         `json:"side"`
	Size            string       `json:"size"`
	FeeRateBps      string       `json:"fee_rate_bps"`
	Price           string       `json:"price"`
	Status          string       `json:"status"`
	MatchTime       string       `json:"match_time"`
	LastUpdate      string       `json:"last_update"`
	Outcome         string       `json:"outcome"`
	BucketIndex     int          `json:"bucket_index"`
	Owner           string       `json:"owner"`
	MakerAddress    string       `json:"maker_address"`
	MakerOrders     []MakerOrder `json:"maker_orders"`
	TransactionHash string       `json:"transaction_hash"`
	TraderSide      string       `json:"trader_side"` // TAKER or MAKER
}

Trade represents a trade

type TradeParams

type TradeParams struct {
	ID           *string `json:"id,omitempty"`
	MakerAddress *string `json:"maker_address,omitempty"`
	Market       *string `json:"market,omitempty"`
	AssetID      *string `json:"asset_id,omitempty"`
	Before       *string `json:"before,omitempty"`
	After        *string `json:"after,omitempty"`
}

TradeParams represents parameters for trade queries

type UserMarketOrder

type UserMarketOrder struct {
	TokenID    string     `json:"tokenID"`
	Price      *float64   `json:"price,omitempty"`
	Amount     float64    `json:"amount"`
	Side       Side       `json:"side"`
	FeeRateBps *int       `json:"feeRateBps,omitempty"`
	Nonce      *int64     `json:"nonce,omitempty"`
	Taker      *string    `json:"taker,omitempty"`
	OrderType  *OrderType `json:"orderType,omitempty"`
}

UserMarketOrder represents a simplified market order for users

type UserOrder

type UserOrder struct {
	TokenID    string  `json:"tokenID"`
	Price      float64 `json:"price"`
	Size       float64 `json:"size"`
	Side       Side    `json:"side"`
	FeeRateBps *int    `json:"feeRateBps,omitempty"`
	Nonce      *int64  `json:"nonce,omitempty"`
	Expiration *int64  `json:"expiration,omitempty"`
	Taker      *string `json:"taker,omitempty"`
}

UserOrder represents a simplified order for users

Directories

Path Synopsis
examples
create_order command
market_data command

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL