> ## Documentation Index
> Fetch the complete documentation index at: https://docs.roxom.com/llms.txt
> Use this file to discover all available pages before exploring further.

# WebSocket Overview

> Learn how Roxom's WebSocket API delivers real-time market data and account updates for trading apps.

## Overview

The Roxom WebSocket API provides real-time access to market data and account updates with minimal latency. Use it to build trading applications, monitor portfolios, and implement algorithmic trading strategies.

### What you can access

<AccordionGroup>
  <Accordion title="Market Data Streams">
    **Authentication required** for market data streams:

    * **Level 1 Quotes**: Best bid and ask prices and quantities
    * **Trade Executions**: Real-time trade data with volume statistics
    * **Order Book Depth**: Complete order book with multiple price levels
    * **Ticker Data**: Real-time price and market statistics including funding rates and open interest
  </Accordion>

  <Accordion title="Private Account Data">
    **Authentication required** for private account streams:

    * **Order Updates**: Real-time order status changes and fills
    * **Balance Changes**: Account balance updates from trades and transfers
    * **Position Updates**: Position changes and PnL updates
  </Accordion>
</AccordionGroup>

### Connection URLs

<CodeGroup>
  ```http Production theme={null}
  wss://ws.roxom.com/ws
  ```

  ```http Sandbox theme={null}
  wss://ws.roxom.io/ws
  ```
</CodeGroup>

<Warning>
  Use the sandbox environment for testing and development. Production credentials will not work with sandbox endpoints.
</Warning>

## Supported trading pairs

Current supported symbols for market data streams:

| Symbol      | Description               | Base Asset | Quote Asset |
| ----------- | ------------------------- | ---------- | ----------- |
| `US500-BTC` | S\&P 500 Index to Bitcoin | SPY        | BTC         |
| `GOLD-BTC`  | Gold to Bitcoin           | PAX        | BTC         |
| `USDT-BTC`  | Tether to Bitcoin         | USDT       | BTC         |
| `OIL-BTC`   | WTI Crude Oil to Bitcoin  | OIL        | BTC         |

## Message format

All WebSocket messages use JSON format with a consistent structure:

### Client to server messages

```json theme={null}
{
  "op": "subscribe|unsubscribe",
  "args": [
    {
      "channel": "channelName",
      "symbol": "tradingPair"
    }
  ]
}
```

### Server to client messages

```json theme={null}
{
  "topic": "channel.symbol",
  "type": "snapshot|delta",
  "createdTime": 1640995200000000000,
  "data": {
    // Channel-specific data
  }
}
```

## Supported channels

| Channel     | Description                             | Symbol Required | Authentication |
| ----------- | --------------------------------------- | --------------- | -------------- |
| `level1`    | Best bid and ask prices and quantities  | Yes             | Yes            |
| `trade`     | Real-time trade executions              | Yes             | Yes            |
| `depth`     | Order book depth (snapshot + deltas)    | Yes             | Yes            |
| `ticker`    | Real-time price and market statistics   | Yes             | Yes            |
| `orders`    | Order updates for authenticated user    | No              | Yes            |
| `balance`   | Balance updates for authenticated user  | No              | Yes            |
| `positions` | Position updates for authenticated user | No              | Yes            |

<Note>
  **Account Event Broadcasting**: Account-related events (`orders`, `positions`, `balance`) are automatically sent to all authenticated connections for your account, regardless of individual subscriptions. This ensures you never miss critical account changes.
</Note>

## Connection lifecycle

<Steps>
  <Step title="Establish Authenticated Connection">
    All WebSocket connections require authentication using API key headers during the connection handshake.

    ```javascript theme={null}
    // Generate RSA signature for the payload 'GET:/ws'
    const signature = generateRSASignature(privateKey, 'GET:/ws');

    const ws = new WebSocket('wss://ws.roxom.com/ws', [], {
      headers: {
        'X-API-Key': 'your_api_key',
        'X-API-Signature': signature
      }
    });
    ```
  </Step>

  <Step title="Handle Connection Events">
    Implement proper event handlers for connection management.

    ```javascript theme={null}
    ws.onopen = () => {
      console.log('✅ WebSocket connected and authenticated');
    };

    ws.onerror = (error) => {
      console.error('❌ WebSocket error:', error);
    };

    ws.onclose = (event) => {
      console.log('🔌 WebSocket closed:', event.code, event.reason);
      // Implement reconnection logic
    };
    ```
  </Step>

  <Step title="Subscribe to Channels">
    Send subscription messages for the data streams you need.

    ```json theme={null}
    {
      "op": "subscribe",
      "args": [
        { "channel": "level1", "symbol": "US500-BTC" },
        { "channel": "depth", "symbol": "GOLD-BTC" },
        { "channel": "orders" }
      ]
    }
    ```
  </Step>

  <Step title="Handle Messages">
    Process incoming real-time data and maintain connection status.

    ```javascript theme={null}
    ws.onmessage = function(event) {
      const data = JSON.parse(event.data);
      console.log('Received:', data);
    };
    ```
  </Step>

  <Step title="Maintain Connection">
    Implement ping/pong and reconnection logic for reliability.

    <Tip>
      Send ping frames every 30 seconds to keep the connection alive.
    </Tip>
  </Step>
</Steps>

## Key features

<CardGroup cols={2}>
  <Card title="Low Latency" icon="bolt">
    Sub-millisecond message delivery for time-sensitive trading applications
  </Card>

  <Card title="Multiple Streams" icon="stream">
    Subscribe to multiple symbols and channels simultaneously
  </Card>

  <Card title="Reliable Delivery" icon="shield-check">
    Built-in heartbeat and reconnection mechanisms
  </Card>

  <Card title="Efficient Updates" icon="arrows-rotate">
    Delta updates minimize bandwidth usage for order book streams
  </Card>
</CardGroup>

## Best practices

<AccordionGroup>
  <Accordion title="Connection Management">
    * **Single Connection**: Use one connection per application when possible
    * **Reconnection Logic**: Implement exponential backoff for reconnections
    * **Heartbeat Monitoring**: Send ping frames every 30 seconds
    * **Resource Cleanup**: Properly close connections when shutting down
  </Accordion>

  <Accordion title="Subscription Management">
    * **Selective Subscriptions**: Only subscribe to data you actually need
    * **Unsubscribe Unused**: Remove subscriptions you no longer need
    * **Batch Operations**: Subscribe to multiple channels in single message
    * **Symbol Validation**: Verify symbol names before subscribing
  </Accordion>

  <Accordion title="Error Handling">
    * **Graceful Degradation**: Handle connection drops gracefully
    * **Error Parsing**: Always validate JSON before parsing
    * **Retry Logic**: Implement smart retry mechanisms
    * **Logging**: Log connection events for debugging
  </Accordion>
</AccordionGroup>

## Getting started

<CardGroup cols={2}>
  <Card title="Connection Setup" icon="plug" href="/websockets/connection">
    Learn how to establish and maintain WebSocket connections
  </Card>

  <Card title="Market Data Streams" icon="chart-line" href="/websockets/market-data">
    Subscribe to real-time market data feeds
  </Card>

  <Card title="Account Updates" icon="user" href="/websockets/account-updates">
    Receive real-time account and order updates
  </Card>

  <Card title="Authentication" icon="key" href="/api-reference/authentication">
    Set up API authentication for private streams
  </Card>
</CardGroup>
