> ## 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.

# Market Data

> Subscribe to real-time level 1 quotes, trades, order book depth, and ticker data via WebSocket.

## Overview

Access real-time market data through WebSocket streams. All WebSocket connections require authentication using API key headers during the connection handshake.

## Available streams

<CardGroup cols={2}>
  <Card title="Level 1 Quotes" icon="chart-line" href="/websockets/market-data/level1">
    Best bid and ask prices and quantities in real-time
  </Card>

  <Card title="Trade Executions" icon="handshake" href="/websockets/market-data/trades">
    Real-time trade data with volume statistics
  </Card>

  <Card title="Order Book Depth" icon="layer-group" href="/websockets/market-data/depth">
    Complete order book with multiple price levels
  </Card>

  <Card title="Ticker Data" icon="clock" href="/websockets/market-data/ticker">
    Real-time ticker data and price statistics
  </Card>
</CardGroup>

## Stream types overview

| Channel  | Description                                                                       | Update Frequency | Authentication |
| -------- | --------------------------------------------------------------------------------- | ---------------- | -------------- |
| `level1` | Best bid and ask quotes                                                           | Real-time        | Required       |
| `trade`  | Trade executions with volume stats                                                | Per trade        | Required       |
| `depth`  | Full order book depth                                                             | Real-time        | Required       |
| `ticker` | Comprehensive ticker data including funding rates, open interest, and mark prices | Real-time        | Required       |

## Quick subscribe

### Multiple streams example

```json theme={null}
{
  "op": "subscribe",
  "args": [
    { "channel": "level1", "symbol": "US500-BTC" },
    { "channel": "trade", "symbol": "GOLD-BTC" },
  ]
}
```

### JavaScript implementation

```javascript theme={null}
// Create authenticated WebSocket connection (see Connection docs)
const ws = new WebSocket('wss://ws.roxom.com/ws', [], {
  headers: {
    'X-API-Key': 'your-api-key',
    'X-API-Signature': 'base64-encoded-rsa-signature'
  }
});

ws.onopen = function() {
  // Subscribe to multiple market data streams
  ws.send(JSON.stringify({
    op: 'subscribe',
    args: [
      { channel: 'level1', symbol: 'US500-BTC' },
      { channel: 'trade', symbol: 'GOLD-BTC' },
    ]
  }));
};

ws.onmessage = function(event) {
  const data = JSON.parse(event.data);
  
  // Handle subscription confirmations
  if (data.event === 'subscribe') {
    console.log('Subscribed to:', data.arg.channel, data.arg.instId);
    return;
  }
  
  // Handle market data events
    if (data.topic) {
      const [channel, symbol] = data.topic.split('.');
      
      switch (channel) {
        case 'level1':
          handleLevel1Update(symbol, data.data);
          break;
        case 'trade':
          handleTradeUpdate(symbol, data.data);
          break;
        case 'depth':
          handleDepthUpdate(symbol, data.data);
          break;
      }
    }
  };

function handleLevel1Update(symbol, data) {
  console.log(`${symbol} Level 1 - Bid: ${data.bid[0]} Ask: ${data.ask[0]}`);
}

function handleTradeUpdate(symbol, data) {
  console.log(`${symbol} Trade - ${data.takerSide} ${data.vwap} Vol: ${data.volume}`);
}

function handleDepthUpdate(symbol, data) {
  console.log(`${symbol} Depth - ${data.type} update with ${data.bid.length} bids, ${data.ask.length} asks`);
}
```

## Supported trading pairs

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

## Message format

All market data messages follow a consistent structure:

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

## Subscription management

### Subscribe to streams

```json theme={null}
{
  "op": "subscribe",
  "args": [
    { "channel": "level1", "symbol": "US500-BTC" }
  ]
}
```

### Unsubscribe from streams

```json theme={null}
{
  "op": "unsubscribe",
  "args": [
      { "channel": "trade", "symbol": "GOLD-BTC" }
  ]
}
```

## Best practices

<AccordionGroup>
  <Accordion title="Subscription Strategy">
    * Subscribe only to data you actually need
    * Use batch subscriptions for multiple symbols
    * Unsubscribe from unused streams to reduce bandwidth
    * Validate symbol names before subscribing
  </Accordion>

  <Accordion title="Data Processing">
    * Handle snapshot vs delta updates appropriately
    * Implement proper order book reconstruction for depth streams
    * Buffer high-frequency updates for UI rendering
    * Maintain local state for efficient processing
  </Accordion>

  <Accordion title="Performance Optimization">
    * Process messages asynchronously
    * Use efficient data structures for order books
    * Implement proper memory management
    * Monitor bandwidth usage and adjust subscriptions
  </Accordion>
</AccordionGroup>

## Error handling

Common market data stream errors and solutions:

<AccordionGroup>
  <Accordion title="Invalid Symbol">
    **Error**: Subscription rejected due to invalid trading pair

    **Solution**: Verify symbol format matches supported trading pairs exactly
  </Accordion>

  <Accordion title="Rate Limiting">
    **Error**: Too many subscription requests

    **Solution**: Batch multiple subscriptions into single request
  </Accordion>

  <Accordion title="Connection Issues">
    **Error**: Message delivery interruption

    **Solution**: Implement reconnection logic and state recovery
  </Accordion>
</AccordionGroup>

## Next steps

* Learn about [Level 1 Quotes](/websockets/market-data/level1) implementation details
* Explore [Trade Executions](/websockets/market-data/trades) for real-time trade data
* Review [Order Book Depth](/websockets/market-data/depth) for full market depth
* Set up [Connection Management](/websockets/connection) for reliable connectivity
* Explore [Account Updates](/websockets/account-updates) for private data streams
