# WebSockets & Live Quotes Stream

This document outlines the real-time quote feeding architecture, covering external data feeds, WebSocket gateways, and live distribution to client apps.

---

## 1. Real-Time Data Flow Overview

To keep virtual portfolios accurate, the system streams live asset prices from external API feeds, caches them inside Redis, and broadcasts updates to connected mobile clients.

```mermaid
graph LR
    KiteFeed[Kite Connect Ticker] -->|Live tick events| KiteWorker[Kite Ticker Worker]
    BinanceFeed[Binance WebSockets] -->|USDT Pair ticks| CryptoWorker[Crypto WebSocket Worker]
    
    KiteWorker -->|Update LTP| Redis[(Redis LTP Cache)]
    CryptoWorker -->|Update LTP| Redis
    
    Redis -->|Read LTP| WSServer[Express WebSocket Server]
    WSServer -->|Broadcast quote updates| Client[Mobile Client App]
```

---

## 2. External Feeds Workers

The backend hosts separate workers to listen to external market tick streams:

### Indian Market (Equity / F&O Derivatives)
* **Script:** `src/websocket/indian_market/kiteticker.js`
* **Feed Provider:** Zerodha Kite Ticker API (WebSocket connection).
* **Workflow:** 
  1. Authenticates using Zerodha Developer API key and daily access token.
  2. Subscribes to instrument tokens corresponding to active watchlists, open positions, and pending orders.
  3. Receives live tick packets, extracts Last Traded Price (LTP), and updates the Redis LTP cache immediately.

### Crypto Market (USDT Pairs)
* **Script:** `src/websocket/crypto_market/server.js`
* **Feed Provider:** Binance WebSockets stream API.
* **Workflow:**
  1. Connects to Binance public streams for USDT pairs (e.g. `btcuesdt@ticker`, `ethusdt@ticker`).
  2. Parses JSON updates and synchronizes current prices into Redis.

---

## 3. WebSocket Gateways (Client Broadcasters)

The system exposes multiple WebSocket endpoints, managed by PM2, that clients connect to based on the segment they are viewing:

| WebSocket Service | Port | Script Path | Purpose |
|---|---|---|---|
| **Indian Market WS** | `3003` | `src/websocket/indian_market/server.js` | Streams Nifty, Bank Nifty indices, and equity stock LTP updates. |
| **Crypto Market WS** | `5005` | `src/websocket/crypto_market/server.js` | Streams major Crypto pair LTP updates. |
| **Admin/System WS** | `4004` | `src/node_api/node_api.js` | System messages, global logs, and background worker status. |

---

## 4. Client Integration Details

### Flutter Client Connection
In the Flutter codebase (e.g., [rest_api.dart](file:///var/www/html_docker/Smartbulls_app/lib/api/rest_api.dart)), the app connects to the corresponding WebSocket server based on active terminal views:
* **Establish Connection:** `IOWebSocketChannel.connect("wss://<domain>:<port>")`
* **Request Format:** The client sends subscription requests specifying the token arrays it wants to watch:
  ```json
  {
    "action": "subscribe",
    "tokens": [123456, 789101]
  }
  ```
* **Response Stream:** The server responds with ticks containing current quotes:
  ```json
  {
    "token": 123456,
    "ltp": 62792.62,
    "change": 0.42
  }
  ```
