WebSocket Events

Complete reference for all WebSocket events, including data formats, event types, and handling patterns.

Overview

WebSocket events provide real-time updates for market data, trading activities, and system notifications. This guide covers all available event types and their data structures.

Event Structure

All WebSocket events follow a consistent structure:

{
  "type": "event_type",
  "channel": "channel_name",
  "symbol": "BTC/USD",
  "data": {
    /* event-specific data */
  },
  "timestamp": "2024-01-15T12:00:00Z",
  "sequence": 12345
}

Market Data Events

Ticker Events

Real-time price updates for trading pairs.

ticker.update

{
  "type": "ticker.update",
  "channel": "ticker",
  "symbol": "BTC/USD",
  "data": {
    "price": 49850.25,
    "bid": 49840.0,
    "ask": 49860.5,
    "bidSize": 0.5,
    "askSize": 0.3,
    "volume24h": 1250.75,
    "change24h": 2.5,
    "changePercent24h": 0.05,
    "high24h": 50200.0,
    "low24h": 48500.0,
    "open24h": 48600.0
  },
  "timestamp": "2024-01-15T12:00:00Z",
  "sequence": 12345
}

Order Book Events

Real-time order book updates with incremental changes.

orderbook.update

{
  "type": "orderbook.update",
  "channel": "orderbook",
  "symbol": "BTC/USD",
  "data": {
    "bids": [
      { "price": 49840.0, "quantity": 0.5 },
      { "price": 49835.0, "quantity": 0.3 }
    ],
    "asks": [
      { "price": 49860.5, "quantity": 0.3 },
      { "price": 49865.0, "quantity": 0.4 }
    ],
    "checksum": "abc123def456"
  },
  "timestamp": "2024-01-15T12:00:00Z",
  "sequence": 12346
}

orderbook.snapshot

Initial order book snapshot when subscribing.

{
  "type": "orderbook.snapshot",
  "channel": "orderbook",
  "symbol": "BTC/USD",
  "data": {
    "bids": [
      { "price": 49840.0, "quantity": 0.5 },
      { "price": 49835.0, "quantity": 0.3 },
      { "price": 49830.0, "quantity": 0.2 }
    ],
    "asks": [
      { "price": 49860.5, "quantity": 0.3 },
      { "price": 49865.0, "quantity": 0.4 },
      { "price": 49870.0, "quantity": 0.1 }
    ],
    "checksum": "abc123def456"
  },
  "timestamp": "2024-01-15T12:00:00Z",
  "sequence": 12345
}

Trade Events

Real-time trade executions.

trade.executed

{
  "type": "trade.executed",
  "channel": "trades",
  "symbol": "BTC/USD",
  "data": {
    "tradeId": "trade_123456",
    "price": 49850.25,
    "quantity": 0.1,
    "side": "buy",
    "makerOrderId": "order_123",
    "takerOrderId": "order_456",
    "timestamp": "2024-01-15T12:00:00Z"
  },
  "timestamp": "2024-01-15T12:00:00Z",
  "sequence": 12347
}

trade.batch

Batch of recent trades (sent periodically).

{
  "type": "trade.batch",
  "channel": "trades",
  "symbol": "BTC/USD",
  "data": {
    "trades": [
      {
        "tradeId": "trade_123456",
        "price": 49850.25,
        "quantity": 0.1,
        "side": "buy",
        "timestamp": "2024-01-15T12:00:00Z"
      },
      {
        "tradeId": "trade_123457",
        "price": 49860.5,
        "quantity": 0.05,
        "side": "sell",
        "timestamp": "2024-01-15T12:00:01Z"
      }
    ]
  },
  "timestamp": "2024-01-15T12:00:01Z",
  "sequence": 12348
}

Trading Events

Order Events

Real-time order status updates for your account.

order.created

{
  "type": "order.created",
  "channel": "orders",
  "data": {
    "orderId": "12345678-1234-1234-1234-123456789012",
    "clientOrderId": "unique_order_id",
    "symbol": "BTC/USD",
    "side": "buy",
    "type": "market",
    "quantity": 0.1,
    "price": 0,
    "status": "pending",
    "timeInForce": "GTC",
    "createdAt": "2024-01-15T10:30:00Z"
  },
  "timestamp": "2024-01-15T10:30:00Z",
  "sequence": 12349
}

order.updated

{
  "type": "order.updated",
  "channel": "orders",
  "data": {
    "orderId": "12345678-1234-1234-1234-123456789012",
    "status": "filled",
    "filledQuantity": 0.1,
    "averagePrice": 49850.25,
    "remainingQuantity": 0,
    "updatedAt": "2024-01-15T10:30:01Z"
  },
  "timestamp": "2024-01-15T10:30:01Z",
  "sequence": 12350
}

order.cancelled

{
  "type": "order.cancelled",
  "channel": "orders",
  "data": {
    "orderId": "12345678-1234-1234-1234-123456789012",
    "status": "cancelled",
    "cancelledAt": "2024-01-15T10:35:00Z",
    "reason": "user_cancelled"
  },
  "timestamp": "2024-01-15T10:35:00Z",
  "sequence": 12351
}

order.partially_filled

{
  "type": "order.partially_filled",
  "channel": "orders",
  "data": {
    "orderId": "12345678-1234-1234-1234-123456789012",
    "status": "partially_filled",
    "filledQuantity": 0.05,
    "remainingQuantity": 0.05,
    "averagePrice": 49850.25,
    "lastFillPrice": 49850.25,
    "updatedAt": "2024-01-15T10:30:01Z"
  },
  "timestamp": "2024-01-15T10:30:01Z",
  "sequence": 12352
}

Position Events

Real-time position updates for your account.

position.opened

{
  "type": "position.opened",
  "channel": "positions",
  "data": {
    "symbol": "BTC/USD",
    "side": "long",
    "quantity": 0.1,
    "averagePrice": 49850.25,
    "unrealizedPnl": 0,
    "unrealizedPnlPercent": 0,
    "marginUsed": 4985.03,
    "marginRatio": 0.1,
    "markPrice": 49850.25,
    "liquidationPrice": 45000.0,
    "createdAt": "2024-01-15T10:30:01Z"
  },
  "timestamp": "2024-01-15T10:30:01Z",
  "sequence": 12353
}

position.updated

{
  "type": "position.updated",
  "channel": "positions",
  "data": {
    "symbol": "BTC/USD",
    "quantity": 0.1,
    "unrealizedPnl": 150.75,
    "unrealizedPnlPercent": 0.3,
    "markPrice": 50000.0,
    "marginRatio": 0.1,
    "updatedAt": "2024-01-15T11:00:00Z"
  },
  "timestamp": "2024-01-15T11:00:00Z",
  "sequence": 12354
}

position.closed

{
  "type": "position.closed",
  "channel": "positions",
  "data": {
    "symbol": "BTC/USD",
    "quantity": 0.1,
    "averagePrice": 49850.25,
    "closePrice": 50000.0,
    "realizedPnl": 149.75,
    "realizedPnlPercent": 0.3,
    "closedAt": "2024-01-15T11:30:00Z"
  },
  "timestamp": "2024-01-15T11:30:00Z",
  "sequence": 12355
}

AI Signal Events

Signal Events

Real-time AI trading signals and recommendations.

signal.generated

{
  "type": "signal.generated",
  "channel": "signals",
  "symbol": "BTC/USD",
  "data": {
    "recommendation": "buy",
    "confidence": 87,
    "timeHorizon": "short_term",
    "riskLevel": "medium",
    "reasoning": [
      "Strong bullish momentum detected",
      "High volume confirmation",
      "Positive sentiment from social media",
      "Technical indicators showing oversold conditions"
    ],
    "technicalAnalysis": {
      "rsi": 35.2,
      "macd": "bullish",
      "movingAverage": "above",
      "support": 48500.0,
      "resistance": 50200.0,
      "trend": "bullish"
    },
    "sentimentAnalysis": {
      "socialSentiment": 0.75,
      "newsSentiment": 0.68,
      "fearGreedIndex": 45,
      "marketSentiment": "neutral"
    },
    "priceTargets": {
      "shortTerm": 51000.0,
      "mediumTerm": 55000.0,
      "longTerm": 60000.0
    }
  },
  "timestamp": "2024-01-15T12:00:00Z",
  "sequence": 12356
}

signal.updated

{
  "type": "signal.updated",
  "channel": "signals",
  "symbol": "BTC/USD",
  "data": {
    "recommendation": "hold",
    "confidence": 72,
    "timeHorizon": "short_term",
    "riskLevel": "medium",
    "reasoning": [
      "Momentum weakening",
      "Volume decreasing",
      "Mixed technical signals"
    ],
    "previousRecommendation": "buy",
    "confidenceChange": -15
  },
  "timestamp": "2024-01-15T12:30:00Z",
  "sequence": 12357
}

Account Events

Balance Events

Real-time account balance updates.

balance.updated

{
  "type": "balance.updated",
  "channel": "account",
  "data": {
    "asset": "USD",
    "available": 9500.0,
    "locked": 500.0,
    "total": 10000.0,
    "change": -500.0,
    "changePercent": -4.76,
    "reason": "order_execution",
    "orderId": "12345678-1234-1234-1234-123456789012"
  },
  "timestamp": "2024-01-15T10:30:01Z",
  "sequence": 12358
}

Transaction Events

Real-time transaction notifications.

transaction.deposit

{
  "type": "transaction.deposit",
  "channel": "account",
  "data": {
    "transactionId": "tx_123456789",
    "asset": "USD",
    "amount": 1000.0,
    "method": "bank_transfer",
    "status": "completed",
    "fee": 0.0,
    "netAmount": 1000.0,
    "receivedAt": "2024-01-15T09:00:00Z"
  },
  "timestamp": "2024-01-15T09:00:00Z",
  "sequence": 12359
}

transaction.withdrawal

{
  "type": "transaction.withdrawal",
  "channel": "account",
  "data": {
    "transactionId": "tx_987654321",
    "asset": "USD",
    "amount": 500.0,
    "method": "bank_transfer",
    "status": "completed",
    "fee": 5.0,
    "netAmount": 495.0,
    "processedAt": "2024-01-15T14:00:00Z"
  },
  "timestamp": "2024-01-15T14:00:00Z",
  "sequence": 12360
}

System Events

System Events

System-wide notifications and alerts.

system.maintenance

{
  "type": "system.maintenance",
  "channel": "system",
  "data": {
    "startTime": "2024-01-15T20:00:00Z",
    "endTime": "2024-01-15T22:00:00Z",
    "description": "Scheduled maintenance for system updates",
    "affectedServices": ["trading", "api", "webhooks"],
    "severity": "medium",
    "estimatedDuration": "2 hours"
  },
  "timestamp": "2024-01-15T18:00:00Z",
  "sequence": 12361
}

system.alert

{
  "type": "system.alert",
  "channel": "system",
  "data": {
    "level": "warning",
    "title": "High Market Volatility",
    "message": "BTC/USD experiencing unusually high volatility",
    "affectedSymbols": ["BTC/USD", "ETH/USD"],
    "recommendation": "Consider reducing position sizes",
    "severity": "medium",
    "actionRequired": false
  },
  "timestamp": "2024-01-15T15:30:00Z",
  "sequence": 12362
}

system.status

{
  "type": "system.status",
  "channel": "system",
  "data": {
    "status": "operational",
    "services": {
      "trading": "operational",
      "api": "operational",
      "webhooks": "operational",
      "websocket": "operational"
    },
    "uptime": 99.9,
    "lastIncident": "2024-01-10T10:00:00Z"
  },
  "timestamp": "2024-01-15T12:00:00Z",
  "sequence": 12363
}

Control Events

Subscription Events

Events related to channel subscriptions.

subscription.confirmed

{
  "type": "subscription.confirmed",
  "channel": "ticker",
  "symbol": "BTC/USD",
  "data": {
    "status": "subscribed",
    "message": "Successfully subscribed to BTC/USD ticker"
  },
  "timestamp": "2024-01-15T12:00:00Z",
  "sequence": 12364
}

subscription.error

{
  "type": "subscription.error",
  "channel": "ticker",
  "symbol": "INVALID/USD",
  "data": {
    "error": "invalid_symbol",
    "message": "The symbol 'INVALID/USD' is not supported"
  },
  "timestamp": "2024-01-15T12:00:00Z",
  "sequence": 12365
}

Heartbeat Events

Connection health monitoring.

ping

{
  "type": "ping",
  "timestamp": "2024-01-15T12:00:00Z"
}

pong

{
  "type": "pong",
  "timestamp": "2024-01-15T12:00:00Z"
}

Event Handling Patterns

JavaScript Event Handler

class WebSocketEventHandler {
  constructor() {
    this.eventHandlers = new Map();
    this.setupDefaultHandlers();
  }

  setupDefaultHandlers() {
    // Market data handlers
    this.eventHandlers.set("ticker.update", this.handleTickerUpdate.bind(this));
    this.eventHandlers.set(
      "orderbook.update",
      this.handleOrderBookUpdate.bind(this)
    );
    this.eventHandlers.set(
      "trade.executed",
      this.handleTradeExecuted.bind(this)
    );

    // Trading handlers
    this.eventHandlers.set("order.created", this.handleOrderCreated.bind(this));
    this.eventHandlers.set("order.updated", this.handleOrderUpdated.bind(this));
    this.eventHandlers.set(
      "position.updated",
      this.handlePositionUpdated.bind(this)
    );

    // AI signal handlers
    this.eventHandlers.set(
      "signal.generated",
      this.handleSignalGenerated.bind(this)
    );

    // System handlers
    this.eventHandlers.set("system.alert", this.handleSystemAlert.bind(this));
  }

  handleEvent(event) {
    const handler = this.eventHandlers.get(event.type);
    if (handler) {
      handler(event);
    } else {
      console.warn(`Unhandled event type: ${event.type}`);
    }
  }

  handleTickerUpdate(event) {
    console.log(`Price update for ${event.symbol}: $${event.data.price}`);
    // Update UI with new price
    this.updatePriceDisplay(event.symbol, event.data.price);
  }

  handleOrderBookUpdate(event) {
    console.log(`Order book update for ${event.symbol}`);
    // Update order book display
    this.updateOrderBook(event.symbol, event.data);
  }

  handleTradeExecuted(event) {
    console.log(
      `Trade executed: ${event.data.quantity} ${event.symbol} at $${event.data.price}`
    );
    // Update trade history
    this.addTradeToHistory(event.data);
  }

  handleOrderCreated(event) {
    console.log(`Order created: ${event.data.orderId}`);
    // Update order list
    this.addOrderToList(event.data);
  }

  handleOrderUpdated(event) {
    console.log(`Order updated: ${event.data.orderId} - ${event.data.status}`);
    // Update order status
    this.updateOrderStatus(event.data.orderId, event.data.status);
  }

  handlePositionUpdated(event) {
    console.log(
      `Position updated: ${event.symbol} - P&L: $${event.data.unrealizedPnl}`
    );
    // Update position display
    this.updatePositionDisplay(event.symbol, event.data);
  }

  handleSignalGenerated(event) {
    console.log(
      `AI Signal: ${event.data.recommendation} ${event.symbol} (${event.data.confidence}% confidence)`
    );
    // Update signal display
    this.updateSignalDisplay(event.symbol, event.data);
  }

  handleSystemAlert(event) {
    console.log(`System Alert: ${event.data.title} - ${event.data.message}`);
    // Show system alert
    this.showSystemAlert(event.data);
  }

  // UI update methods
  updatePriceDisplay(symbol, price) {
    // Implement price display update
  }

  updateOrderBook(symbol, orderBookData) {
    // Implement order book update
  }

  addTradeToHistory(tradeData) {
    // Implement trade history update
  }

  addOrderToList(orderData) {
    // Implement order list update
  }

  updateOrderStatus(orderId, status) {
    // Implement order status update
  }

  updatePositionDisplay(symbol, positionData) {
    // Implement position display update
  }

  updateSignalDisplay(symbol, signalData) {
    // Implement signal display update
  }

  showSystemAlert(alertData) {
    // Implement system alert display
  }
}

// Usage
const eventHandler = new WebSocketEventHandler();

ws.on("message", (data) => {
  const event = JSON.parse(data);
  eventHandler.handleEvent(event);
});

Python Event Handler

import json
from typing import Dict, Callable, Any

class WebSocketEventHandler:
    def __init__(self):
        self.event_handlers: Dict[str, Callable] = {}
        self.setup_default_handlers()

    def setup_default_handlers(self):
        """Setup default event handlers"""
        self.event_handlers.update({
            'ticker.update': self.handle_ticker_update,
            'orderbook.update': self.handle_orderbook_update,
            'trade.executed': self.handle_trade_executed,
            'order.created': self.handle_order_created,
            'order.updated': self.handle_order_updated,
            'position.updated': self.handle_position_updated,
            'signal.generated': self.handle_signal_generated,
            'system.alert': self.handle_system_alert
        })

    def handle_event(self, event: Dict[str, Any]):
        """Handle incoming WebSocket event"""
        event_type = event.get('type')
        handler = self.event_handlers.get(event_type)

        if handler:
            handler(event)
        else:
            print(f"Unhandled event type: {event_type}")

    def handle_ticker_update(self, event: Dict[str, Any]):
        """Handle ticker update event"""
        symbol = event.get('symbol')
        price = event.get('data', {}).get('price')
        print(f"Price update for {symbol}: ${price}")
        # Update UI with new price
        self.update_price_display(symbol, price)

    def handle_orderbook_update(self, event: Dict[str, Any]):
        """Handle order book update event"""
        symbol = event.get('symbol')
        print(f"Order book update for {symbol}")
        # Update order book display
        self.update_orderbook(symbol, event.get('data'))

    def handle_trade_executed(self, event: Dict[str, Any]):
        """Handle trade executed event"""
        data = event.get('data', {})
        symbol = event.get('symbol')
        quantity = data.get('quantity')
        price = data.get('price')
        print(f"Trade executed: {quantity} {symbol} at ${price}")
        # Update trade history
        self.add_trade_to_history(data)

    def handle_order_created(self, event: Dict[str, Any]):
        """Handle order created event"""
        order_id = event.get('data', {}).get('orderId')
        print(f"Order created: {order_id}")
        # Update order list
        self.add_order_to_list(event.get('data'))

    def handle_order_updated(self, event: Dict[str, Any]):
        """Handle order updated event"""
        data = event.get('data', {})
        order_id = data.get('orderId')
        status = data.get('status')
        print(f"Order updated: {order_id} - {status}")
        # Update order status
        self.update_order_status(order_id, status)

    def handle_position_updated(self, event: Dict[str, Any]):
        """Handle position updated event"""
        symbol = event.get('symbol')
        data = event.get('data', {})
        unrealized_pnl = data.get('unrealizedPnl')
        print(f"Position updated: {symbol} - P&L: ${unrealized_pnl}")
        # Update position display
        self.update_position_display(symbol, data)

    def handle_signal_generated(self, event: Dict[str, Any]):
        """Handle AI signal generated event"""
        symbol = event.get('symbol')
        data = event.get('data', {})
        recommendation = data.get('recommendation')
        confidence = data.get('confidence')
        print(f"AI Signal: {recommendation} {symbol} ({confidence}% confidence)")
        # Update signal display
        self.update_signal_display(symbol, data)

    def handle_system_alert(self, event: Dict[str, Any]):
        """Handle system alert event"""
        data = event.get('data', {})
        title = data.get('title')
        message = data.get('message')
        print(f"System Alert: {title} - {message}")
        # Show system alert
        self.show_system_alert(data)

    # UI update methods (implement as needed)
    def update_price_display(self, symbol: str, price: float):
        """Update price display"""
        pass

    def update_orderbook(self, symbol: str, orderbook_data: Dict[str, Any]):
        """Update order book display"""
        pass

    def add_trade_to_history(self, trade_data: Dict[str, Any]):
        """Add trade to history"""
        pass

    def add_order_to_list(self, order_data: Dict[str, Any]):
        """Add order to list"""
        pass

    def update_order_status(self, order_id: str, status: str):
        """Update order status"""
        pass

    def update_position_display(self, symbol: str, position_data: Dict[str, Any]):
        """Update position display"""
        pass

    def update_signal_display(self, symbol: str, signal_data: Dict[str, Any]):
        """Update signal display"""
        pass

    def show_system_alert(self, alert_data: Dict[str, Any]):
        """Show system alert"""
        pass

# Usage
event_handler = WebSocketEventHandler()

async def handle_message(message):
    event = json.loads(message)
    event_handler.handle_event(event)

Event Filtering

Filter by Symbol

// Only handle events for specific symbols
function handleEvent(event) {
  const allowedSymbols = ["BTC/USD", "ETH/USD"];

  if (event.symbol && !allowedSymbols.includes(event.symbol)) {
    return; // Ignore events for other symbols
  }

  // Process event
  processEvent(event);
}

Filter by Event Type

// Only handle specific event types
function handleEvent(event) {
  const allowedTypes = ["ticker.update", "order.updated", "signal.generated"];

  if (!allowedTypes.includes(event.type)) {
    return; // Ignore other event types
  }

  // Process event
  processEvent(event);
}

Filter by Confidence Level

// Only handle AI signals with high confidence
function handleSignalGenerated(event) {
  const minConfidence = 80;

  if (event.data.confidence < minConfidence) {
    return; // Ignore low confidence signals
  }

  // Process high confidence signal
  processSignal(event);
}

Error Handling

Malformed Events

function handleMessage(rawMessage) {
  try {
    const event = JSON.parse(rawMessage);

    // Validate event structure
    if (!event.type || !event.timestamp) {
      console.error("Invalid event structure:", event);
      return;
    }

    // Process event
    processEvent(event);
  } catch (error) {
    console.error("Failed to parse event:", error);
    console.log("Raw message:", rawMessage);
  }
}

Missing Event Handlers

function handleEvent(event) {
  const handler = eventHandlers.get(event.type);

  if (handler) {
    try {
      handler(event);
    } catch (error) {
      console.error(`Error handling event ${event.type}:`, error);
    }
  } else {
    console.warn(`No handler for event type: ${event.type}`);
    // Optionally store unhandled events for later processing
    storeUnhandledEvent(event);
  }
}

Ready to handle WebSocket events? Check out our Message Formats guide or explore Error Handling patterns.