# Real-Time Financial Data Streaming

Our WebSocket API provides real-time financial data streaming with low latency for supported datasets. This guide covers connection setup, subscription management, and data handling using the VNX Quote Dataset as an example.

## Quick Start

Connect to our WebSocket feed using the WSS protocol:

```
wss://api.blueskyapi.com/v1/data/EDGE/VNX_QUOTE/<SYMBOL>?token=<YOUR_TOKEN>
```

## Connection Examples

### Node.js Example

```javascript
const WebSocket = require('ws');

// Connection configuration
const SYMBOL = 'AAPL';
const TOKEN = 'your_access_token_here';
const uri = `wss://api.blueskyapi.com/v1/data/EDGE/VNX_QUOTE/${SYMBOL}?token=${TOKEN}`;

// Create WebSocket connection
const ws = new WebSocket(uri);

// Connection event handlers
ws.on('open', () => {
  console.log('✅ WebSocket connected successfully');
  console.log(`📡 Subscribed to: ${SYMBOL}`);
});

ws.on('message', (data) => {
  try {
    const message = JSON.parse(data.toString());
    console.log('📊 Received data:', message);
    
    // Handle different message types
    if (message.status) {
      console.log(`📋 Status: ${message.status}`);
    }
  } catch (error) {
    console.error('❌ Error parsing message:', error);
  }
});

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

ws.on('close', (code, reason) => {
  console.log(`🔌 Connection closed - Code: ${code}, Reason: ${reason}`);
});

// Graceful shutdown
process.on('SIGINT', () => {
  console.log('🛑 Shutting down...');
  ws.close();
  process.exit(0);
});
```

### Python Example

```python
import asyncio
import websockets
import json
import signal
import sys

async def connect_websocket():
    SYMBOL = 'AAPL'
    TOKEN = 'your_access_token_here'
    uri = f"wss://api.blueskyapi.com/v1/data/EDGE/VNX_QUOTE/{SYMBOL}?token={TOKEN}"
    
    try:
        async with websockets.connect(uri) as websocket:
            print("✅ WebSocket connected successfully")
            print(f"📡 Subscribed to: {SYMBOL}")
            
            async for message in websocket:
                try:
                    data = json.loads(message)
                    print(f"📊 Received data: {data}")
                    
                    if 'status' in data:
                        print(f"📋 Status: {data['status']}")
                        
                except json.JSONDecodeError as e:
                    print(f"❌ Error parsing message: {e}")
                    
    except websockets.exceptions.ConnectionClosed as e:
        print(f"🔌 Connection closed: {e}")
    except Exception as e:
        print(f"❌ Connection error: {e}")

# Run the connection
if __name__ == "__main__":
    asyncio.run(connect_websocket())
```

## Initial Connection Response

Upon successful connection, you'll receive a confirmation message:

```json
{
  "status": "subscribed",
  "symbols": ["AAPL"]
}
```

## Subscription Management

### Adding Symbols

Send a `subscribe` message to add symbols to your feed. This operation is **additive** - new symbols are added to your existing subscription:

```json
{
  "subscribe": {
    "token": "your_access_token_here",
    "symbols": ["WMT", "AAPL", "TSLA"]
  }
}
```

**Response:**
```json
{
  "status": "subscribed",
  "symbols": ["WMT", "AAPL", "TSLA"]
}
```

### Removing Symbols

To remove specific symbols, send an `unsubscribe` message:

```json
{
  "unsubscribe": {
    "token": "your_access_token_here",
    "symbols": ["TSLA"]
  }
}
```

### Complete Disconnection

To disconnect from the server:

```json
{
  "unsubscribe": "disconnect"
}
```

### Subscription Status

To retrieve the current subscription status and the list of subscribed symbols, use the following:

```json
{
  "subscription_status": {}
}
```

## Multiple Symbol Connections

### Initial Connection with Multiple Symbols

Connect to multiple symbols at once using comma-separated values:

```
wss://api.blueskyapi.com/v1/data/EDGE/VNX_QUOTE/AAPL,NVDA,TSLA?token=<YOUR_TOKEN>
```

### Subscribing to All Available Symbols

To access all symbols available under your subscription, connect without specifying symbols:

```
wss://api.blueskyapi.com/v1/data/EDGE/VNX_QUOTE?token=<YOUR_TOKEN>
```

Or send an empty symbols array after connection:

```json
{
  "subscribe": {
    "token": "your_access_token_here",
    "symbols": []
  }
}
```

## Error Handling

### Common Error Scenarios

1. **Invalid Token**
   ```json
   {
     "error": "Invalid token"
   }
   ```

2. **No access to dataset**
   ```json
   {
     "error": "No subscription to premium dataset: <Dataset name>"
   }
   ```
3. **Unauthorized Symbol**
   ```json
   {
     "error": "Symbol(s) <Symbols list> not allowed for your tier."
   }
   ```

### Connection Timeout

WebSocket connections are limited to 1-hour sessions. If your application needs to receive updates for longer periods, you should implement a reconnection strategy to automatically re-establish the connection when it times out.

#### Reconnection Strategy Example

```javascript
const WebSocket = require('ws');

class WebSocketClient {
  constructor(uri, options = {}) {
    this.uri = uri;
    this.options = options;
    this.reconnectAttempts = 0;
    this.maxReconnectAttempts = options.maxReconnectAttempts || 5;
    this.reconnectDelay = options.reconnectDelay || 1000;
    this.connect();
  }

  connect() {
    this.ws = new WebSocket(this.uri);
    
    this.ws.on('open', () => {
      console.log('✅ Connected to WebSocket');
      this.reconnectAttempts = 0;
    });

    this.ws.on('close', () => {
      console.log('🔌 Connection closed');
      this.attemptReconnect();
    });

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

  attemptReconnect() {
    if (this.reconnectAttempts < this.maxReconnectAttempts) {
      this.reconnectAttempts++;
      console.log(`🔄 Attempting reconnection ${this.reconnectAttempts}/${this.maxReconnectAttempts}`);
      
      setTimeout(() => {
        this.connect();
      }, this.reconnectDelay * this.reconnectAttempts);
    } else {
      console.error('❌ Max reconnection attempts reached');
    }
  }
}

// Usage
const client = new WebSocketClient(
  'wss://api.blueskyapi.com/v1/data/EDGE/VNX_QUOTE/AAPL?token=your_token',
  { maxReconnectAttempts: 5, reconnectDelay: 1000 }
);
```

## Best Practices

1. **Always handle connection errors and implement reconnection logic**
2. **Validate incoming messages before processing**
3. **Monitor connection status and implement heartbeat mechanisms**
4. **Use appropriate error handling for different message types**
5. **Implement graceful shutdown procedures**
6. **Keep your access token secure and rotate regularly**

Markdown of https://console.vianexus.com/docs/api-basics/streaming. Append `.md` to any docs URL.
