ws

package
v1.0.8 Latest Latest
Warning

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

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

Documentation

Overview

Package ws provides a high-level WebSocket client for Polymarket. It manages connections to both market data and user-specific event streams, handling automatic reconnection, heartbeats, and event dispatching via channels.

Index

Constants

View Source
const (
	ProdBaseURL        = "wss://ws-subscriptions-clob.polymarket.com"
	DefaultReadTimeout = 60 * time.Second
)

Variables

This section is empty.

Functions

This section is empty.

Types

type AuthPayload

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

type BaseEvent

type BaseEvent struct {
	Type      EventType `json:"type"`
	Timestamp int64     `json:"timestamp,omitempty"`
}

type BestBidAskEvent

type BestBidAskEvent struct {
	Market    string `json:"market,omitempty"`
	AssetID   string `json:"asset_id"`
	BestBid   string `json:"best_bid,omitempty"`
	BestAsk   string `json:"best_ask,omitempty"`
	Spread    string `json:"spread,omitempty"`
	Timestamp string `json:"timestamp,omitempty"`
}

type Channel

type Channel string
const (
	ChannelMarket    Channel = "market"
	ChannelUser      Channel = "user"
	ChannelSubscribe Channel = "subscribe"
)

type Client

type Client interface {

	// Authenticate sets API credentials for private user streams.
	Authenticate(signer auth.Signer, apiKey *auth.APIKey) Client
	// Deauthenticate clears API credentials for private user streams.
	Deauthenticate() Client

	// ConnectionState returns the current status of a specific WebSocket channel.
	ConnectionState(channel Channel) ConnectionState
	// ConnectionStateStream returns a stream of connection state transition events.
	ConnectionStateStream(ctx context.Context) (*Stream[ConnectionStateEvent], error)
	// Close gracefully shuts down all active WebSocket connections and closes all event channels.
	Close() error

	// SubscribeOrderbook subscribes to L2 order book snapshots and updates for specific assets.
	SubscribeOrderbook(ctx context.Context, assetIDs []string) (<-chan OrderbookEvent, error)
	// SubscribePrices subscribes to real-time price change events for specific assets.
	SubscribePrices(ctx context.Context, assetIDs []string) (<-chan PriceChangeEvent, error)
	// SubscribeMidpoints subscribes to mid-price update events for specific assets.
	SubscribeMidpoints(ctx context.Context, assetIDs []string) (<-chan MidpointEvent, error)
	// SubscribeLastTradePrices subscribes to the price of the latest executed trades for specific assets.
	SubscribeLastTradePrices(ctx context.Context, assetIDs []string) (<-chan LastTradePriceEvent, error)
	// SubscribeTickSizeChanges subscribes to minimum price increment changes for specific assets.
	SubscribeTickSizeChanges(ctx context.Context, assetIDs []string) (<-chan TickSizeChangeEvent, error)
	// SubscribeBestBidAsk subscribes to top-of-book (BBO) events for specific assets.
	SubscribeBestBidAsk(ctx context.Context, assetIDs []string) (<-chan BestBidAskEvent, error)
	// SubscribeNewMarkets subscribes to events triggered when new markets are created.
	SubscribeNewMarkets(ctx context.Context, assetIDs []string) (<-chan NewMarketEvent, error)
	// SubscribeMarketResolutions subscribes to events triggered when markets are resolved.
	SubscribeMarketResolutions(ctx context.Context, assetIDs []string) (<-chan MarketResolvedEvent, error)

	// SubscribeUserOrders subscribes to status updates for orders belonging to the authenticated account.
	// Requires an API key to be configured on the client.
	SubscribeUserOrders(ctx context.Context, markets []string) (<-chan OrderEvent, error)
	// SubscribeUserTrades subscribes to trade execution events for the authenticated account.
	// Requires an API key to be configured on the client.
	SubscribeUserTrades(ctx context.Context, markets []string) (<-chan TradeEvent, error)

	// SubscribeOrderbookStream is like SubscribeOrderbook but returns a managed Stream object.
	SubscribeOrderbookStream(ctx context.Context, assetIDs []string) (*Stream[OrderbookEvent], error)
	// SubscribePricesStream is like SubscribePrices but returns a managed Stream object.
	SubscribePricesStream(ctx context.Context, assetIDs []string) (*Stream[PriceChangeEvent], error)
	// SubscribeMidpointsStream is like SubscribeMidpoints but returns a managed Stream object.
	SubscribeMidpointsStream(ctx context.Context, assetIDs []string) (*Stream[MidpointEvent], error)
	// SubscribeLastTradePricesStream is like SubscribeLastTradePrices but returns a managed Stream object.
	SubscribeLastTradePricesStream(ctx context.Context, assetIDs []string) (*Stream[LastTradePriceEvent], error)
	// SubscribeTickSizeChangesStream is like SubscribeTickSizeChanges but returns a managed Stream object.
	SubscribeTickSizeChangesStream(ctx context.Context, assetIDs []string) (*Stream[TickSizeChangeEvent], error)
	// SubscribeBestBidAskStream is like SubscribeBestBidAsk but returns a managed Stream object.
	SubscribeBestBidAskStream(ctx context.Context, assetIDs []string) (*Stream[BestBidAskEvent], error)
	// SubscribeNewMarketsStream is like SubscribeNewMarkets but returns a managed Stream object.
	SubscribeNewMarketsStream(ctx context.Context, assetIDs []string) (*Stream[NewMarketEvent], error)
	// SubscribeMarketResolutionsStream is like SubscribeMarketResolutions but returns a managed Stream object.
	SubscribeMarketResolutionsStream(ctx context.Context, assetIDs []string) (*Stream[MarketResolvedEvent], error)
	// SubscribeUserOrdersStream is like SubscribeUserOrders but returns a managed Stream object.
	SubscribeUserOrdersStream(ctx context.Context, markets []string) (*Stream[OrderEvent], error)
	// SubscribeUserTradesStream is like SubscribeUserTrades but returns a managed Stream object.
	SubscribeUserTradesStream(ctx context.Context, markets []string) (*Stream[TradeEvent], error)

	// Subscribe sends a raw subscription request to the WebSocket server.
	Subscribe(ctx context.Context, req *SubscriptionRequest) error
	// Unsubscribe sends a raw unsubscription request to the WebSocket server.
	Unsubscribe(ctx context.Context, req *SubscriptionRequest) error
	// UnsubscribeMarketAssets unsubscribes from all events related to specific assets on the market channel.
	UnsubscribeMarketAssets(ctx context.Context, assetIDs []string) error
	// UnsubscribeUserMarkets unsubscribes from all account events related to specific markets.
	UnsubscribeUserMarkets(ctx context.Context, markets []string) error
}

Client defines the interface for interacting with Polymarket's WebSocket services. It provides a stream-based API for real-time market data and private account updates.

func NewClient

func NewClient(url string, signer auth.Signer, apiKey *auth.APIKey) (Client, error)

func NewClientWithConfig added in v1.0.8

func NewClientWithConfig(url string, signer auth.Signer, apiKey *auth.APIKey, cfg ClientConfig) (Client, error)

NewClientWithConfig creates a new WebSocket client using explicit configuration.

type ClientConfig added in v1.0.8

type ClientConfig struct {
	Debug               bool
	DisablePing         bool
	Reconnect           bool
	ReconnectDelay      time.Duration
	ReconnectMaxDelay   time.Duration
	ReconnectMultiplier float64
	ReconnectMax        int
	HeartbeatInterval   time.Duration
	HeartbeatTimeout    time.Duration
	ReadTimeout         time.Duration
}

ClientConfig controls runtime behavior of the CLOB WebSocket client.

func ClientConfigFromEnv added in v1.0.8

func ClientConfigFromEnv() ClientConfig

ClientConfigFromEnv preserves legacy behavior for users who configured WS behavior via env vars.

func DefaultClientConfig added in v1.0.8

func DefaultClientConfig() ClientConfig

DefaultClientConfig returns stable defaults independent from process environment variables.

type ConnectionState

type ConnectionState string

ConnectionState represents CLOB WS connection status.

const (
	ConnectionDisconnected ConnectionState = "disconnected"
	ConnectionConnecting   ConnectionState = "connecting"
	ConnectionConnected    ConnectionState = "connected"
	ConnectionReconnecting ConnectionState = "reconnecting"
)

type ConnectionStateEvent

type ConnectionStateEvent struct {
	Channel  Channel         `json:"channel"`
	State    ConnectionState `json:"state"`
	Attempt  int             `json:"attempt,omitempty"`
	Recorded int64           `json:"recorded"`
}

ConnectionStateEvent captures connection transitions.

type EventMessage

type EventMessage struct {
	ID          string `json:"id"`
	Ticker      string `json:"ticker"`
	Slug        string `json:"slug"`
	Title       string `json:"title"`
	Description string `json:"description"`
}

type EventType

type EventType string
const (
	Orderbook                EventType = "orderbook"
	Price                    EventType = "price"
	PriceChange              EventType = "price_change"
	Midpoint                 EventType = "midpoint"
	LastTrade                EventType = "trade" // user trade message
	LastTradePrice           EventType = "last_trade_price"
	TickSizeChange           EventType = "tick_size_change"
	BestBidAsk               EventType = "best_bid_ask"
	NewMarket                EventType = "new_market"
	MarketResolved           EventType = "market_resolved"
	UserOrders               EventType = "orders"
	UserTrades               EventType = "trades"
	ConnectionStateEventType EventType = "connection_state"
)

type LaggedError

type LaggedError struct {
	Count     int
	Channel   Channel
	EventType EventType
}

LaggedError indicates the subscriber missed messages due to backpressure.

func (LaggedError) Error

func (e LaggedError) Error() string

type LastTradePriceEvent

type LastTradePriceEvent struct {
	AssetID    string `json:"asset_id"`
	Market     string `json:"market,omitempty"`
	Price      string `json:"price"`
	Side       string `json:"side,omitempty"`
	Size       string `json:"size,omitempty"`
	FeeRateBps string `json:"fee_rate_bps,omitempty"`
	Timestamp  string `json:"timestamp,omitempty"`
}

type MarketResolvedEvent

type MarketResolvedEvent struct {
	ID             string        `json:"id"`
	Question       string        `json:"question"`
	Market         string        `json:"market,omitempty"`
	Slug           string        `json:"slug,omitempty"`
	Description    string        `json:"description,omitempty"`
	AssetIDs       []string      `json:"assets_ids,omitempty"`
	Outcomes       []string      `json:"outcomes,omitempty"`
	WinningAssetID string        `json:"winning_asset_id,omitempty"`
	WinningOutcome string        `json:"winning_outcome,omitempty"`
	EventMessage   *EventMessage `json:"event_message,omitempty"`
	Timestamp      string        `json:"timestamp,omitempty"`
}

type MidpointEvent

type MidpointEvent struct {
	AssetID  string `json:"asset_id"`
	Midpoint string `json:"midpoint"`
}

type NewMarketEvent

type NewMarketEvent struct {
	ID           string        `json:"id"`
	Question     string        `json:"question"`
	Market       string        `json:"market,omitempty"`
	Slug         string        `json:"slug,omitempty"`
	Description  string        `json:"description,omitempty"`
	AssetIDs     []string      `json:"assets_ids,omitempty"`
	Outcomes     []string      `json:"outcomes,omitempty"`
	EventMessage *EventMessage `json:"event_message,omitempty"`
	Timestamp    string        `json:"timestamp,omitempty"`
}

type Operation

type Operation string
const (
	OperationSubscribe   Operation = "subscribe"
	OperationUnsubscribe Operation = "unsubscribe"
)

type OrderEvent

type OrderEvent struct {
	ID              string   `json:"id"`
	AssetID         string   `json:"asset_id"`
	Market          string   `json:"market"`
	Side            string   `json:"side"`
	Price           string   `json:"price"`
	OriginalSize    string   `json:"original_size"`
	SizeMatched     string   `json:"size_matched"`
	Status          string   `json:"status"` // LIVE, CANCELED, MATCHED
	Type            string   `json:"type"`   // PLACEMENT, UPDATE, CANCELLATION
	Outcome         string   `json:"outcome"`
	OrderOwner      string   `json:"order_owner"`
	Owner           string   `json:"owner"`
	Timestamp       string   `json:"timestamp"` // string
	CreatedAt       string   `json:"created_at"`
	Expiration      string   `json:"expiration"`
	OrderType       string   `json:"order_type"` // GTC, FOK, etc
	MakerAddress    string   `json:"maker_address"`
	AssociateTrades []string `json:"associate_trades"`
	EventType       string   `json:"event_type"`
}

type OrderbookEvent

type OrderbookEvent struct {
	AssetID   string           `json:"asset_id"`
	Market    string           `json:"market,omitempty"`
	Bids      []OrderbookLevel `json:"bids"`
	Asks      []OrderbookLevel `json:"asks"`
	Hash      string           `json:"hash"`
	Timestamp string           `json:"timestamp"` // Sometimes string in JSON
}

type OrderbookLevel

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

type PriceChangeEvent added in v1.0.7

type PriceChangeEvent struct {
	AssetID string `json:"asset_id"`
	BestAsk string `json:"best_ask"`
	BestBid string `json:"best_bid"`
	Hash    string `json:"hash"`
	Price   string `json:"price"`
	Side    string `json:"side"`
	Size    string `json:"size"`
}

type PriceEvent

type PriceEvent struct {
	Market       string             `json:"market"`
	PriceChanges []PriceChangeEvent `json:"price_changes"`
	Timestamp    string             `json:"timestamp"`
}

type Stream

type Stream[T any] struct {
	C   <-chan T
	Err <-chan error
	// contains filtered or unexported fields
}

Stream delivers messages and async errors for a subscription.

func (*Stream[T]) Close

func (s *Stream[T]) Close() error

Close stops the subscription and closes the stream.

type SubscriptionRequest

type SubscriptionRequest struct {
	Type                 Channel      `json:"type"`
	Operation            Operation    `json:"operation,omitempty"`
	Markets              []string     `json:"markets,omitempty"`
	AssetIDs             []string     `json:"assets_ids,omitempty"`
	InitialDump          *bool        `json:"initial_dump,omitempty"`
	CustomFeatureEnabled *bool        `json:"custom_feature_enabled,omitempty"`
	Auth                 *AuthPayload `json:"auth,omitempty"`
}

SubscriptionRequest matches the CLOB WS subscription format.

func NewMarketSubscription

func NewMarketSubscription(assetIDs []string) *SubscriptionRequest

func NewMarketUnsubscribe

func NewMarketUnsubscribe(assetIDs []string) *SubscriptionRequest

func NewUserSubscription

func NewUserSubscription(markets []string) *SubscriptionRequest

func NewUserUnsubscribe

func NewUserUnsubscribe(markets []string) *SubscriptionRequest

func (*SubscriptionRequest) WithCustomFeatures

func (r *SubscriptionRequest) WithCustomFeatures(enabled bool) *SubscriptionRequest

type TickSizeChangeEvent

type TickSizeChangeEvent struct {
	AssetID         string `json:"asset_id"`
	Market          string `json:"market,omitempty"`
	TickSize        string `json:"tick_size,omitempty"`
	MinimumTickSize string `json:"minimum_tick_size,omitempty"`
	Timestamp       string `json:"timestamp,omitempty"`
}

type TradeEvent

type TradeEvent struct {
	AssetID   string `json:"asset_id"`
	Price     string `json:"price"`
	Size      string `json:"size"`
	Side      string `json:"side"`
	Timestamp string `json:"timestamp"`
	ID        string `json:"id,omitempty"`
	Market    string `json:"market,omitempty"`
	Status    string `json:"status,omitempty"`
}

Jump to

Keyboard shortcuts

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