Documentation
¶
Overview ¶
Package ws provides WebSocket clients for live Polymarket CLOB order book and user updates.
Connecting ¶
Basic market stream:
wsClient := ws.NewClient("")
err := wsClient.ConnectMarket(ctx)
User stream with CLOB API credentials:
wsClient := ws.New(ws.Config{
Credentials: &clob.Credentials{
Key: "...",
Secret: "...",
Passphrase: "...",
},
})
err := wsClient.ConnectUser(ctx)
Subscriptions ¶
err = wsClient.SubscribeOrderBook(ctx, []string{"token-id"})
err = wsClient.SubscribeOrders(ctx, []string{"condition-id"})
Reading Updates ¶
for event := range wsClient.Events() {
_ = event
}
Index ¶
- Constants
- type BaseEvent
- type BestBidAskEvent
- type BookEvent
- type Callback
- type Channel
- type Client
- func (c *Client) Close() error
- func (c *Client) ConnectMarket(ctx context.Context) error
- func (c *Client) ConnectSports(ctx context.Context) error
- func (c *Client) ConnectUser(ctx context.Context) error
- func (c *Client) Errors() <-chan error
- func (c *Client) Events() <-chan Event
- func (c *Client) Host() string
- func (c *Client) IsConnected() bool
- func (c *Client) MarketURL() string
- func (c *Client) SportsURL() string
- func (c *Client) SubscribeBestBidAsk(ctx context.Context, assetIDs []string) error
- func (c *Client) SubscribeLastTradePrice(ctx context.Context, assetIDs []string) error
- func (c *Client) SubscribeMarketResolutions(ctx context.Context, assetIDs []string) error
- func (c *Client) SubscribeMidpoints(ctx context.Context, assetIDs []string) error
- func (c *Client) SubscribeNewMarkets(ctx context.Context, assetIDs []string) error
- func (c *Client) SubscribeOrderBook(ctx context.Context, assetIDs []string) error
- func (c *Client) SubscribeOrders(ctx context.Context, markets []string) error
- func (c *Client) SubscribePrices(ctx context.Context, assetIDs []string) error
- func (c *Client) SubscribeTickSizeChange(ctx context.Context, assetIDs []string) error
- func (c *Client) SubscribeTrades(ctx context.Context, markets []string) error
- func (c *Client) SubscribeUserEvents(ctx context.Context, markets []string) error
- func (c *Client) UnsubscribeBestBidAsk(ctx context.Context, assetIDs []string) error
- func (c *Client) UnsubscribeLastTradePrice(ctx context.Context, assetIDs []string) error
- func (c *Client) UnsubscribeMarketResolutions(ctx context.Context, assetIDs []string) error
- func (c *Client) UnsubscribeMidpoints(ctx context.Context, assetIDs []string) error
- func (c *Client) UnsubscribeNewMarkets(ctx context.Context, assetIDs []string) error
- func (c *Client) UnsubscribeOrderBook(ctx context.Context, assetIDs []string) error
- func (c *Client) UnsubscribeOrders(ctx context.Context, markets []string) error
- func (c *Client) UnsubscribePrices(ctx context.Context, assetIDs []string) error
- func (c *Client) UnsubscribeTickSizeChange(ctx context.Context, assetIDs []string) error
- func (c *Client) UnsubscribeTrades(ctx context.Context, markets []string) error
- func (c *Client) UnsubscribeUserEvents(ctx context.Context, markets []string) error
- func (c *Client) UserURL() string
- type Event
- type EventMessage
- type EventType
- type LastTradePriceEvent
- type MarketResolvedEvent
- type MarketSubscription
- type NewMarketEvent
- type Option
- func WithAutoReconnect(v bool) Option
- func WithCredentials(cred *clob.Credentials) Option
- func WithDialOptions(opts *websocket.DialOptions) Option
- func WithHeartbeatInterval(interval time.Duration) Option
- func WithHost(host string) Option
- func WithOnConnected(fn func()) Option
- func WithOnDisconnected(fn func()) Option
- func WithOnReconnected(fn func()) Option
- func WithSportsHost(host string) Option
- func WithStaleCheckInterval(interval time.Duration) Option
- func WithStaleTimeout(timeout time.Duration) Option
- type OrderEvent
- type OrderStatus
- type PriceChangeBatchEvent
- type PriceChangeEvent
- type SportsResultUpdate
- type TickSizeChangeEvent
- type TradeEvent
- type TradeStatus
- type UserSubscription
Constants ¶
const ( // DefaultHost is the production CLOB WebSocket host. DefaultHost = "wss://ws-subscriptions-clob.polymarket.com" DefaultSportsHost = "wss://sports-api.polymarket.com" // DefaultHeartbeatInterval is the documented Market/User channel heartbeat interval. DefaultHeartbeatInterval = 10 * time.Second )
Variables ¶
This section is empty.
Functions ¶
This section is empty.
Types ¶
type BaseEvent ¶
type BaseEvent struct {
// EventType identifies the specific event variant.
EventType EventType `json:"event_type"`
}
BaseEvent is the common prefix of all WebSocket event payloads.
type BestBidAskEvent ¶
type BestBidAskEvent struct {
BaseEvent
// Market is the condition ID.
Market string `json:"market"`
// AssetID is the conditional token identifier.
AssetID string `json:"asset_id"`
// BestBid is the highest bid price.
BestBid clob.Float64 `json:"best_bid"`
// BestAsk is the lowest ask price.
BestAsk clob.Float64 `json:"best_ask"`
// Spread is the difference.
Spread clob.Float64 `json:"spread"`
// Timestamp is the event time.
Timestamp clob.Time `json:"timestamp"`
}
BestBidAskEvent carries top-of-book bid/ask update.
type BookEvent ¶
type BookEvent struct {
BaseEvent
// AssetID is the conditional token identifier.
AssetID string `json:"asset_id"`
// Market Condition ID of the market
Market string `json:"market"`
// Bids are buy order levels.
Bids []clob.OrderSummary `json:"bids"`
// Asks are sell order levels.
Asks []clob.OrderSummary `json:"asks"`
// Timestamp is the event time.
Timestamp clob.Time `json:"timestamp"`
// Hash of the orderbook content
Hash string `json:"hash"`
}
BookEvent carries an order book update.
type Client ¶
type Client struct {
// contains filtered or unexported fields
}
Client is a reconnecting WebSocket client for CLOB market and user streams.
func (*Client) Close ¶ added in v1.0.2
Close closes the active connection and stops background loops.
func (*Client) ConnectMarket ¶ added in v1.0.2
ConnectMarket opens the market-channel WebSocket.
func (*Client) ConnectSports ¶ added in v1.0.2
ConnectSports opens the public sports-channel WebSocket.
func (*Client) ConnectUser ¶ added in v1.0.2
ConnectUser opens the authenticated user-channel WebSocket.
func (*Client) IsConnected ¶ added in v1.0.2
IsConnected reports whether a WebSocket connection is currently attached.
func (*Client) SubscribeBestBidAsk ¶ added in v1.0.2
SubscribeBestBidAsk subscribes to best bid/ask events for asset IDs.
func (*Client) SubscribeLastTradePrice ¶ added in v1.0.2
SubscribeLastTradePrice subscribes to last-trade-price events for asset IDs.
func (*Client) SubscribeMarketResolutions ¶ added in v1.0.2
SubscribeMarketResolutions subscribes to market resolution events.
func (*Client) SubscribeMidpoints ¶ added in v1.0.2
SubscribeMidpoints subscribes to midpoint events for asset IDs.
func (*Client) SubscribeNewMarkets ¶ added in v1.0.2
SubscribeNewMarkets subscribes to new market listing events.
func (*Client) SubscribeOrderBook ¶ added in v1.0.2
SubscribeOrderBook subscribes to order book snapshots and deltas for asset IDs.
func (*Client) SubscribeOrders ¶ added in v1.0.2
SubscribeOrders subscribes to user order status events for markets.
func (*Client) SubscribePrices ¶ added in v1.0.2
SubscribePrices subscribes to price change events for asset IDs.
func (*Client) SubscribeTickSizeChange ¶ added in v1.0.2
SubscribeTickSizeChange subscribes to tick-size-change events for asset IDs.
func (*Client) SubscribeTrades ¶ added in v1.0.2
SubscribeTrades subscribes to user trade events for markets.
func (*Client) SubscribeUserEvents ¶ added in v1.0.2
SubscribeUserEvents subscribes to all user order and trade events for markets.
func (*Client) UnsubscribeBestBidAsk ¶ added in v1.0.2
UnsubscribeBestBidAsk unsubscribes from best bid/ask events for asset IDs.
func (*Client) UnsubscribeLastTradePrice ¶ added in v1.0.2
UnsubscribeLastTradePrice unsubscribes from last-trade-price events for asset IDs.
func (*Client) UnsubscribeMarketResolutions ¶ added in v1.0.2
UnsubscribeMarketResolutions unsubscribes from market resolution events.
func (*Client) UnsubscribeMidpoints ¶ added in v1.0.2
UnsubscribeMidpoints unsubscribes from midpoint events for asset IDs.
func (*Client) UnsubscribeNewMarkets ¶ added in v1.0.2
UnsubscribeNewMarkets unsubscribes from new market listing events.
func (*Client) UnsubscribeOrderBook ¶ added in v1.0.2
UnsubscribeOrderBook unsubscribes from order book events for asset IDs.
func (*Client) UnsubscribeOrders ¶ added in v1.0.2
UnsubscribeOrders unsubscribes from user order events for markets.
func (*Client) UnsubscribePrices ¶ added in v1.0.2
UnsubscribePrices unsubscribes from price change events for asset IDs.
func (*Client) UnsubscribeTickSizeChange ¶ added in v1.0.2
UnsubscribeTickSizeChange unsubscribes from tick-size-change events for asset IDs.
func (*Client) UnsubscribeTrades ¶ added in v1.0.2
UnsubscribeTrades unsubscribes from user trade events for markets.
func (*Client) UnsubscribeUserEvents ¶ added in v1.0.2
UnsubscribeUserEvents unsubscribes from user events for markets.
type Event ¶
type Event interface {
// contains filtered or unexported methods
}
Event is the discriminated-union interface for WebSocket events.
func DecodeEvent ¶
DecodeEvent decodes a raw CLOB WebSocket event payload into a typed Event.
type EventMessage ¶
type EventMessage struct {
// ID is the message identifier.
ID string `json:"id"`
// Ticker is the sports ticker symbol.
Ticker string `json:"ticker"`
// Slug is the event slug.
Slug string `json:"slug"`
// Title is the event title.
Title string `json:"title"`
// Description is the event description.
Description string `json:"description"`
}
EventMessage is the embedded sports event metadata.
type EventType ¶
type EventType string
EventType identifies the kind of WebSocket event.
const ( // EventTypeBook is an order book snapshot or delta. EventTypeBook EventType = "book" // EventTypePriceChange signals a price update. EventTypePriceChange EventType = "price_change" // EventTypeTickSizeChange signals a tick size update. EventTypeTickSizeChange EventType = "tick_size_change" // EventTypeLastTradePrice signals a new trade. EventTypeLastTradePrice EventType = "last_trade_price" // EventTypeOrder is an order status change notification. EventTypeOrder EventType = "order" // EventTypeTrade is a trade confirmation. EventTypeTrade EventType = "trade" // EventTypeBestBidAsk is the top-of-book update. EventTypeBestBidAsk EventType = "best_bid_ask" // EventTypeNewMarket signals market listing. EventTypeNewMarket EventType = "new_market" // EventTypeMarketResolved signals market resolution. EventTypeMarketResolved EventType = "market_resolved" )
type LastTradePriceEvent ¶
type LastTradePriceEvent struct {
BaseEvent
// AssetID is the conditional token identifier.
AssetID string `json:"asset_id"`
// Market is the condition ID.
Market string `json:"market"`
// Price is the trade price.
Price clob.Float64 `json:"price"`
// Size is the trade quantity.
Size clob.Float64 `json:"size"`
// Side is the trade direction.
Side clob.Side `json:"side"`
// FeeRateBps is the fee rate in basis points.
FeeRateBps clob.Float64 `json:"fee_rate_bps"`
// Timestamp is the event time.
Timestamp clob.Time `json:"timestamp"`
// TransactionHash transaction_hash
TransactionHash string `json:"transaction_hash"`
}
LastTradePriceEvent carries the most recent trade price.
type MarketResolvedEvent ¶
type MarketResolvedEvent struct {
BaseEvent
// ID is the market condition identifier.
ID string `json:"id"`
// Question is the market question text.
Question string `json:"question,omitempty"`
// Market is the market name.
Market string `json:"market"`
// Slug is the URL-friendly slug.
Slug string `json:"slug,omitempty"`
// Description is the market description.
Description string `json:"description,omitempty"`
// AssetIDs lists the conditional token identifiers.
AssetIDs []string `json:"assets_ids"`
// AssetIDsAlt accepts the asset_ids variant sometimes emitted by CLOB.
AssetIDsAlt []string `json:"asset_ids,omitempty"`
// Outcomes lists the outcome labels.
Outcomes []string `json:"outcomes,omitempty"`
// WinningAssetID is the resolved winning token ID.
WinningAssetID string `json:"winning_asset_id"`
// WinningOutcome is the resolved outcome label.
WinningOutcome string `json:"winning_outcome"`
// EventMessage is optional embedded event metadata.
EventMessage *EventMessage `json:"event_message,omitempty"`
// Timestamp is the event time.
Timestamp clob.Time `json:"timestamp"`
Tags []string `json:"tags,omitempty"`
}
MarketResolvedEvent signals a market has been resolved.
type MarketSubscription ¶
type MarketSubscription struct {
// Type must be ChannelMarket.
Type Channel `json:"type"`
// Operation is "subscribe" or "unsubscribe".
Operation string `json:"operation,omitempty"`
// Markets optionally limits to specific condition IDs.
Markets []string `json:"markets,omitempty"`
// AssetIDs optionally limits to specific token IDs.
AssetIDs []string `json:"assets_ids,omitempty"`
// InitialDump requests a full order book on subscribe.
InitialDump bool `json:"initial_dump,omitempty"`
// CustomFeatureEnabled enables extended features.
CustomFeatureEnabled bool `json:"custom_feature_enabled,omitempty"`
}
MarketSubscription is sent to subscribe to market-channel events.
type NewMarketEvent ¶
type NewMarketEvent struct {
BaseEvent
// ID is the market condition identifier.
ID string `json:"id"`
// Question is the market question text.
Question string `json:"question"`
// Market is the market name.
Market string `json:"market"`
// Slug is the URL-friendly slug.
Slug string `json:"slug"`
// Description is the market description.
Description string `json:"description"`
// AssetIDs lists the conditional token identifiers.
AssetIDs []string `json:"assets_ids"`
// AssetIDsAlt accepts the asset_ids variant sometimes emitted by CLOB.
AssetIDsAlt []string `json:"asset_ids,omitempty"`
// Outcomes lists the outcome labels.
Outcomes []string `json:"outcomes"`
// EventMessage is optional embedded event metadata.
EventMessage *EventMessage `json:"event_message,omitempty"`
// Timestamp is the event time.
Timestamp clob.Time `json:"timestamp"`
Tags []string `json:"tags,omitempty"`
ConditionID string `json:"condition_id,omitempty"`
Active *bool `json:"active,omitempty"`
CLOBTokenIDs []string `json:"clob_token_ids,omitempty"`
SportsMarketType string `json:"sports_market_type,omitempty"`
Line string `json:"line,omitempty"`
GameStartTime clob.Time `json:"game_start_time,omitzero"` // 如果可能为空字符串,可能要用 string 更稳
OrderPriceMinTickSize clob.TickSize `json:"order_price_min_tick_size,omitempty"`
GroupItemTitle string `json:"group_item_title,omitempty"`
}
NewMarketEvent signals a new market listing via WebSocket.
type Option ¶ added in v1.0.3
type Option func(*Client)
func WithAutoReconnect ¶ added in v1.0.3
func WithCredentials ¶ added in v1.0.3
func WithCredentials(cred *clob.Credentials) Option
func WithDialOptions ¶ added in v1.0.3
func WithDialOptions(opts *websocket.DialOptions) Option
WithDialOptions sets custom dial options for the WebSocket connection.
func WithHeartbeatInterval ¶ added in v1.1.7
WithHeartbeatInterval sets the text PING interval for Market/User channels. Set interval <= 0 to disable heartbeat.
func WithOnConnected ¶ added in v1.0.3
func WithOnConnected(fn func()) Option
WithOnConnected sets a callback fired when the WebSocket first connects.
func WithOnDisconnected ¶ added in v1.0.3
func WithOnDisconnected(fn func()) Option
WithOnDisconnected sets a callback fired when the connection drops and will not reconnect (because autoReconnect is disabled or the client is closed).
func WithOnReconnected ¶ added in v1.0.3
func WithOnReconnected(fn func()) Option
WithOnReconnected sets a callback fired when the WebSocket successfully reconnects.
func WithSportsHost ¶ added in v1.1.7
func WithStaleCheckInterval ¶ added in v1.1.9
WithStaleCheckInterval sets how often stale stream detection runs. Set interval <= 0 to use a default derived from WithStaleTimeout.
func WithStaleTimeout ¶ added in v1.1.9
WithStaleTimeout enables stale stream detection. When enabled, the client forces a reconnect if no message is received for the given duration. Set timeout <= 0 to disable it.
type OrderEvent ¶
type OrderEvent struct {
BaseEvent
// OrderID is the affected order identifier from the user-channel id field.
OrderID string `json:"id"`
// AssetID is the conditional token identifier.
AssetID string `json:"asset_id"`
// Market is the condition ID.
Market string `json:"market"`
// Price is the order price.
Price clob.Float64 `json:"price"`
// Size is the order quantity.
Size clob.Float64 `json:"size"`
// Side is the order direction.
Side clob.Side `json:"side"`
// Status is the updated order status.
Status OrderStatus `json:"status"`
// Reason explains why the order changed state.
Reason string `json:"reason,omitempty"`
// Timestamp is the event time.
Timestamp clob.Time `json:"timestamp"`
}
OrderEvent carries an order status change (fill, cancel, expiry).
func (*OrderEvent) UnmarshalJSON ¶ added in v1.1.7
func (e *OrderEvent) UnmarshalJSON(data []byte) error
UnmarshalJSON decodes the documented user-channel id field into OrderID.
type OrderStatus ¶
type OrderStatus string
OrderStatus identifies the lifecycle state of an order.
const ( // OrderStatusOpen is an active unfilled order. OrderStatusOpen OrderStatus = "OPEN" // OrderStatusCanceled has been canceled by the user. OrderStatusCanceled OrderStatus = "CANCELED" // OrderStatusFilled is fully matched. OrderStatusFilled OrderStatus = "FILLED" // OrderStatusExpired has passed its expiry time. OrderStatusExpired OrderStatus = "EXPIRED" // OrderStatusRetrying is being re-submitted after failure. OrderStatusRetrying OrderStatus = "RETRYING" // OrderStatusFailed was rejected or failed processing. OrderStatusFailed OrderStatus = "FAILED" )
type PriceChangeBatchEvent ¶ added in v1.1.2
type PriceChangeBatchEvent struct {
BaseEvent
// Market is the condition identifier.
Market string `json:"market"`
// Timestamp is the event time.
Timestamp clob.Time `json:"timestamp"`
// PriceChanges
PriceChanges []PriceChangeEvent `json:"price_changes"`
}
PriceChangeBatchEvent carries batch trade price update.
type PriceChangeEvent ¶
type PriceChangeEvent struct {
BaseEvent
// Market is the condition identifier.
Market string `json:"market"`
// Timestamp is the event time.
Timestamp clob.Time `json:"timestamp"`
// AssetID is the conditional token identifier.
AssetID string `json:"asset_id"`
// BestBid is the highest bid price when included in price change messages.
BestBid clob.Float64 `json:"best_bid"`
// BestAsk is the lowest ask price when included in price change messages.
BestAsk clob.Float64 `json:"best_ask"`
// Price is the trade price.
Price clob.Float64 `json:"price"`
// Size is the trade quantity.
Size clob.Float64 `json:"size"`
// Side is the trade direction.
Side clob.Side `json:"side"`
// Hash of the orderbook content
Hash string `json:"hash"`
}
PriceChangeEvent carries a single trade price update.
type SportsResultUpdate ¶
type SportsResultUpdate struct {
// Slug is the sports match slug.
Slug string `json:"slug"`
// Live is true when the match is live.
Live bool `json:"live"`
// Ended is true when the match has ended.
Ended bool `json:"ended"`
// Score is the current score.
Score string `json:"score"`
// Period is the current match period.
Period string `json:"period"`
// Elapsed is the elapsed match time.
Elapsed string `json:"elapsed"`
// LastUpdate is the last update timestamp.
LastUpdate clob.Time `json:"last_update"`
}
SportsResultUpdate is a real-time sports match update from the sports channel.
type TickSizeChangeEvent ¶
type TickSizeChangeEvent struct {
BaseEvent
// AssetID is the conditional token identifier.
AssetID string `json:"asset_id"`
// Market is the condition ID.
Market string `json:"market"`
// OldTickSize is the previous tick size.
OldTickSize clob.TickSize `json:"old_tick_size"`
// NewTickSize is the updated tick size.
NewTickSize clob.TickSize `json:"new_tick_size"`
// Timestamp is the event time.
Timestamp clob.Time `json:"timestamp"`
}
TickSizeChangeEvent carries a tick size update notification.
type TradeEvent ¶
type TradeEvent struct {
BaseEvent
// TradeID is the trade identifier.
TradeID string `json:"trade_id"`
// AssetID is the conditional token identifier.
AssetID string `json:"asset_id"`
// Market is the condition ID.
Market string `json:"market"`
// Price is the execution price.
Price clob.Float64 `json:"price"`
// Size is the matched quantity.
Size clob.Float64 `json:"size"`
// Side is the trade direction.
Side clob.Side `json:"side"`
// Status is the trade processing status.
Status TradeStatus `json:"status"`
// Timestamp is the event time.
Timestamp clob.Time `json:"timestamp"`
}
TradeEvent carries a matched trade notification.
type TradeStatus ¶
type TradeStatus string
TradeStatus identifies the processing state of a trade.
const ( // TradeStatusMatched is a completed trade. TradeStatusMatched TradeStatus = "matched" // TradeStatusRetrying is being re-submitted. TradeStatusRetrying TradeStatus = "RETRYING" // TradeStatusFailed was rejected or failed processing. TradeStatusFailed TradeStatus = "FAILED" )
type UserSubscription ¶
type UserSubscription struct {
// Type must be ChannelUser.
Type Channel `json:"type"`
// Auth contains WebSocket credentials.
Auth clob.WSAuth `json:"auth"`
// Markets optionally scopes subscriptions.
Markets []string `json:"markets,omitempty"`
// Operation is "subscribe" or "unsubscribe".
Operation string `json:"operation,omitempty"`
}
UserSubscription is sent to subscribe to user-channel events.