ws

package
v1.1.5 Latest Latest
Warning

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

Go to latest
Published: May 6, 2026 License: Apache-2.0 Imports: 11 Imported by: 0

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

View Source
const (
	// DefaultHost is the production CLOB WebSocket host.
	DefaultHost = "wss://ws-subscriptions-clob.polymarket.com"
)

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 Callback added in v1.0.3

type Callback func()

type Channel

type Channel string

Channel identifies the WebSocket subscription target.

const (
	// ChannelMarket subscribes to order book updates.
	ChannelMarket Channel = "market"
	// ChannelUser subscribes to user-specific order and trade events.
	ChannelUser Channel = "user"
)

type Client

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

Client is a reconnecting WebSocket client for CLOB market and user streams.

func New

func New(opts ...Option) *Client

New creates a CLOB WebSocket client.

func (*Client) Close added in v1.0.2

func (c *Client) Close() error

Close closes the active connection and stops background loops.

func (*Client) ConnectMarket added in v1.0.2

func (c *Client) ConnectMarket(ctx context.Context) error

ConnectMarket opens the market-channel WebSocket.

func (*Client) ConnectSports added in v1.0.2

func (c *Client) ConnectSports(ctx context.Context) error

ConnectSports opens the public sports-channel WebSocket.

func (*Client) ConnectUser added in v1.0.2

func (c *Client) ConnectUser(ctx context.Context) error

ConnectUser opens the authenticated user-channel WebSocket.

func (*Client) Errors added in v1.0.2

func (c *Client) Errors() <-chan error

Errors returns asynchronous connection and decode errors.

func (*Client) Events added in v1.0.2

func (c *Client) Events() <-chan Event

Events returns decoded CLOB WebSocket events.

func (*Client) Host

func (c *Client) Host() string

Host returns the configured WebSocket host.

func (*Client) IsConnected added in v1.0.2

func (c *Client) IsConnected() bool

IsConnected reports whether a WebSocket connection is currently attached.

func (*Client) MarketURL

func (c *Client) MarketURL() string

MarketURL returns the market-channel WebSocket URL.

func (*Client) SportsURL

func (c *Client) SportsURL() string

SportsURL returns the public sports-channel WebSocket URL.

func (*Client) SubscribeBestBidAsk added in v1.0.2

func (c *Client) SubscribeBestBidAsk(ctx context.Context, assetIDs []string) error

SubscribeBestBidAsk subscribes to best bid/ask events for asset IDs.

func (*Client) SubscribeLastTradePrice added in v1.0.2

func (c *Client) SubscribeLastTradePrice(ctx context.Context, assetIDs []string) error

SubscribeLastTradePrice subscribes to last-trade-price events for asset IDs.

func (*Client) SubscribeMarketResolutions added in v1.0.2

func (c *Client) SubscribeMarketResolutions(ctx context.Context, assetIDs []string) error

SubscribeMarketResolutions subscribes to market resolution events.

func (*Client) SubscribeMidpoints added in v1.0.2

func (c *Client) SubscribeMidpoints(ctx context.Context, assetIDs []string) error

SubscribeMidpoints subscribes to midpoint events for asset IDs.

func (*Client) SubscribeNewMarkets added in v1.0.2

func (c *Client) SubscribeNewMarkets(ctx context.Context, assetIDs []string) error

SubscribeNewMarkets subscribes to new market listing events.

func (*Client) SubscribeOrderBook added in v1.0.2

func (c *Client) SubscribeOrderBook(ctx context.Context, assetIDs []string) error

SubscribeOrderBook subscribes to order book snapshots and deltas for asset IDs.

func (*Client) SubscribeOrders added in v1.0.2

func (c *Client) SubscribeOrders(ctx context.Context, markets []string) error

SubscribeOrders subscribes to user order status events for markets.

func (*Client) SubscribePrices added in v1.0.2

func (c *Client) SubscribePrices(ctx context.Context, assetIDs []string) error

SubscribePrices subscribes to price change events for asset IDs.

func (*Client) SubscribeTickSizeChange added in v1.0.2

func (c *Client) SubscribeTickSizeChange(ctx context.Context, assetIDs []string) error

SubscribeTickSizeChange subscribes to tick-size-change events for asset IDs.

func (*Client) SubscribeTrades added in v1.0.2

func (c *Client) SubscribeTrades(ctx context.Context, markets []string) error

SubscribeTrades subscribes to user trade events for markets.

func (*Client) SubscribeUserEvents added in v1.0.2

func (c *Client) SubscribeUserEvents(ctx context.Context, markets []string) error

SubscribeUserEvents subscribes to all user order and trade events for markets.

func (*Client) UnsubscribeBestBidAsk added in v1.0.2

func (c *Client) UnsubscribeBestBidAsk(ctx context.Context, assetIDs []string) error

UnsubscribeBestBidAsk unsubscribes from best bid/ask events for asset IDs.

func (*Client) UnsubscribeLastTradePrice added in v1.0.2

func (c *Client) UnsubscribeLastTradePrice(ctx context.Context, assetIDs []string) error

UnsubscribeLastTradePrice unsubscribes from last-trade-price events for asset IDs.

func (*Client) UnsubscribeMarketResolutions added in v1.0.2

func (c *Client) UnsubscribeMarketResolutions(ctx context.Context, assetIDs []string) error

UnsubscribeMarketResolutions unsubscribes from market resolution events.

func (*Client) UnsubscribeMidpoints added in v1.0.2

func (c *Client) UnsubscribeMidpoints(ctx context.Context, assetIDs []string) error

UnsubscribeMidpoints unsubscribes from midpoint events for asset IDs.

func (*Client) UnsubscribeNewMarkets added in v1.0.2

func (c *Client) UnsubscribeNewMarkets(ctx context.Context, assetIDs []string) error

UnsubscribeNewMarkets unsubscribes from new market listing events.

func (*Client) UnsubscribeOrderBook added in v1.0.2

func (c *Client) UnsubscribeOrderBook(ctx context.Context, assetIDs []string) error

UnsubscribeOrderBook unsubscribes from order book events for asset IDs.

func (*Client) UnsubscribeOrders added in v1.0.2

func (c *Client) UnsubscribeOrders(ctx context.Context, markets []string) error

UnsubscribeOrders unsubscribes from user order events for markets.

func (*Client) UnsubscribePrices added in v1.0.2

func (c *Client) UnsubscribePrices(ctx context.Context, assetIDs []string) error

UnsubscribePrices unsubscribes from price change events for asset IDs.

func (*Client) UnsubscribeTickSizeChange added in v1.0.2

func (c *Client) UnsubscribeTickSizeChange(ctx context.Context, assetIDs []string) error

UnsubscribeTickSizeChange unsubscribes from tick-size-change events for asset IDs.

func (*Client) UnsubscribeTrades added in v1.0.2

func (c *Client) UnsubscribeTrades(ctx context.Context, markets []string) error

UnsubscribeTrades unsubscribes from user trade events for markets.

func (*Client) UnsubscribeUserEvents added in v1.0.2

func (c *Client) UnsubscribeUserEvents(ctx context.Context, markets []string) error

UnsubscribeUserEvents unsubscribes from user events for markets.

func (*Client) UserURL

func (c *Client) UserURL() string

UserURL returns the user-channel WebSocket URL.

type Event

type Event interface {
	// contains filtered or unexported methods
}

Event is the discriminated-union interface for WebSocket events.

func DecodeEvent

func DecodeEvent(data []byte) (Event, error)

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 WithAutoReconnect(v bool) Option

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 WithHost added in v1.0.3

func WithHost(host string) Option

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.

type OrderEvent

type OrderEvent struct {
	BaseEvent
	// OrderID is the affected order identifier.
	OrderID string `json:"order_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).

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.

Directories

Path Synopsis
Package rtds implements the Polymarket real-time data stream client.
Package rtds implements the Polymarket real-time data stream client.

Jump to

Keyboard shortcuts

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