clob

package
v0.1.0 Latest Latest
Warning

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

Go to latest
Published: Mar 15, 2026 License: MIT Imports: 27 Imported by: 0

Documentation

Index

Constants

View Source
const (
	EndpointBalanceAllowance       = "/balance-allowance"
	EndpointUpdateBalanceAllowance = "/balance-allowance/update"
	EndpointClosedOnlyMode         = "/auth/ban-status/closed-only"
)

Account endpoints

View Source
const (
	EndpointBuilderTrades    = "/builder/trades"
	EndpointBuilderAPIKey    = "/auth/builder-api-key"
	EndpointBuilderAPIKeys   = "/auth/builder-api-key"
	EndpointRevokeBuilderKey = "/auth/builder-api-key"
)

Builder API endpoints

View Source
const (
	EndpointCreateReadonlyKey   = "/auth/readonly-api-key"
	EndpointGetReadonlyKeys     = "/auth/readonly-api-keys"
	EndpointDeleteReadonlyKey   = "/auth/readonly-api-key"
	EndpointValidateReadonlyKey = "/auth/validate-readonly-api-key"
)

Readonly API endpoints

View Source
const (
	EndpointTime                      = "/time"
	EndpointMarkets                   = "/markets"
	EndpointMarket                    = "/markets/"
	EndpointSimplifiedMarkets         = "/simplified-markets"
	EndpointSamplingMarkets           = "/sampling-markets"
	EndpointSamplingSimplifiedMarkets = "/sampling-simplified-markets"
	EndpointOrderBook                 = "/book"
	EndpointOrderBooks                = "/books"
	EndpointMidpoint                  = "/midpoint"
	EndpointMidpoints                 = "/midpoints"
	EndpointPrice                     = "/price"
	EndpointPrices                    = "/prices"
	EndpointSpread                    = "/spread"
	EndpointSpreads                   = "/spreads"
	EndpointLastTradePrice            = "/last-trade-price"
	EndpointLastTradesPrices          = "/last-trades-prices"
	EndpointPricesHistory             = "/prices-history"
	EndpointTrades                    = "/data/trades"
	EndpointMarketTradesEvents        = "/live-activity/events/"
)

Market data endpoints

View Source
const (
	InitialCursor = ""
	EndCursor     = "LTE="
)

Pagination constants

View Source
const (
	EndpointNotifications     = "/notifications"
	EndpointDropNotifications = "/notifications"
)

Notification endpoints

View Source
const (
	EndpointPostOrders         = "/orders"
	EndpointCancelOrders       = "/orders"
	EndpointCancelMarketOrders = "/cancel-market-orders"
	EndpointOpenOrders         = "/data/orders"
	EndpointTickSize           = "/tick-size"
	EndpointNegRisk            = "/neg-risk"
	EndpointFeeRate            = "/fee-rate"
)

Order endpoints

View Source
const (
	CollateralTokenDecimals = 6
	ZeroAddress             = "0x0000000000000000000000000000000000000000"
)
View Source
const (
	EndpointUserEarnings               = "/rewards/user"
	EndpointTotalUserEarnings          = "/rewards/user/total"
	EndpointLiquidityRewardPercentages = "/rewards/user/percentages"
	EndpointRewardsMarketsCurrent      = "/rewards/markets/current"
	EndpointRewardsMarkets             = "/rewards/markets/"
	EndpointRewardsEarningsPercentages = "/rewards/user/markets"
)

Rewards endpoints

View Source
const (
	WsChannelMarket = "market"
	WsChannelBook   = "book"
	WsChannelTrade  = "trade"
	WsChannelUser   = "user"
)

WebSocket channel types

View Source
const (
	BaseURL = "https://clob.polymarket.com"
)
View Source
const (
	WsURL = "wss://ws-subscriptions-clob.polymarket.com/ws"
)

WebSocket endpoints

Variables

View Source
var (
	ErrL1AuthUnavailable   = fmt.Errorf("L1 authentication not available")
	ErrL2AuthNotAvailable  = fmt.Errorf("L2 authentication not available")
	ErrBuilderAuthFailed   = fmt.Errorf("builder authentication failed")
	ErrInvalidSignature    = fmt.Errorf("invalid signature")
	ErrInsufficientBalance = fmt.Errorf("insufficient balance/allowance")
	ErrOrderNotFound       = fmt.Errorf("order not found")
	ErrMarketNotFound      = fmt.Errorf("market not found")
	ErrNotConnected        = fmt.Errorf("WebSocket not connected")
)

Common errors

View Source
var RoundingConfigs = map[TickSize]RoundConfig{
	TickSize01:    {Price: 1, Size: 2, Amount: 3},
	TickSize001:   {Price: 2, Size: 2, Amount: 4},
	TickSize0001:  {Price: 3, Size: 2, Amount: 5},
	TickSize00001: {Price: 4, Size: 2, Amount: 6},
}

Functions

func ClearMetadataCache

func ClearMetadataCache()

ClearMetadataCache clears all cached metadata (useful for testing or forcing refresh)

func FormatPrice

func FormatPrice(price float64, precision int) string

FormatPrice formats price with appropriate precision

func GenerateOrderBookSummaryHash

func GenerateOrderBookSummaryHash(summary *OrderBookSummary) string

GenerateOrderBookSummaryHash generates a hash for orderbook summary

func IsTickSizeSmaller

func IsTickSizeSmaller(a, b string) bool

IsTickSizeSmaller compares two tick sizes

func IsValidPrice

func IsValidPrice(price float64, tickSize TickSize) bool

func NormalizeTickSize

func NormalizeTickSize(tickSize string) string

NormalizeTickSize normalizes API tick size format to builder format "0.0100" -> "0.01", "0.1000" -> "0.1"

func OrderToJSON

func OrderToJSON(order *SignedOrderResponse) (string, error)

OrderToJSON converts an order to JSON string

func ParseFloatSafe

func ParseFloatSafe(s string) (float64, error)

ParseFloatSafe safely parses a float from string

func RoundToTickSize

func RoundToTickSize(price float64, tickSize string) float64

RoundToTickSize rounds a price to the nearest tick size

Types

type APIError

type APIError struct {
	StatusCode int
	Message    string
	Code       int
}

APIError represents a structured API error response

func NewAPIError

func NewAPIError(statusCode int, message string, code int) *APIError

NewAPIError creates a new API error

func (*APIError) Error

func (e *APIError) Error() string

type BalanceAllowanceParams

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

BalanceAllowanceParams for balance/allowance queries

type BalanceAllowanceResponse

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

BalanceAllowanceResponse for balance/allowance data

type BanStatus

type BanStatus struct {
	ClosedOnly bool   `json:"closed_only"`
	Reason     string `json:"reason,omitempty"`
}

BanStatus represents account ban/restriction status

type BatchOrderResponse

type BatchOrderResponse struct {
	Success []OrderResponse `json:"success,omitempty"`
	Errors  []struct {
		Index int    `json:"index"`
		Error string `json:"error"`
	} `json:"errors,omitempty"`
}

BatchOrderResponse for batch order creation

type BookParams

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

BookParams for batch orderbook queries

type BuildOrderOptions

type BuildOrderOptions struct {
	TickSize string
	NegRisk  bool
	Maker    string
}

type BuilderApiKeyResponse

type BuilderApiKeyResponse struct {
	APIKey string `json:"apiKey"`
	Secret string `json:"secret"`
}

BuilderApiKeyResponse for builder API key creation

type BuilderConfig

type BuilderConfig struct {
	BuilderID string `json:"builder_id,omitempty"`
}

BuilderConfig for builder API configuration

type CancelAllResponse

type CancelAllResponse struct {
	Success bool   `json:"success"`
	Error   string `json:"error,omitempty"`
}

CancelAllResponse for cancel-all endpoint

type CancelOrderResponse

type CancelOrderResponse struct {
	Success bool   `json:"success"`
	Error   string `json:"error,omitempty"`
}

CancelOrderResponse for single order cancellation

type CancelOrdersResponse

type CancelOrdersResponse struct {
	Success []string `json:"success,omitempty"`
	Errors  []struct {
		OrderID string `json:"orderId"`
		Error   string `json:"error"`
	} `json:"errors,omitempty"`
}

CancelOrdersResponse for batch order cancellation

type ClobClient

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

func NewClient

func NewClient(baseURL string, logger *zap.SugaredLogger) *ClobClient

func (*ClobClient) ApproveUSDC

func (c *ClobClient) ApproveUSDC(ctx context.Context, amount string) error

ApproveUSDC is a helper method to approve USDC spending for trading This typically requires the user to sign a transaction on-chain For now, this is a placeholder that would need integration with web3 wallet

func (*ClobClient) CalculateMarketPrice

func (c *ClobClient) CalculateMarketPrice(ctx context.Context, tokenID string, side Side, amount float64) (float64, error)

CalculateMarketPrice calculates the worst price needed to fill the amount by traversing the orderbook

func (*ClobClient) CancelAllOrders

func (c *ClobClient) CancelAllOrders(ctx context.Context) error

CancelAllOrders cancels all open orders

func (*ClobClient) CancelMarketOrders

func (c *ClobClient) CancelMarketOrders(ctx context.Context, params OrderMarketCancelParams) error

CancelMarketOrders cancels all orders for a specific market

func (*ClobClient) CancelOrder

func (c *ClobClient) CancelOrder(ctx context.Context, orderID string) error

CancelOrder cancels a single order

func (*ClobClient) CancelOrders

func (c *ClobClient) CancelOrders(ctx context.Context, orderIDs []string) (*CancelOrdersResponse, error)

CancelOrders cancels multiple orders by their IDs

func (*ClobClient) CreateBuilderAPIKey

func (c *ClobClient) CreateBuilderAPIKey(ctx context.Context, builderConfig BuilderConfig) (*BuilderApiKeyResponse, error)

CreateBuilderAPIKey creates a new builder API key

func (*ClobClient) CreateMarketOrder

func (c *ClobClient) CreateMarketOrder(ctx context.Context, userMarketOrder UserMarketOrderParams, tickSize string, negRisk bool) (*OrderResponse, error)

CreateMarketOrder creates a market order by calculating price from orderbook and building a FOK order, then posts it

func (*ClobClient) CreateOrder

func (c *ClobClient) CreateOrder(ctx context.Context, params UserOrderParams, tickSize string, negRisk bool) (*OrderResponse, error)

CreateOrder creates and signs an order, then posts it

func (*ClobClient) DeleteReadonlyAPIKey

func (c *ClobClient) DeleteReadonlyAPIKey(ctx context.Context, key string) (bool, error)

... DeleteReadonlyAPIKey deletes a readonly API key

func (*ClobClient) DropNotifications

func (c *ClobClient) DropNotifications(ctx context.Context, params DropNotificationParams) error

DropNotifications marks notifications as read/dropped

func (*ClobClient) EnsureAuth

func (c *ClobClient) EnsureAuth(ctx context.Context) error

EnsureAuth makes sure we have L2 credentials (API Credentials) If they are missing but we have a Private Key, we try to derive them.

func (*ClobClient) GetAPIKey

func (c *ClobClient) GetAPIKey() string

GetAPIKey returns the L2 API Key (may trigger derivation if not yet available)

func (*ClobClient) GetAPIPassphrase

func (c *ClobClient) GetAPIPassphrase() string

GetAPIPassphrase returns the L2 API Passphrase

func (*ClobClient) GetAPISecret

func (c *ClobClient) GetAPISecret() string

GetAPISecret returns the L2 API Secret

func (*ClobClient) GetActiveMarkets

func (c *ClobClient) GetActiveMarkets(ctx context.Context, nextCursor string) (*PaginationPayload, error)

GetActiveMarkets fetches a paginated list of active markets

func (*ClobClient) GetBalanceAllowance

func (c *ClobClient) GetBalanceAllowance(ctx context.Context, params BalanceAllowanceParams) (*BalanceAllowanceResponse, error)

GetBalanceAllowance fetches the USDC balance and allowance for trading

func (*ClobClient) GetBuilderTrades

func (c *ClobClient) GetBuilderTrades(ctx context.Context, params TradeParams, nextCursor string) (*PaginationPayload, error)

GetBuilderTrades fetches trade history for builder

func (*ClobClient) GetClosedOnlyMode

func (c *ClobClient) GetClosedOnlyMode(ctx context.Context) (*BanStatus, error)

GetClosedOnlyMode checks if the account is in closed-only (ban) mode

func (*ClobClient) GetFeeRateBps

func (c *ClobClient) GetFeeRateBps(ctx context.Context, tokenID string) (int, error)

GetFeeRateBps fetches the fee rate in basis points for a token (with caching)

func (*ClobClient) GetFunderAddress

func (c *ClobClient) GetFunderAddress() string

GetFunderAddress returns the L1 Funder Address

func (*ClobClient) GetLastTradePrice

func (c *ClobClient) GetLastTradePrice(ctx context.Context, tokenID string) (float64, error)

GetLastTradePrice fetches the last trade price for a token

func (*ClobClient) GetLastTradesPrices

func (c *ClobClient) GetLastTradesPrices(ctx context.Context, params []BookParams) ([]float64, error)

GetLastTradesPrices fetches last trade prices for multiple tokens in batch

func (*ClobClient) GetLiquidityRewardPercentages

func (c *ClobClient) GetLiquidityRewardPercentages(ctx context.Context, market string) (*RewardsPercentages, error)

GetLiquidityRewardPercentages fetches reward percentages for a market

func (*ClobClient) GetMarket

func (c *ClobClient) GetMarket(ctx context.Context, conditionID string) (*Market, error)

GetMarket fetches a single market by condition ID

func (*ClobClient) GetMarketTradesEvents

func (c *ClobClient) GetMarketTradesEvents(ctx context.Context, conditionID string) ([]*MarketTradeEvent, error)

GetMarketTradesEvents fetches live activity events for a market

func (*ClobClient) GetMarkets

func (c *ClobClient) GetMarkets(ctx context.Context, nextCursor string) (*PaginationPayload, error)

GetMarkets fetches a paginated list of markets

func (*ClobClient) GetMidpoint

func (c *ClobClient) GetMidpoint(ctx context.Context, tokenID string) (float64, error)

GetMidpoint fetches the midpoint price for a token

func (*ClobClient) GetMidpoints

func (c *ClobClient) GetMidpoints(ctx context.Context, params []BookParams) ([]float64, error)

GetMidpoints fetches midpoints for multiple tokens in batch

func (*ClobClient) GetNegRisk

func (c *ClobClient) GetNegRisk(ctx context.Context, tokenID string) (bool, error)

GetNegRisk checks if a token uses negative risk (with caching)

func (*ClobClient) GetNotifications

func (c *ClobClient) GetNotifications(ctx context.Context) ([]*Notification, error)

GetNotifications fetches user notifications

func (*ClobClient) GetOpenOrders

func (c *ClobClient) GetOpenOrders(ctx context.Context, params OpenOrderParams) (*OpenOrdersResponse, error)

GetOpenOrders fetches open orders for the authenticated user

func (*ClobClient) GetOrder

func (c *ClobClient) GetOrder(ctx context.Context, orderID string) (*OrderResponse, error)

GetOrder fetches a single order.

func (*ClobClient) GetOrderBook

func (c *ClobClient) GetOrderBook(ctx context.Context, tokenID string) (*OrderBookSummary, error)

GetOrderBook fetches the order book for a specific token

func (*ClobClient) GetOrderBooks

func (c *ClobClient) GetOrderBooks(ctx context.Context, params []BookParams) ([]*OrderBookSummary, error)

GetOrderBooks fetches order books for multiple tokens in batch

func (*ClobClient) GetOrderbook

func (c *ClobClient) GetOrderbook(ctx context.Context, tokenID string) (*Orderbook, error)

func (*ClobClient) GetPrice

func (c *ClobClient) GetPrice(ctx context.Context, tokenID string, side Side) (float64, error)

GetPrice fetches the best price for a token and side

func (*ClobClient) GetPrices

func (c *ClobClient) GetPrices(ctx context.Context, params []BookParams) ([]float64, error)

GetPrices fetches prices for multiple tokens in batch

func (*ClobClient) GetPricesHistory

func (c *ClobClient) GetPricesHistory(ctx context.Context, params PriceHistoryFilterParams) ([]MarketPrice, error)

GetPricesHistory fetches historical prices for a market

func (*ClobClient) GetRewardsEarningsPercentages

func (c *ClobClient) GetRewardsEarningsPercentages(ctx context.Context, market string, day string) (*UserRewardsEarning, error)

GetRewardsEarningsPercentages fetches earnings percentages breakdown

func (*ClobClient) GetRewardsMarketsCurrentScoring

func (c *ClobClient) GetRewardsMarketsCurrentScoring(ctx context.Context) ([]*MarketReward, error)

GetRewardsMarketsCurrentScoring fetches currently scoring markets

func (*ClobClient) GetRewardsMarketsScoring

func (c *ClobClient) GetRewardsMarketsScoring(ctx context.Context, market string, day string) (*MarketReward, error)

GetRewardsMarketsScoring fetches scoring info for a specific market and day

func (*ClobClient) GetSamplingMarkets

func (c *ClobClient) GetSamplingMarkets(ctx context.Context, nextCursor string) (*PaginationPayload, error)

GetSamplingMarkets fetches a sample of markets for quick overview

func (*ClobClient) GetServerTime

func (c *ClobClient) GetServerTime(ctx context.Context) (int64, error)

GetServerTime returns the current server timestamp in seconds

func (*ClobClient) GetSimplifiedMarkets

func (c *ClobClient) GetSimplifiedMarkets(ctx context.Context, nextCursor string) (*PaginationPayload, error)

GetSimplifiedMarkets fetches a paginated list of simplified market data

func (*ClobClient) GetSpread

func (c *ClobClient) GetSpread(ctx context.Context, tokenID string) (float64, error)

GetSpread fetches the bid-ask spread for a token

func (*ClobClient) GetSpreads

func (c *ClobClient) GetSpreads(ctx context.Context, params []BookParams) ([]float64, error)

GetSpreads fetches spreads for multiple tokens in batch

func (*ClobClient) GetTickSize

func (c *ClobClient) GetTickSize(ctx context.Context, tokenID string) (string, error)

GetTickSize fetches the tick size for a token (with caching)

func (*ClobClient) GetTotalUserEarnings

func (c *ClobClient) GetTotalUserEarnings(ctx context.Context, day string) (*TotalUserEarning, error)

GetTotalUserEarnings fetches total user earnings for a specific day

func (*ClobClient) GetTrades

func (c *ClobClient) GetTrades(ctx context.Context, params TradeParams) ([]*Trade, error)

GetTrades fetches trade history

func (*ClobClient) GetTradesPaginated

func (c *ClobClient) GetTradesPaginated(ctx context.Context, params TradeParams, nextCursor string) (*PaginationPayload, error)

GetTradesPaginated fetches trade history with pagination

func (*ClobClient) GetUserEarnings

func (c *ClobClient) GetUserEarnings(ctx context.Context, day string) (*UserEarning, error)

GetUserEarnings fetches user earnings for a specific day

func (*ClobClient) PostOrders

func (c *ClobClient) PostOrders(ctx context.Context, orders []PostOrdersArgs, deferExec bool) (*BatchOrderResponse, error)

PostOrders creates multiple orders in a single batch

func (*ClobClient) RevokeBuilderAPIKey

func (c *ClobClient) RevokeBuilderAPIKey(ctx context.Context, builderConfig BuilderConfig, key string) (bool, error)

... RevokeBuilderAPIKey revokes a builder API key

func (*ClobClient) UpdateBalanceAllowance

func (c *ClobClient) UpdateBalanceAllowance(ctx context.Context, params BalanceAllowanceParams) error

UpdateBalanceAllowance updates the USDC allowance for trading

func (*ClobClient) ValidateReadonlyAPIKey

func (c *ClobClient) ValidateReadonlyAPIKey(ctx context.Context, address string, key string) (string, error)

ValidateReadonlyAPIKey validates a readonly API key

func (*ClobClient) WithCredentials

func (c *ClobClient) WithCredentials(creds *Credentials) *ClobClient

type Credentials

type Credentials struct {
	APIKey        string
	APISecret     string
	APIPassphrase string
	PrivateKey    string
	FunderAddress string
	ChainID       int64
}

type DeriveKeyResponse

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

type DropNotificationParams

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

DropNotificationParams for marking notifications as read

type ErrorResponse

type ErrorResponse struct {
	Message string `json:"message"`
	Code    int    `json:"code,omitempty"`
}

ErrorResponse represents error from API

type Market

type Market struct {
	EnableOrderBook         bool     `json:"enable_order_book"`
	Active                  bool     `json:"active"`
	Closed                  bool     `json:"closed"`
	Archived                bool     `json:"archived"`
	AcceptingOrders         bool     `json:"accepting_orders"`
	AcceptingOrderTimestamp string   `json:"accepting_order_timestamp"`
	MinimumOrderSize        int      `json:"minimum_order_size"`
	MinimumTickSize         float64  `json:"minimum_tick_size"`
	ConditionID             string   `json:"condition_id"`
	QuestionID              string   `json:"question_id"`
	Question                string   `json:"question"`
	Description             string   `json:"description"`
	MarketSlug              string   `json:"market_slug"`
	EndDateISO              string   `json:"end_date_iso"`
	GameStartTime           string   `json:"game_start_time"`
	SecondsDelay            int      `json:"seconds_delay"`
	FPMM                    string   `json:"fpmm"`
	MakerBaseFee            int      `json:"maker_base_fee"`
	TakerBaseFee            int      `json:"taker_base_fee"`
	NotificationsEnabled    bool     `json:"notifications_enabled"`
	NegRisk                 bool     `json:"neg_risk"`
	NegRiskMarketID         string   `json:"neg_risk_market_id"`
	NegRiskRequestID        string   `json:"neg_risk_request_id"`
	Icon                    string   `json:"icon"`
	Image                   string   `json:"image"`
	Rewards                 Reward   `json:"rewards"`
	Is5050Outcome           bool     `json:"is_50_50_outcome"`
	Tokens                  []Token  `json:"tokens,omitempty"`
	Tags                    []string `json:"tags"`
}

Market represents a Polymarket conditional market

type MarketPrice

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

MarketPrice represents a price data point

type MarketPriceHistory

type MarketPriceHistory struct {
	History []MarketPrice `json:"history"`
}

type MarketReward

type MarketReward struct {
	Market     string `json:"market"`
	RewardPool string `json:"reward_pool,omitempty"`
	Day        string `json:"day,omitempty"`
}

MarketReward represents market reward information

type MarketTradeEvent

type MarketTradeEvent struct {
	ID        string `json:"id"`
	EventType string `json:"event_type"`
	Market    string `json:"market"`
	Asset     string `json:"asset_id"`
	Price     string `json:"price"`
	Size      string `json:"size"`
	Side      string `json:"side"`
	Timestamp int64  `json:"timestamp"`
}

MarketTradeEvent represents live market activity

type Notification

type Notification struct {
	ID        string `json:"id"`
	Type      string `json:"type"`
	Message   string `json:"message"`
	CreatedAt int64  `json:"created_at"`
	Read      bool   `json:"read,omitempty"`
}

Notification represents a user notification

type OpenOrder

type OpenOrder struct {
	ID              string `json:"id"`
	Market          string `json:"market"`
	Asset           string `json:"asset"`
	Owner           string `json:"owner"`
	Maker           string `json:"maker"`
	Taker           string `json:"taker"`
	Side            Side   `json:"side"`
	Price           string `json:"price"`
	OriginalSize    string `json:"original_size"`
	SizeMatched     string `json:"size_matched,omitempty"`
	Status          string `json:"status"`
	OrderType       string `json:"type,omitempty"`
	CreatedAt       int64  `json:"created_at"`
	Expiration      string `json:"expiration,omitempty"` // Changed to string
	AssociatedOrder string `json:"associated_order,omitempty"`
}

OpenOrder represents an open order

type OpenOrderParams

type OpenOrderParams struct {
	Market     string `json:"market,omitempty"`
	Asset      string `json:"asset,omitempty"`
	NextCursor string `json:"next_cursor,omitempty"`
}

OpenOrderParams for querying open orders

type OpenOrdersResponse

type OpenOrdersResponse struct {
	NextCursor string       `json:"next_cursor"`
	Data       []*OpenOrder `json:"data"`
}

OpenOrdersResponse for open orders query

type OrderArgs

type OrderArgs struct {
	TokenID    string
	Side       string
	Price      string
	Size       string
	FeeRateBps string
	Nonce      string
	Expiration string
}

OrderArgs represents order arguments (simplified, for backward compatibility)

type OrderBookSummary

type OrderBookSummary struct {
	Market       string       `json:"market"`
	AssetID      string       `json:"asset_id"`
	Hash         string       `json:"hash,omitempty"`
	Bids         []PriceLevel `json:"bids"`
	Asks         []PriceLevel `json:"asks"`
	MinOrderSize string       `json:"min_order_size"`
	TickSize     string       `json:"tick_size"`
	Timestamp    string       `json:"timestamp,omitempty"`
}

OrderBookSummary represents order book data

type OrderBuilder

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

func NewOrderBuilder

func NewOrderBuilder(signer *Signer, chainID int64) *OrderBuilder

func (*OrderBuilder) BuildMarketOrder

func (b *OrderBuilder) BuildMarketOrder(params UserMarketOrderParams, opts BuildOrderOptions) (*SignedOrderResponse, error)

BuildMarketOrder builds a market order (amount based)

func (*OrderBuilder) BuildOrder

BuildOrder creates and signs a limit order using official go-order-utils

type OrderMarketCancelParams

type OrderMarketCancelParams struct {
	Market string `json:"market,omitempty"`
	Asset  string `json:"asset,omitempty"`
}

OrderMarketCancelParams for cancelling market orders

type OrderResponse

type OrderResponse struct {
	OrderID string      `json:"orderID"`
	Status  OrderStatus `json:"status"`
}

OrderResponse represents response from Create/GetOrder

type OrderStatus

type OrderStatus string
const (
	OrderStatusMatched   OrderStatus = "MATCHED"
	OrderStatusLive      OrderStatus = "LIVE"
	OrderStatusDelayed   OrderStatus = "DELAYED"
	OrderStatusUnmatched OrderStatus = "UNMATCHED"
)

type OrderSummary

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

OrderSummary represents a price level in the orderbook

type OrderType

type OrderType string

OrderType represents the type of order

const (
	OrderTypeGTC OrderType = "GTC" // Good til cancelled
	OrderTypeGTD OrderType = "GTD" // Good til date
	OrderTypeFOK OrderType = "FOK" // Fill or kill
	OrderTypeFAK OrderType = "FAK" // Fill and kill
)

type Orderbook

type Orderbook struct {
	AssetID string         `json:"asset_id"`
	Bids    []OrderSummary `json:"bids"`
	Asks    []OrderSummary `json:"asks"`
}

Orderbook represents an L2 orderbook for a token

func (*Orderbook) ToGeneric

func (ob *Orderbook) ToGeneric(marketID string) *prediction.Orderbook

ToGenericOrderbook converts the Polymarket Orderbook to the generic prediction.Orderbook

type PaginationPayload

type PaginationPayload struct {
	NextCursor string        `json:"next_cursor"`
	Data       []interface{} `json:"data"`
}

PaginationPayload represents paginated API response

type PostOrdersArgs

type PostOrdersArgs struct {
	Order     *SignedOrderResponse `json:"order"`
	OrderType OrderType            `json:"orderType"`
	Owner     string               `json:"owner"`
}

PostOrdersArgs for batch order creation

type PriceHistoryFilterParams

type PriceHistoryFilterParams struct {
	Market   string `json:"market,omitempty"`
	Interval string `json:"interval,omitempty"`
	StartTS  int64  `json:"startTs,omitempty"`
	EndTS    int64  `json:"endTs,omitempty"`
	Fidelity int    `json:"fidelity,omitempty"`
}

PriceHistoryFilterParams for price history queries

type PriceLevel

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

PriceLevel represents a single price level in order book

type Rate

type Rate struct {
	AssetAddress     string `json:"asset_address"`
	RewardsDailyRate int    `json:"rewards_daily_rate"`
}

type ReadonlyApiKeyResponse

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

ReadonlyApiKeyResponse for readonly API key creation

type Reward

type Reward struct {
	Rates     []Rate  `json:"rates"`
	MinSize   int     `json:"min_size"`
	MaxSpread float64 `json:"max_spread"`
}

type RewardsPercentages

type RewardsPercentages struct {
	Market      string    `json:"market"`
	Percentages []float64 `json:"percentages,omitempty"`
}

RewardsPercentages represents reward percentage breakdown

type RoundConfig

type RoundConfig struct {
	Price  int
	Size   int
	Amount int
}

type Side

type Side string

Side represents the side of an order

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

type SignedOrderResponse

type SignedOrderResponse 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"`
	Side          string `json:"side"`
	Expiration    string `json:"expiration"`
	Nonce         string `json:"nonce"`
	FeeRateBps    string `json:"feeRateBps"`
	SignatureType int    `json:"signatureType"`
	Signature     string `json:"signature"`
}

SignedOrderResponse matches TypeScript SDK's NewOrder.order structure

type Signer

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

Signer wraps official go-order-utils signing functionality

func NewSigner

func NewSigner(privateKeyHex string, chainID int64) (*Signer, error)

NewSigner creates a new signer

func (*Signer) GetAddress

func (s *Signer) GetAddress() string

GetAddress returns the Ethereum address

func (*Signer) SignClobAuth

func (s *Signer) SignClobAuth(nonce, timestamp int64) (string, error)

SignClobAuth signs ClobAuth for L1 authentication

func (*Signer) SignOrder

func (s *Signer) SignOrder(orderData *orderutils.OrderData, contract orderutils.VerifyingContract) (*orderutils.SignedOrder, error)

SignOrder signs an order using official go-order-utils ExchangeOrderBuilder

type TickSize

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

type Token

type Token struct {
	TokenID string  `json:"token_id"`
	Outcome string  `json:"outcome"`
	Price   float64 `json:"price"`
	Winner  bool    `json:"winner"`
}

type TotalUserEarning

type TotalUserEarning struct {
	Total string `json:"total"`
}

TotalUserEarning represents total earnings

type Trade

type Trade struct {
	ID         string `json:"id"`
	Market     string `json:"market"`
	Asset      string `json:"asset"`
	Side       Side   `json:"side"`
	Price      string `json:"price"`
	Size       string `json:"size"`
	FeeRateBps string `json:"fee_rate_bps"`
	Timestamp  int64  `json:"timestamp"`
	Maker      string `json:"maker,omitempty"`
	Taker      string `json:"taker,omitempty"`
	MatchID    string `json:"match_id,omitempty"`
}

Trade represents a trade event

type TradeParams

type TradeParams struct {
	Maker  string `json:"maker,omitempty"`
	Market string `json:"market,omitempty"`
	Asset  string `json:"asset,omitempty"`
}

TradeParams for trade queries

type UserEarning

type UserEarning struct {
	Day      string `json:"day"`
	Earnings string `json:"earnings"`
	Markets  int    `json:"markets,omitempty"`
}

UserEarning represents user earnings data

type UserMarketOrderParams

type UserMarketOrderParams struct {
	TokenID    string
	Amount     float64 // USDC for BUY, Tokens for SELL
	Side       Side
	Price      *float64 // Optional limit price protection
	FeeRateBps int
	Nonce      int64
	Taker      string
	OrderType  OrderType // e.g. FOK, FAK, IOC
}

type UserOrderParams

type UserOrderParams struct {
	TokenID    string
	Price      float64
	Size       float64
	Side       Side
	FeeRateBps int
	Nonce      int64
	Expiration int64
	Taker      string
}

type UserRewardsEarning

type UserRewardsEarning struct {
	Market     string  `json:"market"`
	Day        string  `json:"day"`
	Percentage float64 `json:"percentage,omitempty"`
	Earnings   string  `json:"earnings,omitempty"`
}

UserRewardsEarning represents user rewards earning breakdown

type WsAuthParams

type WsAuthParams struct {
	APIKey     string `json:"apiKey"`
	Secret     string `json:"secret"`
	Passphrase string `json:"passphrase"`
}

WsAuthParams for authenticated channels

type WsBaseEvent

type WsBaseEvent struct {
	EventType string `json:"event_type"` // "order", "trade", "book", "price_change", etc.
}

WsBaseEvent is a minimal structure to determine event type

type WsBestBidAskEvent

type WsBestBidAskEvent struct {
	EventType string `json:"event_type"` // "best_bid_ask"
	AssetID   string `json:"asset_id"`   // Token ID
	Market    string `json:"market"`     // Condition ID
	BestBid   string `json:"best_bid"`   // Best bid price
	BestAsk   string `json:"best_ask"`   // Best ask price
	Timestamp string `json:"timestamp"`  // Unix timestamp
}

WsBestBidAskEvent represents best bid/ask update event

type WsBookEvent

type WsBookEvent struct {
	EventType string        `json:"event_type"` // "book"
	AssetID   string        `json:"asset_id"`   // Token ID
	Market    string        `json:"market"`     // Condition ID
	Timestamp string        `json:"timestamp"`  // Unix timestamp
	Hash      string        `json:"hash"`       // Book hash
	Bids      []WsBookLevel `json:"bids"`       // Bid levels [price, size]
	Asks      []WsBookLevel `json:"asks"`       // Ask levels [price, size]
}

WsBookEvent represents an orderbook update event

type WsBookLevel

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

WsBookLevel represents a single orderbook price level

type WsBookUpdate

type WsBookUpdate struct {
	EventType string       `json:"event_type"`
	Market    string       `json:"market,omitempty"`
	AssetID   string       `json:"asset_id,omitempty"`
	Bids      []PriceLevel `json:"bids,omitempty"`
	Asks      []PriceLevel `json:"asks,omitempty"`
	Timestamp int64        `json:"timestamp"`
	Hash      string       `json:"hash,omitempty"`
}

WsBookUpdate represents orderbook updates

type WsClient

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

WsClient is a standalone WebSocket client for Polymarket Users create it independently: ws := polymarket.NewWsClient(...)

func NewWsClient

func NewWsClient(baseURL string, logger *zap.SugaredLogger) *WsClient

NewWsClient creates a new standalone WebSocket client baseURL should be the base WebSocket URL without the channel path

func (*WsClient) Close

func (ws *WsClient) Close() error

Close closes the WebSocket connection

func (*WsClient) Connect

func (ws *WsClient) Connect(ctx context.Context, channelType string) error

Connect establishes WebSocket connection to a specific channel channelType should be "market" or "user"

func (*WsClient) Subscribe

func (ws *WsClient) Subscribe(sub WsSubscription, handler WsHandler) error

Subscribe sends initial subscription message or dynamic subscription For initial subscription (right after Connect), set sub.Type to channel type For dynamic subscription, set sub.Operation to "subscribe"

func (*WsClient) SubscribeAccount

func (ws *WsClient) SubscribeAccount(ctx context.Context, auth *WsAuthParams, handler WsHandler) error

SubscribeAccount subscribes to user channel for account-level events (orders, trades) This captures all activity for the authenticated account

func (*WsClient) SubscribeMarket

func (ws *WsClient) SubscribeMarket(ctx context.Context, marketID string, assetIDs []string, handler WsHandler) error

SubscribeMarket subscribes to market channel for market data (orderbook, prices, trades) assetIDs: list of asset token IDs to subscribe to

func (*WsClient) Unsubscribe

func (ws *WsClient) Unsubscribe(assetsIDs []string) error

Unsubscribe from specific assets/markets assetsIDs: list of asset IDs to unsubscribe from (for market channel)

func (*WsClient) UnsubscribeMarket

func (ws *WsClient) UnsubscribeMarket(assetIDs []string) error

UnsubscribeMarket unsubscribes from specific assets

type WsHandler

type WsHandler func(data []byte) error

WsHandler is a callback function for WebSocket messages

type WsLastTradePriceEvent

type WsLastTradePriceEvent struct {
	EventType      string `json:"event_type"`       // "last_trade_price"
	AssetID        string `json:"asset_id"`         // Token ID
	Market         string `json:"market"`           // Condition ID
	LastTradePrice string `json:"last_trade_price"` // Last trade price
	Timestamp      string `json:"timestamp"`        // Unix timestamp
}

WsLastTradePriceEvent represents the last trade price event

type WsMakerOrder

type WsMakerOrder struct {
	OrderID       string `json:"order_id"`
	AssetID       string `json:"asset_id"`
	MatchedAmount string `json:"matched_amount"`
	Outcome       string `json:"outcome"`
	Owner         string `json:"owner"`
	Price         string `json:"price"`
}

WsMakerOrder represents a maker order in a trade

type WsMarketResolvedEvent

type WsMarketResolvedEvent struct {
	EventType string `json:"event_type"` // "market_resolved"
	Market    string `json:"market"`     // Condition ID
	Outcome   string `json:"outcome"`    // Resolution outcome
	Timestamp string `json:"timestamp"`  // Unix timestamp
}

WsMarketResolvedEvent represents a market resolution event

type WsMarketUpdate

type WsMarketUpdate struct {
	EventType string `json:"event_type"`
	Market    string `json:"market"`
	AssetID   string `json:"asset_id"`
	Price     string `json:"price"`
	Volume    string `json:"volume,omitempty"`
	Timestamp int64  `json:"timestamp"`
}

WsMarketUpdate represents market data updates

type WsMessage

type WsMessage struct {
	Type    string          `json:"type"`
	Channel string          `json:"channel"`
	Data    json.RawMessage `json:"data,omitempty"`
	Error   string          `json:"error,omitempty"`
}

WsMessage represents incoming WebSocket messages

type WsNewMarketEvent

type WsNewMarketEvent struct {
	EventType string `json:"event_type"` // "new_market"
	Market    string `json:"market"`     // Condition ID
	Question  string `json:"question"`   // Market question
	Timestamp string `json:"timestamp"`  // Unix timestamp
}

WsNewMarketEvent represents a new market creation event

type WsOrderEvent

type WsOrderEvent struct {
	EventType    string `json:"event_type"`    // "order"
	ID           string `json:"id"`            // Order ID
	Type         string `json:"type"`          // "PLACEMENT", "UPDATE", "CANCELLATION"
	AssetID      string `json:"asset_id"`      // Token ID
	Market       string `json:"market"`        // Condition ID
	OrderOwner   string `json:"order_owner"`   // Owner UUID
	Owner        string `json:"owner"`         // Owner address
	OriginalSize string `json:"original_size"` // Original order size
	Price        string `json:"price"`         // Order price
	Side         string `json:"side"`          // "BUY" or "SELL"
	SizeMatched  string `json:"size_matched"`  // Size that has been matched
	Outcome      string `json:"outcome"`       // "YES" or "NO"
	Timestamp    string `json:"timestamp"`     // Unix timestamp
}

WsOrderEvent represents an order lifecycle event (PLACEMENT, UPDATE, CANCELLATION)

type WsPriceChange

type WsPriceChange struct {
	AssetID string `json:"asset_id"` // Token ID
	Price   string `json:"price"`    // New price
	Size    string `json:"size"`     // Trade size
	Side    string `json:"side"`     // "BUY" or "SELL"
	Hash    string `json:"hash"`     // Trade hash
	BestBid string `json:"best_bid"` // Current best bid
	BestAsk string `json:"best_ask"` // Current best ask
}

WsPriceChange represents a single price change

type WsPriceChangeEvent

type WsPriceChangeEvent struct {
	EventType    string          `json:"event_type"`    // "price_change"
	Market       string          `json:"market"`        // Condition ID
	PriceChanges []WsPriceChange `json:"price_changes"` // Array of price changes
	Timestamp    string          `json:"timestamp"`     // Unix timestamp
}

WsPriceChangeEvent represents a price change event

type WsSubscription

type WsSubscription struct {
	Type                 string        `json:"type,omitempty"`      // Channel type: "market" or "user"
	Operation            string        `json:"operation,omitempty"` // "subscribe" or "unsubscribe" for dynamic ops
	Auth                 *WsAuthParams `json:"auth,omitempty"`
	Markets              []string      `json:"markets,omitempty"`                // For user channel
	AssetsIDs            []string      `json:"assets_ids,omitempty"`             // For market channel
	CustomFeatureEnabled bool          `json:"custom_feature_enabled,omitempty"` // For market channel
}

WsSubscription represents a subscription request

type WsTickSizeChangeEvent

type WsTickSizeChangeEvent struct {
	EventType string `json:"event_type"` // "tick_size_change"
	AssetID   string `json:"asset_id"`   // Token ID
	Market    string `json:"market"`     // Condition ID
	TickSize  string `json:"tick_size"`  // New tick size
	Timestamp string `json:"timestamp"`  // Unix timestamp
}

WsTickSizeChangeEvent represents a tick size change event

type WsTradeEvent

type WsTradeEvent struct {
	EventType    string         `json:"event_type"` // "trade"
	ID           string         `json:"id"`         // Trade ID
	Type         string         `json:"type"`       // "TRADE"
	Status       string         `json:"status"`     // "MATCHED", "MINED", "CONFIRMED", "RETRYING", "FAILED"
	AssetID      string         `json:"asset_id"`   // Token ID
	Market       string         `json:"market"`     // Condition ID
	TakerOrderID string         `json:"taker_order_id"`
	MakerOrders  []WsMakerOrder `json:"maker_orders"`
	Size         string         `json:"size"`    // Trade size
	Price        string         `json:"price"`   // Trade price
	Side         string         `json:"side"`    // "BUY" or "SELL"
	Outcome      string         `json:"outcome"` // "YES" or "NO"
	Owner        string         `json:"owner"`   // Trade owner
	TradeOwner   string         `json:"trade_owner"`
	MatchTime    string         `json:"matchtime"` // Match timestamp
	LastUpdate   string         `json:"last_update"`
	Timestamp    string         `json:"timestamp"`
}

WsTradeEvent represents a trade execution event (MATCHED, MINED, CONFIRMED, FAILED)

type WsTradeUpdate

type WsTradeUpdate struct {
	EventType string `json:"event_type"`
	TradeID   string `json:"id"`
	Market    string `json:"market"`
	AssetID   string `json:"asset_id"`
	Price     string `json:"price"`
	Size      string `json:"size"`
	Side      string `json:"side"`
	Maker     string `json:"maker,omitempty"`
	Taker     string `json:"taker,omitempty"`
	Timestamp int64  `json:"timestamp"`
}

WsTradeUpdate represents trade feed updates

type WsUserUpdate

type WsUserUpdate struct {
	EventType   string `json:"event_type"`
	OrderID     string `json:"order_id"`
	Market      string `json:"market,omitempty"`
	AssetID     string `json:"asset_id,omitempty"`
	Status      string `json:"status"`
	Price       string `json:"price,omitempty"`
	Size        string `json:"size,omitempty"`
	SizeMatched string `json:"size_matched,omitempty"`
	Side        string `json:"side,omitempty"`
	Timestamp   int64  `json:"timestamp"`
}

WsUserUpdate represents user order updates

Jump to

Keyboard shortcuts

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