# Real-Time Quotes & WebSockets Integration

This document outlines the websocket connection management, subscription workflows, and UI sync strategies for real-time asset quotes in the mobile application.

---

## 1. Real-Time Quotes Stream Flow

```mermaid
sequenceDiagram
    participant Screen as Stock Watchlist Screen
    participant Provider as MarketSocketProvider
    participant WS as WebSocket Channel (Port 3003/5005)
    
    Screen->>Provider: Request live quotes for tokens [12345, 67890]
    Provider->>WS: Establish Connection (wss://app.edistry.com:3003)
    Provider->>WS: Send subscription request {"action": "subscribe", "tokens": [...]}
    WS-->>Provider: Continuous ticks stream {"token", "ltp", "change"}
    Provider-->>Screen: Trigger state refresh
    Note over Screen: Widget updates Last Traded Price (LTP) dynamically
```

---

## 2. Dynamic WebSocket Gateways

The client application resolves socket gateways dynamically based on the current market view:
* **Equity & F&O segments:** Connects to `wss://app.edistry.com:3003` to stream Indian stock ticks.
* **Crypto segment:** Connects to `wss://app.edistry.com:5005` to stream USDT token pair ticks.

---

## 3. Subscription & Ticker Logic

Inside `MarketSocketProvider`:
1. When a user opens a stock watchlist, the screen passes the list of active stock instrument tokens to the provider.
2. The provider establishes/reuses the WebSocket channel.
3. Transmits subscription packet containing instrument tokens to the socket server.
4. When a new tick packet arrives, the provider:
   * Decodes the JSON payload.
   * Updates the token's price in the memory map cache.
   * Calls `notifyListeners()` to trigger a redraw of the UI widgets displaying that stock's LTP.
5. When the user exits the screen, the provider sends an `unsubscribe` packet to release resources.

---

## 4. Connection State & Offline Handling

* **Internet Check:** The app integrates the `internet_connection_checker` library inside `ConnectivityProvider`.
* **State Updates:** If the internet connection drops:
  * The WebSocket channel is safely closed.
  * A banner is displayed: `"Network disconnected. Showing offline data."`.
* **Auto Reconnect:** Once connection is restored:
  * The socket channel automatically reconnects.
  * Re-subscribes to active watchlist tokens.
