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

# WebSockets

> Real-time data streaming with WebSocket connections

# WebSocket Connections

Aries provides real-time WebSocket APIs for streaming market data, account updates, and other time-sensitive information.

<Note>
  **New to WebSockets?** Regular REST API calls work like asking a question and waiting for a single answer — you ask, the server responds, then the conversation ends. A **WebSocket** is more like a phone call: you open one connection and the server keeps pushing updates to you as they happen (prices changing, orders filling, etc.) until you hang up. Use WebSockets whenever you need live, continuously updating data instead of refreshing on a timer.
</Note>

## Available WebSocket Endpoints

Aries provides separate WebSocket endpoints so you can connect only to the streams you actually need:

* **Market data** — live prices and trading activity for stocks, options, and indices.
* **Charting** — a TradingView-compatible feed for charting widgets.
* **Account** — your own orders, positions, balances, P\&L, watchlists, and news.

### Market Endpoint

<Card title="Market Data WebSocket" icon="chart-line" href="/websockets/market-data">
  Real-time equity quotes, options data, time & sales, level 2 order book, and market status. Authentication required.

  **Endpoint:** `wss://api.aries.com/v1/market/ws`
</Card>

<Card title="Charting WebSocket" icon="chart-candlestick" href="/websockets/tradingview-chart">
  Real-time quotes and trades for charting (TradingView-compatible). Authentication required (send token via POST /auth after connect).

  **Endpoint:** `wss://api.aries.com/v1/charts/ws`
</Card>

### Accounts Endpoint

<Card title="Account Updates WebSocket" icon="wallet" href="/websockets/account-updates">
  Orders, positions, balances, P\&L candles, watchlist updates, and news. All account-related streams use this endpoint.

  **Endpoint:** `wss://api.aries.com/v1/accounts/ws`
</Card>

***

## WebSocket Features

### Real-Time Data Streaming

The connection stays open both ways, so the server can push updates the moment they happen rather than you having to poll. Typical latency is in the low milliseconds.

### Authentication

Every Aries WebSocket requires authentication before you can subscribe to anything. The flow is:

1. Open the WebSocket connection.
2. Send a **request** message to **POST /auth** with your OAuth2 access token. The envelope looks like `type: "request"`, `payload: { method: "POST", path: "/auth", body: { token: "<access_token>" } }`.
3. Wait for the server to respond with **authSuccess**.
4. Only after that, send your subscribe messages.

If you skip authentication or use an expired token, the server will close the connection or reject your subscribe requests.

### Keep-Alive Support

WebSockets can be dropped silently by network equipment if they go quiet. To prevent that, send a small `ping` message every 30–60 seconds; the server replies with `pong`. If you don't hear back, treat the connection as dead and reconnect.

### Selective Subscriptions

Tell the server exactly which symbols and which fields you want. This keeps your bandwidth usage low and your app responsive — you won't receive data you weren't going to use anyway.

***

## Connection Flow

<Steps>
  <Step title="Establish Connection">
    Open a secure WebSocket connection (`wss://...`) to one of the endpoints listed above.
  </Step>

  <Step title="Authenticate">
    Send a request message containing your OAuth2 access token and wait for the server's **authSuccess** response.
  </Step>

  <Step title="Subscribe">
    Tell the server which symbols, accounts, or topics you want updates for (for example, quotes for AAPL or all order activity on one account).
  </Step>

  <Step title="Receive Data">
    Read messages off the connection as the server pushes them and update your UI, store, or strategy logic accordingly.
  </Step>

  <Step title="Maintain Connection">
    Send a ping every 30–60 seconds so the connection isn't closed by an idle-timeout, and reconnect with exponential backoff if it drops.
  </Step>
</Steps>

***

## Best Practices

### Connection Management

<AccordionGroup>
  <Accordion title="Handle Reconnections">
    Implement automatic reconnection logic with exponential backoff when connections drop:

    ```javascript theme={null}
    let reconnectAttempts = 0;
    const maxReconnectDelay = 30000;

    function reconnect() {
      const delay = Math.min(1000 * Math.pow(2, reconnectAttempts), maxReconnectDelay);
      setTimeout(() => {
        reconnectAttempts++;
        connectWebSocket();
      }, delay);
    }
    ```
  </Accordion>

  <Accordion title="Maintain Keep-Alive">
    Send ping messages regularly (recommended every 30-60 seconds) to maintain the connection:

    ```javascript theme={null}
    const pingInterval = setInterval(() => {
      if (ws.readyState === WebSocket.OPEN) {
        ws.send(JSON.stringify({ type: "ping", id: `ping-${Date.now()}` }));
      }
    }, 30000);
    ```
  </Accordion>

  <Accordion title="Handle Errors Gracefully">
    Implement proper error handling for connection failures, authentication errors, and data parsing issues:

    ```javascript theme={null}
    ws.onerror = (error) => {
      console.error('WebSocket error:', error);
      // Log error details and attempt reconnection
      reconnect();
    };
    ```
  </Accordion>

  <Accordion title="Clean Up Resources">
    Always close WebSocket connections and clear intervals when they're no longer needed:

    ```javascript theme={null}
    function disconnect() {
      clearInterval(pingInterval);
      ws.close();
    }
    ```
  </Accordion>
</AccordionGroup>

### Performance Optimization

<CardGroup cols={2}>
  <Card title="Selective Subscriptions" icon="filter">
    Only subscribe to symbols and fields you actively need to reduce bandwidth and processing overhead
  </Card>

  <Card title="Batch Updates" icon="layer-group">
    Process incoming messages in batches rather than individually for better performance
  </Card>

  <Card title="Connection Pooling" icon="network-wired">
    Reuse WebSocket connections when possible instead of creating new connections frequently
  </Card>

  <Card title="Message Throttling" icon="gauge-high">
    Implement client-side throttling to handle high-frequency updates without overwhelming your UI
  </Card>
</CardGroup>

***

## Quick Start Example

Here's a basic example of connecting to the Market Data WebSocket:

```javascript theme={null}
const ws = new WebSocket('wss://api.aries.com/v1/market/ws');

ws.onopen = () => {
  // Authenticate
  ws.send(JSON.stringify({
    type: "request",
    id: "auth-001",
    payload: {
      method: "POST",
      path: "/auth",
      body: {
        token: "YOUR_ACCESS_TOKEN"
      }
    }
  }));
};

ws.onmessage = (event) => {
  // Handle NDJSON: frames may contain multiple newline-delimited messages
  const lines = event.data.split('\n').filter(Boolean);
  for (const line of lines) {
    const message = JSON.parse(line);
    const payload = message.payload;

    if (payload?.action === "authSuccess") {
      // Subscribe to AAPL quotes after successful auth
      ws.send(JSON.stringify({
        type: "subscribe",
        id: "sub-1",
        payload: [{
          symbol: "AAPL",
          quoteFields: ["askPrice", "bidPrice", "lastPrice"]
        }]
      }));
    } else if (payload?.action === "update" && payload?.type === "quote") {
      // Process real-time quote data
      console.log('Quote update:', payload.symbol, payload.data);
    }
  }
};

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

ws.onclose = () => {
  console.log('WebSocket connection closed');
};
```

***

## Authentication

All WebSocket endpoints require authentication. After connecting, send your OAuth2 access token in a request message:

```json theme={null}
{
  "type": "request",
  "id": "auth-001",
  "payload": {
    "method": "POST",
    "path": "/auth",
    "body": {
      "token": "YOUR_ACCESS_TOKEN"
    }
  }
}
```

<Note>
  Obtain your access token through the OAuth2 flow. See the [API References](/api-reference) section for authentication details.
</Note>

***

## Support

Need help with WebSocket integration?

<CardGroup cols={2}>
  <Card title="Email Support" icon="envelope">
    [dev@aries.com](mailto:dev@aries.com)
  </Card>

  <Card title="API Status" icon="activity">
    [status.aries.com](https://status.aries.com)
  </Card>
</CardGroup>
