Skip to main content

Overview

The WebSocketClient provides real-time streaming of orderbook updates, prices, order events, transactions, and market lifecycle data over a persistent WebSocket connection. It supports automatic reconnection with exponential backoff and event-driven message handling. The WebSocket client is standalone and does not require an HttpClient.

Setup

Connecting

Connection states

Check the current state with ws.State() or ws.IsConnected().

Event handlers

Register handlers using On() for persistent handlers or Once() for one-time handlers. Both return a handler ID that you can use with Off() to unregister. The raw handler receives the message as json.RawMessage.

Typed event handlers

The SDK provides convenience methods that automatically deserialize events into typed structs:

Available events

Position updates are delivered as a raw positions event — register with ws.On("positions", func(data json.RawMessage) { ... }).

Subscribing to channels

After connecting, subscribe to a channel to receive its events. CLOB orderbook updates are delivered through the market-price subscription:
The server answers every subscribe_market_prices call, first or repeat, with one orderbookUpdate per CLOB slug carrying the full current book, including books with empty bids and asks. You do not need a REST call to seed local state. See Initial snapshot.

Public channels (no authentication required)

Authenticated channels (require API key)

SubscriptionOptions

Unsubscribing

Auto-reconnect

When WithAutoReconnect(true) is set (the default), the client automatically reconnects after a disconnection using exponential backoff with jitter (capped at 60 seconds):
  1. The connection drops (network issue, server restart, etc.)
  2. The client waits with exponential backoff
  3. The client establishes a new connection
  4. You must re-establish your subscriptions
Re-subscribe to your channels after reconnection. You can detect reconnection by checking ws.State().

Complete example

The ws.Disconnect() call cleans up the connection and clears all subscriptions. Always defer it after a successful Connect().