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 can be used 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:

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. A new connection is established
  4. Subscriptions must be re-established
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().