# WEB DASHBOARD FRONTEND ARCHITECTURE SPECIFICATION (`web/`)

> **Subsystem:** Single-Page Application (SPA) Client Dashboard & Telemetry UI  
> **Source Files:** `web/index.html`, `web/index_v2.html` — both are **generated output**; the actual editable source is `build_html.py` (see its Routing section)  
> **Target Framework:** Standalone HTML5 / CSS3 / JavaScript (No node/npm runtime required)  
> **Primary Consumers:** PySide6 QWebEngineView / PyWebView Desktop Window, Browser Client  

---

## 📌 1. ARCHITECTURAL OVERVIEW & PURPOSE

The `web/` directory houses the complete frontend dashboard UI for the AI Gold Quant Engine.
Key capabilities include:
1. **Zero-Dependency Standalone SPA:** Bundles CSS stylesheets, SVG components, and Lightweight Charts into self-contained HTML files (`index.html` / `index_v2.html`), allowing instantaneous loading from local filesystem or `http://127.0.0.1:9100/`.
2. **Real-Time Polling & Telemetry Loop:** Periodically polls the embedded `observability/health.py` server (every 1,000ms) for account equity, active positions, win rates, and kill switch status.
3. **Interactive Financial Charting (Lightweight Charts):** Renders multi-timeframe candlestick data (`1M`, `5M`, `15M`, `30M`, `1H`), structural Support/Resistance pivots, Fair Value Gaps (FVG), and order entry markers.
4. **AI Trade Journaling Cards:** Dynamically renders trade post-mortem debrief cards streamed from `execution/journal_ai.py`.
5. **Interactive Risk & Configuration Controls:** Form controls allowing the user to update risk percent, max spread, and trailing stop multipliers on the fly (`POST /api/config`), or reset kill-switch latches (`POST /api/reset`).
6. **Responsive Design & Mobile PWA Layout:** Adapts dynamically via `@media (max-width: 900px)` from a desktop sidebar layout to a touch-optimized mobile bottom navigation bar (`.sidebar` flips to `position: fixed; bottom: 0; height: 60px`); `.main-stage` (the scrollable content wrapper) gets `padding-bottom: 80px` in the same breakpoint so page content clears the fixed bar instead of scrolling underneath it, and `.side-col` drops its fixed 280px desktop width to `100%` so it doesn't overflow the stacked column. A further `@media (max-width: 480px)` breakpoint collapses the metrics grid to a single column, stacks the header bar vertically (`.header-bar`), and lets the chart timeframe button row (`#tf-buttons`) wrap instead of overflowing on narrow phone screens. See F-38 in `CLAUDE.md` for the dead-selector bug this replaced.

---

## 🎨 2. UI COMPONENTS & DESIGN SYSTEM

### 1. Speedometer Sentiment Dial
* **Visual:** SVG circular gauge with radial-gradient dark face, red warning zones, and an orange dynamic needle.
* **Mapping Formula:** Maps `sentiment_score` (-50 to +50) to degrees:
  $$	ext{Angle} = (	ext{score} - 50) 	imes 2.4 \quad (	ext{Range: } -120^\circ 	ext{ to } +120^\circ)$$

### 2. Equity & PnL Telemetry Cards
* Live Account Equity with High-Water Mark indicator.
* Today's Net PnL ($) and daily percentage gain/loss.
* Win Rate ($W$) percentage calculated across closed session deals.
* Circuit Breaker & Kill-Switch status (Green for Normal, Red for Latched, Orange for News/Cooling Pause).

### 3. Lightweight Charts Technical Canvas
* Candlestick series with UTC timestamp formatting.
* Duplicate timestamp offset shift: guarantees concurrent ticks are rendered cleanly without JavaScript runtime errors.
* Overlay markers for Buy (Green arrows) and Sell (Red arrows) executions.

### 4. Forensic Audit & AI Journal Feed
* Historical trade table with period filtering (`today`, `week`, `month`, `all`) and custom date ranges.
* AI Trade Post-Mortems displaying strategy name, net profit, and classified lesson.

---

## 🌐 3. BACKEND API INTERACTION PROTOCOL

```mermaid
sequenceDiagram
    participant UI as web/index.html (Client)
    participant HS as observability/health.py (127.0.0.1:9100)
    participant Engine as Bot Subsystems (Core/Execution/Risk)

    loop Every 1000ms
        UI->>HS: GET /api/data?period=today
        HS-->>UI: {equity: 5420.50, pnl: 420.50, regime: "TRENDING", positions: [...]}
        UI->>UI: Update Telemetry Cards & Position List
    end

    opt User Changes Timeframe
        UI->>HS: GET /api/chart?tf=15M
        HS-->>UI: Candlesticks & S/R Pivots
        UI->>UI: Re-render Lightweight Chart
    end

    opt User Updates Settings
        UI->>HS: POST /api/config {risk_pct: 0.02, max_spread: 25}
        HS->>Engine: Hot-reload runtime config
        HS-->>UI: 200 OK {"status": "update_received"}
    end
```

---

## 🔗 Routing — Change-Impact Map

- **`/api/config` accepts a `trade_direction` field for backward API compatibility, but it has no
  effect** — direction is AI/AUTO-driven by deliberate policy, enforced in `orchestrator.py`'s
  `_update_status_cache`. There is no UI control that sends this field today.
- **The Speedometer Sentiment Dial and the `dir-guard-label` both read `active_bias`/`sentiment_score`
  from `/api/data`** — changing either field's shape in `orchestrator.py`'s status cache breaks both UI
  elements simultaneously.
- **Chart data (`/api/chart`) and live telemetry (`/api/data`) are separate polling loops on the
  frontend** — a slow/blocked chart request should never stall the telemetry poll; keep them
  independent if modifying the JS polling logic.
