Documentation
¶
Index ¶
- Constants
- Variables
- func ClearMetadataCache()
- func FormatPrice(price float64, precision int) string
- func GenerateOrderBookSummaryHash(summary *OrderBookSummary) string
- func IsTickSizeSmaller(a, b string) bool
- func IsValidPrice(price float64, tickSize TickSize) bool
- func NormalizeTickSize(tickSize string) string
- func OrderToJSON(order *SignedOrderResponse) (string, error)
- func ParseFloatSafe(s string) (float64, error)
- func RoundToTickSize(price float64, tickSize string) float64
- type APIError
- type BalanceAllowanceParams
- type BalanceAllowanceResponse
- type BanStatus
- type BatchOrderResponse
- type BookParams
- type BuildOrderOptions
- type BuilderApiKeyResponse
- type BuilderConfig
- type CancelAllResponse
- type CancelOrderResponse
- type CancelOrdersResponse
- type ClobClient
- func (c *ClobClient) ApproveUSDC(ctx context.Context, amount string) error
- func (c *ClobClient) CalculateMarketPrice(ctx context.Context, tokenID string, side Side, amount float64) (float64, error)
- func (c *ClobClient) CancelAllOrders(ctx context.Context) error
- func (c *ClobClient) CancelMarketOrders(ctx context.Context, params OrderMarketCancelParams) error
- func (c *ClobClient) CancelOrder(ctx context.Context, orderID string) error
- func (c *ClobClient) CancelOrders(ctx context.Context, orderIDs []string) (*CancelOrdersResponse, error)
- func (c *ClobClient) CreateBuilderAPIKey(ctx context.Context, builderConfig BuilderConfig) (*BuilderApiKeyResponse, error)
- func (c *ClobClient) CreateMarketOrder(ctx context.Context, userMarketOrder UserMarketOrderParams, tickSize string, ...) (*OrderResponse, error)
- func (c *ClobClient) CreateOrder(ctx context.Context, params UserOrderParams, tickSize string, negRisk bool) (*OrderResponse, error)
- func (c *ClobClient) DeleteReadonlyAPIKey(ctx context.Context, key string) (bool, error)
- func (c *ClobClient) DropNotifications(ctx context.Context, params DropNotificationParams) error
- func (c *ClobClient) EnsureAuth(ctx context.Context) error
- func (c *ClobClient) GetAPIKey() string
- func (c *ClobClient) GetAPIPassphrase() string
- func (c *ClobClient) GetAPISecret() string
- func (c *ClobClient) GetActiveMarkets(ctx context.Context, nextCursor string) (*PaginationPayload, error)
- func (c *ClobClient) GetBalanceAllowance(ctx context.Context, params BalanceAllowanceParams) (*BalanceAllowanceResponse, error)
- func (c *ClobClient) GetBuilderTrades(ctx context.Context, params TradeParams, nextCursor string) (*PaginationPayload, error)
- func (c *ClobClient) GetClosedOnlyMode(ctx context.Context) (*BanStatus, error)
- func (c *ClobClient) GetFeeRateBps(ctx context.Context, tokenID string) (int, error)
- func (c *ClobClient) GetFunderAddress() string
- func (c *ClobClient) GetLastTradePrice(ctx context.Context, tokenID string) (float64, error)
- func (c *ClobClient) GetLastTradesPrices(ctx context.Context, params []BookParams) ([]float64, error)
- func (c *ClobClient) GetLiquidityRewardPercentages(ctx context.Context, market string) (*RewardsPercentages, error)
- func (c *ClobClient) GetMarket(ctx context.Context, conditionID string) (*Market, error)
- func (c *ClobClient) GetMarketTradesEvents(ctx context.Context, conditionID string) ([]*MarketTradeEvent, error)
- func (c *ClobClient) GetMarkets(ctx context.Context, nextCursor string) (*PaginationPayload, error)
- func (c *ClobClient) GetMidpoint(ctx context.Context, tokenID string) (float64, error)
- func (c *ClobClient) GetMidpoints(ctx context.Context, params []BookParams) ([]float64, error)
- func (c *ClobClient) GetNegRisk(ctx context.Context, tokenID string) (bool, error)
- func (c *ClobClient) GetNotifications(ctx context.Context) ([]*Notification, error)
- func (c *ClobClient) GetOpenOrders(ctx context.Context, params OpenOrderParams) (*OpenOrdersResponse, error)
- func (c *ClobClient) GetOrder(ctx context.Context, orderID string) (*OrderResponse, error)
- func (c *ClobClient) GetOrderBook(ctx context.Context, tokenID string) (*OrderBookSummary, error)
- func (c *ClobClient) GetOrderBooks(ctx context.Context, params []BookParams) ([]*OrderBookSummary, error)
- func (c *ClobClient) GetOrderbook(ctx context.Context, tokenID string) (*Orderbook, error)
- func (c *ClobClient) GetPrice(ctx context.Context, tokenID string, side Side) (float64, error)
- func (c *ClobClient) GetPrices(ctx context.Context, params []BookParams) ([]float64, error)
- func (c *ClobClient) GetPricesHistory(ctx context.Context, params PriceHistoryFilterParams) ([]MarketPrice, error)
- func (c *ClobClient) GetRewardsEarningsPercentages(ctx context.Context, market string, day string) (*UserRewardsEarning, error)
- func (c *ClobClient) GetRewardsMarketsCurrentScoring(ctx context.Context) ([]*MarketReward, error)
- func (c *ClobClient) GetRewardsMarketsScoring(ctx context.Context, market string, day string) (*MarketReward, error)
- func (c *ClobClient) GetSamplingMarkets(ctx context.Context, nextCursor string) (*PaginationPayload, error)
- func (c *ClobClient) GetServerTime(ctx context.Context) (int64, error)
- func (c *ClobClient) GetSimplifiedMarkets(ctx context.Context, nextCursor string) (*PaginationPayload, error)
- func (c *ClobClient) GetSpread(ctx context.Context, tokenID string) (float64, error)
- func (c *ClobClient) GetSpreads(ctx context.Context, params []BookParams) ([]float64, error)
- func (c *ClobClient) GetTickSize(ctx context.Context, tokenID string) (string, error)
- func (c *ClobClient) GetTotalUserEarnings(ctx context.Context, day string) (*TotalUserEarning, error)
- func (c *ClobClient) GetTrades(ctx context.Context, params TradeParams) ([]*Trade, error)
- func (c *ClobClient) GetTradesPaginated(ctx context.Context, params TradeParams, nextCursor string) (*PaginationPayload, error)
- func (c *ClobClient) GetUserEarnings(ctx context.Context, day string) (*UserEarning, error)
- func (c *ClobClient) PostOrders(ctx context.Context, orders []PostOrdersArgs, deferExec bool) (*BatchOrderResponse, error)
- func (c *ClobClient) RevokeBuilderAPIKey(ctx context.Context, builderConfig BuilderConfig, key string) (bool, error)
- func (c *ClobClient) UpdateBalanceAllowance(ctx context.Context, params BalanceAllowanceParams) error
- func (c *ClobClient) ValidateReadonlyAPIKey(ctx context.Context, address string, key string) (string, error)
- func (c *ClobClient) WithCredentials(creds *Credentials) *ClobClient
- type Credentials
- type DeriveKeyResponse
- type DropNotificationParams
- type ErrorResponse
- type Market
- type MarketPrice
- type MarketPriceHistory
- type MarketReward
- type MarketTradeEvent
- type Notification
- type OpenOrder
- type OpenOrderParams
- type OpenOrdersResponse
- type OrderArgs
- type OrderBookSummary
- type OrderBuilder
- type OrderMarketCancelParams
- type OrderResponse
- type OrderStatus
- type OrderSummary
- type OrderType
- type Orderbook
- type PaginationPayload
- type PostOrdersArgs
- type PriceHistoryFilterParams
- type PriceLevel
- type Rate
- type ReadonlyApiKeyResponse
- type Reward
- type RewardsPercentages
- type RoundConfig
- type Side
- type SignedOrderResponse
- type Signer
- type TickSize
- type Token
- type TotalUserEarning
- type Trade
- type TradeParams
- type UserEarning
- type UserMarketOrderParams
- type UserOrderParams
- type UserRewardsEarning
- type WsAuthParams
- type WsBaseEvent
- type WsBestBidAskEvent
- type WsBookEvent
- type WsBookLevel
- type WsBookUpdate
- type WsClient
- func (ws *WsClient) Close() error
- func (ws *WsClient) Connect(ctx context.Context, channelType string) error
- func (ws *WsClient) Subscribe(sub WsSubscription, handler WsHandler) error
- func (ws *WsClient) SubscribeAccount(ctx context.Context, auth *WsAuthParams, handler WsHandler) error
- func (ws *WsClient) SubscribeMarket(ctx context.Context, marketID string, assetIDs []string, handler WsHandler) error
- func (ws *WsClient) Unsubscribe(assetsIDs []string) error
- func (ws *WsClient) UnsubscribeMarket(assetIDs []string) error
- type WsHandler
- type WsLastTradePriceEvent
- type WsMakerOrder
- type WsMarketResolvedEvent
- type WsMarketUpdate
- type WsMessage
- type WsNewMarketEvent
- type WsOrderEvent
- type WsPriceChange
- type WsPriceChangeEvent
- type WsSubscription
- type WsTickSizeChangeEvent
- type WsTradeEvent
- type WsTradeUpdate
- type WsUserUpdate
Constants ¶
const ( EndpointBalanceAllowance = "/balance-allowance" EndpointUpdateBalanceAllowance = "/balance-allowance/update" EndpointClosedOnlyMode = "/auth/ban-status/closed-only" )
Account endpoints
const ( EndpointBuilderTrades = "/builder/trades" EndpointBuilderAPIKey = "/auth/builder-api-key" EndpointBuilderAPIKeys = "/auth/builder-api-key" EndpointRevokeBuilderKey = "/auth/builder-api-key" )
Builder API endpoints
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
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
const ( InitialCursor = "" EndCursor = "LTE=" )
Pagination constants
const ( EndpointNotifications = "/notifications" EndpointDropNotifications = "/notifications" )
Notification endpoints
const ( EndpointPostOrders = "/orders" EndpointCancelOrders = "/orders" EndpointCancelMarketOrders = "/cancel-market-orders" EndpointOpenOrders = "/data/orders" EndpointTickSize = "/tick-size" EndpointNegRisk = "/neg-risk" EndpointFeeRate = "/fee-rate" )
Order endpoints
const ( CollateralTokenDecimals = 6 ZeroAddress = "0x0000000000000000000000000000000000000000" )
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
const ( WsChannelMarket = "market" WsChannelBook = "book" WsChannelTrade = "trade" WsChannelUser = "user" )
WebSocket channel types
const (
BaseURL = "https://clob.polymarket.com"
)
const (
WsURL = "wss://ws-subscriptions-clob.polymarket.com/ws"
)
WebSocket endpoints
Variables ¶
var ( 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
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 ¶
FormatPrice formats price with appropriate precision
func GenerateOrderBookSummaryHash ¶
func GenerateOrderBookSummaryHash(summary *OrderBookSummary) string
GenerateOrderBookSummaryHash generates a hash for orderbook summary
func IsTickSizeSmaller ¶
IsTickSizeSmaller compares two tick sizes
func IsValidPrice ¶
func NormalizeTickSize ¶
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 ¶
ParseFloatSafe safely parses a float from string
func RoundToTickSize ¶
RoundToTickSize rounds a price to the nearest tick size
Types ¶
type APIError ¶
APIError represents a structured API error response
func NewAPIError ¶
NewAPIError creates a new API error
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 BuilderApiKeyResponse ¶
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 ¶
... 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 ¶
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 ¶
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) 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 ¶
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 ¶
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 (*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) GetSpreads ¶
func (c *ClobClient) GetSpreads(ctx context.Context, params []BookParams) ([]float64, error)
GetSpreads fetches spreads for multiple tokens in batch
func (*ClobClient) GetTickSize ¶
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 DeriveKeyResponse ¶
type DropNotificationParams ¶
type DropNotificationParams struct {
IDs []string `json:"ids,omitempty"`
}
DropNotificationParams for marking notifications as read
type ErrorResponse ¶
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 ¶
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 ¶
func (b *OrderBuilder) BuildOrder(params UserOrderParams, opts BuildOrderOptions) (*SignedOrderResponse, error)
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 ¶
OrderSummary represents a price level in the orderbook
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
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 ¶
PriceLevel represents a single price level in order book
type ReadonlyApiKeyResponse ¶
type ReadonlyApiKeyResponse struct {
APIKey string `json:"apiKey"`
}
ReadonlyApiKeyResponse for readonly API key creation
type RewardsPercentages ¶
type RewardsPercentages struct {
Market string `json:"market"`
Percentages []float64 `json:"percentages,omitempty"`
}
RewardsPercentages represents reward percentage breakdown
type RoundConfig ¶
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 (*Signer) GetAddress ¶
GetAddress returns the Ethereum address
func (*Signer) SignClobAuth ¶
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 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 UserOrderParams ¶
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 ¶
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) Connect ¶
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 ¶
Unsubscribe from specific assets/markets assetsIDs: list of asset IDs to unsubscribe from (for market channel)
func (*WsClient) UnsubscribeMarket ¶
UnsubscribeMarket unsubscribes from specific assets
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