Skip to content

FinceptTerminal is a modern finance application offering advanced market analytics, investment research, and economic data tools, designed for interactive exploration and data-driven decision-making in a user-friendly environment.

workflow scripts added

tilakpatel22c7d860625ab3
diff --git a/.github/workflows/build-cpp.yml b/.github/workflows/build-cpp.yml
index a57250504..5f8d5901b 100644
--- a/.github/workflows/build-cpp.yml
+++ b/.github/workflows/build-cpp.yml
@@ -2,6 +2,9 @@ name: Build C++ Terminal — All Platforms
on:
workflow_dispatch:
+ push:
+ tags:
+ - 'v*'
env:
BUILD_TYPE: Release
@@ -311,9 +314,9 @@ jobs:
- name: Create Release
uses: softprops/action-gh-release@v2
with:
- tag_name: cpp-v${{ github.run_number }}
- name: "Fincept Terminal C++ Build #${{ github.run_number }}"
- make_latest: false
+ tag_name: ${{ github.ref_type == 'tag' && github.ref_name || format('cpp-build-{0}', github.run_number) }}
+ name: ${{ github.ref_type == 'tag' && format('Fincept Terminal {0}', github.ref_name) || format('Fincept Terminal C++ Build #{0}', github.run_number) }}
+ make_latest: ${{ github.ref_type == 'tag' }}
body: |
Automated C++ build from commit ${{ github.sha }}
@@ -339,4 +342,4 @@ jobs:
FinceptTerminal-macOS-universal.tar.gz
fail_on_unmatched_files: false
draft: false
- prerelease: true
+ prerelease: ${{ github.ref_type != 'tag' }}
diff --git a/.github/workflows/test-setup.yml b/.github/workflows/test-setup.yml
new file mode 100644
index 000000000..f5d4e7479
--- /dev/null
+++ b/.github/workflows/test-setup.yml
@@ -0,0 +1,81 @@
+name: Test Setup Scripts
+
+on:
+ push:
+ paths:
+ - 'setup.sh'
+ - 'setup.bat'
+ - 'fincept-cpp/CMakeLists.txt'
+ - 'fincept-cpp/vcpkg.json'
+ pull_request:
+ paths:
+ - 'setup.sh'
+ - 'setup.bat'
+ - 'fincept-cpp/CMakeLists.txt'
+ - 'fincept-cpp/vcpkg.json'
+ workflow_dispatch:
+
+env:
+ VCPKG_BINARY_SOURCES: "clear;x-gha,readwrite"
+
+jobs:
+ test-setup:
+ strategy:
+ fail-fast: false
+ matrix:
+ include:
+ - os: ubuntu-22.04
+ platform: Linux
+ binary: fincept-cpp/build/FinceptTerminal
+
+ - os: macos-14
+ platform: macOS
+ binary: fincept-cpp/build/FinceptTerminal
+
+ - os: windows-2022
+ platform: Windows
+ binary: fincept-cpp/build/Release/FinceptTerminal.exe
+
+ runs-on: ${{ matrix.os }}
+ name: ${{ matrix.platform }}
+
+ steps:
+ - name: Checkout
+ uses: actions/checkout@v4
+
+ - name: Setup vcpkg caching
+ uses: actions/github-script@v7
+ with:
+ script: |
+ core.exportVariable('ACTIONS_CACHE_URL', process.env.ACTIONS_CACHE_URL || '');
+ core.exportVariable('ACTIONS_RUNTIME_TOKEN', process.env.ACTIONS_RUNTIME_TOKEN || '');
+
+ # ── Linux / macOS — run setup.sh --ci ──────────────────
+ - name: Run setup.sh --ci (Linux/macOS)
+ if: runner.os != 'Windows'
+ env:
+ VCPKG_ROOT: ${{ github.workspace }}/vcpkg
+ run: |
+ chmod +x setup.sh
+ ./setup.sh --ci
+
+ # ── Windows — run setup.bat --ci ───────────────────────
+ - name: Run setup.bat --ci (Windows)
+ if: runner.os == 'Windows'
+ shell: cmd
+ env:
+ VCPKG_ROOT: ${{ github.workspace }}\vcpkg
+ run: setup.bat --ci
+
+ # ── Verify binary exists ────────────────────────────────
+ - name: Verify binary
+ shell: bash
+ run: |
+ if [ ! -f "${{ matrix.binary }}" ]; then
+ echo "ERROR: Binary not found at ${{ matrix.binary }}"
+ ls -la fincept-cpp/build/ 2>/dev/null || true
+ ls -la fincept-cpp/build/Release/ 2>/dev/null || true
+ exit 1
+ fi
+ echo "Binary verified: ${{ matrix.binary }}"
+ ls -lh "${{ matrix.binary }}"
diff --git a/README.md b/README.md
index 38a8248ca..cc75ba0cb 100644
--- a/README.md
+++ b/README.md
@@ -78,14 +78,86 @@ State-of-the-art financial intelligence platform with CFA-level analytics, AI au
---
+## Quick Start (One-Click Setup)
+
+Clone and run the setup script — it installs all dependencies and builds the app automatically:
+
+```bash
+# Linux / macOS
+git clone https://github.com/Fincept-Corporation/FinceptTerminal.git
+cd FinceptTerminal
+chmod +x setup.sh && ./setup.sh
+```
+
+```bat
+# Windows — run from Developer Command Prompt for VS 2022
+git clone https://github.com/Fincept-Corporation/FinceptTerminal.git
+cd FinceptTerminal
+setup.bat
+```
+
+The script handles: compiler check, CMake, Ninja, Python, vcpkg, all C++ dependencies, build, and launch.
+
+---
+
+## Download & Run (No Build Required)
+
+Pre-built binaries are available on the [Releases page](https://github.com/Fincept-Corporation/FinceptTerminal/releases).
+
+| Platform | Download | Run |
+|----------|----------|-----|
+| **Windows x64** | `FinceptTerminal-Windows-x64.zip` | Extract → `FinceptTerminal.exe` |
+| **Linux x64** | `FinceptTerminal-Linux-x64.tar.gz` | Extract → `./FinceptTerminal` |
+| **macOS (Apple Silicon)** | `FinceptTerminal-macOS-arm64.tar.gz` | Extract → `./FinceptTerminal` |
+| **macOS (Intel)** | `FinceptTerminal-macOS-x64.tar.gz` | Extract → `./FinceptTerminal` |
+| **macOS (Universal)** | `FinceptTerminal-macOS-universal.tar.gz` | Extract → `./FinceptTerminal` |
+
+No installation required — just extract and run.
+
+---
+
## Build from Source
### Prerequisites
-- **CMake** 3.20+
-- **vcpkg** (for dependency management)
-- **C++20 compiler** (MSVC 2022, GCC 12+, or Clang 15+)
-- **Python** 3.11+ (for analytics scripts)
+| Tool | Version | Windows | Linux | macOS |
+|------|---------|---------|-------|-------|
+| **Git** | latest | `winget install Git.Git` | `apt install git` | `brew install git` |
+| **CMake** | 3.20+ | `winget install Kitware.CMake` | `apt install cmake` | `brew install cmake` |
+| **Ninja** | latest | `winget install Ninja-build.Ninja` | `apt install ninja-build` | `brew install ninja` |
+| **C++ compiler** | C++20 | MSVC 2022 ([Visual Studio](https://visualstudio.microsoft.com/)) | `apt install g++` | Xcode CLT: `xcode-select --install` |
+| **vcpkg** | latest | See below | See below | See below |
+| **Python** | 3.11+ | [python.org](https://www.python.org/downloads/) | `apt install python3` | `brew install python` |
+
+#### Install vcpkg
+
+```bash
+git clone https://github.com/microsoft/vcpkg.git ~/vcpkg
+~/vcpkg/bootstrap-vcpkg.sh # Linux / macOS
+# or
+git clone https://github.com/microsoft/vcpkg.git %USERPROFILE%\vcpkg
+%USERPROFILE%\vcpkg\bootstrap-vcpkg.bat # Windows
+```
+
+Then set `VCPKG_ROOT` permanently:
+
+```bash
+# Linux / macOS — add to ~/.bashrc or ~/.zshrc
+export VCPKG_ROOT=~/vcpkg
+
+# Windows (PowerShell — run once)
+[System.Environment]::SetEnvironmentVariable("VCPKG_ROOT","$env:USERPROFILE\vcpkg","User")
+```
+
+#### Linux system dependencies
+
+```bash
+sudo apt install -y \
+ libxinerama-dev libxcursor-dev xorg-dev libglu1-mesa-dev \
+ libxrandr-dev libxi-dev libxext-dev libxfixes-dev \
+ libwayland-dev libxkbcommon-dev \
+ pkg-config
+```
### Build
@@ -93,24 +165,21 @@ State-of-the-art financial intelligence platform with CFA-level analytics, AI au
git clone https://github.com/Fincept-Corporation/FinceptTerminal.git
cd FinceptTerminal/fincept-cpp
-# Windows (MSVC)
+# All platforms (requires VCPKG_ROOT set)
cmake --preset=default
cmake --build build --config Release
-
-# Linux / macOS
-cmake -B build -DCMAKE_BUILD_TYPE=Release
-cmake --build build
```
### Run
```bash
./build/FinceptTerminal # Linux / macOS
-.\build\Release\FinceptTerminal # Windows
+.\build\Release\FinceptTerminal.exe # Windows
```
### vcpkg Dependencies
+All dependencies are installed automatically by vcpkg:
glfw3, curl, nlohmann-json, sqlite3, openssl, imgui (docking + freetype), yoga, stb, implot, spdlog, miniaudio
---
diff --git a/docs/GETTING_STARTED.md b/docs/GETTING_STARTED.md
index 6f02d18e4..5079ed0e9 100644
--- a/docs/GETTING_STARTED.md
+++ b/docs/GETTING_STARTED.md
@@ -37,13 +37,47 @@ Fincept Terminal is an **open-source financial analysis platform** — a free, o
### Prerequisites
-| Tool | Version | Install |
-|------|---------|---------|
-| CMake | 3.20+ | [cmake.org](https://cmake.org/download/) |
-| vcpkg | latest | [vcpkg.io](https://vcpkg.io/) |
-| C++ Compiler | C++20 | MSVC 2022 / GCC 12+ / Clang 15+ |
-| Python | 3.11+ | [python.org](https://www.python.org/downloads/) |
-| Git | latest | [git-scm.com](https://git-scm.com/downloads) |
+#### 1. Install a C++20 compiler
+
+- **Windows**: Install [Visual Studio 2022](https://visualstudio.microsoft.com/) with "Desktop development with C++" workload
+- **Linux**: `sudo apt install -y g++ cmake ninja-build`
+- **macOS**: `xcode-select --install && brew install cmake ninja`
+
+#### 2. Install CMake 3.20+ and Ninja
+
+- **Windows**: `winget install Kitware.CMake Ninja-build.Ninja`
+- **Linux/macOS**: included in step above
+
+#### 3. Install vcpkg and set VCPKG_ROOT
+
+```bash
+# Linux / macOS
+git clone https://github.com/microsoft/vcpkg.git ~/vcpkg
+~/vcpkg/bootstrap-vcpkg.sh
+echo 'export VCPKG_ROOT=~/vcpkg' >> ~/.bashrc # or ~/.zshrc
+source ~/.bashrc
+
+# Windows (PowerShell)
+git clone https://github.com/microsoft/vcpkg.git "$env:USERPROFILE\vcpkg"
+& "$env:USERPROFILE\vcpkg\bootstrap-vcpkg.bat"
+[System.Environment]::SetEnvironmentVariable("VCPKG_ROOT","$env:USERPROFILE\vcpkg","User")
+# Restart your terminal after this
+```
+
+#### 4. Linux only — install system dependencies
+
+```bash
+sudo apt install -y \
+ libxinerama-dev libxcursor-dev xorg-dev libglu1-mesa-dev \
+ libxrandr-dev libxi-dev libxext-dev libxfixes-dev \
+ libwayland-dev libxkbcommon-dev pkg-config
+```
+
+#### 5. Install Python 3.11+
+
+- **Windows**: [python.org](https://www.python.org/downloads/) (check "Add to PATH")
+- **Linux**: `sudo apt install python3`
+- **macOS**: `brew install python`
### Setup in 4 Steps
@@ -52,15 +86,15 @@ Fincept Terminal is an **open-source financial analysis platform** — a free, o
git clone https://github.com/Fincept-Corporation/FinceptTerminal.git
cd FinceptTerminal/fincept-cpp
-# 2. Configure (vcpkg will install dependencies)
+# 2. Configure — vcpkg installs all C++ dependencies automatically
cmake --preset=default
# 3. Build
cmake --build build --config Release
# 4. Run
-./build/FinceptTerminal # Linux / macOS
-.\build\Release\FinceptTerminal # Windows
+./build/FinceptTerminal # Linux / macOS
+.\build\Release\FinceptTerminal.exe # Windows
```
**Expected Result:** Fincept Terminal window should open, showing the login screen.
@@ -228,9 +262,10 @@ git push origin fix/issue-123-description
### Build fails — missing vcpkg packages
```bash
# Ensure VCPKG_ROOT is set
-echo $VCPKG_ROOT
+echo $VCPKG_ROOT # Linux / macOS (should print the vcpkg path)
+echo %VCPKG_ROOT% # Windows CMD
-# Reconfigure
+# If empty, set it (see Prerequisites step 3 above), then reconfigure
cmake --preset=default --fresh
cmake --build build --config Release
```
diff --git a/docs/superpowers/plans/2026-03-19-surface-csv-import.md b/docs/superpowers/plans/2026-03-19-surface-csv-import.md
new file mode 100644
index 000000000..6e7120108
--- /dev/null
+++ b/docs/superpowers/plans/2026-03-19-surface-csv-import.md
@@ -0,0 +1,1547 @@
+# Surface Analytics CSV Import Implementation Plan
+
+> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking.
+
+**Goal:** Add per-surface CSV import to all 35 Surface Analytics surfaces, with an in-UI column schema reference shown before import, so users can load real data and analyze it instead of demo data.
+
+**Architecture:** A single shared CSV parser (`csv_importer.cpp`) reads rows into `vector<vector<string>>`, then per-surface parser functions convert that into the existing typed data structs (`VolatilitySurfaceData`, `BondSpreadData`, etc.). A reusable `render_csv_import_dialog()` modal shows the required column schema, a path input, parse errors, and a load button. The `SurfaceScreen` adds an IMPORT button to the control bar that opens this modal for the active surface.
+
+**Tech Stack:** C++20, Dear ImGui (`BeginPopupModal`), standard `<fstream>` + `<sstream>` for CSV parsing, existing theme helpers (`theme::AccentButton`, `theme::SecondaryButton`), existing data structs in `surface_types.h`.
+
+---
+
+## CSV Column Schemas (locked format for all 35 surfaces)
+
+These are the canonical column definitions. They must be shown in the UI at import time.
+
+### Equity Derivatives
+| Surface | Required Columns |
+|---|---|
+| VOL SURFACE | `strike, dte, iv_pct` |
+| DELTA | `strike, dte, delta` |
+| GAMMA | `strike, dte, gamma` |
+| VEGA | `strike, dte, vega` |
+| THETA | `strike, dte, theta` |
+| SKEW | `dte, delta, skew_pct` |
+| LOCAL VOL | `strike, dte, local_vol_pct` |
+
+### Fixed Income
+| Surface | Required Columns |
+|---|---|
+| YIELD CURVE | `maturity_months, date, yield_pct` |
+| SWAPTION VOL | `option_expiry_months, swap_tenor_months, vol_bps` |
+| CAP/FLOOR | `maturity_months, strike_pct, vol_bps` |
+| BOND SPREAD | `rating, maturity_months, spread_bps` |
+| OIS BASIS | `day, tenor_months, basis_bps` |
+| REAL YIELD | `day, maturity_months, yield_pct` |
+| FWD RATE | `start_months, fwd_period_months, rate_pct` |
+
+### FX
+| Surface | Required Columns |
+|---|---|
+| FX VOL | `tenor_days, delta, vol_pct` |
+| FX FORWARD | `pair, tenor_days, pips` |
+| XCCY BASIS | `pair, tenor_months, basis_bps` |
+
+### Credit
+| Surface | Required Columns |
+|---|---|
+| CDS SPREAD | `entity, tenor_months, spread_bps` |
+| TRANSITION | `from_rating, to_rating, probability_pct` |
+| RECOVERY | `sector, seniority, recovery_pct` |
+
+### Commodities
+| Surface | Required Columns |
+|---|---|
+| CMDTY FWD | `commodity, contract_months, price` |
+| CMDTY VOL | `dte, strike_pct, vol_pct` |
+| CRACK/CRUSH | `spread_type, contract_months, spread_usd` |
+| CONTANGO | `commodity, contract_months, pct_from_spot` |
+
+### Risk & Portfolio
+| Surface | Required Columns |
+|---|---|
+| CORRELATION | `asset_i, asset_j, correlation` |
+| PCA | `asset, factor, loading` |
+| VAR | `confidence_pct, horizon_days, var_pct` |
+| STRESS TEST | `scenario, portfolio, pnl_pct` |
+| FACTOR EXP | `asset, factor, exposure` |
+| LIQUIDITY | `dte, strike, spread` |
+| DRAWDOWN | `asset, window_days, max_dd_pct` |
+| BETA | `asset, horizon_days, beta` |
+| IMPL DIV | `dte, strike, div_yield_pct` |
+
+### Macro
+| Surface | Required Columns |
+|---|---|
+| INFLATION | `day, horizon_years, bei_pct` |
+| RATE PATH | `central_bank, meeting_num, rate_pct` |
+
+---
+
+## File Map
+
+| File | Action | Responsibility |
+|---|---|---|
+| `src/screens/surface_analytics/csv_importer.h` | **CREATE** | Schema definitions, parser function declarations |
+| `src/screens/surface_analytics/csv_importer.cpp` | **CREATE** | Generic CSV parser + all 35 per-surface parse functions |
+| `src/screens/surface_analytics/surface_screen.h` | **MODIFY** | Add import state members + `render_csv_import_dialog()` declaration |
+| `src/screens/surface_analytics/surface_screen.cpp` | **MODIFY** | Add IMPORT button to control bar; call `render_csv_import_dialog()` |
+| `src/screens/surface_analytics/import_dialog.cpp` | **CREATE** | `render_csv_import_dialog()` — modal UI with schema display + load logic |
+| `CMakeLists.txt` | **MODIFY** | Add `csv_importer.cpp` and `import_dialog.cpp` to SOURCES + SKIP_UNITY_BUILD |
+
+---
+
+## Task 1: CSV Schema Definitions + Generic Parser (`csv_importer.h` + `csv_importer.cpp`)
+
+**Files:**
+- Create: `src/screens/surface_analytics/csv_importer.h`
+- Create: `src/screens/surface_analytics/csv_importer.cpp`
+
+- [ ] **Step 1: Create `csv_importer.h`**
+
+```cpp
+#pragma once
+#include "surface_types.h"
+#include <string>
+#include <vector>
+
+namespace fincept::surface {
+
+// ── Schema descriptor ────────────────────────────────────────────────────────
+struct CsvColumn {
+ const char* name; // e.g. "strike"
+ const char* description; // e.g. "Option strike price (absolute, not %)"
+};
+
+struct CsvSchema {
+ ChartType type;
+ const char* surface_name;
+ std::vector<CsvColumn> columns;
+ const char* example_row; // one realistic example row
+};
+
+// Returns the schema for the given chart type
+const CsvSchema& get_csv_schema(ChartType type);
+
+// ── Generic CSV parser ────────────────────────────────────────────────────────
+// Returns rows as vector<vector<string>>; first row assumed header.
+// On error, out_error is set and return is empty.
+std::vector<std::vector<std::string>> parse_csv_file(
+ const std::string& path,
+ std::string& out_error);
+
+// ── Per-surface loaders ───────────────────────────────────────────────────────
+// Each function reads the parsed rows and fills the data struct.
+// Returns true on success; sets out_error on failure.
+
+bool load_vol_surface( const std::vector<std::vector<std::string>>& rows, VolatilitySurfaceData& out, std::string& err);
+bool load_greeks_surface( const std::vector<std::vector<std::string>>& rows, GreeksSurfaceData& out, std::string& err, const std::string& greek_name);
+bool load_skew_surface( const std::vector<std::vector<std::string>>& rows, SkewSurfaceData& out, std::string& err);
+bool load_local_vol( const std::vector<std::vector<std::string>>& rows, LocalVolData& out, std::string& err);
+bool load_yield_curve( const std::vector<std::vector<std::string>>& rows, YieldCurveData& out, std::string& err);
+bool load_swaption_vol( const std::vector<std::vector<std::string>>& rows, SwaptionVolData& out, std::string& err);
+bool load_capfloor_vol( const std::vector<std::vector<std::string>>& rows, CapFloorVolData& out, std::string& err);
+bool load_bond_spread( const std::vector<std::vector<std::string>>& rows, BondSpreadData& out, std::string& err);
+bool load_ois_basis( const std::vector<std::vector<std::string>>& rows, OISBasisData& out, std::string& err);
+bool load_real_yield( const std::vector<std::vector<std::string>>& rows, RealYieldData& out, std::string& err);
+bool load_forward_rate( const std::vector<std::vector<std::string>>& rows, ForwardRateData& out, std::string& err);
+bool load_fx_vol( const std::vector<std::vector<std::string>>& rows, FXVolData& out, std::string& err);
+bool load_fx_forward( const std::vector<std::vector<std::string>>& rows, FXForwardPointsData& out, std::string& err);
+bool load_xccy_basis( const std::vector<std::vector<std::string>>& rows, CrossCurrencyBasisData& out,std::string& err);
+bool load_cds_spread( const std::vector<std::vector<std::string>>& rows, CDSSpreadData& out, std::string& err);
+bool load_credit_trans( const std::vector<std::vector<std::string>>& rows, CreditTransitionData& out, std::string& err);
+bool load_recovery_rate( const std::vector<std::vector<std::string>>& rows, RecoveryRateData& out, std::string& err);
+bool load_cmdty_forward( const std::vector<std::vector<std::string>>& rows, CommodityForwardData& out, std::string& err);
+bool load_cmdty_vol( const std::vector<std::vector<std::string>>& rows, CommodityVolData& out, std::string& err);
+bool load_crack_spread( const std::vector<std::vector<std::string>>& rows, CrackSpreadData& out, std::string& err);
+bool load_contango( const std::vector<std::vector<std::string>>& rows, ContangoData& out, std::string& err);
+bool load_correlation( const std::vector<std::vector<std::string>>& rows, CorrelationMatrixData& out, std::string& err);
+bool load_pca( const std::vector<std::vector<std::string>>& rows, PCAData& out, std::string& err);
+bool load_var( const std::vector<std::vector<std::string>>& rows, VaRData& out, std::string& err);
+bool load_stress_test( const std::vector<std::vector<std::string>>& rows, StressTestData& out, std::string& err);
+bool load_factor_exposure(const std::vector<std::vector<std::string>>& rows, FactorExposureData& out, std::string& err);
+bool load_liquidity( const std::vector<std::vector<std::string>>& rows, LiquidityData& out, std::string& err);
+bool load_drawdown( const std::vector<std::vector<std::string>>& rows, DrawdownData& out, std::string& err);
+bool load_beta( const std::vector<std::vector<std::string>>& rows, BetaData& out, std::string& err);
+bool load_implied_div( const std::vector<std::vector<std::string>>& rows, ImpliedDividendData& out, std::string& err);
+bool load_inflation( const std::vector<std::vector<std::string>>& rows, InflationExpData& out, std::string& err);
+bool load_monetary( const std::vector<std::vector<std::string>>& rows, MonetaryPolicyData& out, std::string& err);
+
+} // namespace fincept::surface
+```
+
+- [ ] **Step 2: Create `csv_importer.cpp` — schema table + generic parser**
+
+```cpp
+#include "csv_importer.h"
+#include <fstream>
+#include <sstream>
+#include <algorithm>
+#include <map>
+#include <cstdio>
+
+// Must be listed in SKIP_UNITY_BUILD_INCLUSION in CMakeLists.txt
+
+namespace fincept::surface {
+
+// ── Schema table ─────────────────────────────────────────────────────────────
+static const CsvSchema SCHEMAS[] = {
+ { ChartType::Volatility, "VOL SURFACE",
+ {{"strike","Option strike (absolute price)"},{"dte","Days to expiry (integer)"},{"iv_pct","Implied vol % e.g. 22.5"}},
+ "450.0,30,22.5" },
+ { ChartType::DeltaSurface, "DELTA",
+ {{"strike","Option strike"},{"dte","Days to expiry"},{"delta","Delta value 0..1"}},
+ "450.0,30,0.52" },
+ { ChartType::GammaSurface, "GAMMA",
+ {{"strike","Option strike"},{"dte","Days to expiry"},{"gamma","Gamma value"}},
+ "450.0,30,0.0031" },
+ { ChartType::VegaSurface, "VEGA",
+ {{"strike","Option strike"},{"dte","Days to expiry"},{"vega","Vega value"}},
+ "450.0,30,0.85" },
+ { ChartType::ThetaSurface, "THETA",
+ {{"strike","Option strike"},{"dte","Days to expiry"},{"theta","Theta (negative decay per day)"}},
+ "450.0,30,-0.12" },
+ { ChartType::SkewSurface, "SKEW",
+ {{"dte","Days to expiry"},{"delta","Delta e.g. 10,25,50,75,90"},{"skew_pct","Skew value %"}},
+ "30,25,-1.2" },
+ { ChartType::LocalVolSurface, "LOCAL VOL",
+ {{"strike","Option strike"},{"dte","Days to expiry"},{"local_vol_pct","Local vol % (Dupire)"}},
+ "450.0,30,21.0" },
+ { ChartType::YieldCurve, "YIELD CURVE",
+ {{"maturity_months","Maturity in months e.g. 3,6,12,24"},{"date","Row date label (integer day index or YYYY-MM-DD)"},{"yield_pct","Yield % e.g. 4.35"}},
+ "24,2024-01-15,4.35" },
+ { ChartType::SwaptionVol, "SWAPTION VOL",
+ {{"option_expiry_months","Option expiry in months"},{"swap_tenor_months","Swap tenor in months"},{"vol_bps","Normal vol in bps"}},
+ "12,60,85" },
+ { ChartType::CapFloorVol, "CAP/FLOOR VOL",
+ {{"maturity_months","Cap/floor maturity months"},{"strike_pct","Strike rate %"},{"vol_bps","Normal vol bps"}},
+ "24,4.5,62" },
+ { ChartType::BondSpread, "BOND SPREAD",
+ {{"rating","Credit rating e.g. AAA,AA,A,BBB,BB,B,CCC"},{"maturity_months","Bond maturity months"},{"spread_bps","OAS spread bps"}},
+ "BBB,60,120" },
+ { ChartType::OISBasis, "OIS BASIS",
+ {{"day","Time point index (integer, oldest=0)"},{"tenor_months","Tenor months"},{"basis_bps","OIS-SOFR basis bps"}},
+ "0,12,2.5" },
+ { ChartType::RealYield, "REAL YIELD",
+ {{"day","Time point index"},{"maturity_months","TIPS maturity months"},{"yield_pct","Real yield %"}},
+ "0,60,1.82" },
+ { ChartType::ForwardRate, "FWD RATE",
+ {{"start_months","Forward start in months"},{"fwd_period_months","Forward period months"},{"rate_pct","Forward rate %"}},
+ "12,12,4.8" },
+ { ChartType::FXVol, "FX VOL",
+ {{"tenor_days","Tenor in days"},{"delta","Delta e.g. 10,25,50,75,90"},{"vol_pct","FX implied vol %"}},
+ "30,25,7.2" },
+ { ChartType::FXForwardPoints, "FX FORWARD",
+ {{"pair","Currency pair e.g. EUR/USD"},{"tenor_days","Tenor days"},{"pips","Forward points in pips"}},
+ "EUR/USD,30,-12.5" },
+ { ChartType::CrossCurrencyBasis, "XCCY BASIS",
+ {{"pair","Currency pair vs USD e.g. EUR"},{"tenor_months","Tenor months"},{"basis_bps","XCCY basis bps (negative=USD premium)"}},
+ "EUR,12,-22" },
+ { ChartType::CDSSpread, "CDS SPREAD",
+ {{"entity","Company or sovereign name"},{"tenor_months","CDS tenor months"},{"spread_bps","CDS spread bps"}},
+ "Apple Inc,60,45" },
+ { ChartType::CreditTransition, "TRANSITION MATRIX",
+ {{"from_rating","Initial rating e.g. AAA"},{"to_rating","Final rating e.g. AA"},{"probability_pct","Transition probability %"}},
+ "AAA,AA,8.2" },
+ { ChartType::RecoveryRate, "RECOVERY RATE",
+ {{"sector","Industry sector e.g. Technology"},{"seniority","Debt seniority e.g. Senior,Sub,Junior"},{"recovery_pct","Recovery rate %"}},
+ "Technology,Senior,52.0" },
+ { ChartType::CommodityForward, "CMDTY FORWARD",
+ {{"commodity","Commodity name e.g. WTI Crude"},{"contract_months","Months forward"},{"price","Forward price"}},
+ "WTI Crude,3,78.50" },
+ { ChartType::CommodityVol, "CMDTY VOL",
+ {{"dte","Days to expiry"},{"strike_pct","Strike as % of spot e.g. 90,100,110"},{"vol_pct","Implied vol %"}},
+ "30,100,32.5" },
+ { ChartType::CrackSpread, "CRACK/CRUSH SPREAD",
+ {{"spread_type","Spread name e.g. 3-2-1 Crack"},{"contract_months","Months forward"},{"spread_usd","Spread value USD/unit"}},
+ "3-2-1 Crack,3,24.5" },
+ { ChartType::ContangoBackwardation, "CONTANGO/BACKWARDATION",
+ {{"commodity","Commodity name"},{"contract_months","Months forward"},{"pct_from_spot","% above(+) or below(-) spot"}},
+ "WTI Crude,3,1.8" },
+ { ChartType::Correlation, "CORRELATION",
+ {{"asset_i","First asset ticker"},{"asset_j","Second asset ticker"},{"correlation","Pearson correlation -1..1"}},
+ "SPY,QQQ,0.92" },
+ { ChartType::PCA, "PCA LOADINGS",
+ {{"asset","Asset ticker"},{"factor","Factor name e.g. PC1,PC2,PC3"},{"loading","Factor loading value"}},
+ "SPY,PC1,0.45" },
+ { ChartType::VaR, "VAR",
+ {{"confidence_pct","Confidence level % e.g. 95,99"},{"horizon_days","Holding period days"},{"var_pct","VaR as % of portfolio"}},
+ "99,1,2.35" },
+ { ChartType::StressTestPnL, "STRESS TEST",
+ {{"scenario","Scenario name e.g. 2008 Crisis"},{"portfolio","Portfolio name"},{"pnl_pct","P&L % (negative=loss)"}},
+ "2008 Crisis,Core Portfolio,-18.5" },
+ { ChartType::FactorExposure, "FACTOR EXPOSURE",
+ {{"asset","Asset ticker"},{"factor","Factor name e.g. Market,Size,Value"},{"exposure","Factor exposure (beta-like)"}},
+ "AAPL,Market,1.12" },
+ { ChartType::LiquidityHeatmap, "LIQUIDITY",
+ {{"dte","Days to expiry"},{"strike","Strike price"},{"spread","Bid-ask spread"}},
+ "30,450,0.15" },
+ { ChartType::Drawdown, "DRAWDOWN",
+ {{"asset","Asset ticker"},{"window_days","Rolling window days"},{"max_dd_pct","Max drawdown % (negative)"}},
+ "SPY,252,-19.4" },
+ { ChartType::BetaSurface, "BETA",
+ {{"asset","Asset ticker"},{"horizon_days","Rolling horizon days"},{"beta","Beta to SPX"}},
+ "AAPL,60,1.18" },
+ { ChartType::ImpliedDividend, "IMPLIED DIVIDEND",
+ {{"dte","Days to expiry"},{"strike","Strike price"},{"div_yield_pct","Implied dividend yield %"}},
+ "60,450,0.58" },
+ { ChartType::InflationExpectations, "INFLATION EXPECTATIONS",
+ {{"day","Time point index"},{"horizon_years","Breakeven horizon years e.g. 1,2,5,10"},{"bei_pct","Breakeven inflation %"}},
+ "0,5,2.38" },
+ { ChartType::MonetaryPolicyPath, "RATE PATH",
+ {{"central_bank","Bank name e.g. Fed,ECB,BoJ"},{"meeting_num","Meeting number ahead (1-based)"},{"rate_pct","Implied policy rate %"}},
+ "Fed,1,5.25" },
+};
+
+static constexpr int N_SCHEMAS = (int)(sizeof(SCHEMAS) / sizeof(SCHEMAS[0]));
+
+const CsvSchema& get_csv_schema(ChartType type) {
+ for (int i = 0; i < N_SCHEMAS; i++)
+ if (SCHEMAS[i].type == type) return SCHEMAS[i];
+ return SCHEMAS[0]; // fallback
+}
+
+// ── Generic CSV parser ────────────────────────────────────────────────────────
+static std::string trim(const std::string& s) {
+ size_t a = s.find_first_not_of(" \t\r\n");
+ size_t b = s.find_last_not_of(" \t\r\n");
+ return (a == std::string::npos) ? "" : s.substr(a, b - a + 1);
+}
+
+static std::vector<std::string> split_csv_line(const std::string& line) {
+ std::vector<std::string> cols;
+ std::string cur;
+ bool in_quotes = false;
+ for (char c : line) {
+ if (c == '"') { in_quotes = !in_quotes; }
+ else if (c == ',' && !in_quotes) { cols.push_back(trim(cur)); cur.clear(); }
+ else { cur += c; }
+ }
+ cols.push_back(trim(cur));
+ return cols;
+}
+
+std::vector<std::vector<std::string>> parse_csv_file(
+ const std::string& path, std::string& out_error)
+{
+ std::ifstream f(path);
+ if (!f.is_open()) { out_error = "Cannot open file: " + path; return {}; }
+ std::vector<std::vector<std::string>> rows;
+ std::string line;
+ while (std::getline(f, line)) {
+ if (line.empty() || line[0] == '#') continue; // skip blank/comment
+ rows.push_back(split_csv_line(line));
+ }
+ if (rows.empty()) { out_error = "File is empty."; return {}; }
+ return rows;
+}
+
+// ── Helper: find column index by header name ──────────────────────────────────
+static int col_idx(const std::vector<std::string>& header, const std::string& name) {
+ for (int i = 0; i < (int)header.size(); i++)
+ if (trim(header[i]) == name) return i;
+ return -1;
+}
+
+static float to_f(const std::string& s) { return std::stof(s); }
+static int to_i(const std::string& s) { return std::stoi(s); }
+
+// ── Per-surface loaders ───────────────────────────────────────────────────────
+
+// Pivot helper: rows with (row_key_col, col_key_col, value_col)
+// builds a sorted 2D grid: unique row keys → unique col keys → float values
+// Fills string vectors and float 2D grid into output parameters.
+static bool pivot_string_string_float(
+ const std::vector<std::vector<std::string>>& rows,
+ int ri, int ci, int vi,
+ std::vector<std::string>& out_rows,
+ std::vector<std::string>& out_cols,
+ std::vector<std::vector<float>>& out_z,
+ std::string& err)
+{
+ // Collect unique keys preserving first-seen order
+ std::vector<std::string> rkeys, ckeys;
+ for (int i = 1; i < (int)rows.size(); i++) {
+ if ((int)rows[i].size() <= vi) continue;
+ const std::string& rk = rows[i][ri];
+ const std::string& ck = rows[i][ci];
+ if (std::find(rkeys.begin(), rkeys.end(), rk) == rkeys.end()) rkeys.push_back(rk);
+ if (std::find(ckeys.begin(), ckeys.end(), ck) == ckeys.end()) ckeys.push_back(ck);
+ }
+ if (rkeys.empty() || ckeys.empty()) { err = "No data rows found."; return false; }
+ out_rows = rkeys; out_cols = ckeys;
+ out_z.assign(rkeys.size(), std::vector<float>(ckeys.size(), 0.0f));
+ for (int i = 1; i < (int)rows.size(); i++) {
+ if ((int)rows[i].size() <= vi) continue;
+ int ri2 = (int)(std::find(rkeys.begin(), rkeys.end(), rows[i][ri]) - rkeys.begin());
+ int ci2 = (int)(std::find(ckeys.begin(), ckeys.end(), rows[i][ci]) - ckeys.begin());
+ try { out_z[ri2][ci2] = to_f(rows[i][vi]); } catch (...) {}
+ }
+ return true;
+}
+
+// VOL SURFACE: strike, dte, iv_pct → z[dte_idx][strike_idx]
+bool load_vol_surface(const std::vector<std::vector<std::string>>& rows,
+ VolatilitySurfaceData& out, std::string& err)
+{
+ const auto& h = rows[0];
+ int si = col_idx(h,"strike"), di = col_idx(h,"dte"), vi = col_idx(h,"iv_pct");
+ if (si<0||di<0||vi<0) { err="Missing columns: strike, dte, iv_pct"; return false; }
+
+ std::map<int,std::map<float,float>> grid; // dte -> strike -> iv
+ for (int i=1;i<(int)rows.size();i++) {
+ if ((int)rows[i].size()<=vi) continue;
+ try {
+ int dte = to_i(rows[i][di]);
+ float sk = to_f(rows[i][si]);
+ float iv = to_f(rows[i][vi]);
+ grid[dte][sk] = iv;
+ } catch (...) {}
+ }
+ if (grid.empty()) { err="No valid data rows."; return false; }
+
+ out.expirations.clear(); out.strikes.clear(); out.z.clear();
+ // Build sorted dte list
+ for (auto& [d,_] : grid) out.expirations.push_back(d);
+ // Build sorted strike list from first dte
+ for (auto& [s,_] : grid.begin()->second) out.strikes.push_back(s);
+ // Fill z
+ for (int d : out.expirations) {
+ std::vector<float> row2;
+ for (float s : out.strikes)
+ row2.push_back(grid[d].count(s) ? grid[d][s] : 0.0f);
+ out.z.push_back(row2);
+ }
+ out.underlying = "IMPORTED";
+ out.spot_price = out.strikes[out.strikes.size()/2];
+ return true;
+}
+
+// GREEKS SURFACE: strike, dte, <greek_col>
+bool load_greeks_surface(const std::vector<std::vector<std::string>>& rows,
+ GreeksSurfaceData& out, std::string& err,
+ const std::string& greek_name)
+{
+ // Column name is lowercase greek name: delta/gamma/vega/theta/local_vol_pct/skew_pct
+ std::string vcol = greek_name;
+ // normalize
+ if (vcol=="Delta") vcol="delta";
+ else if (vcol=="Gamma") vcol="gamma";
+ else if (vcol=="Vega") vcol="vega";
+ else if (vcol=="Theta") vcol="theta";
+
+ const auto& h = rows[0];
+ int si=col_idx(h,"strike"), di=col_idx(h,"dte"), vi=col_idx(h,vcol);
+ if (si<0||di<0||vi<0) { err="Missing columns: strike, dte, "+vcol; return false; }
+
+ std::map<int,std::map<float,float>> grid;
+ for (int i=1;i<(int)rows.size();i++) {
+ if ((int)rows[i].size()<=vi) continue;
+ try { grid[to_i(rows[i][di])][to_f(rows[i][si])] = to_f(rows[i][vi]); } catch (...) {}
+ }
+ if (grid.empty()) { err="No valid data rows."; return false; }
+
+ out.expirations.clear(); out.strikes.clear(); out.z.clear();
+ for (auto& [d,_]:grid) out.expirations.push_back(d);
+ for (auto& [s,_]:grid.begin()->second) out.strikes.push_back(s);
+ for (int d:out.expirations) {
+ std::vector<float> row2;
+ for (float s:out.strikes) row2.push_back(grid[d].count(s)?grid[d][s]:0.0f);
+ out.z.push_back(row2);
+ }
+ out.greek_name = greek_name;
+ out.underlying = "IMPORTED";
+ out.spot_price = out.strikes[out.strikes.size()/2];
+ return true;
+}
+
+// SKEW: dte, delta, skew_pct
+bool load_skew_surface(const std::vector<std::vector<std::string>>& rows,
+ SkewSurfaceData& out, std::string& err)
+{
+ const auto& h = rows[0];
+ int di=col_idx(h,"dte"), li=col_idx(h,"delta"), vi=col_idx(h,"skew_pct");
+ if (di<0||li<0||vi<0){err="Missing columns: dte, delta, skew_pct";return false;}
+ std::map<int,std::map<float,float>> grid;
+ for (int i=1;i<(int)rows.size();i++){
+ if ((int)rows[i].size()<=vi) continue;
+ try{grid[to_i(rows[i][di])][to_f(rows[i][li])]=to_f(rows[i][vi]);}catch(...){}
+ }
+ if (grid.empty()){err="No valid data rows.";return false;}
+ out.expirations.clear();out.deltas.clear();out.z.clear();
+ for(auto&[d,_]:grid) out.expirations.push_back(d);
+ for(auto&[d,_]:grid.begin()->second) out.deltas.push_back(d);
+ for(int d:out.expirations){
+ std::vector<float> r;
+ for(float dl:out.deltas) r.push_back(grid[d].count(dl)?grid[d][dl]:0.0f);
+ out.z.push_back(r);
+ }
+ out.underlying="IMPORTED";
+ return true;
+}
+
+// LOCAL VOL: strike, dte, local_vol_pct
+bool load_local_vol(const std::vector<std::vector<std::string>>& rows,
+ LocalVolData& out, std::string& err)
+{
+ const auto& h=rows[0];
+ int si=col_idx(h,"strike"),di=col_idx(h,"dte"),vi=col_idx(h,"local_vol_pct");
+ if(si<0||di<0||vi<0){err="Missing columns: strike, dte, local_vol_pct";return false;}
+ std::map<int,std::map<float,float>> grid;
+ for(int i=1;i<(int)rows.size();i++){
+ if((int)rows[i].size()<=vi) continue;
+ try{grid[to_i(rows[i][di])][to_f(rows[i][si])]=to_f(rows[i][vi]);}catch(...){}
+ }
+ if(grid.empty()){err="No valid data rows.";return false;}
+ out.expirations.clear();out.strikes.clear();out.z.clear();
+ for(auto&[d,_]:grid) out.expirations.push_back(d);
+ for(auto&[s,_]:grid.begin()->second) out.strikes.push_back(s);
+ for(int d:out.expirations){
+ std::vector<float> r;
+ for(float s:out.strikes) r.push_back(grid[d].count(s)?grid[d][s]:0.0f);
+ out.z.push_back(r);
+ }
+ out.underlying="IMPORTED"; out.spot_price=out.strikes[out.strikes.size()/2];
+ return true;
+}
+
+// YIELD CURVE: maturity_months, date, yield_pct → z[time][maturity]
+bool load_yield_curve(const std::vector<std::vector<std::string>>& rows,
+ YieldCurveData& out, std::string& err)
+{
+ const auto& h=rows[0];
+ int mi=col_idx(h,"maturity_months"),di=col_idx(h,"date"),vi=col_idx(h,"yield_pct");
+ if(mi<0||di<0||vi<0){err="Missing columns: maturity_months, date, yield_pct";return false;}
+ // date strings as row keys, maturities as col keys
+ std::vector<std::string> dates; std::vector<int> mats;
+ std::map<std::string,std::map<int,float>> grid;
+ for(int i=1;i<(int)rows.size();i++){
+ if((int)rows[i].size()<=vi) continue;
+ try{
+ std::string dt=rows[i][di]; int m=to_i(rows[i][mi]); float y=to_f(rows[i][vi]);
+ if(std::find(dates.begin(),dates.end(),dt)==dates.end()) dates.push_back(dt);
+ if(std::find(mats.begin(),mats.end(),m)==mats.end()) mats.push_back(m);
+ grid[dt][m]=y;
+ }catch(...){}
+ }
+ if(grid.empty()){err="No valid data rows.";return false;}
+ std::sort(mats.begin(),mats.end());
+ out.maturities=mats; out.z.clear();
+ for(auto& dt:dates){
+ std::vector<float> r;
+ for(int m:mats) r.push_back(grid[dt].count(m)?grid[dt][m]:0.0f);
+ out.z.push_back(r);
+ }
+ return true;
+}
+
+// SWAPTION VOL: option_expiry_months, swap_tenor_months, vol_bps
+bool load_swaption_vol(const std::vector<std::vector<std::string>>& rows,
+ SwaptionVolData& out, std::string& err)
+{
+ const auto& h=rows[0];
+ int ei=col_idx(h,"option_expiry_months"),ti=col_idx(h,"swap_tenor_months"),vi=col_idx(h,"vol_bps");
+ if(ei<0||ti<0||vi<0){err="Missing: option_expiry_months, swap_tenor_months, vol_bps";return false;}
+ std::map<int,std::map<int,float>> grid;
+ std::vector<int> exps,tenors;
+ for(int i=1;i<(int)rows.size();i++){
+ if((int)rows[i].size()<=vi) continue;
+ try{
+ int e=to_i(rows[i][ei]),t=to_i(rows[i][ti]); float v=to_f(rows[i][vi]);
+ if(std::find(exps.begin(),exps.end(),e)==exps.end()) exps.push_back(e);
+ if(std::find(tenors.begin(),tenors.end(),t)==tenors.end()) tenors.push_back(t);
+ grid[e][t]=v;
+ }catch(...){}
+ }
+ std::sort(exps.begin(),exps.end()); std::sort(tenors.begin(),tenors.end());
+ out.option_expiries=exps; out.swap_tenors=tenors; out.z.clear();
+ for(int e:exps){std::vector<float> r; for(int t:tenors) r.push_back(grid[e].count(t)?grid[e][t]:0.0f); out.z.push_back(r);}
+ return true;
+}
+
+// CAP/FLOOR VOL: maturity_months, strike_pct, vol_bps
+bool load_capfloor_vol(const std::vector<std::vector<std::string>>& rows,
+ CapFloorVolData& out, std::string& err)
+{
+ const auto& h=rows[0];
+ int mi=col_idx(h,"maturity_months"),si=col_idx(h,"strike_pct"),vi=col_idx(h,"vol_bps");
+ if(mi<0||si<0||vi<0){err="Missing: maturity_months, strike_pct, vol_bps";return false;}
+ std::map<int,std::map<float,float>> grid; std::vector<int> mats; std::vector<float> strikes;
+ for(int i=1;i<(int)rows.size();i++){
+ if((int)rows[i].size()<=vi) continue;
+ try{
+ int m=to_i(rows[i][mi]); float s=to_f(rows[i][si]),v=to_f(rows[i][vi]);
+ if(std::find(mats.begin(),mats.end(),m)==mats.end()) mats.push_back(m);
+ if(std::find(strikes.begin(),strikes.end(),s)==strikes.end()) strikes.push_back(s);
+ grid[m][s]=v;
+ }catch(...){}
+ }
+ std::sort(mats.begin(),mats.end()); std::sort(strikes.begin(),strikes.end());
+ out.maturities=mats; out.strikes=strikes; out.z.clear();
+ for(int m:mats){std::vector<float> r; for(float s:strikes) r.push_back(grid[m].count(s)?grid[m][s]:0.0f); out.z.push_back(r);}
+ return true;
+}
+
+// BOND SPREAD: rating, maturity_months, spread_bps
+bool load_bond_spread(const std::vector<std::vector<std::string>>& rows,
+ BondSpreadData& out, std::string& err)
+{
+ const auto& h=rows[0];
+ int ri=col_idx(h,"rating"),mi=col_idx(h,"maturity_months"),vi=col_idx(h,"spread_bps");
+ if(ri<0||mi<0||vi<0){err="Missing: rating, maturity_months, spread_bps";return false;}
+ std::vector<std::string> ratings; std::vector<int> mats;
+ std::map<std::string,std::map<int,float>> grid;
+ for(int i=1;i<(int)rows.size();i++){
+ if((int)rows[i].size()<=vi) continue;
+ try{
+ std::string rg=rows[i][ri]; int m=to_i(rows[i][mi]); float v=to_f(rows[i][vi]);
+ if(std::find(ratings.begin(),ratings.end(),rg)==ratings.end()) ratings.push_back(rg);
+ if(std::find(mats.begin(),mats.end(),m)==mats.end()) mats.push_back(m);
+ grid[rg][m]=v;
+ }catch(...){}
+ }
+ std::sort(mats.begin(),mats.end());
+ out.ratings=ratings; out.maturities=mats; out.z.clear();
+ for(auto& rg:ratings){std::vector<float> r; for(int m:mats) r.push_back(grid[rg].count(m)?grid[rg][m]:0.0f); out.z.push_back(r);}
+ return true;
+}
+
+// OIS BASIS: day, tenor_months, basis_bps
+bool load_ois_basis(const std::vector<std::vector<std::string>>& rows,
+ OISBasisData& out, std::string& err)
+{
+ const auto& h=rows[0];
+ int di=col_idx(h,"day"),ti=col_idx(h,"tenor_months"),vi=col_idx(h,"basis_bps");
+ if(di<0||ti<0||vi<0){err="Missing: day, tenor_months, basis_bps";return false;}
+ std::map<int,std::map<int,float>> grid; std::vector<int> days,tenors;
+ for(int i=1;i<(int)rows.size();i++){
+ if((int)rows[i].size()<=vi) continue;
+ try{
+ int d=to_i(rows[i][di]),t=to_i(rows[i][ti]); float v=to_f(rows[i][vi]);
+ if(std::find(days.begin(),days.end(),d)==days.end()) days.push_back(d);
+ if(std::find(tenors.begin(),tenors.end(),t)==tenors.end()) tenors.push_back(t);
+ grid[d][t]=v;
+ }catch(...){}
+ }
+ std::sort(days.begin(),days.end()); std::sort(tenors.begin(),tenors.end());
+ out.time_points=days; out.tenors=tenors; out.z.clear();
+ for(int d:days){std::vector<float> r; for(int t:tenors) r.push_back(grid[d].count(t)?grid[d][t]:0.0f); out.z.push_back(r);}
+ return true;
+}
+
+// REAL YIELD: day, maturity_months, yield_pct
+bool load_real_yield(const std::vector<std::vector<std::string>>& rows,
+ RealYieldData& out, std::string& err)
+{
+ const auto& h=rows[0];
+ int di=col_idx(h,"day"),mi=col_idx(h,"maturity_months"),vi=col_idx(h,"yield_pct");
+ if(di<0||mi<0||vi<0){err="Missing: day, maturity_months, yield_pct";return false;}
+ std::map<int,std::map<int,float>> grid; std::vector<int> days,mats;
+ for(int i=1;i<(int)rows.size();i++){
+ if((int)rows[i].size()<=vi) continue;
+ try{
+ int d=to_i(rows[i][di]),m=to_i(rows[i][mi]); float v=to_f(rows[i][vi]);
+ if(std::find(days.begin(),days.end(),d)==days.end()) days.push_back(d);
+ if(std::find(mats.begin(),mats.end(),m)==mats.end()) mats.push_back(m);
+ grid[d][m]=v;
+ }catch(...){}
+ }
+ std::sort(days.begin(),days.end()); std::sort(mats.begin(),mats.end());
+ out.time_points=days; out.maturities=mats; out.z.clear();
+ for(int d:days){std::vector<float> r; for(int m:mats) r.push_back(grid[d].count(m)?grid[d][m]:0.0f); out.z.push_back(r);}
+ return true;
+}
+
+// FORWARD RATE: start_months, fwd_period_months, rate_pct
+bool load_forward_rate(const std::vector<std::vector<std::string>>& rows,
+ ForwardRateData& out, std::string& err)
+{
+ const auto& h=rows[0];
+ int si=col_idx(h,"start_months"),fi=col_idx(h,"fwd_period_months"),vi=col_idx(h,"rate_pct");
+ if(si<0||fi<0||vi<0){err="Missing: start_months, fwd_period_months, rate_pct";return false;}
+ std::map<int,std::map<int,float>> grid; std::vector<int> starts,fwds;
+ for(int i=1;i<(int)rows.size();i++){
+ if((int)rows[i].size()<=vi) continue;
+ try{
+ int s=to_i(rows[i][si]),f=to_i(rows[i][fi]); float v=to_f(rows[i][vi]);
+ if(std::find(starts.begin(),starts.end(),s)==starts.end()) starts.push_back(s);
+ if(std::find(fwds.begin(),fwds.end(),f)==fwds.end()) fwds.push_back(f);
+ grid[s][f]=v;
+ }catch(...){}
+ }
+ std::sort(starts.begin(),starts.end()); std::sort(fwds.begin(),fwds.end());
+ out.start_tenors=starts; out.forward_periods=fwds; out.z.clear();
+ for(int s:starts){std::vector<float> r; for(int f:fwds) r.push_back(grid[s].count(f)?grid[s][f]:0.0f); out.z.push_back(r);}
+ return true;
+}
+
+// FX VOL: tenor_days, delta, vol_pct
+bool load_fx_vol(const std::vector<std::vector<std::string>>& rows,
+ FXVolData& out, std::string& err)
+{
+ const auto& h=rows[0];
+ int ti=col_idx(h,"tenor_days"),di=col_idx(h,"delta"),vi=col_idx(h,"vol_pct");
+ if(ti<0||di<0||vi<0){err="Missing: tenor_days, delta, vol_pct";return false;}
+ std::map<int,std::map<float,float>> grid; std::vector<int> tenors; std::vector<float> deltas;
+ for(int i=1;i<(int)rows.size();i++){
+ if((int)rows[i].size()<=vi) continue;
+ try{
+ int t=to_i(rows[i][ti]); float d=to_f(rows[i][di]),v=to_f(rows[i][vi]);
+ if(std::find(tenors.begin(),tenors.end(),t)==tenors.end()) tenors.push_back(t);
+ if(std::find(deltas.begin(),deltas.end(),d)==deltas.end()) deltas.push_back(d);
+ grid[t][d]=v;
+ }catch(...){}
+ }
+ std::sort(tenors.begin(),tenors.end()); std::sort(deltas.begin(),deltas.end());
+ out.tenors=tenors; out.deltas=deltas; out.pair="IMPORTED"; out.z.clear();
+ for(int t:tenors){std::vector<float> r; for(float d:deltas) r.push_back(grid[t].count(d)?grid[t][d]:0.0f); out.z.push_back(r);}
+ return true;
+}
+
+// FX FORWARD: pair, tenor_days, pips
+bool load_fx_forward(const std::vector<std::vector<std::string>>& rows,
+ FXForwardPointsData& out, std::string& err)
+{
+ const auto& h=rows[0];
+ int pi=col_idx(h,"pair"),ti=col_idx(h,"tenor_days"),vi=col_idx(h,"pips");
+ if(pi<0||ti<0||vi<0){err="Missing: pair, tenor_days, pips";return false;}
+ std::vector<std::string> pairs; std::vector<int> tenors;
+ std::map<std::string,std::map<int,float>> grid;
+ for(int i=1;i<(int)rows.size();i++){
+ if((int)rows[i].size()<=vi) continue;
+ try{
+ std::string p=rows[i][pi]; int t=to_i(rows[i][ti]); float v=to_f(rows[i][vi]);
+ if(std::find(pairs.begin(),pairs.end(),p)==pairs.end()) pairs.push_back(p);
+ if(std::find(tenors.begin(),tenors.end(),t)==tenors.end()) tenors.push_back(t);
+ grid[p][t]=v;
+ }catch(...){}
+ }
+ std::sort(tenors.begin(),tenors.end());
+ out.pairs=pairs; out.tenors=tenors; out.z.clear();
+ for(auto& p:pairs){std::vector<float> r; for(int t:tenors) r.push_back(grid[p].count(t)?grid[p][t]:0.0f); out.z.push_back(r);}
+ return true;
+}
+
+// XCCY BASIS: pair, tenor_months, basis_bps
+bool load_xccy_basis(const std::vector<std::vector<std::string>>& rows,
+ CrossCurrencyBasisData& out, std::string& err)
+{
+ const auto& h=rows[0];
+ int pi=col_idx(h,"pair"),ti=col_idx(h,"tenor_months"),vi=col_idx(h,"basis_bps");
+ if(pi<0||ti<0||vi<0){err="Missing: pair, tenor_months, basis_bps";return false;}
+ std::vector<std::string> pairs; std::vector<int> tenors;
+ std::map<std::string,std::map<int,float>> grid;
+ for(int i=1;i<(int)rows.size();i++){
+ if((int)rows[i].size()<=vi) continue;
+ try{
+ std::string p=rows[i][pi]; int t=to_i(rows[i][ti]); float v=to_f(rows[i][vi]);
+ if(std::find(pairs.begin(),pairs.end(),p)==pairs.end()) pairs.push_back(p);
+ if(std::find(tenors.begin(),tenors.end(),t)==tenors.end()) tenors.push_back(t);
+ grid[p][t]=v;
+ }catch(...){}
+ }
+ std::sort(tenors.begin(),tenors.end());
+ out.pairs=pairs; out.tenors=tenors; out.z.clear();
+ for(auto& p:pairs){std::vector<float> r; for(int t:tenors) r.push_back(grid[p].count(t)?grid[p][t]:0.0f); out.z.push_back(r);}
+ return true;
+}
+
+// CDS SPREAD: entity, tenor_months, spread_bps
+bool load_cds_spread(const std::vector<std::vector<std::string>>& rows,
+ CDSSpreadData& out, std::string& err)
+{
+ const auto& h=rows[0];
+ int ei=col_idx(h,"entity"),ti=col_idx(h,"tenor_months"),vi=col_idx(h,"spread_bps");
+ if(ei<0||ti<0||vi<0){err="Missing: entity, tenor_months, spread_bps";return false;}
+ std::vector<std::string> entities; std::vector<int> tenors;
+ std::map<std::string,std::map<int,float>> grid;
+ for(int i=1;i<(int)rows.size();i++){
+ if((int)rows[i].size()<=vi) continue;
+ try{
+ std::string e=rows[i][ei]; int t=to_i(rows[i][ti]); float v=to_f(rows[i][vi]);
+ if(std::find(entities.begin(),entities.end(),e)==entities.end()) entities.push_back(e);
+ if(std::find(tenors.begin(),tenors.end(),t)==tenors.end()) tenors.push_back(t);
+ grid[e][t]=v;
+ }catch(...){}
+ }
+ std::sort(tenors.begin(),tenors.end());
+ out.entities=entities; out.tenors=tenors; out.z.clear();
+ for(auto& e:entities){std::vector<float> r; for(int t:tenors) r.push_back(grid[e].count(t)?grid[e][t]:0.0f); out.z.push_back(r);}
+ return true;
+}
+
+// CREDIT TRANSITION: from_rating, to_rating, probability_pct
+bool load_credit_trans(const std::vector<std::vector<std::string>>& rows,
+ CreditTransitionData& out, std::string& err)
+{
+ const auto& h=rows[0];
+ int fi=col_idx(h,"from_rating"),ti=col_idx(h,"to_rating"),vi=col_idx(h,"probability_pct");
+ if(fi<0||ti<0||vi<0){err="Missing: from_rating, to_rating, probability_pct";return false;}
+ std::vector<std::string> froms,tos;
+ std::map<std::string,std::map<std::string,float>> grid;
+ for(int i=1;i<(int)rows.size();i++){
+ if((int)rows[i].size()<=vi) continue;
+ try{
+ std::string f=rows[i][fi],t=rows[i][ti]; float v=to_f(rows[i][vi]);
+ if(std::find(froms.begin(),froms.end(),f)==froms.end()) froms.push_back(f);
+ if(std::find(tos.begin(),tos.end(),t)==tos.end()) tos.push_back(t);
+ grid[f][t]=v;
+ }catch(...){}
+ }
+ out.ratings=froms; out.to_ratings=tos; out.z.clear();
+ for(auto& f:froms){std::vector<float> r; for(auto& t:tos) r.push_back(grid[f].count(t)?grid[f][t]:0.0f); out.z.push_back(r);}
+ return true;
+}
+
+// RECOVERY RATE: sector, seniority, recovery_pct
+bool load_recovery_rate(const std::vector<std::vector<std::string>>& rows,
+ RecoveryRateData& out, std::string& err)
+{
+ const auto& h=rows[0];
+ int si=col_idx(h,"sector"),ni=col_idx(h,"seniority"),vi=col_idx(h,"recovery_pct");
+ if(si<0||ni<0||vi<0){err="Missing: sector, seniority, recovery_pct";return false;}
+ std::vector<std::string> sects,sens;
+ std::map<std::string,std::map<std::string,float>> grid;
+ for(int i=1;i<(int)rows.size();i++){
+ if((int)rows[i].size()<=vi) continue;
+ try{
+ std::string s=rows[i][si],n=rows[i][ni]; float v=to_f(rows[i][vi]);
+ if(std::find(sects.begin(),sects.end(),s)==sects.end()) sects.push_back(s);
+ if(std::find(sens.begin(),sens.end(),n)==sens.end()) sens.push_back(n);
+ grid[s][n]=v;
+ }catch(...){}
+ }
+ out.sectors=sects; out.seniorities=sens; out.z.clear();
+ for(auto& s:sects){std::vector<float> r; for(auto& n:sens) r.push_back(grid[s].count(n)?grid[s][n]:0.0f); out.z.push_back(r);}
+ return true;
+}
+
+// COMMODITY FORWARD: commodity, contract_months, price
+bool load_cmdty_forward(const std::vector<std::vector<std::string>>& rows,
+ CommodityForwardData& out, std::string& err)
+{
+ const auto& h=rows[0];
+ int ci=col_idx(h,"commodity"),mi=col_idx(h,"contract_months"),vi=col_idx(h,"price");
+ if(ci<0||mi<0||vi<0){err="Missing: commodity, contract_months, price";return false;}
+ std::vector<std::string> comms; std::vector<int> months;
+ std::map<std::string,std::map<int,float>> grid;
+ for(int i=1;i<(int)rows.size();i++){
+ if((int)rows[i].size()<=vi) continue;
+ try{
+ std::string c=rows[i][ci]; int m=to_i(rows[i][mi]); float v=to_f(rows[i][vi]);
+ if(std::find(comms.begin(),comms.end(),c)==comms.end()) comms.push_back(c);
+ if(std::find(months.begin(),months.end(),m)==months.end()) months.push_back(m);
+ grid[c][m]=v;
+ }catch(...){}
+ }
+ std::sort(months.begin(),months.end());
+ out.commodities=comms; out.contract_months=months; out.z.clear();
+ for(auto& c:comms){std::vector<float> r; for(int m:months) r.push_back(grid[c].count(m)?grid[c][m]:0.0f); out.z.push_back(r);}
+ return true;
+}
+
+// COMMODITY VOL: dte, strike_pct, vol_pct
+bool load_cmdty_vol(const std::vector<std::vector<std::string>>& rows,
+ CommodityVolData& out, std::string& err)
+{
+ const auto& h=rows[0];
+ int di=col_idx(h,"dte"),si=col_idx(h,"strike_pct"),vi=col_idx(h,"vol_pct");
+ if(di<0||si<0||vi<0){err="Missing: dte, strike_pct, vol_pct";return false;}
+ std::map<int,std::map<float,float>> grid; std::vector<int> dtes; std::vector<float> strikes;
+ for(int i=1;i<(int)rows.size();i++){
+ if((int)rows[i].size()<=vi) continue;
+ try{
+ int d=to_i(rows[i][di]); float s=to_f(rows[i][si]),v=to_f(rows[i][vi]);
+ if(std::find(dtes.begin(),dtes.end(),d)==dtes.end()) dtes.push_back(d);
+ if(std::find(strikes.begin(),strikes.end(),s)==strikes.end()) strikes.push_back(s);
+ grid[d][s]=v;
+ }catch(...){}
+ }
+ std::sort(dtes.begin(),dtes.end()); std::sort(strikes.begin(),strikes.end());
+ out.expirations=dtes; out.strikes=strikes; out.commodity="IMPORTED"; out.z.clear();
+ for(int d:dtes){std::vector<float> r; for(float s:strikes) r.push_back(grid[d].count(s)?grid[d][s]:0.0f); out.z.push_back(r);}
+ return true;
+}
+
+// CRACK SPREAD: spread_type, contract_months, spread_usd
+bool load_crack_spread(const std::vector<std::vector<std::string>>& rows,
+ CrackSpreadData& out, std::string& err)
+{
+ const auto& h=rows[0];
+ int ti=col_idx(h,"spread_type"),mi=col_idx(h,"contract_months"),vi=col_idx(h,"spread_usd");
+ if(ti<0||mi<0||vi<0){err="Missing: spread_type, contract_months, spread_usd";return false;}
+ std::vector<std::string> types; std::vector<int> months;
+ std::map<std::string,std::map<int,float>> grid;
+ for(int i=1;i<(int)rows.size();i++){
+ if((int)rows[i].size()<=vi) continue;
+ try{
+ std::string t=rows[i][ti]; int m=to_i(rows[i][mi]); float v=to_f(rows[i][vi]);
+ if(std::find(types.begin(),types.end(),t)==types.end()) types.push_back(t);
+ if(std::find(months.begin(),months.end(),m)==months.end()) months.push_back(m);
+ grid[t][m]=v;
+ }catch(...){}
+ }
+ std::sort(months.begin(),months.end());
+ out.spread_types=types; out.contract_months=months; out.z.clear();
+ for(auto& t:types){std::vector<float> r; for(int m:months) r.push_back(grid[t].count(m)?grid[t][m]:0.0f); out.z.push_back(r);}
+ return true;
+}
+
+// CONTANGO: commodity, contract_months, pct_from_spot
+bool load_contango(const std::vector<std::vector<std::string>>& rows,
+ ContangoData& out, std::string& err)
+{
+ const auto& h=rows[0];
+ int ci=col_idx(h,"commodity"),mi=col_idx(h,"contract_months"),vi=col_idx(h,"pct_from_spot");
+ if(ci<0||mi<0||vi<0){err="Missing: commodity, contract_months, pct_from_spot";return false;}
+ std::vector<std::string> comms; std::vector<int> months;
+ std::map<std::string,std::map<int,float>> grid;
+ for(int i=1;i<(int)rows.size();i++){
+ if((int)rows[i].size()<=vi) continue;
+ try{
+ std::string c=rows[i][ci]; int m=to_i(rows[i][mi]); float v=to_f(rows[i][vi]);
+ if(std::find(comms.begin(),comms.end(),c)==comms.end()) comms.push_back(c);
+ if(std::find(months.begin(),months.end(),m)==months.end()) months.push_back(m);
+ grid[c][m]=v;
+ }catch(...){}
+ }
+ std::sort(months.begin(),months.end());
+ out.commodities=comms; out.contract_months=months; out.z.clear();
+ for(auto& c:comms){std::vector<float> r; for(int m:months) r.push_back(grid[c].count(m)?grid[c][m]:0.0f); out.z.push_back(r);}
+ return true;
+}
+
+// CORRELATION: asset_i, asset_j, correlation
+bool load_correlation(const std::vector<std::vector<std::string>>& rows,
+ CorrelationMatrixData& out, std::string& err)
+{
+ const auto& h=rows[0];
+ int ai=col_idx(h,"asset_i"),aj=col_idx(h,"asset_j"),vi=col_idx(h,"correlation");
+ if(ai<0||aj<0||vi<0){err="Missing: asset_i, asset_j, correlation";return false;}
+ std::vector<std::string> assets;
+ std::map<std::string,std::map<std::string,float>> grid;
+ for(int i=1;i<(int)rows.size();i++){
+ if((int)rows[i].size()<=vi) continue;
+ try{
+ std::string a=rows[i][ai],b=rows[i][aj]; float v=to_f(rows[i][vi]);
+ if(std::find(assets.begin(),assets.end(),a)==assets.end()) assets.push_back(a);
+ if(std::find(assets.begin(),assets.end(),b)==assets.end()) assets.push_back(b);
+ grid[a][b]=v; grid[b][a]=v;
+ }catch(...){}
+ }
+ int n=(int)assets.size();
+ out.assets=assets; out.z.clear();
+ std::vector<float> flat(n*n,0.0f);
+ for(int i=0;i<n;i++) for(int j=0;j<n;j++){
+ if(i==j) flat[i*n+j]=1.0f;
+ else if(grid.count(assets[i])&&grid[assets[i]].count(assets[j]))
+ flat[i*n+j]=grid[assets[i]][assets[j]];
+ }
+ out.z.push_back(flat);
+ out.window=0;
+ return true;
+}
+
+// PCA: asset, factor, loading
+bool load_pca(const std::vector<std::vector<std::string>>& rows,
+ PCAData& out, std::string& err)
+{
+ const auto& h=rows[0];
+ int ai=col_idx(h,"asset"),fi=col_idx(h,"factor"),vi=col_idx(h,"loading");
+ if(ai<0||fi<0||vi<0){err="Missing: asset, factor, loading";return false;}
+ std::vector<std::string> assets,factors;
+ std::map<std::string,std::map<std::string,float>> grid;
+ for(int i=1;i<(int)rows.size();i++){
+ if((int)rows[i].size()<=vi) continue;
+ try{
+ std::string a=rows[i][ai],f=rows[i][fi]; float v=to_f(rows[i][vi]);
+ if(std::find(assets.begin(),assets.end(),a)==assets.end()) assets.push_back(a);
+ if(std::find(factors.begin(),factors.end(),f)==factors.end()) factors.push_back(f);
+ grid[a][f]=v;
+ }catch(...){}
+ }
+ out.assets=assets; out.factors=factors; out.z.clear();
+ for(auto& a:assets){std::vector<float> r; for(auto& f:factors) r.push_back(grid[a].count(f)?grid[a][f]:0.0f); out.z.push_back(r);}
+ out.variance_explained.assign(factors.size(),1.0f/(float)factors.size());
+ return true;
+}
+
+// VAR: confidence_pct, horizon_days, var_pct
+bool load_var(const std::vector<std::vector<std::string>>& rows,
+ VaRData& out, std::string& err)
+{
+ const auto& h=rows[0];
+ int ci=col_idx(h,"confidence_pct"),hi=col_idx(h,"horizon_days"),vi=col_idx(h,"var_pct");
+ if(ci<0||hi<0||vi<0){err="Missing: confidence_pct, horizon_days, var_pct";return false;}
+ std::vector<float> confs; std::vector<int> horizons;
+ std::map<float,std::map<int,float>> grid;
+ for(int i=1;i<(int)rows.size();i++){
+ if((int)rows[i].size()<=vi) continue;
+ try{
+ float c=to_f(rows[i][ci]); int h2=to_i(rows[i][hi]); float v=to_f(rows[i][vi]);
+ if(std::find(confs.begin(),confs.end(),c)==confs.end()) confs.push_back(c);
+ if(std::find(horizons.begin(),horizons.end(),h2)==horizons.end()) horizons.push_back(h2);
+ grid[c][h2]=v;
+ }catch(...){}
+ }
+ std::sort(confs.begin(),confs.end()); std::sort(horizons.begin(),horizons.end());
+ out.confidence_levels=confs; out.horizons=horizons; out.z.clear();
+ for(float c:confs){std::vector<float> r; for(int h2:horizons) r.push_back(grid[c].count(h2)?grid[c][h2]:0.0f); out.z.push_back(r);}
+ return true;
+}
+
+// STRESS TEST: scenario, portfolio, pnl_pct
+bool load_stress_test(const std::vector<std::vector<std::string>>& rows,
+ StressTestData& out, std::string& err)
+{
+ const auto& h=rows[0];
+ int si=col_idx(h,"scenario"),pi=col_idx(h,"portfolio"),vi=col_idx(h,"pnl_pct");
+ if(si<0||pi<0||vi<0){err="Missing: scenario, portfolio, pnl_pct";return false;}
+ std::vector<std::string> scens,ports;
+ std::map<std::string,std::map<std::string,float>> grid;
+ for(int i=1;i<(int)rows.size();i++){
+ if((int)rows[i].size()<=vi) continue;
+ try{
+ std::string s=rows[i][si],p=rows[i][pi]; float v=to_f(rows[i][vi]);
+ if(std::find(scens.begin(),scens.end(),s)==scens.end()) scens.push_back(s);
+ if(std::find(ports.begin(),ports.end(),p)==ports.end()) ports.push_back(p);
+ grid[s][p]=v;
+ }catch(...){}
+ }
+ out.scenarios=scens; out.portfolios=ports; out.z.clear();
+ for(auto& s:scens){std::vector<float> r; for(auto& p:ports) r.push_back(grid[s].count(p)?grid[s][p]:0.0f); out.z.push_back(r);}
+ return true;
+}
+
+// FACTOR EXPOSURE: asset, factor, exposure
+bool load_factor_exposure(const std::vector<std::vector<std::string>>& rows,
+ FactorExposureData& out, std::string& err)
+{
+ const auto& h=rows[0];
+ int ai=col_idx(h,"asset"),fi=col_idx(h,"factor"),vi=col_idx(h,"exposure");
+ if(ai<0||fi<0||vi<0){err="Missing: asset, factor, exposure";return false;}
+ std::vector<std::string> assets,factors;
+ std::map<std::string,std::map<std::string,float>> grid;
+ for(int i=1;i<(int)rows.size();i++){
+ if((int)rows[i].size()<=vi) continue;
+ try{
+ std::string a=rows[i][ai],f=rows[i][fi]; float v=to_f(rows[i][vi]);
+ if(std::find(assets.begin(),assets.end(),a)==assets.end()) assets.push_back(a);
+ if(std::find(factors.begin(),factors.end(),f)==factors.end()) factors.push_back(f);
+ grid[a][f]=v;
+ }catch(...){}
+ }
+ out.assets=assets; out.factors=factors; out.z.clear();
+ for(auto& a:assets){std::vector<float> r; for(auto& f:factors) r.push_back(grid[a].count(f)?grid[a][f]:0.0f); out.z.push_back(r);}
+ return true;
+}
+
+// LIQUIDITY: dte, strike, spread
+bool load_liquidity(const std::vector<std::vector<std::string>>& rows,
+ LiquidityData& out, std::string& err)
+{
+ const auto& h=rows[0];
+ int di=col_idx(h,"dte"),si=col_idx(h,"strike"),vi=col_idx(h,"spread");
+ if(di<0||si<0||vi<0){err="Missing: dte, strike, spread";return false;}
+ std::map<int,std::map<float,float>> grid; std::vector<int> dtes; std::vector<float> strikes;
+ for(int i=1;i<(int)rows.size();i++){
+ if((int)rows[i].size()<=vi) continue;
+ try{
+ int d=to_i(rows[i][di]); float s=to_f(rows[i][si]),v=to_f(rows[i][vi]);
+ if(std::find(dtes.begin(),dtes.end(),d)==dtes.end()) dtes.push_back(d);
+ if(std::find(strikes.begin(),strikes.end(),s)==strikes.end()) strikes.push_back(s);
+ grid[d][s]=v;
+ }catch(...){}
+ }
+ std::sort(dtes.begin(),dtes.end()); std::sort(strikes.begin(),strikes.end());
+ out.expirations=dtes; out.strikes=strikes; out.underlying="IMPORTED"; out.z.clear();
+ for(int d:dtes){std::vector<float> r; for(float s:strikes) r.push_back(grid[d].count(s)?grid[d][s]:0.0f); out.z.push_back(r);}
+ return true;
+}
+
+// DRAWDOWN: asset, window_days, max_dd_pct
+bool load_drawdown(const std::vector<std::vector<std::string>>& rows,
+ DrawdownData& out, std::string& err)
+{
+ const auto& h=rows[0];
+ int ai=col_idx(h,"asset"),wi=col_idx(h,"window_days"),vi=col_idx(h,"max_dd_pct");
+ if(ai<0||wi<0||vi<0){err="Missing: asset, window_days, max_dd_pct";return false;}
+ std::vector<std::string> assets; std::vector<int> windows;
+ std::map<std::string,std::map<int,float>> grid;
+ for(int i=1;i<(int)rows.size();i++){
+ if((int)rows[i].size()<=vi) continue;
+ try{
+ std::string a=rows[i][ai]; int w=to_i(rows[i][wi]); float v=to_f(rows[i][vi]);
+ if(std::find(assets.begin(),assets.end(),a)==assets.end()) assets.push_back(a);
+ if(std::find(windows.begin(),windows.end(),w)==windows.end()) windows.push_back(w);
+ grid[a][w]=v;
+ }catch(...){}
+ }
+ std::sort(windows.begin(),windows.end());
+ out.assets=assets; out.windows=windows; out.z.clear();
+ for(auto& a:assets){std::vector<float> r; for(int w:windows) r.push_back(grid[a].count(w)?grid[a][w]:0.0f); out.z.push_back(r);}
+ return true;
+}
+
+// BETA: asset, horizon_days, beta
+bool load_beta(const std::vector<std::vector<std::string>>& rows,
+ BetaData& out, std::string& err)
+{
+ const auto& h=rows[0];
+ int ai=col_idx(h,"asset"),hi=col_idx(h,"horizon_days"),vi=col_idx(h,"beta");
+ if(ai<0||hi<0||vi<0){err="Missing: asset, horizon_days, beta";return false;}
+ std::vector<std::string> assets; std::vector<int> horizons;
+ std::map<std::string,std::map<int,float>> grid;
+ for(int i=1;i<(int)rows.size();i++){
+ if((int)rows[i].size()<=vi) continue;
+ try{
+ std::string a=rows[i][ai]; int h2=to_i(rows[i][hi]); float v=to_f(rows[i][vi]);
+ if(std::find(assets.begin(),assets.end(),a)==assets.end()) assets.push_back(a);
+ if(std::find(horizons.begin(),horizons.end(),h2)==horizons.end()) horizons.push_back(h2);
+ grid[a][h2]=v;
+ }catch(...){}
+ }
+ std::sort(horizons.begin(),horizons.end());
+ out.assets=assets; out.horizons=horizons; out.z.clear();
+ for(auto& a:assets){std::vector<float> r; for(int h2:horizons) r.push_back(grid[a].count(h2)?grid[a][h2]:0.0f); out.z.push_back(r);}
+ return true;
+}
+
+// IMPLIED DIVIDEND: dte, strike, div_yield_pct
+bool load_implied_div(const std::vector<std::vector<std::string>>& rows,
+ ImpliedDividendData& out, std::string& err)
+{
+ const auto& h=rows[0];
+ int di=col_idx(h,"dte"),si=col_idx(h,"strike"),vi=col_idx(h,"div_yield_pct");
+ if(di<0||si<0||vi<0){err="Missing: dte, strike, div_yield_pct";return false;}
+ std::map<int,std::map<float,float>> grid; std::vector<int> dtes; std::vector<float> strikes;
+ for(int i=1;i<(int)rows.size();i++){
+ if((int)rows[i].size()<=vi) continue;
+ try{
+ int d=to_i(rows[i][di]); float s=to_f(rows[i][si]),v=to_f(rows[i][vi]);
+ if(std::find(dtes.begin(),dtes.end(),d)==dtes.end()) dtes.push_back(d);
+ if(std::find(strikes.begin(),strikes.end(),s)==strikes.end()) strikes.push_back(s);
+ grid[d][s]=v;
+ }catch(...){}
+ }
+ std::sort(dtes.begin(),dtes.end()); std::sort(strikes.begin(),strikes.end());
+ out.expirations=dtes; out.strikes=strikes; out.underlying="IMPORTED"; out.z.clear();
+ for(int d:dtes){std::vector<float> r; for(float s:strikes) r.push_back(grid[d].count(s)?grid[d][s]:0.0f); out.z.push_back(r);}
+ return true;
+}
+
+// INFLATION: day, horizon_years, bei_pct
+bool load_inflation(const std::vector<std::vector<std::string>>& rows,
+ InflationExpData& out, std::string& err)
+{
+ const auto& h=rows[0];
+ int di=col_idx(h,"day"),hi=col_idx(h,"horizon_years"),vi=col_idx(h,"bei_pct");
+ if(di<0||hi<0||vi<0){err="Missing: day, horizon_years, bei_pct";return false;}
+ std::map<int,std::map<int,float>> grid; std::vector<int> days,horizons;
+ for(int i=1;i<(int)rows.size();i++){
+ if((int)rows[i].size()<=vi) continue;
+ try{
+ int d=to_i(rows[i][di]),h2=to_i(rows[i][hi]); float v=to_f(rows[i][vi]);
+ if(std::find(days.begin(),days.end(),d)==days.end()) days.push_back(d);
+ if(std::find(horizons.begin(),horizons.end(),h2)==horizons.end()) horizons.push_back(h2);
+ grid[d][h2]=v;
+ }catch(...){}
+ }
+ std::sort(days.begin(),days.end()); std::sort(horizons.begin(),horizons.end());
+ out.time_points=days; out.horizons=horizons; out.z.clear();
+ for(int d:days){std::vector<float> r; for(int h2:horizons) r.push_back(grid[d].count(h2)?grid[d][h2]:0.0f); out.z.push_back(r);}
+ return true;
+}
+
+// MONETARY POLICY: central_bank, meeting_num, rate_pct
+bool load_monetary(const std::vector<std::vector<std::string>>& rows,
+ MonetaryPolicyData& out, std::string& err)
+{
+ const auto& h=rows[0];
+ int bi=col_idx(h,"central_bank"),mi=col_idx(h,"meeting_num"),vi=col_idx(h,"rate_pct");
+ if(bi<0||mi<0||vi<0){err="Missing: central_bank, meeting_num, rate_pct";return false;}
+ std::vector<std::string> banks; std::vector<int> meetings;
+ std::map<std::string,std::map<int,float>> grid;
+ for(int i=1;i<(int)rows.size();i++){
+ if((int)rows[i].size()<=vi) continue;
+ try{
+ std::string b=rows[i][bi]; int m=to_i(rows[i][mi]); float v=to_f(rows[i][vi]);
+ if(std::find(banks.begin(),banks.end(),b)==banks.end()) banks.push_back(b);
+ if(std::find(meetings.begin(),meetings.end(),m)==meetings.end()) meetings.push_back(m);
+ grid[b][m]=v;
+ }catch(...){}
+ }
+ std::sort(meetings.begin(),meetings.end());
+ out.central_banks=banks; out.meetings_ahead=meetings; out.z.clear();
+ for(auto& b:banks){std::vector<float> r; for(int m:meetings) r.push_back(grid[b].count(m)?grid[b][m]:0.0f); out.z.push_back(r);}
+ return true;
+}
+
+} // namespace fincept::surface
+```
+
+- [ ] **Step 3: Verify it compiles (added to CMake in Task 4 first)**
+
+---
+
+## Task 2: Import Dialog UI (`import_dialog.cpp`)
+
+**Files:**
+- Create: `src/screens/surface_analytics/import_dialog.cpp`
+- Modify: `src/screens/surface_analytics/surface_screen.h` (add state + declaration)
+
+- [ ] **Step 1: Add state members + declaration to `surface_screen.h`**
+
+Add inside `class SurfaceScreen { private:` after `bool show_table_ = false;`:
+
+```cpp
+// CSV import state
+bool show_import_dialog_ = false;
+char import_path_buf_[512] = {};
+std::string import_error_;
+bool import_success_ = false;
+
+void render_csv_import_dialog();
+bool dispatch_csv_load(const std::string& path, std::string& err);
+```
+
+- [ ] **Step 2: Create `import_dialog.cpp`**
+
+```cpp
+#include "surface_screen.h"
+#include "csv_importer.h"
+#include "ui/theme.h"
+#include <imgui.h>
+#include <cstring>
+#include <cstdio>
+
+// Must be listed in SKIP_UNITY_BUILD_INCLUSION in CMakeLists.txt
+
+namespace fincept::surface {
+
+using namespace theme::colors;
+
+// ── dispatch_csv_load ─────────────────────────────────────────────────────────
+// Parses file then calls the correct per-surface loader based on active_chart_.
+bool SurfaceScreen::dispatch_csv_load(const std::string& path, std::string& err) {
+ auto rows = parse_csv_file(path, err);
+ if (rows.empty()) return false;
+
+ switch (active_chart_) {
+ case ChartType::Volatility:
+ return load_vol_surface(rows, vol_data_, err);
+ case ChartType::DeltaSurface:
+ return load_greeks_surface(rows, delta_data_, err, "Delta");
+ case ChartType::GammaSurface:
+ return load_greeks_surface(rows, gamma_data_, err, "Gamma");
+ case ChartType::VegaSurface:
+ return load_greeks_surface(rows, vega_data_, err, "Vega");
+ case ChartType::ThetaSurface:
+ return load_greeks_surface(rows, theta_data_, err, "Theta");
+ case ChartType::SkewSurface:
+ return load_skew_surface(rows, skew_data_, err);
+ case ChartType::LocalVolSurface:
+ return load_local_vol(rows, local_vol_data_, err);
+ case ChartType::YieldCurve:
+ return load_yield_curve(rows, yield_data_, err);
+ case ChartType::SwaptionVol:
+ return load_swaption_vol(rows, swaption_data_, err);
+ case ChartType::CapFloorVol:
+ return load_capfloor_vol(rows, capfloor_data_, err);
+ case ChartType::BondSpread:
+ return load_bond_spread(rows, bond_spread_data_, err);
+ case ChartType::OISBasis:
+ return load_ois_basis(rows, ois_data_, err);
+ case ChartType::RealYield:
+ return load_real_yield(rows, real_yield_data_, err);
+ case ChartType::ForwardRate:
+ return load_forward_rate(rows, fwd_rate_data_, err);
+ case ChartType::FXVol:
+ return load_fx_vol(rows, fx_vol_data_, err);
+ case ChartType::FXForwardPoints:
+ return load_fx_forward(rows, fx_fwd_data_, err);
+ case ChartType::CrossCurrencyBasis:
+ return load_xccy_basis(rows, xccy_data_, err);
+ case ChartType::CDSSpread:
+ return load_cds_spread(rows, cds_data_, err);
+ case ChartType::CreditTransition:
+ return load_credit_trans(rows, credit_trans_data_, err);
+ case ChartType::RecoveryRate:
+ return load_recovery_rate(rows, recovery_data_, err);
+ case ChartType::CommodityForward:
+ return load_cmdty_forward(rows, cmdty_fwd_data_, err);
+ case ChartType::CommodityVol:
+ return load_cmdty_vol(rows, cmdty_vol_data_, err);
+ case ChartType::CrackSpread:
+ return load_crack_spread(rows, crack_data_, err);
+ case ChartType::ContangoBackwardation:
+ return load_contango(rows, contango_data_, err);
+ case ChartType::Correlation:
+ return load_correlation(rows, corr_data_, err);
+ case ChartType::PCA:
+ return load_pca(rows, pca_data_, err);
+ case ChartType::VaR:
+ return load_var(rows, var_data_, err);
+ case ChartType::StressTestPnL:
+ return load_stress_test(rows, stress_data_, err);
+ case ChartType::FactorExposure:
+ return load_factor_exposure(rows, factor_data_, err);
+ case ChartType::LiquidityHeatmap:
+ return load_liquidity(rows, liquidity_data_, err);
+ case ChartType::Drawdown:
+ return load_drawdown(rows, drawdown_data_, err);
+ case ChartType::BetaSurface:
+ return load_beta(rows, beta_data_, err);
+ case ChartType::ImpliedDividend:
+ return load_implied_div(rows, impl_div_data_, err);
+ case ChartType::InflationExpectations:
+ return load_inflation(rows, inflation_data_, err);
+ case ChartType::MonetaryPolicyPath:
+ return load_monetary(rows, monetary_data_, err);
+ }
+ err = "Unknown surface type.";
+ return false;
+}
+
+// ── render_csv_import_dialog ──────────────────────────────────────────────────
+void SurfaceScreen::render_csv_import_dialog() {
+ if (show_import_dialog_) {
+ ImGui::OpenPopup("##sa_import_modal");
+ show_import_dialog_ = false;
+ import_error_.clear();
+ import_success_ = false;
+ }
+
+ ImGui::SetNextWindowSize(ImVec2(580, 420), ImGuiCond_Always);
+ ImGui::SetNextWindowPos(ImGui::GetMainViewport()->GetCenter(), ImGuiCond_Always, ImVec2(0.5f, 0.5f));
+
+ ImGui::PushStyleColor(ImGuiCol_PopupBg, BG_PANEL);
+ ImGui::PushStyleColor(ImGuiCol_ModalWindowDimBg, ImVec4(0,0,0,0.6f));
+
+ if (!ImGui::BeginPopupModal("##sa_import_modal", nullptr,
+ ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_NoResize | ImGuiWindowFlags_NoMove)) {
+ ImGui::PopStyleColor(2);
+ return;
+ }
+
+ const auto categories = get_surface_categories();
+ const ImVec4& cat_col = CAT_COLORS[active_category_];
+ const CsvSchema& schema = get_csv_schema(active_chart_);
+ ImDrawList* dl = ImGui::GetWindowDrawList();
+
+ // ── Header bar ────────────────────────────────────────────────────────────
+ {
+ ImVec2 p0 = ImGui::GetCursorScreenPos();
+ dl->AddRectFilled(p0, ImVec2(p0.x + 580, p0.y + 38),
+ ImGui::GetColorU32(ImVec4(cat_col.x*0.15f, cat_col.y*0.15f, cat_col.z*0.15f, 1.0f)));
+ dl->AddLine(ImVec2(p0.x, p0.y + 38), ImVec2(p0.x + 580, p0.y + 38),
+ ImGui::GetColorU32(ImVec4(cat_col.x, cat_col.y, cat_col.z, 0.5f)));
+ ImGui::SetCursorPosX(12); ImGui::SetCursorPosY(ImGui::GetCursorPosY() + 8);
+ ImGui::TextColored(cat_col, "IMPORT CSV");
+ ImGui::SameLine(0, 10);
+ ImGui::TextColored(TEXT_SECONDARY, "%s / %s", categories[active_category_].name, schema.surface_name);
+ ImGui::Dummy(ImVec2(0, 8));
+ }
+
+ ImGui::SetCursorPosX(12);
+
+ // ── Schema reference table ────────────────────────────────────────────────
+ ImGui::TextColored(TEXT_DIM, "REQUIRED COLUMNS");
+ ImGui::Spacing();
+
+ if (ImGui::BeginTable("##schema_tbl", 2,
+ ImGuiTableFlags_Borders | ImGuiTableFlags_RowBg | ImGuiTableFlags_SizingStretchProp,
+ ImVec2(556, 0))) {
+ ImGui::TableSetupColumn("COLUMN NAME", ImGuiTableColumnFlags_WidthFixed, 160);
+ ImGui::TableSetupColumn("DESCRIPTION", ImGuiTableColumnFlags_WidthStretch);
+ ImGui::TableHeadersRow();
+
+ for (const auto& col : schema.columns) {
+ ImGui::TableNextRow();
+ ImGui::TableSetColumnIndex(0);
+ ImGui::TextColored(cat_col, "%s", col.name);
+ ImGui::TableSetColumnIndex(1);
+ ImGui::TextColored(TEXT_SECONDARY, "%s", col.description);
+ }
+ ImGui::EndTable();
+ }
+
+ ImGui::Spacing();
+
+ // ── Example row ──────────────────────────────────────────────────────────
+ ImGui::TextColored(TEXT_DIM, "EXAMPLE ROW");
+ ImGui::SameLine(0, 8);
+ // Build header line from schema
+ std::string header_line;
+ for (int i = 0; i < (int)schema.columns.size(); i++) {
+ if (i > 0) header_line += ", ";
+ header_line += schema.columns[i].name;
+ }
+ ImGui::TextColored(TEXT_DISABLED, "%s", header_line.c_str());
+ ImGui::SetCursorPosX(12);
+ ImGui::TextColored(TEXT_DIM, " DATA");
+ ImGui::SameLine(0, 8);
+ ImGui::TextColored(MARKET_GREEN, "%s", schema.example_row);
+
+ ImGui::Spacing();
+ ImGui::Separator();
+ ImGui::Spacing();
+
+ // ── Path input ───────────────────────────────────────────────────────────
+ ImGui::TextColored(TEXT_DIM, "CSV FILE PATH");
+ ImGui::SetNextItemWidth(556);
+ ImGui::PushStyleColor(ImGuiCol_FrameBg, BG_INPUT);
+ bool enter = ImGui::InputText("##import_path", import_path_buf_, sizeof(import_path_buf_),
+ ImGuiInputTextFlags_EnterReturnsTrue);
+ ImGui::PopStyleColor();
+
+ ImGui::Spacing();
+
+ // ── Status message ────────────────────────────────────────────────────────
+ if (import_success_) {
+ ImGui::TextColored(MARKET_GREEN, " Data loaded successfully.");
+ } else if (!import_error_.empty()) {
+ ImGui::TextColored(MARKET_RED, " Error: %s", import_error_.c_str());
+ } else {
+ ImGui::TextColored(TEXT_DISABLED, " First row must be the header. Blank lines and #comments are ignored.");
+ }
+
+ ImGui::Spacing();
+
+ // ── Action buttons ────────────────────────────────────────────────────────
+ bool do_load = enter;
+
+ ImGui::SetCursorPosX(12);
+ ImGui::PushStyleColor(ImGuiCol_Button, ImVec4(cat_col.x*0.3f, cat_col.y*0.3f, cat_col.z*0.3f, 1.0f));
+ ImGui::PushStyleColor(ImGuiCol_ButtonHovered, ImVec4(cat_col.x*0.5f, cat_col.y*0.5f, cat_col.z*0.5f, 1.0f));
+ ImGui::PushStyleColor(ImGuiCol_Text, cat_col);
+ if (ImGui::Button("LOAD", ImVec2(100, 28))) do_load = true;
+ ImGui::PopStyleColor(3);
+
+ ImGui::SameLine(0, 8);
+ ImGui::PushStyleColor(ImGuiCol_Button, BG_WIDGET);
+ ImGui::PushStyleColor(ImGuiCol_ButtonHovered, BG_HOVER);
+ ImGui::PushStyleColor(ImGuiCol_Text, TEXT_SECONDARY);
+ if (ImGui::Button("CANCEL", ImVec2(80, 28))) {
+ import_error_.clear();
+ import_success_ = false;
+ ImGui::CloseCurrentPopup();
+ }
+ ImGui::PopStyleColor(3);
+
+ // ── Load action ───────────────────────────────────────────────────────────
+ if (do_load && std::strlen(import_path_buf_) > 0) {
+ import_error_.clear();
+ import_success_ = false;
+ std::string path(import_path_buf_);
+ if (dispatch_csv_load(path, import_error_)) {
+ import_success_ = true;
+ data_loaded_ = true; // mark loaded so chart renders imported data
+ }
+ }
+
+ // Auto-close on success after showing the message for one frame
+ if (import_success_) {
+ ImGui::SameLine(0, 16);
+ ImGui::TextColored(TEXT_DIM, "(close to view)");
+ if (ImGui::IsKeyPressed(ImGuiKey_Escape) || ImGui::IsKeyPressed(ImGuiKey_Enter))
+ ImGui::CloseCurrentPopup();
+ }
+
+ ImGui::EndPopup();
+ ImGui::PopStyleColor(2);
+}
+
+} // namespace fincept::surface
+```
+
+- [ ] **Step 3: Add `render_csv_import_dialog()` call at end of `SurfaceScreen::render()` in `surface_screen.cpp`**
+
+In `render()`, just before `frame.end()`:
+```cpp
+render_csv_import_dialog();
+```
+
+---
+
+## Task 3: IMPORT Button in Control Bar
+
+**Files:**
+- Modify: `src/screens/surface_analytics/surface_screen.cpp` — `render_control_bar()`
+
+- [ ] **Step 1: Add IMPORT button in the right side of Row 1 (category bar), alongside REFRESH**
+
+In `render_control_bar()`, in the right-side button group after the REFRESH `InvisibleButton` block, add:
+
+```cpp
+ImGui::SameLine(0, 4);
+{
+ float iw = ImGui::CalcTextSize("IMPORT").x + 14.0f;
+ ImVec2 ic = ImGui::GetCursorScreenPos();
+ ImVec2 imn = ic, imx = ImVec2(ic.x + iw, ic.y + 20.0f);
+ bool ihov = ImGui::IsMouseHoveringRect(imn, imx);
+ dl->AddRectFilled(imn, imx,
+ ImGui::GetColorU32(ihov
+ ? ImVec4(cat_accent.x*0.35f, cat_accent.y*0.35f, cat_accent.z*0.35f, 1.0f)
+ : BG_WIDGET));
+ dl->AddRect(imn, imx,
+ ImGui::GetColorU32(ImVec4(cat_accent.x, cat_accent.y, cat_accent.z, 0.4f)));
+ dl->AddText(ImVec2(imn.x + 7, imn.y + (20.0f - ImGui::GetTextLineHeight()) * 0.5f),
+ ImGui::GetColorU32(cat_accent), "IMPORT");
+ ImGui::InvisibleButton("##import", ImVec2(iw, 20.0f));
+ if (ImGui::IsItemClicked()) show_import_dialog_ = true;
+}
+```
+
+---
+
+## Task 4: CMakeLists.txt
+
+**Files:**
+- Modify: `CMakeLists.txt`
+
+- [ ] **Step 1: Add new source files to SOURCES list**
+
+In the `set(SOURCES ...)` block, alongside the other surface analytics files, add:
+```cmake
+src/screens/surface_analytics/csv_importer.cpp
+src/screens/surface_analytics/import_dialog.cpp
+```
+
+- [ ] **Step 2: Add to SKIP_UNITY_BUILD_INCLUSION**
+
+In the `set_source_files_properties(... SKIP_UNITY_BUILD_INCLUSION TRUE)` block, add:
+```cmake
+${CMAKE_CURRENT_SOURCE_DIR}/src/screens/surface_analytics/csv_importer.cpp
+${CMAKE_CURRENT_SOURCE_DIR}/src/screens/surface_analytics/import_dialog.cpp
+```
+
+- [ ] **Step 3: Build and verify 0 errors**
+
+```bash
+cd fincept-cpp
+cmake --build build --config Release 2>&1 | tail -5
+```
+Expected: `FinceptTerminal.exe` with 0 errors.
+
+---
+
+## Task 5: Smoke Test
+
+- [ ] Run the terminal, navigate to Surface Analytics
+- [ ] Click IMPORT button — verify modal opens showing correct columns for active surface
+- [ ] Switch surface, re-open IMPORT — verify columns update for new surface
+- [ ] Enter a non-existent path — verify error message shown
+- [ ] Create a minimal CSV for VOL SURFACE (`strike,dte,iv_pct` header + a few rows) and import — verify 3D surface updates
+- [ ] Verify REFRESH reloads demo data (overwriting imported data)
+- [ ] Verify TABLE view works after import
+
+---
+
+## Notes
+
+- `csv_importer.cpp` and `import_dialog.cpp` **must** be in `SKIP_UNITY_BUILD_INCLUSION` — they use `<fstream>`, `<map>`, and `using namespace theme::colors` which conflict in unity builds
+- Imported data replaces demo data in the same struct — REFRESH always restores demo data
+- The modal is per-surface: switching active surface changes which loader fires and which schema is shown
+- No new dependencies required — uses only `<fstream>`, `<sstream>`, `<map>`, `<algorithm>` from the standard library
diff --git a/fincept-cpp/CMakeLists.txt b/fincept-cpp/CMakeLists.txt
index 586adf094..9132eeda9 100644
--- a/fincept-cpp/CMakeLists.txt
+++ b/fincept-cpp/CMakeLists.txt
@@ -230,6 +230,7 @@ set(SOURCES
src/trading/paper_trading.cpp
src/trading/order_matcher.cpp
src/trading/exchange_service.cpp
+ src/trading/equity_stream.cpp
src/trading/broker_registry.cpp
src/trading/brokers/fyers_broker.cpp
src/trading/brokers/zerodha_broker.cpp
diff --git a/fincept-cpp/build-ninja/CMakeCache.txt b/fincept-cpp/build-ninja/CMakeCache.txt
new file mode 100644
index 000000000..4d6fcd765
--- /dev/null
+++ b/fincept-cpp/build-ninja/CMakeCache.txt
@@ -0,0 +1,110 @@
+# This is the CMakeCache file.
+# For build in directory: c:/windowsdisk/finceptTerminal/fincept-cpp/build-ninja
+# It was generated by CMake: C:/Program Files/CMake/bin/cmake.exe
+# You can edit this file to change values found and used by cmake.
+# If you do not want to change any of the values, simply exit the editor.
+# If you do want to change a value, simply edit, save, and exit the editor.
+# The syntax for the file is as follows:
+# KEY:TYPE=VALUE
+# KEY is the name of a variable in the cache.
+# TYPE is a hint to GUIs for the type of VALUE, DO NOT EDIT TYPE!.
+# VALUE is the current value for the KEY.
+
+########################
+# EXTERNAL cache entries
+########################
+
+//No help, variable specified on the command line.
+CMAKE_BUILD_TYPE:UNINITIALIZED=RelWithDebInfo
+
+//No help, variable specified on the command line.
+CMAKE_EXPORT_COMPILE_COMMANDS:UNINITIALIZED=ON
+
+//Value Computed by CMake.
+CMAKE_FIND_PACKAGE_REDIRECTS_DIR:STATIC=C:/windowsdisk/finceptTerminal/fincept-cpp/build-ninja/CMakeFiles/pkgRedirects
+
+//Value Computed by CMake
+CMAKE_PROJECT_COMPAT_VERSION:STATIC=
+
+//Value Computed by CMake
+CMAKE_PROJECT_DESCRIPTION:STATIC=
+
+//Value Computed by CMake
+CMAKE_PROJECT_HOMEPAGE_URL:STATIC=
+
+//Value Computed by CMake
+CMAKE_PROJECT_NAME:STATIC=FinceptTerminal
+
+//Value Computed by CMake
+CMAKE_PROJECT_SPDX_LICENSE:STATIC=
+
+//Value Computed by CMake
+CMAKE_PROJECT_VERSION:STATIC=4.0.0
+
+//Value Computed by CMake
+CMAKE_PROJECT_VERSION_MAJOR:STATIC=4
+
+//Value Computed by CMake
+CMAKE_PROJECT_VERSION_MINOR:STATIC=0
+
+//Value Computed by CMake
+CMAKE_PROJECT_VERSION_PATCH:STATIC=0
+
+//Value Computed by CMake
+CMAKE_PROJECT_VERSION_TWEAK:STATIC=
+
+//No help, variable specified on the command line.
+CMAKE_TOOLCHAIN_FILE:UNINITIALIZED=C:/Program Files/Git/scripts/buildsystems/vcpkg.cmake
+
+//Value Computed by CMake
+FinceptTerminal_BINARY_DIR:STATIC=C:/windowsdisk/finceptTerminal/fincept-cpp/build-ninja
+
+//Value Computed by CMake
+FinceptTerminal_IS_TOP_LEVEL:STATIC=ON
+
+//Value Computed by CMake
+FinceptTerminal_SOURCE_DIR:STATIC=C:/windowsdisk/finceptTerminal/fincept-cpp
+
+
+########################
+# INTERNAL cache entries
+########################
+
+//This is the directory where this CMakeCache.txt was created
+CMAKE_CACHEFILE_DIR:INTERNAL=c:/windowsdisk/finceptTerminal/fincept-cpp/build-ninja
+//Major version of cmake used to create the current loaded cache
+CMAKE_CACHE_MAJOR_VERSION:INTERNAL=4
+//Minor version of cmake used to create the current loaded cache
+CMAKE_CACHE_MINOR_VERSION:INTERNAL=2
+//Patch version of cmake used to create the current loaded cache
+CMAKE_CACHE_PATCH_VERSION:INTERNAL=3
+//Path to CMake executable.
+CMAKE_COMMAND:INTERNAL=C:/Program Files/CMake/bin/cmake.exe
+//Path to cpack program executable.
+CMAKE_CPACK_COMMAND:INTERNAL=C:/Program Files/CMake/bin/cpack.exe
+//Path to ctest program executable.
+CMAKE_CTEST_COMMAND:INTERNAL=C:/Program Files/CMake/bin/ctest.exe
+//Path to cache edit program executable.
+CMAKE_EDIT_COMMAND:INTERNAL=C:/Program Files/CMake/bin/cmake-gui.exe
+//Name of external makefile project generator.
+CMAKE_EXTRA_GENERATOR:INTERNAL=
+//Name of generator.
+CMAKE_GENERATOR:INTERNAL=Ninja
+//Generator instance identifier.
+CMAKE_GENERATOR_INSTANCE:INTERNAL=
+//Name of generator platform.
+CMAKE_GENERATOR_PLATFORM:INTERNAL=
+//Name of generator toolset.
+CMAKE_GENERATOR_TOOLSET:INTERNAL=
+//Source directory with the top level CMakeLists.txt file for this
+// project
+CMAKE_HOME_DIRECTORY:INTERNAL=C:/windowsdisk/finceptTerminal/fincept-cpp
+//Name of CMakeLists files to read
+CMAKE_LIST_FILE_NAME:INTERNAL=CMakeLists.txt
+//number of local generators
+CMAKE_NUMBER_OF_MAKEFILES:INTERNAL=1
+//Platform information initialized
+CMAKE_PLATFORM_INFO_INITIALIZED:INTERNAL=1
+//Path to CMake installation.
+CMAKE_ROOT:INTERNAL=C:/Program Files/CMake/share/cmake-4.2
+
diff --git a/fincept-cpp/build-ninja/CMakeFiles/cmake.check_cache b/fincept-cpp/build-ninja/CMakeFiles/cmake.check_cache
new file mode 100644
index 000000000..3dccd7317
--- /dev/null
+++ b/fincept-cpp/build-ninja/CMakeFiles/cmake.check_cache
@@ -0,0 +1 @@
+# This file is generated by cmake for dependency checking of the CMakeCache.txt file
diff --git a/fincept-cpp/imgui.ini b/fincept-cpp/imgui.ini
new file mode 100644
index 000000000..2e4db0839
--- /dev/null
+++ b/fincept-cpp/imgui.ini
@@ -0,0 +1,10 @@
+[Window][Debug##Default]
+Pos=60,60
+Size=400,400
+Collapsed=0
+
+[Window][##main]
+Pos=0,0
+Size=900,600
+Collapsed=0
+
diff --git a/fincept-cpp/scripts/exchange/broker_ws_bridge.py b/fincept-cpp/scripts/exchange/broker_ws_bridge.py
new file mode 100644
index 000000000..209dfe41b
--- /dev/null
+++ b/fincept-cpp/scripts/exchange/broker_ws_bridge.py
@@ -0,0 +1,437 @@
+"""
+broker_ws_bridge.py — Equity broker WebSocket streaming bridge.
+
+Spawned as a subprocess by ExchangeService (same pattern as ws_stream.py).
+Imports the openalgo broker streaming adapters directly, captures their
+ZMQ output, and re-emits normalized JSON lines to stdout.
+
+Usage:
+ python broker_ws_bridge.py <broker> <api_key> <access_token> \
+ [user_id] [--symbols SYM:EXCH:TOKEN ...]
+
+Where TOKEN is the broker-specific instrument token (int).
+If no TOKEN is known, pass 0 and we fall back to a symbol-only subscribe.
+
+Each output line is a JSON object:
+ {"type":"tick", "symbol":"RELIANCE", "exchange":"NSE", "ltp":2450.5,
+ "open":2400.0, "high":2460.0, "low":2390.0, "close":2440.0,
+ "volume":1234567, "bid":2450.0, "ask":2451.0, "timestamp":1712345678000}
+ {"type":"status", "connected":true, "broker":"zerodha", "message":"..."}
+ {"type":"error", "broker":"zerodha", "message":"..."}
+"""
+
+import json
+import os
+import sys
+import threading
+import time
+import argparse
+
+OPENALGO_PATH = r"C:\projects\openalgo"
+
+
+def emit(obj):
+ """Write JSON line to stdout, flush immediately."""
+ try:
+ print(json.dumps(obj, default=str), flush=True)
+ except Exception:
+ pass
+
+
+def emit_status(broker, connected, message=""):
+ emit({"type": "status", "connected": connected, "broker": broker, "message": message})
+
+
+def emit_error(broker, message):
+ emit({"type": "error", "broker": broker, "message": message})
+
+
+def emit_tick(symbol, exchange, data: dict):
+ """Normalize market data dict → unified tick format."""
+ ltp = (data.get("ltp") or data.get("last_price") or
+ data.get("last_traded_price") or data.get("LastTradedPrice") or 0)
+ # Some brokers (AngelOne) send prices in paise
+ if isinstance(ltp, (int, float)) and ltp > 1_000_000:
+ ltp /= 100.0
+
+ ohlc = data.get("ohlc") or {}
+ emit({
+ "type": "tick",
+ "symbol": symbol,
+ "exchange": exchange,
+ "ltp": float(ltp),
+ "open": float(data.get("open") or ohlc.get("open") or 0),
+ "high": float(data.get("high") or ohlc.get("high") or 0),
+ "low": float(data.get("low") or ohlc.get("low") or 0),
+ "close": float(data.get("close") or ohlc.get("close") or 0),
+ "volume": float(data.get("volume") or data.get("Volume") or 0),
+ "bid": float(data.get("bid") or data.get("best_bid") or 0),
+ "ask": float(data.get("ask") or data.get("best_ask") or 0),
+ "timestamp": int(data.get("timestamp") or data.get("ltt") or
+ int(time.time() * 1000)),
+ })
+
+
+# ─────────────────────────────────────────────────────────────────────────────
+# ZMQ subscriber thread — listens to the adapter's PUB socket and re-emits
+# ─────────────────────────────────────────────────────────────────────────────
+
+def zmq_listener(zmq_port: int, broker: str, sym_map: dict, stop_event: threading.Event):
+ """
+ Subscribe to the adapter's ZMQ PUB socket and re-emit ticks as JSON lines.
+ sym_map: {topic_prefix: (symbol, exchange)} e.g. {"NSE_RELIANCE": ("RELIANCE","NSE")}
+ """
+ try:
+ import zmq
+ except ImportError:
+ emit_error(broker, "pyzmq not installed — cannot receive market data")
+ return
+
+ ctx = zmq.Context()
+ sock = ctx.socket(zmq.SUB)
+ sock.connect(f"tcp://127.0.0.1:{zmq_port}")
+ sock.setsockopt(zmq.SUBSCRIBE, b"") # subscribe to all topics
+ sock.setsockopt(zmq.RCVTIMEO, 500) # 500 ms poll timeout
+
+ emit_status(broker, True, f"ZMQ subscriber connected on port {zmq_port}")
+
+ while not stop_event.is_set():
+ try:
+ parts = sock.recv_multipart()
+ if len(parts) < 2:
+ continue
+ topic_bytes, data_bytes = parts[0], parts[1]
+ topic = topic_bytes.decode("utf-8", errors="ignore")
+ data = json.loads(data_bytes.decode("utf-8", errors="ignore"))
+
+ # Resolve symbol/exchange from topic or data payload
+ symbol = data.get("symbol") or data.get("trading_symbol") or ""
+ exchange = data.get("exchange") or ""
+
+ # Fallback: match topic prefix against sym_map
+ if not symbol:
+ for prefix, (sym, exch) in sym_map.items():
+ if topic.startswith(prefix):
+ symbol, exchange = sym, exch
+ break
+
+ if symbol:
+ emit_tick(symbol, exchange, data)
+
+ except Exception as e:
+ err = str(e)
+ if "Resource temporarily unavailable" in err or "EAGAIN" in err:
+ continue # timeout — normal, keep looping
+ if not stop_event.is_set():
+ emit_error(broker, f"ZMQ receive error: {err}")
+ break
+
+ sock.close()
+ ctx.term()
+
+
+# ─────────────────────────────────────────────────────────────────────────────
+# Token resolution — fetch broker-specific instrument tokens via REST
+# ─────────────────────────────────────────────────────────────────────────────
+
+def _resolve_tokens(broker: str, api_key: str, access_token: str, user_id: str,
+ symbols: list) -> dict:
+ """
+ Resolve (symbol, exchange) → (token, brexchange) via broker REST API.
+ Returns dict of {(symbol, exchange): (token, brexchange)}.
+ Only implemented for brokers that expose a symbol search/lookup endpoint.
+ """
+ result = {}
+ try:
+ if broker == "angelone":
+ result = _resolve_tokens_angelone(api_key, access_token, user_id, symbols)
+ # Other brokers can be added here
+ except Exception as e:
+ emit_error(broker, f"Token resolution failed: {e}")
+ return result
+
+
+def _resolve_tokens_angelone(api_key: str, access_token: str, user_id: str,
+ symbols: list) -> dict:
+ """
+ AngelOne: download the instrument master CSV and look up tokens by symbol+exchange.
+ Instrument list URL: https://margincalculator.angelbroking.com/OpenAPI_File/files/OpenAPIScripMaster.json
+ This is a public endpoint — no auth needed.
+ """
+ try:
+ import urllib.request
+ url = "https://margincalculator.angelbroking.com/OpenAPI_File/files/OpenAPIScripMaster.json"
+ emit_status("angelone", False, "Downloading instrument master for token resolution...")
+ with urllib.request.urlopen(url, timeout=15) as resp:
+ instruments = json.loads(resp.read().decode("utf-8"))
+ except Exception as e:
+ emit_error("angelone", f"Could not download instrument master: {e}")
+ return {}
+
+ # Build lookup: (symbol, extype) → token
+ # extype in master: "NSE" = NSE EQ, "BSE" = BSE EQ, "NFO" = F&O, etc.
+ lookup = {}
+ for inst in instruments:
+ sym = inst.get("symbol") or inst.get("name") or ""
+ exch = inst.get("exch_seg") or inst.get("exchange") or ""
+ token = inst.get("token") or inst.get("symboltoken") or ""
+ if sym and exch and token:
+ lookup[(sym.upper(), exch.upper())] = (str(token), exch.upper())
+
+ result = {}
+ for sym, exch in symbols:
+ key = (sym.upper(), exch.upper())
+ if key in lookup:
+ result[(sym, exch)] = lookup[key]
+ else:
+ emit_error("angelone", f"Token not found in master for {sym}/{exch}")
+ return result
+
+
+# ─────────────────────────────────────────────────────────────────────────────
+# Per-broker adapter launchers
+# ─────────────────────────────────────────────────────────────────────────────
+
+def run_broker(broker: str, api_key: str, access_token: str, user_id: str,
+ symbols: list, stop_event: threading.Event, feed_token: str = ""):
+ """
+ Import the openalgo adapter for `broker`, initialize it with credentials,
+ subscribe to symbols, then start a ZMQ listener that re-emits ticks.
+
+ symbols: list of (symbol, exchange, token_str)
+ """
+ sys.path.insert(0, OPENALGO_PATH)
+
+ # Build token map for SymbolMapper — use provided tokens where available.
+ # For symbols with token "0", try to resolve via broker REST API.
+ _BREXCH_MAP = {
+ "NSE": "NSE", "BSE": "BSE", "NFO": "NFO",
+ "MCX": "MCX", "CDS": "CDS", "BFO": "BFO",
+ }
+ symbol_token_map = {}
+ for sym, exch, token in symbols:
+ if token and token != "0":
+ brexch = _BREXCH_MAP.get(exch.upper(), exch)
+ symbol_token_map[(sym, exch)] = (token, brexch)
+
+ # Resolve missing tokens via broker API where supported
+ unresolved = [(sym, exch) for sym, exch, tok in symbols if not tok or tok == "0"]
+ if unresolved:
+ resolved = _resolve_tokens(broker, api_key, access_token, user_id, unresolved)
+ for (sym, exch), (token, brexch) in resolved.items():
+ symbol_token_map[(sym, exch)] = (token, brexch)
+ emit_status(broker, False, f"Resolved token {sym}/{exch} → {token}")
+
+ # Patch database deps — we pass auth_data directly so DB is never called
+ _patch_db_modules(symbol_token_map=symbol_token_map)
+
+ adapter = None
+ zmq_thread = None
+
+ try:
+ adapter = _create_adapter(broker)
+ if adapter is None:
+ emit_error(broker, f"No adapter found for broker '{broker}'")
+ return
+
+ auth_data = {
+ "auth_token": access_token,
+ "access_token": access_token,
+ "api_key": api_key,
+ "feed_token": feed_token if feed_token else access_token,
+ "client_id": user_id,
+ }
+
+ # Initialize
+ result = adapter.initialize(broker, user_id, auth_data=auth_data)
+ emit_status(broker, False, f"Adapter initialized: {result}")
+
+ # Connect
+ conn = adapter.connect()
+ emit_status(broker, True, f"Connected: {conn}")
+
+ # Build sym_map for ZMQ listener
+ sym_map = {}
+ for sym, exch, token in symbols:
+ sym_map[f"{exch}_{sym}"] = (sym, exch)
+ sym_map[f"{exch}_{sym}_LTP"] = (sym, exch)
+ sym_map[f"{exch}_{sym}_QUOTE"] = (sym, exch)
+
+ # Start ZMQ listener thread
+ zmq_port = getattr(adapter, "zmq_port", None)
+ if zmq_port:
+ zmq_thread = threading.Thread(
+ target=zmq_listener,
+ args=(zmq_port, broker, sym_map, stop_event),
+ daemon=True
+ )
+ zmq_thread.start()
+ else:
+ emit_error(broker, "Adapter has no zmq_port — cannot receive data")
+
+ # Subscribe to all requested symbols
+ for sym, exch, token in symbols:
+ try:
+ result = adapter.subscribe(sym, exch, mode=2) # mode 2 = Quote
+ emit_status(broker, True, f"Subscribed {sym}/{exch}: {result}")
+ except Exception as e:
+ emit_error(broker, f"Subscribe failed for {sym}/{exch}: {e}")
+
+ # Keep alive — heartbeat every 30s until stop
+ while not stop_event.is_set():
+ stop_event.wait(30)
+ if not stop_event.is_set():
+ connected = getattr(adapter, "connected", False)
+ emit_status(broker, bool(connected), "heartbeat")
+
+ except Exception as e:
+ emit_error(broker, f"Fatal: {e}")
+ import traceback
+ traceback.print_exc(file=sys.stderr)
+ finally:
+ if adapter:
+ try:
+ adapter.disconnect()
+ except Exception:
+ pass
+ emit_status(broker, False, "disconnected")
+
+
+def _patch_db_modules(symbol_token_map: dict = None):
+ """
+ Stub out openalgo's database modules so adapters that call
+ get_auth_token() / get_feed_token() don't crash when no DB exists.
+ We always pass auth_data directly so the DB path is never taken.
+
+ symbol_token_map: optional dict of (symbol, exchange) -> (token, brexchange)
+ used to answer get_token / get_brexchange calls from SymbolMapper.
+ """
+ import types
+
+ # Build token lookup from the provided map
+ _token_map = symbol_token_map or {}
+
+ def _get_token(symbol, exchange, *a, **kw):
+ return _token_map.get((symbol, exchange), (None, None))[0]
+
+ def _get_brexchange(symbol, exchange, *a, **kw):
+ return _token_map.get((symbol, exchange), (None, None))[1]
+
+ def _make_stub(name):
+ m = types.ModuleType(name)
+ m.get_auth_token = lambda *a, **kw: None
+ m.get_feed_token = lambda *a, **kw: None
+ m.get_token = _get_token
+ m.get_brexchange = _get_brexchange
+ m.get_br_symbol = lambda *a, **kw: None
+ m.get_oa_symbol = lambda *a, **kw: None
+ return m
+
+ for mod in ["database.auth_db", "database.token_db",
+ "database.token_db_enhanced", "database.symbol"]:
+ # Always re-patch so token map is fresh
+ sys.modules[mod] = _make_stub(mod)
+
+ # Stub utils.logging to use stdlib logging
+ import logging
+ m = types.ModuleType("utils.logging")
+ m.get_logger = lambda name=None: logging.getLogger(name or __name__)
+ sys.modules["utils.logging"] = m
+ if "utils" not in sys.modules:
+ sys.modules["utils"] = types.ModuleType("utils")
+ sys.modules["utils"].logging = m
+
+
+def _create_adapter(broker: str):
+ """Dynamically import and instantiate the broker's WebSocket adapter."""
+ broker_lower = broker.lower()
+
+ # Map our broker names → openalgo module names
+ BROKER_MODULE_MAP = {
+ "zerodha": ("broker.zerodha.streaming.zerodha_adapter", "ZerodhaWebSocketAdapter"),
+ "fyers": ("broker.fyers.streaming.fyers_websocket_adapter", "FyersWebSocketAdapter"),
+ "upstox": ("broker.upstox.streaming.upstox_adapter", "UpstoxWebSocketAdapter"),
+ "dhan": ("broker.dhan.streaming.dhan_adapter", "DhanWebSocketAdapter"),
+ "kotak": ("broker.kotak.streaming.kotak_adapter", "KotakWebSocketAdapter"),
+ "groww": ("broker.groww.streaming.groww_adapter", "GrowwWebSocketAdapter"),
+ "aliceblue": ("broker.aliceblue.streaming.aliceblue_adapter", "AliceBlueWebSocketAdapter"),
+ "angelone": ("broker.angel.streaming.angel_adapter", "AngelWebSocketAdapter"),
+ "shoonya": ("broker.shoonya.streaming.shoonya_adapter", "ShoonyaWebSocketAdapter"),
+ "iifl": ("broker.iifl.streaming.iifl_adapter", "IIFLWebSocketAdapter"),
+ "motilal": ("broker.motilal.streaming.motilal_adapter", "MotilalWebSocketAdapter"),
+ "fivepaisa": ("broker.fivepaisa.streaming.fivepaisa_adapter", "FivePaisaWebSocketAdapter"),
+ }
+
+ if broker_lower not in BROKER_MODULE_MAP:
+ emit_error(broker, f"Broker '{broker}' not in bridge map")
+ return None
+
+ module_path, class_name = BROKER_MODULE_MAP[broker_lower]
+ try:
+ import importlib
+ mod = importlib.import_module(module_path)
+ cls = getattr(mod, class_name)
+ return cls()
+ except (ImportError, AttributeError) as e:
+ emit_error(broker, f"Failed to import {module_path}.{class_name}: {e}")
+ return None
+
+
+# ─────────────────────────────────────────────────────────────────────────────
+# Entry point
+# ─────────────────────────────────────────────────────────────────────────────
+
+def parse_args():
+ p = argparse.ArgumentParser()
+ p.add_argument("broker", help="Broker name e.g. zerodha")
+ p.add_argument("api_key", help="API key")
+ p.add_argument("access_token", help="Access/auth token")
+ p.add_argument("user_id", nargs="?", default="", help="User/client ID")
+ p.add_argument("--feed-token", default="", dest="feed_token",
+ help="Separate feed token (AngelOne feedToken)")
+ p.add_argument("--symbols", nargs="*", default=[],
+ help="Symbols as SYMBOL:EXCHANGE[:TOKEN] e.g. RELIANCE:NSE:738561")
+ return p.parse_args()
+
+
+def main():
+ args = parse_args()
+
+ broker = args.broker.lower()
+ api_key = args.api_key
+ access_token = args.access_token
+ user_id = args.user_id or api_key
+ feed_token = args.feed_token or access_token # fallback to access_token if not provided
+
+ # Parse symbol list: "RELIANCE:NSE:738561" → ("RELIANCE","NSE","738561")
+ symbols = []
+ for s in (args.symbols or []):
+ parts = s.split(":")
+ sym = parts[0] if len(parts) > 0 else s
+ exch = parts[1] if len(parts) > 1 else "NSE"
+ token = parts[2] if len(parts) > 2 else "0"
+ symbols.append((sym, exch, token))
+
+ if not symbols:
+ emit_error(broker, "No symbols provided — nothing to stream")
+ sys.exit(1)
+
+ emit_status(broker, False, f"Starting bridge for {len(symbols)} symbol(s)")
+
+ stop_event = threading.Event()
+
+ import signal
+ def _shutdown(sig, frame):
+ stop_event.set()
+ try:
+ signal.signal(signal.SIGTERM, _shutdown)
+ signal.signal(signal.SIGINT, _shutdown)
+ except Exception:
+ pass
+
+ run_broker(broker, api_key, access_token, user_id, symbols, stop_event,
+ feed_token=feed_token)
+
+
+if __name__ == "__main__":
+ main()
diff --git a/fincept-cpp/scripts/exchange/totp_gen.py b/fincept-cpp/scripts/exchange/totp_gen.py
new file mode 100644
index 000000000..0c46d6d7f
--- /dev/null
+++ b/fincept-cpp/scripts/exchange/totp_gen.py
@@ -0,0 +1,33 @@
+"""Generate current TOTP code from a base32 secret.
+Usage: totp_gen.py <base32_secret>
+Prints JSON: {"code": "123456", "valid_for": 15}
+"""
+import sys, json, time
+
+def main():
+ if len(sys.argv) < 2:
+ print(json.dumps({"error": "No secret provided"}))
+ sys.exit(1)
+
+ secret = sys.argv[1].strip()
+ try:
+ import pyotp
+ totp = pyotp.TOTP(secret)
+ code = totp.now()
+ # Seconds remaining in this 30s window
+ valid_for = 30 - (int(time.time()) % 30)
+ print(json.dumps({"code": code, "valid_for": valid_for}))
+ except ImportError:
+ # Fallback: implement TOTP manually (RFC 6238)
+ import hmac, hashlib, base64, struct
+ key = base64.b32decode(secret.upper() + '=' * (-len(secret) % 8))
+ t = int(time.time()) // 30
+ msg = struct.pack('>Q', t)
+ h = hmac.new(key, msg, hashlib.sha1).digest()
+ offset = h[-1] & 0x0f
+ code = str((struct.unpack('>I', h[offset:offset+4])[0] & 0x7fffffff) % 1000000).zfill(6)
+ valid_for = 30 - (int(time.time()) % 30)
+ print(json.dumps({"code": code, "valid_for": valid_for}))
+
+if __name__ == "__main__":
+ main()
diff --git a/fincept-cpp/src/app.cpp b/fincept-cpp/src/app.cpp
index 82f497fa1..dbd641487 100644
--- a/fincept-cpp/src/app.cpp
+++ b/fincept-cpp/src/app.cpp
@@ -491,7 +491,11 @@ void App::render_command_bar() {
using namespace theme::colors;
// Only show when focused and has text
- if (!cmd_focused_ || cmd_buf_[0] == '\0') return;
+ if (!cmd_focused_ || cmd_buf_[0] == '\0') {
+ // If buffer is empty but focus flag is stuck, clear it
+ if (cmd_focused_ && cmd_buf_[0] == '\0') cmd_focused_ = false;
+ return;
+ }
// Navigation command registry
struct CmdEntry {
diff --git a/fincept-cpp/src/screens/equity_trading/equity_trading_screen.cpp b/fincept-cpp/src/screens/equity_trading/equity_trading_screen.cpp
index 2f0dc6c54..d56931d59 100644
--- a/fincept-cpp/src/screens/equity_trading/equity_trading_screen.cpp
+++ b/fincept-cpp/src/screens/equity_trading/equity_trading_screen.cpp
@@ -1,1681 +1,964 @@
#include "equity_trading_screen.h"
#include "ui/theme.h"
-#include "ui/yoga_helpers.h"
#include "core/logger.h"
-#include "core/notification.h"
#include "trading/broker_registry.h"
+#include "trading/paper_trading.h"
+#include "trading/equity_stream.h"
+#include "python/python_runner.h"
#include <imgui.h>
+#ifdef _WIN32
+#include <windows.h>
+#include <shellapi.h>
+#endif
#include <cstdio>
#include <cstring>
#include <cmath>
#include <algorithm>
#include <chrono>
#include <future>
+#include <thread>
+#include <nlohmann/json.hpp>
namespace fincept::equity_trading {
using namespace theme::colors;
-static constexpr const char* TAG = "EquityTrading";
-
-// Named constants (ES.45)
-static constexpr float NAV_HEIGHT = 38.0f;
-static constexpr float TICKER_HEIGHT = 54.0f;
-static constexpr float STATUS_HEIGHT = 24.0f;
-static constexpr float LEFT_PANEL_WIDTH = 240.0f;
-static constexpr float RIGHT_PANEL_WIDTH = 290.0f;
-static constexpr float BOTTOM_PANEL_FRAC = 0.32f;
-static constexpr int MAX_DEPTH_LEVELS = 10;
-static constexpr int MAX_CHART_CANDLES = 200;
-
-// UI helper colors
-static constexpr ImVec4 BUY_GREEN = {0.05f, 0.65f, 0.30f, 1.0f};
-static constexpr ImVec4 BUY_GREEN_HOVER = {0.05f, 0.75f, 0.35f, 1.0f};
-static constexpr ImVec4 BUY_GREEN_BG = {0.05f, 0.65f, 0.30f, 0.15f};
-static constexpr ImVec4 SELL_RED = {0.75f, 0.15f, 0.15f, 1.0f};
-static constexpr ImVec4 SELL_RED_HOVER = {0.85f, 0.20f, 0.20f, 1.0f};
-static constexpr ImVec4 SELL_RED_BG = {0.75f, 0.15f, 0.15f, 0.15f};
-static constexpr ImVec4 PILL_CONNECTED = {0.10f, 0.55f, 0.25f, 1.0f};
-static constexpr ImVec4 PILL_PAPER = {0.70f, 0.55f, 0.05f, 1.0f};
-static constexpr ImVec4 PILL_LIVE = {0.75f, 0.15f, 0.15f, 1.0f};
-static constexpr ImVec4 DEPTH_BID_BAR = {0.05f, 0.65f, 0.30f, 0.20f};
-static constexpr ImVec4 DEPTH_ASK_BAR = {0.75f, 0.15f, 0.15f, 0.20f};
-static constexpr ImVec4 REGION_INDIA = {1.0f, 0.55f, 0.10f, 1.0f};
-static constexpr ImVec4 REGION_US = {0.30f, 0.60f, 0.96f, 1.0f};
-static constexpr ImVec4 REGION_EU = {0.55f, 0.40f, 0.90f, 1.0f};
-
-// ============================================================================
-// UI Helpers
-// ============================================================================
-
-static void eq_draw_pill(const char* text, ImVec4 bg_color, ImVec4 text_color = TEXT_PRIMARY) {
- const ImVec2 text_size = ImGui::CalcTextSize(text);
- const ImVec2 cursor = ImGui::GetCursorScreenPos();
- auto* draw = ImGui::GetWindowDrawList();
-
- const float pad_x = 8.0f;
- const float pad_y = 2.0f;
- const ImVec2 rect_min = {cursor.x, cursor.y + 1.0f};
- const ImVec2 rect_max = {cursor.x + text_size.x + pad_x * 2, cursor.y + text_size.y + pad_y * 2 + 1.0f};
-
- draw->AddRectFilled(rect_min, rect_max,
- ImGui::ColorConvertFloat4ToU32(bg_color), 3.0f);
- draw->AddText({rect_min.x + pad_x, rect_min.y + pad_y},
- ImGui::ColorConvertFloat4ToU32(text_color), text);
-
- ImGui::Dummy({rect_max.x - rect_min.x, rect_max.y - rect_min.y});
-}
-
-static void eq_draw_separator_line(float width) {
- const ImVec2 p = ImGui::GetCursorScreenPos();
- auto* draw = ImGui::GetWindowDrawList();
- draw->AddLine({p.x, p.y}, {p.x + width, p.y},
- ImGui::ColorConvertFloat4ToU32(BORDER_DIM));
- ImGui::Dummy({width, 1.0f});
-}
-
-static const char* eq_format_volume(double vol, char* buf, size_t buf_size) {
- if (vol >= 1e9)
- std::snprintf(buf, buf_size, "%.1fB", vol / 1e9);
- else if (vol >= 1e6)
- std::snprintf(buf, buf_size, "%.1fM", vol / 1e6);
- else if (vol >= 1e3)
- std::snprintf(buf, buf_size, "%.1fK", vol / 1e3);
- else
- std::snprintf(buf, buf_size, "%.0f", vol);
- return buf;
-}
-
-static ImVec4 eq_region_color(const char* region) {
- if (std::strcmp(region, "India") == 0) return REGION_INDIA;
- if (std::strcmp(region, "US") == 0) return REGION_US;
- if (std::strcmp(region, "EU") == 0) return REGION_EU;
- return TEXT_DIM;
-}
+using json = nlohmann::json;
-// ============================================================================
-// Initialization
-// ============================================================================
-
-void EquityTradingScreen::init() {
- LOG_INFO(TAG, "Initializing equity trading screen");
-
- watchlist_.clear();
- for (int i = 0; i < DEFAULT_WATCHLIST_COUNT; ++i) {
- WatchlistEntry e;
- e.symbol = DEFAULT_WATCHLIST[i];
- e.exchange = "NSE";
- watchlist_.push_back(e);
- }
-
- std::strncpy(order_form_.symbol_buf, selected_symbol_.c_str(),
- sizeof(order_form_.symbol_buf) - 1);
-
- initialized_ = true;
- LOG_INFO(TAG, "Initialized with %d watchlist entries", static_cast<int>(watchlist_.size()));
-}
-
-// ============================================================================
-// Main render — polls futures, lays out multi-panel Bloomberg-style UI
-// ============================================================================
+static constexpr ImVec4 C_GRN = {0.10f,0.75f,0.35f,1};
+static constexpr ImVec4 C_RED = {0.85f,0.25f,0.25f,1};
+static constexpr ImVec4 C_YEL = {0.90f,0.70f,0.10f,1};
+// ═══════════════════════════════════════════════════════════════════════
+// render
+// ═══════════════════════════════════════════════════════════════════════
void EquityTradingScreen::render() {
- if (!initialized_) init();
-
- // Poll async futures
- if (quote_future_.valid()) {
- if (quote_future_.wait_for(std::chrono::milliseconds(0)) == std::future_status::ready) {
- try {
- current_quote_ = quote_future_.get();
- has_quote_ = true;
- } catch (...) {
- LOG_WARN(TAG, "Quote fetch failed");
+ if (!inited_) {
+ watchlist_.clear();
+ for (int i = 0; i < DEFAULT_WATCHLIST_COUNT; ++i)
+ watchlist_.push_back({DEFAULT_WATCHLIST[i], "NSE"});
+ std::strncpy(order_form_.symbol_buf, sel_sym_.c_str(), sizeof(order_form_.symbol_buf)-1);
+ if (paper_id_.empty()) {
+ auto ex = trading::pt_find_portfolio("Equity Paper", "NSE");
+ if (ex) paper_id_ = ex->id;
+ else paper_id_ = trading::pt_create_portfolio("Equity Paper",1000000.0,"INR",1.0,"cross",0.0003,"NSE").id;
+ }
+ // Restore saved credentials into UI fields
+ // Also set active_broker_/active_creds_ for the first broker that has a valid token,
+ // so REST quotes work immediately (even in paper mode, even after market hours).
+ for (int i = 0; i < BROKER_META_COUNT; ++i) {
+ auto* b = trading::BrokerRegistry::instance().get(BROKER_META[i].id);
+ if (!b) continue;
+ auto creds = b->load_credentials();
+ if (creds.api_key.empty()) continue;
+ auto& ci = cred_ui_[i];
+ std::strncpy(ci.api_key, creds.api_key.c_str(), sizeof(ci.api_key)-1);
+ std::strncpy(ci.api_secret, creds.api_secret.c_str(), sizeof(ci.api_secret)-1);
+ std::strncpy(ci.user_id, creds.user_id.c_str(), sizeof(ci.user_id)-1);
+ // Restore additional fields from additional_data JSON
+ if (!creds.additional_data.empty()) {
+ try {
+ auto j = json::parse(creds.additional_data);
+ std::string pw = j.value("password", "");
+ std::string totp = j.value("totp_secret", "");
+ if (!pw.empty()) std::strncpy(ci.password, pw.c_str(), sizeof(ci.password)-1);
+ if (!totp.empty()) std::strncpy(ci.totp_secret, totp.c_str(), sizeof(ci.totp_secret)-1);
+ } catch (...) {}
}
- loading_quote_ = false;
- }
- }
-
- if (candle_future_.valid()) {
- if (candle_future_.wait_for(std::chrono::milliseconds(0)) == std::future_status::ready) {
- try {
- candles_ = candle_future_.get();
- } catch (...) {
- LOG_WARN(TAG, "Candle fetch failed");
+ ci.token_valid = !creds.access_token.empty();
+ // Use first non-OAuth broker with a saved token for REST price lookups.
+ // Skip OAuth brokers (Fyers, Zerodha, Upstox, Dhan…) — their tokens expire
+ // and require re-auth; only TOTP/ApiKey brokers have durable tokens.
+ // connected_ stays false — user must explicitly click Connect to go live.
+ if (!active_broker_ && !creds.access_token.empty()
+ && BROKER_META[i].auth_type != BrokerAuthType::OAuth) {
+ active_creds_ = creds;
+ active_broker_ = BROKER_META[i].id;
}
- loading_candles_ = false;
}
- }
-
- // Full-screen frame — matches dashboard/markets pattern (no debug window)
- ui::ScreenFrame frame("##equity_trading", ImVec2(0, 0), BG_DARKEST);
- if (!frame.begin()) { frame.end(); return; }
-
- const float w = frame.width();
- const float total_h = frame.height();
-
- render_top_nav(w);
- render_ticker_bar(w);
-
- const float body_y = ImGui::GetCursorPosY();
- const float body_h = total_h - body_y - STATUS_HEIGHT;
-
- if (body_h > 50.0f) {
- const float left_w = LEFT_PANEL_WIDTH;
- const float right_w = RIGHT_PANEL_WIDTH;
- const float center_w = w - left_w - right_w;
-
- const float bottom_h = bottom_minimized_ ? 0.0f : body_h * BOTTOM_PANEL_FRAC;
- const float chart_h = body_h - bottom_h;
-
- render_watchlist_panel(0.0f, body_y, left_w, body_h);
- render_chart_panel(left_w, body_y, center_w, chart_h);
- if (!bottom_minimized_) {
- render_bottom_panel(left_w, body_y + chart_h, center_w, bottom_h);
+ inited_ = true;
+ refresh_paper_portfolio();
+ if (active_broker_) {
+ fetch_quote();
+ refresh_watchlist_quotes();
}
-
- const float order_h = body_h * 0.55f;
- const float depth_h = body_h - order_h;
- render_order_entry(left_w + center_w, body_y, right_w, order_h);
- render_order_book(left_w + center_w, body_y + order_h, right_w, depth_h);
}
- render_status_bar(w, total_h);
+ using namespace std::chrono;
+ auto now = steady_clock::now();
- frame.end();
-}
-
-// ============================================================================
-// Top Navigation Bar — broker status pill, exchange selector, symbol input
-// ============================================================================
-
-void EquityTradingScreen::render_top_nav(float w) {
- ImGui::PushStyleColor(ImGuiCol_ChildBg, BG_DARKEST);
- ImGui::PushStyleVar(ImGuiStyleVar_WindowPadding, ImVec2(10, 6));
- ImGui::BeginChild("##eq_nav", ImVec2(w, NAV_HEIGHT), false);
-
- // Broker status pill
- if (is_connected_ && active_broker_.has_value()) {
- char pill[64];
- std::snprintf(pill, sizeof(pill), " %s ", trading::broker_id_str(*active_broker_));
- eq_draw_pill(pill, PILL_CONNECTED, ImVec4(1, 1, 1, 1));
- } else {
- eq_draw_pill(" DISCONNECTED ", {0.3f, 0.3f, 0.3f, 0.6f}, TEXT_DIM);
+ // Poll futures
+ if (quote_fut_.valid() && quote_fut_.wait_for(milliseconds(0)) == std::future_status::ready) {
+ try { quote_ = quote_fut_.get(); has_quote_ = true; } catch(...) {}
+ loading_quote_ = false;
}
-
- ImGui::SameLine(0.0f, 12.0f);
-
- // Exchange selector with region info
- ImGui::SetNextItemWidth(130.0f);
- char combo_label[64];
- std::snprintf(combo_label, sizeof(combo_label), "%s (%s)",
- EXCHANGES[exchange_idx_].code, EXCHANGES[exchange_idx_].currency);
- if (ImGui::BeginCombo("##exchange", combo_label)) {
- const char* last_region = nullptr;
- for (int i = 0; i < EXCHANGE_COUNT; ++i) {
- // Region separator
- if (!last_region || std::strcmp(last_region, EXCHANGES[i].region) != 0) {
- if (last_region) ImGui::Separator();
- ImGui::TextColored(eq_region_color(EXCHANGES[i].region), " %s", EXCHANGES[i].region);
- last_region = EXCHANGES[i].region;
- }
-
- const bool selected = (i == exchange_idx_);
- char label[128];
- std::snprintf(label, sizeof(label), " %s %s (%s)",
- EXCHANGES[i].code, EXCHANGES[i].name, EXCHANGES[i].currency);
- if (ImGui::Selectable(label, selected)) {
- exchange_idx_ = i;
- selected_exchange_ = EXCHANGES[i].code;
- }
- if (selected) ImGui::SetItemDefaultFocus();
- }
- ImGui::EndCombo();
+ if (candle_fut_.valid() && candle_fut_.wait_for(milliseconds(0)) == std::future_status::ready) {
+ try { candles_ = candle_fut_.get(); } catch(...) {}
+ loading_candles_ = false;
}
- ImGui::SameLine(0.0f, 8.0f);
-
- // Symbol input with accent border on focus
- ImGui::PushStyleColor(ImGuiCol_FrameBg, BG_INPUT);
- ImGui::PushStyleColor(ImGuiCol_FrameBgHovered, BG_HOVER);
- ImGui::PushStyleColor(ImGuiCol_FrameBgActive, ImVec4(0.2f, 0.15f, 0.1f, 1.0f));
- ImGui::SetNextItemWidth(140.0f);
- if (ImGui::InputText("##sym_input", symbol_buf_, sizeof(symbol_buf_),
- ImGuiInputTextFlags_EnterReturnsTrue | ImGuiInputTextFlags_CharsUppercase)) {
- select_symbol(symbol_buf_, selected_exchange_);
- }
- ImGui::PopStyleColor(3);
-
- ImGui::SameLine(0.0f, 4.0f);
- ImGui::PushStyleColor(ImGuiCol_Button, ACCENT_DIM);
- ImGui::PushStyleColor(ImGuiCol_ButtonHovered, ACCENT);
- ImGui::PushStyleColor(ImGuiCol_Text, ImVec4(1, 1, 1, 1));
- if (ImGui::Button("GO", ImVec2(32, 0))) {
- select_symbol(symbol_buf_, selected_exchange_);
+ // Poll broker connect future — resolve on main thread
+ if (connecting_ && connect_fut_.valid() &&
+ connect_fut_.wait_for(milliseconds(0)) == std::future_status::ready) {
+ ConnectResult r;
+ try { r = connect_fut_.get(); } catch(...) { r.error = "Exception during auth"; }
+ connecting_ = false;
+ finish_connect(r);
}
- ImGui::PopStyleColor(3);
-
- // Right side controls
- ImGui::SameLine(w - 260.0f);
-
- // Paper/Live mode pill
- if (is_paper_mode_) {
- ImGui::PushStyleColor(ImGuiCol_Button, PILL_PAPER);
- ImGui::PushStyleColor(ImGuiCol_ButtonHovered, ImVec4(0.80f, 0.65f, 0.10f, 1.0f));
- ImGui::PushStyleColor(ImGuiCol_Text, ImVec4(0, 0, 0, 1));
- if (ImGui::SmallButton(" PAPER ")) { is_paper_mode_ = false; }
- ImGui::PopStyleColor(3);
- } else {
- ImGui::PushStyleColor(ImGuiCol_Button, PILL_LIVE);
- ImGui::PushStyleColor(ImGuiCol_ButtonHovered, ImVec4(0.85f, 0.20f, 0.20f, 1.0f));
- ImGui::PushStyleColor(ImGuiCol_Text, ImVec4(1, 1, 1, 1));
- if (ImGui::SmallButton(" LIVE ")) { is_paper_mode_ = true; }
- ImGui::PopStyleColor(3);
- }
-
- ImGui::SameLine(0.0f, 8.0f);
- // Connect/Disconnect button
- if (!is_connected_) {
- ImGui::PushStyleColor(ImGuiCol_Button, ACCENT_DIM);
- ImGui::PushStyleColor(ImGuiCol_ButtonHovered, ACCENT);
- ImGui::PushStyleColor(ImGuiCol_Text, ImVec4(1, 1, 1, 1));
- if (ImGui::SmallButton(" Connect Broker ")) {
- bottom_tab_ = BottomTab::brokers;
- bottom_minimized_ = false;
- }
- ImGui::PopStyleColor(3);
- } else {
- ImGui::PushStyleColor(ImGuiCol_Button, ImVec4(0.4f, 0.15f, 0.15f, 0.8f));
- ImGui::PushStyleColor(ImGuiCol_ButtonHovered, SELL_RED);
- ImGui::PushStyleColor(ImGuiCol_Text, ImVec4(1, 1, 1, 1));
- if (ImGui::SmallButton(" Disconnect ")) {
- is_connected_ = false;
- active_broker_ = std::nullopt;
- }
- ImGui::PopStyleColor(3);
+ // Auto-refresh portfolio
+ if (!loading_port_ && duration_cast<seconds>(now - last_port_refresh_).count() >= PORT_REFRESH_SECS) {
+ last_port_refresh_ = now;
+ if (paper_mode_) refresh_paper_portfolio();
+ else if (connected_) refresh_portfolio();
}
- ImGui::EndChild();
- ImGui::PopStyleVar();
- ImGui::PopStyleColor();
-}
-
-// ============================================================================
-// Ticker Bar — current symbol quote strip with spread & range indicators
-// ============================================================================
-
-void EquityTradingScreen::render_ticker_bar(float w) {
- ImGui::PushStyleColor(ImGuiCol_ChildBg, BG_DARK);
- ImGui::PushStyleVar(ImGuiStyleVar_WindowPadding, ImVec2(12, 8));
- ImGui::BeginChild("##eq_ticker", ImVec2(w, TICKER_HEIGHT), false);
-
- // Symbol name (large)
- ImGui::TextColored(ACCENT, "%s", selected_symbol_.c_str());
- ImGui::SameLine(0.0f, 4.0f);
- ImGui::TextColored(TEXT_DIM, "%s", selected_exchange_.c_str());
+ // Auto-refresh quote every 5s when we have an active broker (live or paper mode)
+ if (!loading_quote_ && active_broker_ &&
+ duration_cast<seconds>(now - last_quote_refresh_).count() >= QUOTE_REFRESH_SECS) {
+ last_quote_refresh_ = now;
+ fetch_quote();
+ }
+ // Auto-refresh watchlist quotes every 15s via REST
+ if (!loading_wl_quotes_ && active_broker_ &&
+ duration_cast<seconds>(now - last_wl_refresh_).count() >= WL_REFRESH_SECS) {
+ last_wl_refresh_ = now;
+ refresh_watchlist_quotes();
+ }
+
+ // Status timeout
+ if (!status_msg_.empty() && duration_cast<seconds>(now - status_time_).count() >= 5)
+ status_msg_.clear();
+
+ // Window — same pattern as standalone test that works
+ ImGuiViewport* vp = ImGui::GetMainViewport();
+ float top_off = ImGui::GetFrameHeight() + 4;
+ float bot_off = ImGui::GetFrameHeight();
+ ImGui::SetNextWindowPos({vp->WorkPos.x, vp->WorkPos.y + top_off});
+ ImGui::SetNextWindowSize({vp->WorkSize.x, vp->WorkSize.y - top_off - bot_off});
+
+ ImGui::Begin("##equity_main", nullptr,
+ ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_NoResize |
+ ImGuiWindowFlags_NoMove | ImGuiWindowFlags_NoCollapse);
+
+ // Status
+ if (!status_msg_.empty()) { ImGui::TextColored(C_GRN, "%s", status_msg_.c_str()); ImGui::Spacing(); }
+
+ // Mode + symbol bar
+ if (paper_mode_) ImGui::TextColored(C_YEL, "[PAPER]");
+ else if (connected_ && ws_streaming_ &&
+ trading::EquityStreamManager::instance().is_connected())
+ ImGui::TextColored(C_GRN, "[LIVE\xE2\x97\x8F WS]");
+ else if (connected_) ImGui::TextColored(C_GRN, "[LIVE REST]");
+ else ImGui::TextColored(C_RED, "[DISCONNECTED]");
+ ImGui::SameLine(0,12);
+ ImGui::SetNextItemWidth(80);
+ if (ImGui::Combo("##exch", &exch_idx_, [](void* d, int i) -> const char* {
+ return EXCHANGES[i].code; }, nullptr, EXCHANGE_COUNT)) {
+ sel_exch_ = EXCHANGES[exch_idx_].code;
+ }
+ ImGui::SameLine(0,4);
+ ImGui::SetNextItemWidth(120);
+ if (ImGui::InputText("##sym", sym_buf_, sizeof(sym_buf_), ImGuiInputTextFlags_EnterReturnsTrue)) {
+ select_symbol(sym_buf_, EXCHANGES[exch_idx_].code);
+ }
+ ImGui::SameLine();
+ if (ImGui::Button("Go")) select_symbol(sym_buf_, EXCHANGES[exch_idx_].code);
+ ImGui::SameLine(0,16);
if (has_quote_) {
- ImGui::SameLine(0.0f, 20.0f);
-
- // LTP — large text style
- ImGui::TextColored(TEXT_PRIMARY, "%.2f", current_quote_.ltp);
- ImGui::SameLine(0.0f, 8.0f);
-
- // Change with arrow
- const bool positive = (current_quote_.change >= 0.0);
- const ImVec4& chg_color = positive ? MARKET_GREEN : MARKET_RED;
- const char* arrow = positive ? "\xe2\x96\xb2" : "\xe2\x96\xbc"; // ▲ or ▼
- char chg_buf[64];
- std::snprintf(chg_buf, sizeof(chg_buf), "%s %+.2f (%+.2f%%)",
- arrow, current_quote_.change, current_quote_.change_pct);
- ImGui::TextColored(chg_color, "%s", chg_buf);
-
- // OHLV strip
- ImGui::SameLine(0.0f, 24.0f);
- ImGui::TextColored(TEXT_DIM, "O");
- ImGui::SameLine(0.0f, 2.0f);
- ImGui::TextColored(TEXT_SECONDARY, "%.2f", current_quote_.open);
-
- ImGui::SameLine(0.0f, 10.0f);
- ImGui::TextColored(TEXT_DIM, "H");
- ImGui::SameLine(0.0f, 2.0f);
- ImGui::TextColored(MARKET_GREEN, "%.2f", current_quote_.high);
-
- ImGui::SameLine(0.0f, 10.0f);
- ImGui::TextColored(TEXT_DIM, "L");
- ImGui::SameLine(0.0f, 2.0f);
- ImGui::TextColored(MARKET_RED, "%.2f", current_quote_.low);
-
- ImGui::SameLine(0.0f, 10.0f);
- ImGui::TextColored(TEXT_DIM, "V");
- ImGui::SameLine(0.0f, 2.0f);
- char vol_buf[32];
- ImGui::TextColored(TEXT_SECONDARY, "%s", eq_format_volume(current_quote_.volume, vol_buf, sizeof(vol_buf)));
-
- // Bid/Ask with spread
- ImGui::SameLine(0.0f, 24.0f);
- ImGui::TextColored(MARKET_GREEN, "%.2f", current_quote_.bid);
- ImGui::SameLine(0.0f, 2.0f);
- ImGui::TextColored(TEXT_DIM, "/");
- ImGui::SameLine(0.0f, 2.0f);
- ImGui::TextColored(MARKET_RED, "%.2f", current_quote_.ask);
-
- if (current_quote_.bid > 0.0 && current_quote_.ask > 0.0) {
- ImGui::SameLine(0.0f, 6.0f);
- const double spread = current_quote_.ask - current_quote_.bid;
- char spread_buf[32];
- std::snprintf(spread_buf, sizeof(spread_buf), "(%.2f)", spread);
- ImGui::TextColored(TEXT_DIM, "%s", spread_buf);
- }
-
- // Day range bar (visual indicator between L and H)
- if (current_quote_.high > current_quote_.low) {
- ImGui::SameLine(0.0f, 16.0f);
- const ImVec2 bar_pos = ImGui::GetCursorScreenPos();
- const float bar_w = 80.0f;
- const float bar_h = 4.0f;
- auto* draw = ImGui::GetWindowDrawList();
-
- const float bar_y = bar_pos.y + 6.0f;
- draw->AddRectFilled({bar_pos.x, bar_y}, {bar_pos.x + bar_w, bar_y + bar_h},
- IM_COL32(60, 60, 65, 200), 2.0f);
-
- // LTP position within range
- const double range = current_quote_.high - current_quote_.low;
- const float ltp_pct = static_cast<float>((current_quote_.ltp - current_quote_.low) / range);
- const float ltp_x = bar_pos.x + ltp_pct * bar_w;
-
- // Filled portion
- const ImU32 fill_col = positive ? IM_COL32(13, 180, 100, 200) : IM_COL32(220, 60, 60, 200);
- draw->AddRectFilled({bar_pos.x, bar_y}, {ltp_x, bar_y + bar_h}, fill_col, 2.0f);
-
- // LTP marker
- draw->AddCircleFilled({ltp_x, bar_y + bar_h * 0.5f}, 3.0f, IM_COL32(255, 255, 255, 220));
-
- ImGui::Dummy({bar_w + 4.0f, 14.0f});
- }
+ ImGui::Text("%.2f", quote_.ltp);
+ ImGui::SameLine(0,6);
+ ImGui::TextColored(quote_.change >= 0 ? C_GRN : C_RED, "%+.2f (%.2f%%)", quote_.change, quote_.change_pct);
+ }
+ ImGui::SameLine(0,20);
+ if (connected_) ImGui::BeginDisabled();
+ ImGui::Checkbox("Paper", &paper_mode_);
+ if (connected_) ImGui::EndDisabled();
+ ImGui::Separator();
+
+ // Navigation buttons
+ static const char* nav[] = {"Overview","Watchlist","Order","Positions","Orders","Funds","Brokers"};
+ for (int i = 0; i < 7; ++i) {
+ if (i > 0) ImGui::SameLine();
+ bool active = (section_ == i);
+ if (active) ImGui::PushStyleColor(ImGuiCol_Button, ACCENT_BG);
+ if (ImGui::Button(nav[i])) section_ = i;
+ if (active) ImGui::PopStyleColor();
+ }
+ ImGui::Separator();
+ ImGui::Spacing();
- } else if (loading_quote_) {
- ImGui::SameLine(0.0f, 24.0f);
- theme::LoadingSpinner("Fetching quote...");
- } else {
- ImGui::SameLine(0.0f, 24.0f);
- ImGui::TextColored(TEXT_DIM, "Connect a broker to view live data");
+ // Content
+ switch (section_) {
+ case 0: section_overview(); break;
+ case 1: section_watchlist(); break;
+ case 2: section_order(); break;
+ case 3: section_positions(); break;
+ case 4: section_orders(); break;
+ case 5: section_funds(); break;
+ case 6: section_brokers(); break;
}
- ImGui::EndChild();
- ImGui::PopStyleVar();
- ImGui::PopStyleColor();
+ ImGui::End();
}
-// ============================================================================
-// Watchlist Panel — left sidebar with search, stocks, indices
-// ============================================================================
-
-void EquityTradingScreen::render_watchlist_panel(float x, float y, float w, float h) {
- ImGui::SetCursorPos(ImVec2(x, y));
- ImGui::PushStyleColor(ImGuiCol_ChildBg, BG_PANEL);
- ImGui::PushStyleVar(ImGuiStyleVar_WindowPadding, ImVec2(6, 6));
- ImGui::BeginChild("##eq_watchlist", ImVec2(w, h), true);
-
- // Tab-style toggle
- const float tab_w = (w - 20.0f) * 0.5f;
- {
- const bool stocks_active = (sidebar_view_ == SidebarView::watchlist);
-
- if (stocks_active) {
- ImGui::PushStyleColor(ImGuiCol_Button, ACCENT_DIM);
- ImGui::PushStyleColor(ImGuiCol_Text, ImVec4(1, 1, 1, 1));
- } else {
- ImGui::PushStyleColor(ImGuiCol_Button, BG_WIDGET);
- ImGui::PushStyleColor(ImGuiCol_Text, TEXT_DIM);
- }
- if (ImGui::Button("STOCKS", ImVec2(tab_w, 24.0f))) {
- sidebar_view_ = SidebarView::watchlist;
- }
- ImGui::PopStyleColor(2);
-
- ImGui::SameLine(0.0f, 2.0f);
-
- const bool idx_active = (sidebar_view_ == SidebarView::indices);
- if (idx_active) {
- ImGui::PushStyleColor(ImGuiCol_Button, ACCENT_DIM);
- ImGui::PushStyleColor(ImGuiCol_Text, ImVec4(1, 1, 1, 1));
- } else {
- ImGui::PushStyleColor(ImGuiCol_Button, BG_WIDGET);
- ImGui::PushStyleColor(ImGuiCol_Text, TEXT_DIM);
- }
- if (ImGui::Button("INDICES", ImVec2(tab_w, 24.0f))) {
- sidebar_view_ = SidebarView::indices;
- }
- ImGui::PopStyleColor(2);
- }
+// ═══════════════════════════════════════════════════════════════════════
+// Overview
+// ═══════════════════════════════════════════════════════════════════════
+void EquityTradingScreen::section_overview() {
+ ImGui::Text("Equity Trading");
+ ImGui::Separator();
+ if (connected_ && active_broker_)
+ ImGui::TextColored(C_GRN, "Connected: %s", trading::broker_id_str(*active_broker_));
+ else if (paper_mode_ && active_broker_)
+ ImGui::TextColored(C_YEL, "Paper mode | %s (REST quotes active)", trading::broker_id_str(*active_broker_));
+ else if (paper_mode_)
+ ImGui::Text("Paper trading active. Connect a broker in Brokers tab to go live.");
+ else
+ ImGui::TextColored(C_RED, "No broker connected.");
ImGui::Spacing();
+ ImGui::Text("Symbol: %s [%s]", sel_sym_.c_str(), sel_exch_.c_str());
- if (sidebar_view_ == SidebarView::watchlist) {
- // Search with icon hint
- ImGui::PushStyleColor(ImGuiCol_FrameBg, BG_INPUT);
- ImGui::SetNextItemWidth(w - 14.0f);
- ImGui::InputTextWithHint("##wl_search", "Search symbols...", watchlist_search_,
- sizeof(watchlist_search_));
- ImGui::PopStyleColor();
-
- const std::string filter(watchlist_search_);
-
- ImGui::Spacing();
-
- // Watchlist table with improved visuals
- if (ImGui::BeginTable("##wl_tbl", 3,
- ImGuiTableFlags_RowBg | ImGuiTableFlags_ScrollY | ImGuiTableFlags_SizingStretchProp |
- ImGuiTableFlags_PadOuterX,
- ImVec2(0, h - 90.0f))) {
- ImGui::TableSetupColumn("Symbol", ImGuiTableColumnFlags_None, 0.40f);
- ImGui::TableSetupColumn("LTP", ImGuiTableColumnFlags_None, 0.30f);
- ImGui::TableSetupColumn("Chg%", ImGuiTableColumnFlags_None, 0.30f);
- ImGui::TableHeadersRow();
-
- int row_idx = 0;
- for (const auto& entry : watchlist_) {
- if (!filter.empty()) {
- bool match = false;
- for (size_t i = 0; i < entry.symbol.size() && i < filter.size(); ++i) {
- if (std::tolower(static_cast<unsigned char>(entry.symbol[i])) !=
- std::tolower(static_cast<unsigned char>(filter[i]))) break;
- if (i + 1 == filter.size()) match = true;
- }
- if (!match && entry.symbol.find(filter) == std::string::npos) continue;
- }
-
- ImGui::TableNextRow();
-
- // Highlight selected row
- const bool is_sel = (entry.symbol == selected_symbol_);
- if (is_sel) {
- ImGui::TableSetBgColor(ImGuiTableBgTarget_RowBg0,
- ImGui::ColorConvertFloat4ToU32(ACCENT_BG));
- }
-
- ImGui::TableNextColumn();
- if (ImGui::Selectable(entry.symbol.c_str(), is_sel,
- ImGuiSelectableFlags_SpanAllColumns)) {
- select_symbol(entry.symbol, entry.exchange);
- }
-
- ImGui::TableNextColumn();
- if (entry.ltp > 0.0) {
- ImGui::Text("%.2f", entry.ltp);
- } else {
- ImGui::TextColored(TEXT_DIM, "--");
- }
-
- ImGui::TableNextColumn();
- if (std::abs(entry.change_pct) > 0.001) {
- const ImVec4& c = (entry.change_pct >= 0.0) ? MARKET_GREEN : MARKET_RED;
- // Draw small change bar behind text
- const ImVec2 cell_min = ImGui::GetCursorScreenPos();
- const float bar_frac = std::min(1.0f, static_cast<float>(std::abs(entry.change_pct)) / 5.0f);
- auto* draw = ImGui::GetWindowDrawList();
- const ImVec4& bar_col = (entry.change_pct >= 0.0) ? BUY_GREEN_BG : SELL_RED_BG;
- draw->AddRectFilled(cell_min,
- {cell_min.x + bar_frac * 60.0f, cell_min.y + ImGui::GetTextLineHeight()},
- ImGui::ColorConvertFloat4ToU32(bar_col));
-
- ImGui::TextColored(c, "%+.2f%%", entry.change_pct);
- } else {
- ImGui::TextColored(TEXT_DIM, "0.00%%");
- }
-
- ++row_idx;
- }
- ImGui::EndTable();
- }
-
- // Bottom actions
- ImGui::Spacing();
- if (loading_watchlist_) {
- theme::LoadingSpinner("Refreshing...");
- } else {
- const float btn_w = w - 14.0f;
- ImGui::PushStyleColor(ImGuiCol_Button, BG_WIDGET);
- ImGui::PushStyleColor(ImGuiCol_ButtonHovered, BG_HOVER);
- if (ImGui::Button("Refresh Watchlist", ImVec2(btn_w, 24.0f))) {
- fetch_watchlist_quotes();
- }
- ImGui::PopStyleColor(2);
- }
-
- } else {
- // Market Indices view
- ImGui::TextColored(ACCENT, "MARKET INDICES");
- ImGui::Spacing();
- eq_draw_separator_line(w - 14.0f);
- ImGui::Spacing();
-
- for (int i = 0; i < MARKET_INDICES_COUNT; ++i) {
- const auto& idx = MARKET_INDICES[i];
- ImGui::PushStyleColor(ImGuiCol_Header, BG_WIDGET);
- ImGui::PushStyleColor(ImGuiCol_HeaderHovered, BG_HOVER);
- if (ImGui::Selectable(idx.symbol, false, 0, ImVec2(0, 24.0f))) {
- select_symbol(idx.symbol, idx.exchange);
- }
- ImGui::PopStyleColor(2);
-
- if (i < MARKET_INDICES_COUNT - 1) {
- ImGui::PushStyleColor(ImGuiCol_Separator, BORDER_DIM);
- ImGui::Separator();
- ImGui::PopStyleColor();
- }
- }
+ if (has_quote_) {
+ ImGui::Text("LTP: %.2f | Open: %.2f | High: %.2f | Low: %.2f",
+ quote_.ltp, quote_.open, quote_.high, quote_.low);
+ ImGui::Text("Volume: %.0f | Bid: %.2f | Ask: %.2f",
+ quote_.volume, quote_.bid, quote_.ask);
+ } else if (loading_quote_) {
+ ImGui::TextColored(C_YEL, "Loading quote...");
+ } else if (!active_broker_) {
+ ImGui::TextColored(TEXT_DIM, "No broker configured — connect one in Brokers tab.");
}
-
- ImGui::EndChild();
- ImGui::PopStyleVar();
- ImGui::PopStyleColor();
}
-// ============================================================================
-// Chart Panel — candlestick chart with timeframe selector
-// ============================================================================
-
-void EquityTradingScreen::render_chart_panel(float x, float y, float w, float h) {
- ImGui::SetCursorPos(ImVec2(x, y));
- ImGui::PushStyleColor(ImGuiCol_ChildBg, BG_DARKEST);
- ImGui::PushStyleVar(ImGuiStyleVar_WindowPadding, ImVec2(8, 6));
- ImGui::BeginChild("##eq_chart", ImVec2(w, h), true);
-
- // Timeframe buttons — pill style
- static constexpr TimeFrame tfs[] = {
- TimeFrame::m1, TimeFrame::m5, TimeFrame::m15, TimeFrame::m30,
- TimeFrame::h1, TimeFrame::h4, TimeFrame::d1, TimeFrame::w1
- };
-
- ImGui::PushStyleVar(ImGuiStyleVar_FramePadding, ImVec2(8, 3));
- for (const auto tf : tfs) {
- const bool active = (tf == chart_timeframe_);
- if (active) {
- ImGui::PushStyleColor(ImGuiCol_Button, ACCENT_DIM);
- ImGui::PushStyleColor(ImGuiCol_Text, ImVec4(1, 1, 1, 1));
- } else {
- ImGui::PushStyleColor(ImGuiCol_Button, BG_WIDGET);
- ImGui::PushStyleColor(ImGuiCol_Text, TEXT_DIM);
- }
- if (ImGui::SmallButton(timeframe_label(tf))) {
- chart_timeframe_ = tf;
+// ═══════════════════════════════════════════════════════════════════════
+// Watchlist
+// ═══════════════════════════════════════════════════════════════════════
+void EquityTradingScreen::section_watchlist() {
+ ImGui::Text("Watchlist (%d)", (int)watchlist_.size());
+ ImGui::Separator();
+ if (ImGui::BeginTable("##wl", 4, ImGuiTableFlags_Borders | ImGuiTableFlags_RowBg | ImGuiTableFlags_ScrollY)) {
+ ImGui::TableSetupColumn("Symbol", ImGuiTableColumnFlags_WidthFixed, 100);
+ ImGui::TableSetupColumn("LTP", ImGuiTableColumnFlags_WidthFixed, 80);
+ ImGui::TableSetupColumn("Chg", ImGuiTableColumnFlags_WidthFixed, 70);
+ ImGui::TableSetupColumn("Chg%", ImGuiTableColumnFlags_WidthStretch);
+ ImGui::TableHeadersRow();
+ for (auto& e : watchlist_) {
+ ImGui::TableNextRow();
+ ImGui::TableSetColumnIndex(0);
+ char sl[64]; std::snprintf(sl, sizeof(sl), "%s##wl_%s", e.symbol.c_str(), e.symbol.c_str());
+ if (ImGui::Selectable(sl, false, ImGuiSelectableFlags_SpanAllColumns))
+ select_symbol(e.symbol, e.exchange);
+ ImGui::TableSetColumnIndex(1);
+ e.ltp > 0 ? ImGui::Text("%.2f", e.ltp) : ImGui::TextColored(TEXT_DIM, "-");
+ ImGui::TableSetColumnIndex(2);
+ e.ltp > 0 ? ImGui::TextColored(e.change>=0?C_GRN:C_RED,"%+.2f",e.change) : ImGui::TextColored(TEXT_DIM,"-");
+ ImGui::TableSetColumnIndex(3);
+ e.ltp > 0 ? ImGui::TextColored(e.change_pct>=0?C_GRN:C_RED,"%.2f%%",e.change_pct) : ImGui::TextColored(TEXT_DIM,"-");
}
- ImGui::PopStyleColor(2);
- ImGui::SameLine(0.0f, 2.0f);
- }
- ImGui::PopStyleVar();
-
- // Hide/Show bottom panel toggle
- ImGui::SameLine(w - 70.0f);
- ImGui::PushStyleColor(ImGuiCol_Button, BG_WIDGET);
- ImGui::PushStyleColor(ImGuiCol_ButtonHovered, BG_HOVER);
- if (ImGui::SmallButton(bottom_minimized_ ? "Show" : "Hide")) {
- bottom_minimized_ = !bottom_minimized_;
- }
- ImGui::PopStyleColor(2);
-
- eq_draw_separator_line(w - 16.0f);
-
- // Chart area
- if (loading_candles_) {
- const float cx = w * 0.4f;
- const float cy = h * 0.4f;
- ImGui::SetCursorPos(ImVec2(cx, cy));
- theme::LoadingSpinner("Loading chart...");
- } else if (candles_.empty()) {
- // Empty state with centered message
- const float cx = w * 0.25f;
- const float cy = h * 0.35f;
- ImGui::SetCursorPos(ImVec2(cx, cy));
- ImGui::TextColored(TEXT_DIM, "No chart data available");
- ImGui::SetCursorPosX(cx - 20.0f);
- ImGui::Spacing();
- ImGui::TextColored(TEXT_DISABLED, "Connect a broker and select a symbol");
- ImGui::TextColored(TEXT_DISABLED, "to view candlestick charts");
- } else {
- render_candle_chart(w - 16.0f, h - 40.0f);
+ ImGui::EndTable();
}
-
- ImGui::EndChild();
- ImGui::PopStyleVar();
- ImGui::PopStyleColor();
}
-// ============================================================================
-// Candle Chart Renderer — improved with volume bars and crosshair
-// ============================================================================
+// ═══════════════════════════════════════════════════════════════════════
+// Order Entry
+// ═══════════════════════════════════════════════════════════════════════
+void EquityTradingScreen::section_order() {
+ ImGui::Text("Place Order");
+ ImGui::Separator();
+ auto& f = order_form_;
-void EquityTradingScreen::render_candle_chart(float w, float h) {
- if (candles_.empty() || w < 20.0f || h < 20.0f) return;
+ ImGui::Text("Symbol"); ImGui::SameLine(120); ImGui::SetNextItemWidth(160);
+ ImGui::InputText("##osym", f.symbol_buf, sizeof(f.symbol_buf));
- const ImVec2 p = ImGui::GetCursorScreenPos();
- auto* draw = ImGui::GetWindowDrawList();
+ ImGui::Text("Side"); ImGui::SameLine(120);
+ if (ImGui::RadioButton("BUY##buy", f.side == trading::OrderSide::Buy)) f.side = trading::OrderSide::Buy;
+ ImGui::SameLine();
+ if (ImGui::RadioButton("SELL##sell", f.side == trading::OrderSide::Sell)) f.side = trading::OrderSide::Sell;
- // Reserve 20% height for volume
- const float vol_h = h * 0.15f;
- const float price_h = h - vol_h - 4.0f;
+ ImGui::Text("Type"); ImGui::SameLine(120);
+ static const char* OT[] = {"Market","Limit","StopLoss","SL-Limit"};
+ int ot = (int)f.type; ImGui::SetNextItemWidth(160);
+ if (ImGui::Combo("##ot", &ot, OT, 4)) f.type = (trading::OrderType)ot;
- // Background
- draw->AddRectFilled(p, ImVec2(p.x + w, p.y + h), IM_COL32(15, 15, 17, 255));
+ ImGui::Text("Product"); ImGui::SameLine(120);
+ static const char* PT[] = {"Intraday","Delivery","Margin","Cover","Bracket"};
+ int pt = (int)f.product; ImGui::SetNextItemWidth(160);
+ if (ImGui::Combo("##pt", &pt, PT, 5)) f.product = (trading::ProductType)pt;
- // Find price min/max
- double min_price = 1e18;
- double max_price = -1e18;
- double max_vol = 0.0;
- for (const auto& c : candles_) {
- min_price = std::min(min_price, c.low);
- max_price = std::max(max_price, c.high);
- max_vol = std::max(max_vol, c.volume);
- }
- if (max_price <= min_price) max_price = min_price + 1.0;
- if (max_vol <= 0.0) max_vol = 1.0;
-
- const double price_range = max_price - min_price;
- const float padding = price_h * 0.04f;
- const float chart_h = price_h - 2.0f * padding;
- const int n = static_cast<int>(candles_.size());
- const float label_w = 50.0f;
- const float chart_w = w - label_w;
- const float candle_w = std::max(1.0f, chart_w / static_cast<float>(n));
- const float gap = std::max(1.0f, candle_w * 0.15f);
- const float body_w = candle_w - gap;
-
- // Price grid lines (5 levels) with labels
- for (int i = 0; i <= 4; ++i) {
- const float fy = p.y + padding + chart_h * static_cast<float>(i) / 4.0f;
- draw->AddLine(ImVec2(p.x + label_w, fy), ImVec2(p.x + w, fy),
- IM_COL32(40, 40, 48, 120));
- const double price_at = max_price - price_range * static_cast<double>(i) / 4.0;
- char buf[32];
- std::snprintf(buf, sizeof(buf), "%.2f", price_at);
- draw->AddText(ImVec2(p.x + 2.0f, fy - 6.0f), IM_COL32(120, 120, 130, 200), buf);
- }
+ ImGui::Text("Quantity"); ImGui::SameLine(120); ImGui::SetNextItemWidth(160);
+ ImGui::InputDouble("##qty", &f.quantity, 1, 10, "%.0f");
- // Volume separator line
- const float vol_top = p.y + price_h + 2.0f;
- draw->AddLine(ImVec2(p.x + label_w, vol_top), ImVec2(p.x + w, vol_top),
- IM_COL32(50, 50, 58, 150));
-
- // Draw candles + volume
- for (int i = 0; i < n; ++i) {
- const auto& c = candles_[i];
- const float cx = p.x + label_w + static_cast<float>(i) * candle_w + candle_w * 0.5f;
-
- auto price_to_y = [&](double price) -> float {
- return p.y + padding + chart_h * static_cast<float>((max_price - price) / price_range);
- };
-
- const float y_open = price_to_y(c.open);
- const float y_close = price_to_y(c.close);
- const float y_high = price_to_y(c.high);
- const float y_low = price_to_y(c.low);
-
- const bool bullish = (c.close >= c.open);
- const ImU32 col = bullish ? IM_COL32(13, 217, 107, 255) : IM_COL32(245, 64, 64, 255);
- const ImU32 col_dim = bullish ? IM_COL32(13, 217, 107, 80) : IM_COL32(245, 64, 64, 80);
-
- // Wick
- draw->AddLine(ImVec2(cx, y_high), ImVec2(cx, y_low), col, 1.0f);
-
- // Body
- const float body_top = std::min(y_open, y_close);
- const float body_bot = std::max(y_open, y_close);
- if (body_bot - body_top < 1.0f) {
- draw->AddLine(ImVec2(cx - body_w * 0.5f, body_top),
- ImVec2(cx + body_w * 0.5f, body_top), col, 1.0f);
- } else {
- draw->AddRectFilled(
- ImVec2(cx - body_w * 0.5f, body_top),
- ImVec2(cx + body_w * 0.5f, body_bot), col);
- }
-
- // Volume bar
- const float vol_bar_h = static_cast<float>(c.volume / max_vol) * (vol_h - 4.0f);
- const float vol_bot = p.y + h;
- draw->AddRectFilled(
- ImVec2(cx - body_w * 0.4f, vol_bot - vol_bar_h),
- ImVec2(cx + body_w * 0.4f, vol_bot), col_dim);
+ if (f.type != trading::OrderType::Market) {
+ ImGui::Text("Price"); ImGui::SameLine(120); ImGui::SetNextItemWidth(160);
+ ImGui::InputDouble("##price", &f.price, 0.05, 1.0, "%.2f");
}
-
- ImGui::Dummy(ImVec2(w, h));
-}
-
-// ============================================================================
-// Bottom Panel — tabbed: positions, holdings, orders, history, brokers
-// ============================================================================
-
-void EquityTradingScreen::render_bottom_panel(float x, float y, float w, float h) {
- ImGui::SetCursorPos(ImVec2(x, y));
- ImGui::PushStyleColor(ImGuiCol_ChildBg, BG_PANEL);
- ImGui::PushStyleVar(ImGuiStyleVar_WindowPadding, ImVec2(8, 6));
- ImGui::BeginChild("##eq_bottom", ImVec2(w, h), true);
-
- // Tab bar with underline-style indicators and item counts
- static constexpr BottomTab tabs[] = {
- BottomTab::positions, BottomTab::holdings, BottomTab::orders,
- BottomTab::history, BottomTab::brokers
- };
-
- ImGui::PushStyleVar(ImGuiStyleVar_FramePadding, ImVec2(10, 4));
- for (const auto t : tabs) {
- const bool active = (t == bottom_tab_);
-
- // Get count for badge
- int count = 0;
- switch (t) {
- case BottomTab::positions: count = static_cast<int>(positions_.size()); break;
- case BottomTab::holdings: count = static_cast<int>(holdings_.size()); break;
- case BottomTab::orders: count = static_cast<int>(orders_.size()); break;
- default: break;
- }
-
- if (active) {
- ImGui::PushStyleColor(ImGuiCol_Button, ImVec4(0, 0, 0, 0));
- ImGui::PushStyleColor(ImGuiCol_Text, ACCENT);
- } else {
- ImGui::PushStyleColor(ImGuiCol_Button, ImVec4(0, 0, 0, 0));
- ImGui::PushStyleColor(ImGuiCol_Text, TEXT_DIM);
- }
-
- char tab_label[64];
- if (count > 0)
- std::snprintf(tab_label, sizeof(tab_label), "%s (%d)", bottom_tab_label(t), count);
- else
- std::snprintf(tab_label, sizeof(tab_label), "%s", bottom_tab_label(t));
-
- if (ImGui::SmallButton(tab_label)) {
- bottom_tab_ = t;
- }
-
- // Active underline
- if (active) {
- const ImVec2 btn_min = ImGui::GetItemRectMin();
- const ImVec2 btn_max = ImGui::GetItemRectMax();
- auto* draw = ImGui::GetWindowDrawList();
- draw->AddLine({btn_min.x, btn_max.y}, {btn_max.x, btn_max.y},
- ImGui::ColorConvertFloat4ToU32(ACCENT), 2.0f);
- }
-
- ImGui::PopStyleColor(2);
- ImGui::SameLine(0.0f, 2.0f);
+ if (f.type == trading::OrderType::StopLoss || f.type == trading::OrderType::StopLossLimit) {
+ ImGui::Text("Stop Price"); ImGui::SameLine(120); ImGui::SetNextItemWidth(160);
+ ImGui::InputDouble("##sp", &f.stop_price, 0.05, 1.0, "%.2f");
}
- ImGui::PopStyleVar();
-
- // Refresh button (right-aligned)
- ImGui::SameLine(w - 80.0f);
- ImGui::PushStyleColor(ImGuiCol_Button, BG_WIDGET);
- ImGui::PushStyleColor(ImGuiCol_ButtonHovered, BG_HOVER);
- if (ImGui::SmallButton("Refresh")) {
- refresh_portfolio();
- }
- ImGui::PopStyleColor(2);
-
- eq_draw_separator_line(w - 16.0f);
-
- const float content_h = h - 50.0f;
- switch (bottom_tab_) {
- case BottomTab::positions: render_positions_table(w, content_h); break;
- case BottomTab::holdings: render_holdings_table(w, content_h); break;
- case BottomTab::orders: render_orders_table(w, content_h); break;
- case BottomTab::history: render_orders_table(w, content_h); break;
- case BottomTab::brokers: render_broker_config(w, content_h); break;
- }
+ ImGui::Spacing(); ImGui::Separator(); ImGui::Spacing();
+ if (has_quote_) ImGui::TextColored(TEXT_DIM, "LTP: %.2f | %s", quote_.ltp, paper_mode_ ? "PAPER" : "LIVE");
- ImGui::EndChild();
- ImGui::PopStyleVar();
+ bool is_buy = (f.side == trading::OrderSide::Buy);
+ ImGui::PushStyleColor(ImGuiCol_Button, is_buy ? ImVec4(0.05f,0.55f,0.25f,1) : ImVec4(0.65f,0.15f,0.15f,1));
+ char ob[48]; std::snprintf(ob, sizeof(ob), " %s %.0f x %s ", is_buy?"BUY":"SELL", f.quantity, f.symbol_buf);
+ if (ImGui::Button(ob)) place_order();
ImGui::PopStyleColor();
}
-// ============================================================================
-// Positions Table — with P&L summary row
-// ============================================================================
-
-void EquityTradingScreen::render_positions_table(float w, float h) {
- if (loading_portfolio_) {
- theme::LoadingSpinner("Loading positions...");
- return;
- }
- if (positions_.empty()) {
- ImGui::Spacing();
- ImGui::TextColored(TEXT_DIM, " No open positions");
- ImGui::TextColored(TEXT_DISABLED, " Place an order to see positions here");
- return;
- }
-
- // P&L summary bar
- double total_pnl = 0.0;
- double total_day = 0.0;
- for (const auto& p : positions_) {
- total_pnl += p.pnl;
- total_day += p.day_pnl;
- }
-
- {
- const ImVec4& pnl_col = (total_pnl >= 0.0) ? MARKET_GREEN : MARKET_RED;
- const ImVec4& day_col = (total_day >= 0.0) ? MARKET_GREEN : MARKET_RED;
- ImGui::TextColored(TEXT_DIM, "Total P&L:");
- ImGui::SameLine();
- ImGui::TextColored(pnl_col, "%+.2f", total_pnl);
- ImGui::SameLine(0.0f, 20.0f);
- ImGui::TextColored(TEXT_DIM, "Day:");
- ImGui::SameLine();
- ImGui::TextColored(day_col, "%+.2f", total_day);
- ImGui::SameLine(0.0f, 20.0f);
- ImGui::TextColored(TEXT_DIM, "%d positions", static_cast<int>(positions_.size()));
- }
-
- ImGui::Spacing();
-
- if (ImGui::BeginTable("##pos_tbl", 7,
- ImGuiTableFlags_RowBg | ImGuiTableFlags_ScrollY | ImGuiTableFlags_Borders |
- ImGuiTableFlags_SizingStretchProp | ImGuiTableFlags_Sortable, ImVec2(0, h - 28.0f))) {
- ImGui::TableSetupColumn("Symbol", ImGuiTableColumnFlags_None, 0.18f);
- ImGui::TableSetupColumn("Side", ImGuiTableColumnFlags_None, 0.08f);
- ImGui::TableSetupColumn("Qty", ImGuiTableColumnFlags_None, 0.10f);
- ImGui::TableSetupColumn("Avg", ImGuiTableColumnFlags_None, 0.14f);
- ImGui::TableSetupColumn("LTP", ImGuiTableColumnFlags_None, 0.14f);
- ImGui::TableSetupColumn("P&L", ImGuiTableColumnFlags_DefaultSort, 0.18f);
- ImGui::TableSetupColumn("Day P&L", ImGuiTableColumnFlags_None, 0.18f);
+// ═══════════════════════════════════════════════════════════════════════
+// Positions
+// ═══════════════════════════════════════════════════════════════════════
+void EquityTradingScreen::section_positions() {
+ ImGui::Text("Open Positions");
+ ImGui::SameLine(0,20);
+ if (ImGui::Button("Refresh##pos")) { paper_mode_ ? refresh_paper_portfolio() : refresh_portfolio(); }
+ ImGui::Separator();
+ if (positions_.empty()) { ImGui::TextColored(TEXT_DIM, "No open positions."); return; }
+ if (ImGui::BeginTable("##pos", 6, ImGuiTableFlags_Borders | ImGuiTableFlags_RowBg)) {
+ ImGui::TableSetupColumn("Symbol"); ImGui::TableSetupColumn("Side");
+ ImGui::TableSetupColumn("Qty"); ImGui::TableSetupColumn("Avg");
+ ImGui::TableSetupColumn("LTP"); ImGui::TableSetupColumn("P&L");
ImGui::TableHeadersRow();
-
- for (const auto& pos : positions_) {
+ for (auto& p : positions_) {
ImGui::TableNextRow();
- ImGui::TableNextColumn();
- ImGui::TextColored(TEXT_PRIMARY, "%s", pos.symbol.c_str());
-
- ImGui::TableNextColumn();
- const ImVec4& side_col = (pos.side == "buy") ? MARKET_GREEN : MARKET_RED;
- ImGui::TextColored(side_col, "%s", pos.side == "buy" ? "BUY" : "SELL");
-
- ImGui::TableNextColumn();
- ImGui::Text("%.0f", pos.quantity);
-
- ImGui::TableNextColumn();
- ImGui::Text("%.2f", pos.avg_price);
-
- ImGui::TableNextColumn();
- ImGui::Text("%.2f", pos.ltp);
-
- ImGui::TableNextColumn();
- const ImVec4& pnl_col = (pos.pnl >= 0.0) ? MARKET_GREEN : MARKET_RED;
- ImGui::TextColored(pnl_col, "%+.2f", pos.pnl);
-
- ImGui::TableNextColumn();
- const ImVec4& day_col = (pos.day_pnl >= 0.0) ? MARKET_GREEN : MARKET_RED;
- ImGui::TextColored(day_col, "%+.2f", pos.day_pnl);
+ ImGui::TableSetColumnIndex(0); ImGui::Text("%s", p.symbol.c_str());
+ ImGui::TableSetColumnIndex(1); ImGui::TextColored(p.side=="buy"?C_GRN:C_RED, "%s", p.side.c_str());
+ ImGui::TableSetColumnIndex(2); ImGui::Text("%.0f", p.quantity);
+ ImGui::TableSetColumnIndex(3); ImGui::Text("%.2f", p.avg_price);
+ ImGui::TableSetColumnIndex(4); ImGui::Text("%.2f", p.ltp);
+ ImGui::TableSetColumnIndex(5); ImGui::TextColored(p.pnl>=0?C_GRN:C_RED, "%+.2f", p.pnl);
}
ImGui::EndTable();
}
}
-// ============================================================================
-// Holdings Table — with investment summary
-// ============================================================================
-
-void EquityTradingScreen::render_holdings_table(float w, float h) {
- if (loading_portfolio_) {
- theme::LoadingSpinner("Loading holdings...");
- return;
- }
- if (holdings_.empty()) {
- ImGui::Spacing();
- ImGui::TextColored(TEXT_DIM, " No holdings");
- ImGui::TextColored(TEXT_DISABLED, " Delivery positions will appear here");
- return;
- }
-
- // Summary bar
- double total_invested = 0.0;
- double total_current = 0.0;
- double total_pnl = 0.0;
- for (const auto& h : holdings_) {
- total_invested += h.invested_value;
- total_current += h.current_value;
- total_pnl += h.pnl;
- }
- const double total_pct = (total_invested > 0.0) ? (total_pnl / total_invested) * 100.0 : 0.0;
-
- {
- const ImVec4& col = (total_pnl >= 0.0) ? MARKET_GREEN : MARKET_RED;
- ImGui::TextColored(TEXT_DIM, "Invested:");
- ImGui::SameLine();
- ImGui::TextColored(TEXT_SECONDARY, "%.2f", total_invested);
- ImGui::SameLine(0.0f, 12.0f);
- ImGui::TextColored(TEXT_DIM, "Current:");
- ImGui::SameLine();
- ImGui::TextColored(TEXT_SECONDARY, "%.2f", total_current);
- ImGui::SameLine(0.0f, 12.0f);
- ImGui::TextColored(TEXT_DIM, "P&L:");
- ImGui::SameLine();
- ImGui::TextColored(col, "%+.2f (%+.2f%%)", total_pnl, total_pct);
- }
-
- ImGui::Spacing();
-
- if (ImGui::BeginTable("##hold_tbl", 7,
- ImGuiTableFlags_RowBg | ImGuiTableFlags_ScrollY | ImGuiTableFlags_Borders |
- ImGuiTableFlags_SizingStretchProp, ImVec2(0, h - 28.0f))) {
- ImGui::TableSetupColumn("Symbol", ImGuiTableColumnFlags_None, 0.18f);
- ImGui::TableSetupColumn("Qty", ImGuiTableColumnFlags_None, 0.08f);
- ImGui::TableSetupColumn("Avg", ImGuiTableColumnFlags_None, 0.14f);
- ImGui::TableSetupColumn("LTP", ImGuiTableColumnFlags_None, 0.14f);
- ImGui::TableSetupColumn("Invested", ImGuiTableColumnFlags_None, 0.16f);
- ImGui::TableSetupColumn("P&L", ImGuiTableColumnFlags_None, 0.16f);
- ImGui::TableSetupColumn("P&L%", ImGuiTableColumnFlags_None, 0.14f);
+// ═══════════════════════════════════════════════════════════════════════
+// Orders
+// ═══════════════════════════════════════════════════════════════════════
+void EquityTradingScreen::section_orders() {
+ ImGui::Text("Order Book");
+ ImGui::SameLine(0,20);
+ if (ImGui::Button("Refresh##ord")) { paper_mode_ ? refresh_paper_portfolio() : refresh_portfolio(); }
+ ImGui::Separator();
+ if (orders_.empty()) { ImGui::TextColored(TEXT_DIM, "No orders."); return; }
+ if (ImGui::BeginTable("##ord", 7, ImGuiTableFlags_Borders | ImGuiTableFlags_RowBg)) {
+ ImGui::TableSetupColumn("Symbol", ImGuiTableColumnFlags_WidthFixed, 100);
+ ImGui::TableSetupColumn("Side", ImGuiTableColumnFlags_WidthFixed, 50);
+ ImGui::TableSetupColumn("Type", ImGuiTableColumnFlags_WidthFixed, 70);
+ ImGui::TableSetupColumn("Qty", ImGuiTableColumnFlags_WidthFixed, 60);
+ ImGui::TableSetupColumn("Price", ImGuiTableColumnFlags_WidthFixed, 70);
+ ImGui::TableSetupColumn("Status", ImGuiTableColumnFlags_WidthFixed, 80);
+ ImGui::TableSetupColumn("Actions", ImGuiTableColumnFlags_WidthStretch);
ImGui::TableHeadersRow();
-
- for (const auto& hld : holdings_) {
+ for (auto& o : orders_) {
ImGui::TableNextRow();
- ImGui::TableNextColumn();
- ImGui::TextColored(TEXT_PRIMARY, "%s", hld.symbol.c_str());
-
- ImGui::TableNextColumn();
- ImGui::Text("%.0f", hld.quantity);
-
- ImGui::TableNextColumn();
- ImGui::Text("%.2f", hld.avg_price);
-
- ImGui::TableNextColumn();
- ImGui::Text("%.2f", hld.ltp);
-
- ImGui::TableNextColumn();
- ImGui::TextColored(TEXT_SECONDARY, "%.2f", hld.invested_value);
-
- ImGui::TableNextColumn();
- const ImVec4& c = (hld.pnl >= 0.0) ? MARKET_GREEN : MARKET_RED;
- ImGui::TextColored(c, "%+.2f", hld.pnl);
-
- ImGui::TableNextColumn();
- ImGui::TextColored(c, "%+.2f%%", hld.pnl_pct);
+ ImGui::TableSetColumnIndex(0); ImGui::Text("%s", o.symbol.c_str());
+ ImGui::TableSetColumnIndex(1); ImGui::TextColored(o.side=="buy"?C_GRN:C_RED, "%s", o.side.c_str());
+ ImGui::TableSetColumnIndex(2); ImGui::Text("%s", o.order_type.c_str());
+ ImGui::TableSetColumnIndex(3); ImGui::Text("%.0f", o.quantity);
+ ImGui::TableSetColumnIndex(4); ImGui::Text("%.2f", o.price);
+ ImGui::TableSetColumnIndex(5);
+ ImVec4 sc = TEXT_DIM;
+ if (o.status=="filled") sc=C_GRN; else if (o.status=="cancelled") sc=C_RED; else if (o.status=="pending") sc=C_YEL;
+ ImGui::TextColored(sc, "%s", o.status.c_str());
+ ImGui::TableSetColumnIndex(6);
+ bool is_active = (o.status=="pending" || o.status=="open" || o.status=="trigger pending");
+ if (is_active) {
+ char ml[48]; std::snprintf(ml, sizeof(ml), "Modify##mo_%s", o.order_id.c_str());
+ if (ImGui::SmallButton(ml)) {
+ modify_state_.order_id = o.order_id;
+ modify_state_.price = o.price;
+ modify_state_.qty = o.quantity;
+ modify_state_.trigger_price = 0.0;
+ modify_state_.open = true;
+ ImGui::OpenPopup("Modify Order");
+ }
+ ImGui::SameLine(0, 4);
+ char cl[48]; std::snprintf(cl, sizeof(cl), "Cancel##co_%s", o.order_id.c_str());
+ ImGui::PushStyleColor(ImGuiCol_Button, ImVec4(0.55f,0.12f,0.12f,1));
+ if (ImGui::SmallButton(cl)) cancel_order_async(o.order_id);
+ ImGui::PopStyleColor();
+ }
}
ImGui::EndTable();
}
-}
-
-// ============================================================================
-// Orders Table — with status badges
-// ============================================================================
-void EquityTradingScreen::render_orders_table(float w, float h) {
- if (loading_portfolio_) {
- theme::LoadingSpinner("Loading orders...");
- return;
- }
- if (orders_.empty()) {
+ // Modify Order popup
+ if (ImGui::BeginPopupModal("Modify Order", nullptr, ImGuiWindowFlags_AlwaysAutoResize)) {
+ ImGui::Text("Order: %s", modify_state_.order_id.c_str());
+ ImGui::Separator();
+ ImGui::Text("Price"); ImGui::SameLine(120); ImGui::SetNextItemWidth(140);
+ ImGui::InputDouble("##mp", &modify_state_.price, 0.05, 1.0, "%.2f");
+ ImGui::Text("Quantity"); ImGui::SameLine(120); ImGui::SetNextItemWidth(140);
+ ImGui::InputDouble("##mq", &modify_state_.qty, 1.0, 10.0, "%.0f");
+ ImGui::Text("Stop Price"); ImGui::SameLine(120); ImGui::SetNextItemWidth(140);
+ ImGui::InputDouble("##mt", &modify_state_.trigger_price, 0.05, 1.0, "%.2f");
ImGui::Spacing();
- ImGui::TextColored(TEXT_DIM, " No orders");
- ImGui::TextColored(TEXT_DISABLED, " Place an order to see it here");
- return;
- }
-
- if (ImGui::BeginTable("##ord_tbl", 7,
- ImGuiTableFlags_RowBg | ImGuiTableFlags_ScrollY | ImGuiTableFlags_Borders |
- ImGuiTableFlags_SizingStretchProp, ImVec2(0, h))) {
- ImGui::TableSetupColumn("Symbol", ImGuiTableColumnFlags_None, 0.15f);
- ImGui::TableSetupColumn("Side", ImGuiTableColumnFlags_None, 0.08f);
- ImGui::TableSetupColumn("Type", ImGuiTableColumnFlags_None, 0.10f);
- ImGui::TableSetupColumn("Qty", ImGuiTableColumnFlags_None, 0.10f);
- ImGui::TableSetupColumn("Price", ImGuiTableColumnFlags_None, 0.14f);
- ImGui::TableSetupColumn("Status", ImGuiTableColumnFlags_None, 0.13f);
- ImGui::TableSetupColumn("Time", ImGuiTableColumnFlags_None, 0.30f);
- ImGui::TableHeadersRow();
-
- for (const auto& ord : orders_) {
- ImGui::TableNextRow();
- ImGui::TableNextColumn();
- ImGui::TextColored(TEXT_PRIMARY, "%s", ord.symbol.c_str());
-
- ImGui::TableNextColumn();
- const ImVec4& sc = (ord.side == "buy" || ord.side == "BUY") ? MARKET_GREEN : MARKET_RED;
- const char* side_str = (ord.side == "buy" || ord.side == "BUY") ? "BUY" : "SELL";
- ImGui::TextColored(sc, "%s", side_str);
-
- ImGui::TableNextColumn();
- ImGui::TextColored(TEXT_SECONDARY, "%s", ord.order_type.c_str());
-
- ImGui::TableNextColumn();
- ImGui::Text("%.0f/%.0f", ord.filled_qty, ord.quantity);
-
- ImGui::TableNextColumn();
- if (ord.avg_price > 0.0)
- ImGui::Text("%.2f", ord.avg_price);
- else
- ImGui::Text("%.2f", ord.price);
-
- ImGui::TableNextColumn();
- // Status badge
- ImVec4 status_col = TEXT_SECONDARY;
- if (ord.status == "filled" || ord.status == "complete") status_col = MARKET_GREEN;
- else if (ord.status == "pending" || ord.status == "open") status_col = WARNING;
- else if (ord.status == "cancelled" || ord.status == "rejected") status_col = MARKET_RED;
- else if (ord.status == "partially_filled") status_col = INFO;
- ImGui::TextColored(status_col, "%s", ord.status.c_str());
-
- ImGui::TableNextColumn();
- ImGui::TextColored(TEXT_DIM, "%s", ord.timestamp.c_str());
+ ImGui::PushStyleColor(ImGuiCol_Button, ImVec4(0.10f,0.50f,0.80f,1));
+ if (ImGui::Button("Modify##confirm", {120,0})) {
+ modify_order_async(modify_state_.order_id,
+ modify_state_.price,
+ modify_state_.qty,
+ modify_state_.trigger_price);
+ modify_state_.open = false;
+ ImGui::CloseCurrentPopup();
}
- ImGui::EndTable();
+ ImGui::PopStyleColor();
+ ImGui::SameLine(0,8);
+ if (ImGui::Button("Cancel##modcancel", {80,0})) {
+ modify_state_.open = false;
+ ImGui::CloseCurrentPopup();
+ }
+ ImGui::EndPopup();
}
}
-// ============================================================================
-// Broker Configuration Panel — card-style grid with regions
-// ============================================================================
-
-void EquityTradingScreen::render_broker_config(float w, float h) {
- // Header
- ImGui::TextColored(ACCENT, "BROKER CONNECTIONS");
- ImGui::SameLine(w - 160.0f);
- ImGui::TextColored(TEXT_DIM, "16 brokers available");
-
- eq_draw_separator_line(w - 16.0f);
- ImGui::Spacing();
-
- struct BrokerInfo { trading::BrokerId id; const char* name; const char* region; };
- static constexpr BrokerInfo known_brokers[] = {
- // Indian brokers (12)
- {trading::BrokerId::Fyers, "Fyers", "India"},
- {trading::BrokerId::Zerodha, "Zerodha", "India"},
- {trading::BrokerId::AngelOne, "Angel One", "India"},
- {trading::BrokerId::Upstox, "Upstox", "India"},
- {trading::BrokerId::Dhan, "Dhan", "India"},
- {trading::BrokerId::Kotak, "Kotak", "India"},
- {trading::BrokerId::Groww, "Groww", "India"},
- {trading::BrokerId::AliceBlue, "AliceBlue", "India"},
- {trading::BrokerId::FivePaisa, "5Paisa", "India"},
- {trading::BrokerId::IIFL, "IIFL", "India"},
- {trading::BrokerId::Motilal, "Motilal", "India"},
- {trading::BrokerId::Shoonya, "Shoonya", "India"},
- // US brokers (3)
- {trading::BrokerId::Alpaca, "Alpaca", "US"},
- {trading::BrokerId::IBKR, "IBKR", "US"},
- {trading::BrokerId::Tradier, "Tradier", "US"},
- // EU brokers (1)
- {trading::BrokerId::SaxoBank, "Saxo Bank", "EU"},
- };
-
- if (ImGui::BeginTable("##broker_grid", 5,
- ImGuiTableFlags_RowBg | ImGuiTableFlags_Borders |
- ImGuiTableFlags_SizingStretchProp | ImGuiTableFlags_ScrollY,
- ImVec2(0, h - 30.0f))) {
- ImGui::TableSetupColumn("Broker", ImGuiTableColumnFlags_None, 0.22f);
- ImGui::TableSetupColumn("Region", ImGuiTableColumnFlags_None, 0.12f);
- ImGui::TableSetupColumn("Status", ImGuiTableColumnFlags_None, 0.18f);
- ImGui::TableSetupColumn("Credentials", ImGuiTableColumnFlags_None, 0.18f);
- ImGui::TableSetupColumn("Action", ImGuiTableColumnFlags_None, 0.30f);
- ImGui::TableHeadersRow();
-
- const char* last_region = nullptr;
-
- for (const auto& b : known_brokers) {
- // Region separator row
- if (!last_region || std::strcmp(last_region, b.region) != 0) {
- if (last_region) {
- ImGui::TableNextRow();
- ImGui::TableNextColumn();
- ImGui::Spacing();
- }
- last_region = b.region;
- }
-
- ImGui::TableNextRow();
-
- // Broker name
- ImGui::TableNextColumn();
- ImGui::TextColored(TEXT_PRIMARY, "%s", b.name);
-
- // Region pill
- ImGui::TableNextColumn();
- ImGui::TextColored(eq_region_color(b.region), "%s", b.region);
-
- // Status
- ImGui::TableNextColumn();
- const bool connected = (active_broker_.has_value() && *active_broker_ == b.id && is_connected_);
- if (connected) {
- ImGui::TextColored(MARKET_GREEN, "Connected");
- } else {
- ImGui::TextColored(TEXT_DISABLED, "Offline");
- }
-
- // Credential status
- ImGui::TableNextColumn();
- {
- auto* broker = trading::BrokerRegistry::instance().get(b.id);
- if (broker) {
- auto creds = broker->load_credentials();
- if (!creds.api_key.empty()) {
- ImGui::TextColored(SUCCESS, "Configured");
- } else {
- ImGui::TextColored(TEXT_DISABLED, "Not set");
- }
- }
- }
-
- // Action buttons
- ImGui::TableNextColumn();
- char btn_id[64];
- if (!connected) {
- std::snprintf(btn_id, sizeof(btn_id), "Connect##%s", b.name);
- ImGui::PushStyleColor(ImGuiCol_Button, BUY_GREEN);
- ImGui::PushStyleColor(ImGuiCol_ButtonHovered, BUY_GREEN_HOVER);
- ImGui::PushStyleColor(ImGuiCol_Text, ImVec4(1, 1, 1, 1));
- if (ImGui::SmallButton(btn_id)) {
- connect_broker(b.id);
- }
- ImGui::PopStyleColor(3);
- } else {
- std::snprintf(btn_id, sizeof(btn_id), "Disconnect##%s", b.name);
- ImGui::PushStyleColor(ImGuiCol_Button, SELL_RED);
- ImGui::PushStyleColor(ImGuiCol_ButtonHovered, SELL_RED_HOVER);
- ImGui::PushStyleColor(ImGuiCol_Text, ImVec4(1, 1, 1, 1));
- if (ImGui::SmallButton(btn_id)) {
- is_connected_ = false;
- active_broker_ = std::nullopt;
- }
- ImGui::PopStyleColor(3);
+// ═══════════════════════════════════════════════════════════════════════
+// Funds
+// ═══════════════════════════════════════════════════════════════════════
+void EquityTradingScreen::section_funds() {
+ ImGui::Text("Funds / Portfolio");
+ ImGui::Separator();
+ if (paper_mode_ && !paper_id_.empty()) {
+ try {
+ auto p = trading::pt_get_portfolio(paper_id_);
+ ImGui::Text("Portfolio: %s", p.name.c_str());
+ ImGui::Text("Balance: %.2f %s", p.balance, p.currency.c_str());
+ ImGui::Text("Initial: %.2f", p.initial_balance);
+ double pnl = p.balance - p.initial_balance;
+ ImGui::TextColored(pnl>=0?C_GRN:C_RED, "Net P&L: %+.2f", pnl);
+ ImGui::Spacing();
+ if (ImGui::Button("Reset Paper Portfolio")) {
+ trading::pt_reset_portfolio(paper_id_);
+ refresh_paper_portfolio();
+ set_status("Paper portfolio reset.");
}
- }
- ImGui::EndTable();
+ } catch (...) { ImGui::TextColored(C_RED, "Failed to load portfolio."); }
+ } else if (funds_) {
+ ImGui::Text("Available: %.2f", funds_->available_balance);
+ ImGui::Text("Used Margin: %.2f", funds_->used_margin);
+ ImGui::Text("Total: %.2f", funds_->total_balance);
+ } else {
+ ImGui::TextColored(TEXT_DIM, "Connect a broker to see live funds.");
}
}
-// ============================================================================
-// Order Entry Panel — improved buy/sell toggle, margin bar
-// ============================================================================
-
-void EquityTradingScreen::render_order_entry(float x, float y, float w, float h) {
- ImGui::SetCursorPos(ImVec2(x, y));
- ImGui::PushStyleColor(ImGuiCol_ChildBg, BG_PANEL);
- ImGui::PushStyleVar(ImGuiStyleVar_WindowPadding, ImVec2(10, 8));
- ImGui::BeginChild("##eq_order", ImVec2(w, h), true);
-
- ImGui::TextColored(ACCENT, "ORDER ENTRY");
- eq_draw_separator_line(w - 20.0f);
- ImGui::Spacing();
-
- const float input_w = w - 28.0f;
- const bool is_buy = (order_form_.side == trading::OrderSide::Buy);
-
- // Buy / Sell toggle — full width, colored backgrounds
- {
- const float half_w = input_w * 0.49f;
- const float btn_h = 32.0f;
-
- // BUY button
- if (is_buy) {
- ImGui::PushStyleColor(ImGuiCol_Button, BUY_GREEN);
- ImGui::PushStyleColor(ImGuiCol_ButtonHovered, BUY_GREEN_HOVER);
- ImGui::PushStyleColor(ImGuiCol_Text, ImVec4(1, 1, 1, 1));
- } else {
- ImGui::PushStyleColor(ImGuiCol_Button, BG_WIDGET);
- ImGui::PushStyleColor(ImGuiCol_ButtonHovered, BG_HOVER);
- ImGui::PushStyleColor(ImGuiCol_Text, TEXT_DIM);
- }
- if (ImGui::Button("BUY", ImVec2(half_w, btn_h))) {
- order_form_.side = trading::OrderSide::Buy;
- }
- ImGui::PopStyleColor(3);
-
- ImGui::SameLine(0.0f, input_w * 0.02f);
-
- // SELL button
- if (!is_buy) {
- ImGui::PushStyleColor(ImGuiCol_Button, SELL_RED);
- ImGui::PushStyleColor(ImGuiCol_ButtonHovered, SELL_RED_HOVER);
- ImGui::PushStyleColor(ImGuiCol_Text, ImVec4(1, 1, 1, 1));
- } else {
- ImGui::PushStyleColor(ImGuiCol_Button, BG_WIDGET);
- ImGui::PushStyleColor(ImGuiCol_ButtonHovered, BG_HOVER);
- ImGui::PushStyleColor(ImGuiCol_Text, TEXT_DIM);
- }
- if (ImGui::Button("SELL", ImVec2(half_w, btn_h))) {
- order_form_.side = trading::OrderSide::Sell;
- }
- ImGui::PopStyleColor(3);
- }
-
+// ═══════════════════════════════════════════════════════════════════════
+// Brokers
+// ═══════════════════════════════════════════════════════════════════════
+void EquityTradingScreen::section_brokers() {
+ ImGui::Text("Broker Configuration");
+ ImGui::Separator();
ImGui::Spacing();
- // Symbol
- ImGui::TextColored(TEXT_DIM, "Symbol");
- ImGui::SetNextItemWidth(input_w);
- ImGui::InputText("##ord_sym", order_form_.symbol_buf, sizeof(order_form_.symbol_buf),
- ImGuiInputTextFlags_CharsUppercase);
-
- // Order type
- ImGui::TextColored(TEXT_DIM, "Type");
- ImGui::SetNextItemWidth(input_w);
- static constexpr const char* type_labels[] = {"Market", "Limit", "Stop Loss", "SL Limit"};
- int type_idx = static_cast<int>(order_form_.type);
- if (ImGui::Combo("##ord_type", &type_idx, type_labels, 4)) {
- order_form_.type = static_cast<trading::OrderType>(type_idx);
- }
-
- // Product type
- ImGui::TextColored(TEXT_DIM, "Product");
- ImGui::SetNextItemWidth(input_w);
- static constexpr const char* prod_labels[] = {"Intraday", "Delivery", "Margin", "Cover", "Bracket"};
- int prod_idx = static_cast<int>(order_form_.product);
- if (ImGui::Combo("##ord_prod", &prod_idx, prod_labels, 5)) {
- order_form_.product = static_cast<trading::ProductType>(prod_idx);
- }
-
- // Quantity
- ImGui::TextColored(TEXT_DIM, "Quantity");
- ImGui::SetNextItemWidth(input_w);
- ImGui::InputDouble("##ord_qty", &order_form_.quantity, 1.0, 10.0, "%.0f");
-
- // Price (for limit/SL orders)
- if (order_form_.type != trading::OrderType::Market) {
- ImGui::TextColored(TEXT_DIM, "Price");
- ImGui::SetNextItemWidth(input_w);
- ImGui::InputDouble("##ord_price", &order_form_.price, 0.05, 1.0, "%.2f");
- }
-
- // Stop price
- if (order_form_.type == trading::OrderType::StopLoss ||
- order_form_.type == trading::OrderType::StopLossLimit) {
- ImGui::TextColored(TEXT_DIM, "Trigger Price");
- ImGui::SetNextItemWidth(input_w);
- ImGui::InputDouble("##ord_trigger", &order_form_.stop_price, 0.05, 1.0, "%.2f");
- }
-
+ // Broker radio buttons
+ const char* last_rgn = nullptr;
+ for (int i = 0; i < BROKER_META_COUNT; ++i) {
+ const auto& m = BROKER_META[i];
+ if (!last_rgn || std::strcmp(last_rgn, m.region) != 0) {
+ if (last_rgn) { ImGui::Spacing(); ImGui::Spacing(); }
+ ImGui::TextColored(TEXT_DIM, "%s:", m.region);
+ ImGui::SameLine(60);
+ last_rgn = m.region;
+ } else { ImGui::SameLine(); }
+ bool conn = (active_broker_ && *active_broker_ == m.id && connected_);
+ char lbl[64]; std::snprintf(lbl, sizeof(lbl), "%s%s", conn?"* ":"", m.name);
+ if (ImGui::RadioButton(lbl, broker_sel_ == i)) broker_sel_ = i;
+ }
+
+ ImGui::Spacing(); ImGui::Separator(); ImGui::Spacing();
+
+ if (broker_sel_ < 0) { ImGui::TextColored(TEXT_DIM, "Select a broker above."); return; }
+
+ int idx = broker_sel_;
+ const auto& m = BROKER_META[idx];
+ auto& ci = cred_ui_[idx];
+ bool conn = (active_broker_ && *active_broker_ == m.id && connected_);
+
+ ImGui::Text("%s (%s)", m.name, m.region);
+ ImGui::TextColored(TEXT_DIM, "Auth: %s",
+ m.auth_type==BrokerAuthType::OAuth?"OAuth":m.auth_type==BrokerAuthType::TOTP?"TOTP":"API Key");
ImGui::Spacing();
- eq_draw_separator_line(input_w);
- ImGui::Spacing();
-
- // Estimated value & available funds
- const double est_value = order_form_.quantity *
- (order_form_.type == trading::OrderType::Market ? current_quote_.ltp : order_form_.price);
- if (est_value > 0.0) {
- ImGui::TextColored(TEXT_DIM, "Est. Value");
- ImGui::SameLine(input_w * 0.5f);
- ImGui::TextColored(TEXT_PRIMARY, "%.2f", est_value);
+ // Credential fields
+ ImGui::Text("%s", m.api_key_label[0] ? m.api_key_label : "API Key");
+ ImGui::SameLine(150); ImGui::SetNextItemWidth(250);
+ char kl[32]; std::snprintf(kl,sizeof(kl),"##ak_%d",idx);
+ ImGui::InputText(kl, ci.api_key, sizeof(ci.api_key));
+
+ if (m.api_secret_label[0]) {
+ ImGui::Text("%s", m.api_secret_label);
+ ImGui::SameLine(150); ImGui::SetNextItemWidth(250);
+ char sl[32]; std::snprintf(sl,sizeof(sl),"##as_%d",idx);
+ ImGui::InputText(sl, ci.api_secret, sizeof(ci.api_secret), ci.show_secret?0:ImGuiInputTextFlags_Password);
+ ImGui::SameLine();
+ if (ImGui::SmallButton(ci.show_secret?"Hide":"Show")) ci.show_secret = !ci.show_secret;
+ }
+ if (m.needs_user_id && m.user_id_label[0]) {
+ ImGui::Text("%s", m.user_id_label);
+ ImGui::SameLine(150); ImGui::SetNextItemWidth(250);
+ char ul[32]; std::snprintf(ul,sizeof(ul),"##uid_%d",idx);
+ ImGui::InputText(ul, ci.user_id, sizeof(ci.user_id));
+ }
+ if (m.needs_password && m.password_label[0]) {
+ ImGui::Text("%s", m.password_label);
+ ImGui::SameLine(150); ImGui::SetNextItemWidth(250);
+ char pl[32]; std::snprintf(pl,sizeof(pl),"##pw_%d",idx);
+ ImGui::InputText(pl, ci.password, sizeof(ci.password), ci.show_pw?0:ImGuiInputTextFlags_Password);
+ }
+ if (m.needs_totp) {
+ ImGui::Text("TOTP Secret");
+ ImGui::SameLine(150); ImGui::SetNextItemWidth(250);
+ char tl[32]; std::snprintf(tl,sizeof(tl),"##totp_%d",idx);
+ ImGui::InputText(tl, ci.totp_secret, sizeof(ci.totp_secret));
+ ImGui::Spacing();
+ ImGui::Text("TOTP Code");
+ ImGui::SameLine(150); ImGui::SetNextItemWidth(120);
+ char tcl[32]; std::snprintf(tcl,sizeof(tcl),"##tcode_%d",idx);
+ ImGui::InputText(tcl, ci.auth_code, sizeof(ci.auth_code));
+ ImGui::SameLine(); ImGui::TextColored(TEXT_DIM, "(6-digit, refresh each 30s)");
}
- if (funds_.has_value()) {
- ImGui::TextColored(TEXT_DIM, "Available");
- ImGui::SameLine(input_w * 0.5f);
- ImGui::TextColored(MARKET_GREEN, "%.2f", funds_->available_balance);
-
- // Margin usage bar
- if (funds_->total_balance > 0.0) {
- const float usage = static_cast<float>(funds_->used_margin / funds_->total_balance);
- ImGui::Spacing();
-
- const ImVec2 bar_pos = ImGui::GetCursorScreenPos();
- const float bar_h = 4.0f;
- auto* draw = ImGui::GetWindowDrawList();
-
- // Background
- draw->AddRectFilled(bar_pos, {bar_pos.x + input_w, bar_pos.y + bar_h},
- IM_COL32(40, 40, 48, 200), 2.0f);
+ ImGui::Spacing(); ImGui::Separator(); ImGui::Spacing();
- // Used portion
- const ImU32 usage_col = (usage < 0.7f) ? IM_COL32(13, 180, 100, 200) :
- (usage < 0.9f) ? IM_COL32(255, 199, 20, 200) :
- IM_COL32(245, 64, 64, 200);
- draw->AddRectFilled(bar_pos, {bar_pos.x + input_w * usage, bar_pos.y + bar_h},
- usage_col, 2.0f);
-
- ImGui::Dummy({input_w, bar_h + 2.0f});
- ImGui::TextColored(TEXT_DIM, "Margin: %.0f%%", usage * 100.0f);
+ // OAuth
+ if (m.auth_type == BrokerAuthType::OAuth) {
+ if (!ci.oauth_url.empty()) {
+ ImGui::TextWrapped("Step 1: Open URL:");
+ ImGui::PushStyleColor(ImGuiCol_Text, ACCENT);
+ ImGui::TextWrapped("%s", ci.oauth_url.c_str());
+ ImGui::PopStyleColor();
+ if (ImGui::IsItemHovered()) { ImGui::SetMouseCursor(ImGuiMouseCursor_Hand); ImGui::SetTooltip("Click to open in browser"); }
+ if (ImGui::IsItemClicked()) {
+#ifdef _WIN32
+ ShellExecuteA(nullptr, "open", ci.oauth_url.c_str(), nullptr, nullptr, SW_SHOWNORMAL);
+#else
+ std::string cmd = "xdg-open \"" + ci.oauth_url + "\"";
+ std::system(cmd.c_str());
+#endif
+ }
+ ImGui::Text("Step 2: Paste code:");
+ ImGui::SameLine(150); ImGui::SetNextItemWidth(250);
+ char al[32]; std::snprintf(al,sizeof(al),"##ac_%d",idx);
+ ImGui::InputText(al, ci.auth_code, sizeof(ci.auth_code));
+ char el[48]; std::snprintf(el,sizeof(el),"Exchange Token##ex_%d",idx);
+ if (ImGui::Button(el)) exchange_token_async(idx);
+ } else {
+ char gl[48]; std::snprintf(gl,sizeof(gl),"Generate OAuth URL##gen_%d",idx);
+ if (ImGui::Button(gl)) {
+ ci.oauth_url = generate_oauth_url(m.id, ci.api_key);
+ if (ci.oauth_url.empty()) set_status("Enter API key first.");
+ }
}
+ ImGui::SameLine();
+ if (ImGui::SmallButton("Clear")) { ci.oauth_url.clear(); ci.auth_code[0]=0; }
}
ImGui::Spacing();
- // Place order button — full width, colored
- const bool can_order = is_connected_ || is_paper_mode_;
- if (!can_order) ImGui::BeginDisabled();
-
- const ImVec4& btn_col = is_buy ? BUY_GREEN : SELL_RED;
- const ImVec4& btn_hover = is_buy ? BUY_GREEN_HOVER : SELL_RED_HOVER;
- ImGui::PushStyleColor(ImGuiCol_Button, btn_col);
- ImGui::PushStyleColor(ImGuiCol_ButtonHovered, btn_hover);
- ImGui::PushStyleColor(ImGuiCol_Text, ImVec4(1, 1, 1, 1));
- ImGui::PushStyleVar(ImGuiStyleVar_FrameRounding, 3.0f);
-
- const char* btn_text = is_buy ? "PLACE BUY ORDER" : "PLACE SELL ORDER";
- if (ImGui::Button(btn_text, ImVec2(input_w, 36.0f))) {
- place_order();
- }
-
- ImGui::PopStyleVar();
- ImGui::PopStyleColor(3);
-
- if (!can_order) ImGui::EndDisabled();
-
- if (!can_order) {
- ImGui::Spacing();
- ImGui::TextColored(WARNING, "Connect broker or enable paper mode");
+ // Save
+ char svl[48]; std::snprintf(svl,sizeof(svl),"Save##save_%d",idx);
+ if (ImGui::Button(svl)) {
+ json extra;
+ if (ci.totp_secret[0]) extra["totp_secret"] = ci.totp_secret;
+ if (ci.password[0]) extra["password"] = ci.password;
+ if (ci.user_id[0]) extra["user_id"] = ci.user_id;
+ trading::BrokerCredentials creds;
+ creds.broker_id = trading::broker_id_str(m.id);
+ creds.api_key = ci.api_key; creds.api_secret = ci.api_secret;
+ creds.user_id = ci.user_id; creds.additional_data = extra.dump();
+ auto* broker = trading::BrokerRegistry::instance().get(m.id);
+ if (broker) { broker->save_credentials(creds); set_status(std::string("Saved: ")+m.name); }
+ }
+ ImGui::SameLine(0,20);
+
+ if (!conn) {
+ char cnl[48]; std::snprintf(cnl,sizeof(cnl),"Connect##con_%d",idx);
+ if (ImGui::Button(cnl)) connect_broker(m.id);
+ } else {
+ ImGui::TextColored(C_GRN, "CONNECTED");
+ ImGui::SameLine(0,12);
+ if (ImGui::Button("Disconnect")) { stop_ws_stream(); connected_=false; active_broker_=std::nullopt; set_status("Disconnected."); }
}
- ImGui::EndChild();
- ImGui::PopStyleVar();
- ImGui::PopStyleColor();
+ if (!ci.err.empty()) ImGui::TextColored(C_RED, "%s", ci.err.c_str());
+ if (!ci.ok.empty()) ImGui::TextColored(C_GRN, "%s", ci.ok.c_str());
}
-// ============================================================================
-// Market Depth Panel — with visual depth bars
-// ============================================================================
-
-void EquityTradingScreen::render_order_book(float x, float y, float w, float h) {
- ImGui::SetCursorPos(ImVec2(x, y));
- ImGui::PushStyleColor(ImGuiCol_ChildBg, BG_DARK);
- ImGui::PushStyleVar(ImGuiStyleVar_WindowPadding, ImVec2(8, 6));
- ImGui::BeginChild("##eq_depth", ImVec2(w, h), true);
-
- ImGui::TextColored(ACCENT, "MARKET DEPTH");
- eq_draw_separator_line(w - 16.0f);
-
- if (ImGui::BeginTable("##depth_tbl", 4,
- ImGuiTableFlags_RowBg | ImGuiTableFlags_Borders |
- ImGuiTableFlags_SizingStretchProp, ImVec2(0, h - 40.0f))) {
- ImGui::TableSetupColumn("Bid Qty", ImGuiTableColumnFlags_None, 0.25f);
- ImGui::TableSetupColumn("Bid", ImGuiTableColumnFlags_None, 0.25f);
- ImGui::TableSetupColumn("Ask", ImGuiTableColumnFlags_None, 0.25f);
- ImGui::TableSetupColumn("Ask Qty", ImGuiTableColumnFlags_None, 0.25f);
- ImGui::TableHeadersRow();
-
- if (has_quote_ && current_quote_.ltp > 0.0) {
- const double mid = current_quote_.ltp;
- const double tick = std::max(0.05, mid * 0.001);
- const int max_qty = (MAX_DEPTH_LEVELS) * 100;
-
- for (int i = 0; i < MAX_DEPTH_LEVELS; ++i) {
- ImGui::TableNextRow();
- const double bid_price = mid - tick * static_cast<double>(i + 1);
- const double ask_price = mid + tick * static_cast<double>(i + 1);
- const int bid_qty = (MAX_DEPTH_LEVELS - i) * 100;
- const int ask_qty = (i + 1) * 80;
-
- // Bid Qty with depth bar
- ImGui::TableNextColumn();
- {
- const ImVec2 cell_min = ImGui::GetCursorScreenPos();
- const float cell_w = ImGui::GetContentRegionAvail().x;
- const float bar_frac = static_cast<float>(bid_qty) / static_cast<float>(max_qty);
- auto* draw = ImGui::GetWindowDrawList();
- // Bar grows from right to left
- draw->AddRectFilled(
- {cell_min.x + cell_w * (1.0f - bar_frac), cell_min.y},
- {cell_min.x + cell_w, cell_min.y + ImGui::GetTextLineHeight()},
- ImGui::ColorConvertFloat4ToU32(DEPTH_BID_BAR));
- ImGui::TextColored(MARKET_GREEN, "%d", bid_qty);
- }
-
- // Bid Price
- ImGui::TableNextColumn();
- ImGui::TextColored(MARKET_GREEN, "%.2f", bid_price);
-
- // Ask Price
- ImGui::TableNextColumn();
- ImGui::TextColored(MARKET_RED, "%.2f", ask_price);
-
- // Ask Qty with depth bar
- ImGui::TableNextColumn();
- {
- const ImVec2 cell_min = ImGui::GetCursorScreenPos();
- const float cell_w = ImGui::GetContentRegionAvail().x;
- const float bar_frac = static_cast<float>(ask_qty) / static_cast<float>(max_qty);
- auto* draw = ImGui::GetWindowDrawList();
- // Bar grows from left to right
- draw->AddRectFilled(
- cell_min,
- {cell_min.x + cell_w * bar_frac, cell_min.y + ImGui::GetTextLineHeight()},
- ImGui::ColorConvertFloat4ToU32(DEPTH_ASK_BAR));
- ImGui::TextColored(MARKET_RED, "%d", ask_qty);
- }
- }
- } else {
- for (int i = 0; i < 5; ++i) {
- ImGui::TableNextRow();
- for (int j = 0; j < 4; ++j) {
- ImGui::TableNextColumn();
- ImGui::TextColored(TEXT_DISABLED, "--");
- }
- }
- }
+// ═══════════════════════════════════════════════════════════════════════
+// Actions
+// ═══════════════════════════════════════════════════════════════════════
+void EquityTradingScreen::select_symbol(const std::string& sym, const std::string& exch) {
+ sel_sym_ = sym; sel_exch_ = exch;
+ std::strncpy(sym_buf_, sym.c_str(), sizeof(sym_buf_)-1);
+ std::strncpy(order_form_.symbol_buf, sym.c_str(), sizeof(order_form_.symbol_buf)-1);
+ fetch_quote(); fetch_candles();
+}
- ImGui::EndTable();
- }
+void EquityTradingScreen::fetch_quote() {
+ // If WS is streaming, pull from tick cache instead of making a REST call
+ if (ws_streaming_) {
+ trading::EquityTick tick;
+ if (trading::EquityStreamManager::instance().get_tick(sel_sym_, tick) && tick.ltp > 0) {
+ quote_.ltp = tick.ltp;
+ quote_.open = tick.open;
+ quote_.high = tick.high;
+ quote_.low = tick.low;
+ quote_.bid = tick.bid;
+ quote_.ask = tick.ask;
+ quote_.volume = tick.volume;
+ quote_.change = tick.ltp - tick.close;
+ quote_.change_pct = tick.close > 0 ? (quote_.change / tick.close * 100.0) : 0.0;
+ has_quote_ = true;
+ return; // got live tick, done
+ }
+ // WS connected but no tick yet — fall through to REST for initial quote
+ }
+
+ if (loading_quote_) return;
+ // Fetch quote if broker connected (even in paper mode — price display is always useful)
+ auto* b = active_broker_ ? trading::BrokerRegistry::instance().get(*active_broker_) : nullptr;
+ if (!b) { has_quote_=false; return; }
+ if (active_creds_.api_key.empty()) { has_quote_=false; return; }
+ loading_quote_ = true;
+ last_quote_refresh_ = std::chrono::steady_clock::now();
+ std::string query = sel_exch_ + ":" + sel_sym_;
+ quote_fut_ = std::async(std::launch::async, [b, query, sym=sel_sym_, c=active_creds_]() {
+ auto r = b->get_quotes(c, {query});
+ if (r.data && !r.data->empty()) return r.data->front();
+ auto r2 = b->get_quotes(c, {sym});
+ return (r2.data && !r2.data->empty()) ? r2.data->front() : trading::BrokerQuote{};
+ });
+}
- ImGui::EndChild();
- ImGui::PopStyleVar();
- ImGui::PopStyleColor();
+void EquityTradingScreen::fetch_candles() {
+ if (loading_candles_) return;
+ auto* b = connected_ && active_broker_ ? trading::BrokerRegistry::instance().get(*active_broker_) : nullptr;
+ if (!b) return;
+ loading_candles_ = true;
+ candle_fut_ = std::async(std::launch::async,
+ [b, s=sel_sym_, res=std::string(timeframe_resolution(timeframe_)), c=active_creds_]() {
+ auto r = b->get_history(c, s, res, "2024-01-01", "2099-12-31");
+ return r.data.value_or(std::vector<trading::BrokerCandle>{});
+ });
}
-// ============================================================================
-// Status Bar — richer with clock, position count, balance
-// ============================================================================
-
-void EquityTradingScreen::render_status_bar(float w, float total_h) {
- ImGui::SetCursorPos(ImVec2(0.0f, total_h - STATUS_HEIGHT));
- ImGui::PushStyleColor(ImGuiCol_ChildBg, BG_DARKEST);
- ImGui::PushStyleVar(ImGuiStyleVar_WindowPadding, ImVec2(10, 3));
- ImGui::BeginChild("##eq_status", ImVec2(w, STATUS_HEIGHT), false);
-
- // Connection status pill
- if (is_connected_ && active_broker_.has_value()) {
- ImGui::TextColored(MARKET_GREEN, "\xe2\x97\x8f"); // ● filled circle
- ImGui::SameLine(0.0f, 4.0f);
- ImGui::TextColored(TEXT_SECONDARY, "%s", trading::broker_id_str(*active_broker_));
+void EquityTradingScreen::place_order() {
+ auto& f = order_form_;
+ if (!f.symbol_buf[0] || f.quantity <= 0) { set_status("Invalid order."); return; }
+ if (paper_mode_) {
+ double fp = has_quote_ ? quote_.ltp : f.price;
+ if (fp <= 0) fp = f.price;
+ if (fp <= 0) { set_status("No price."); return; }
+ try {
+ auto ord = trading::pt_place_order(paper_id_, f.symbol_buf,
+ f.side==trading::OrderSide::Buy?"buy":"sell",
+ f.type==trading::OrderType::Market?"market":"limit",
+ f.quantity, f.price>0?f.price:fp, false);
+ trading::pt_fill_order(ord.id, fp, f.quantity);
+ set_status(std::string("[Paper] Filled: ")+f.symbol_buf);
+ refresh_paper_portfolio();
+ } catch (const std::exception& e) { set_status(std::string("Paper fail: ")+e.what()); }
} else {
- ImGui::TextColored(TEXT_DISABLED, "\xe2\x97\x8b"); // ○ empty circle
- ImGui::SameLine(0.0f, 4.0f);
- ImGui::TextColored(TEXT_DISABLED, "No broker");
+ if (!connected_ || !active_broker_) { set_status("Not connected."); return; }
+ auto* broker = trading::BrokerRegistry::instance().get(*active_broker_);
+ if (!broker) { set_status("Broker not found."); return; }
+ trading::UnifiedOrder order;
+ order.symbol=f.symbol_buf; order.exchange=sel_exch_;
+ order.side=f.side; order.order_type=f.type;
+ order.quantity=f.quantity; order.price=f.price; order.stop_price=f.stop_price;
+ order.product_type=f.product; order.validity=validity_label(f.validity);
+ order.amo=f.is_amo;
+ std::thread([this,broker,order,creds=active_creds_](){
+ auto r = broker->place_order(creds,order);
+ if(r.success){set_status("Placed: "+r.order_id);refresh_portfolio();}
+ else set_status("Failed: "+r.error);
+ }).detach();
}
+}
- ImGui::SameLine(0.0f, 16.0f);
-
- // Mode
- if (is_paper_mode_) {
- ImGui::TextColored(PILL_PAPER, "PAPER");
- } else {
- ImGui::TextColored(PILL_LIVE, "LIVE");
- }
+void EquityTradingScreen::connect_broker(trading::BrokerId id) {
+ if (connecting_) return;
+ auto* b = trading::BrokerRegistry::instance().get(id);
+ if (!b) { set_status("Broker unavailable."); return; }
- ImGui::SameLine(0.0f, 16.0f);
- ImGui::TextColored(TEXT_DIM, "%s:%s",
- selected_exchange_.c_str(), selected_symbol_.c_str());
+ int idx = -1;
+ for (int i = 0; i < BROKER_META_COUNT; ++i)
+ if (BROKER_META[i].id == id) { idx = i; break; }
- // Position count
- if (!positions_.empty()) {
- ImGui::SameLine(0.0f, 16.0f);
- ImGui::TextColored(TEXT_DIM, "%d pos", static_cast<int>(positions_.size()));
- }
+ auto creds = b->load_credentials();
+ if (creds.api_key.empty()) { set_status("Save credentials first."); return; }
- // Funds on the right
- if (funds_.has_value()) {
- ImGui::SameLine(w - 250.0f);
- ImGui::TextColored(TEXT_DIM, "Bal:");
- ImGui::SameLine(0.0f, 4.0f);
- ImGui::TextColored(MARKET_GREEN, "%.2f", funds_->available_balance);
- ImGui::SameLine(0.0f, 12.0f);
- ImGui::TextColored(TEXT_DIM, "Margin:");
- ImGui::SameLine(0.0f, 4.0f);
- ImGui::TextColored(TEXT_SECONDARY, "%.2f", funds_->used_margin);
+ // TOTP brokers: re-authenticate via exchange_token_async, then finalize on main thread
+ if (idx >= 0 && BROKER_META[idx].auth_type == BrokerAuthType::TOTP) {
+ if (cred_ui_[idx].auth_code[0] == '\0') {
+ set_status("Enter TOTP code first."); return;
+ }
+ exchange_token_async(idx); // sets connect_fut_, connecting_=true
+ // render() will poll connect_fut_ and call finish_connect()
+ return;
}
- ImGui::EndChild();
- ImGui::PopStyleVar();
- ImGui::PopStyleColor();
+ // OAuth / ApiKey: need a saved token
+ if (creds.access_token.empty()) { set_status("No access token — generate token first."); return; }
+ finish_connect({true, id, creds, ""});
}
-// ============================================================================
-// Actions
-// ============================================================================
-
-void EquityTradingScreen::select_symbol(const std::string& symbol, const std::string& exchange) {
- selected_symbol_ = symbol;
- selected_exchange_ = exchange;
- std::strncpy(symbol_buf_, symbol.c_str(), sizeof(symbol_buf_) - 1);
- std::strncpy(order_form_.symbol_buf, symbol.c_str(), sizeof(order_form_.symbol_buf) - 1);
- has_quote_ = false;
- candles_.clear();
-
- LOG_INFO(TAG, "Selected %s:%s", exchange.c_str(), symbol.c_str());
-
- if (is_connected_) {
- fetch_quote();
+void EquityTradingScreen::finish_connect(ConnectResult r) {
+ int idx = connecting_idx_;
+ connecting_idx_ = -1;
+ if (!r.success) {
+ set_status("Auth failed: " + r.error);
+ if (idx >= 0) { cred_ui_[idx].err = r.error; cred_ui_[idx].ok.clear(); }
+ return;
}
+ active_creds_ = r.creds;
+ active_broker_ = r.broker_id;
+ connected_ = true;
+ paper_mode_ = false;
+ if (idx >= 0) { cred_ui_[idx].ok = "Connected!"; cred_ui_[idx].err.clear(); cred_ui_[idx].token_valid = true; }
+ set_status(std::string("Connected: ") + trading::broker_id_str(r.broker_id));
+ refresh_portfolio();
+ start_ws_stream();
+ fetch_quote();
+ refresh_watchlist_quotes();
}
-void EquityTradingScreen::fetch_quote() {
- if (!active_broker_.has_value() || loading_quote_) return;
-
- auto* broker = trading::BrokerRegistry::instance().get(*active_broker_);
- if (!broker) return;
-
- loading_quote_ = true;
- const auto creds = active_creds_;
- const auto sym = selected_symbol_;
+void EquityTradingScreen::refresh_portfolio() {
+ if (loading_port_||!connected_||!active_broker_) return;
+ auto* b = trading::BrokerRegistry::instance().get(*active_broker_);
+ if (!b) return;
+ loading_port_=true; last_port_refresh_=std::chrono::steady_clock::now();
+ std::thread([this,b,c=active_creds_](){
+ auto pr=b->get_positions(c); if(pr.data) positions_=*pr.data;
+ auto or_=b->get_orders(c); if(or_.data) orders_=*or_.data;
+ auto fr=b->get_funds(c); if(fr.data) funds_=*fr.data;
+ loading_port_=false;
+ }).detach();
+}
- quote_future_ = std::async(std::launch::async, [broker, creds, sym]() {
- auto resp = broker->get_quotes(creds, {sym});
- if (resp.success && resp.data.has_value() && !resp.data->empty()) {
- return resp.data->front();
- }
- return trading::BrokerQuote{};
- });
+void EquityTradingScreen::refresh_paper_portfolio() {
+ if (paper_id_.empty()) return;
+ loading_port_=true; last_port_refresh_=std::chrono::steady_clock::now();
+ std::thread([this](){
+ try {
+ auto rp=trading::pt_get_positions(paper_id_);
+ positions_.clear();
+ for(auto&p:rp){trading::BrokerPosition bp; bp.symbol=p.symbol; bp.exchange=sel_exch_;
+ bp.quantity=p.quantity; bp.avg_price=p.entry_price; bp.ltp=p.current_price;
+ bp.pnl=p.unrealized_pnl; bp.side=(p.side=="long")?"buy":"sell"; positions_.push_back(bp);}
+ auto ro=trading::pt_get_orders(paper_id_,"");
+ orders_.clear();
+ for(auto&o:ro){trading::BrokerOrderInfo bo; bo.order_id=o.id; bo.symbol=o.symbol;
+ bo.side=o.side; bo.order_type=o.order_type; bo.quantity=o.quantity;
+ bo.status=o.status; orders_.push_back(bo);}
+ } catch(...){}
+ loading_port_=false;
+ }).detach();
}
-void EquityTradingScreen::fetch_watchlist_quotes() {
- if (!active_broker_.has_value() || loading_watchlist_) return;
-
- auto* broker = trading::BrokerRegistry::instance().get(*active_broker_);
- if (!broker) return;
-
- loading_watchlist_ = true;
- const auto creds = active_creds_;
- std::vector<std::string> symbols;
- symbols.reserve(watchlist_.size());
- for (const auto& e : watchlist_) symbols.push_back(e.symbol);
-
- std::thread([this, broker, creds, symbols]() {
- auto resp = broker->get_quotes(creds, symbols);
- if (resp.success && resp.data.has_value()) {
- for (const auto& q : *resp.data) {
- for (auto& e : watchlist_) {
- if (e.symbol == q.symbol) {
- e.ltp = q.ltp;
- e.change = q.change;
- e.change_pct = q.change_pct;
- e.volume = q.volume;
+// Batch-fetch LTP for every watchlist entry in one REST call.
+// AngelOne accepts up to 50 tokens per request — all 47 fit in one shot.
+void EquityTradingScreen::refresh_watchlist_quotes() {
+ if (loading_wl_quotes_ || !active_broker_) return;
+ auto* b = trading::BrokerRegistry::instance().get(*active_broker_);
+ if (!b) return;
+ loading_wl_quotes_ = true;
+
+ // Build token list: "EXCHANGE:SYMBOL" for each watchlist entry
+ std::vector<std::string> tokens;
+ tokens.reserve(watchlist_.size());
+ for (const auto& w : watchlist_)
+ tokens.push_back(w.exchange + ":" + w.symbol);
+
+ std::thread([this, b, tokens, c=active_creds_]() {
+ auto r = b->get_quotes(c, tokens);
+ if (r.data) {
+ for (const auto& q : *r.data) {
+ for (auto& w : watchlist_) {
+ if (w.symbol == q.symbol) {
+ w.ltp = q.ltp;
+ w.change = q.change;
+ w.change_pct = q.change_pct;
+ w.volume = q.volume;
break;
}
}
}
}
- loading_watchlist_ = false;
+ loading_wl_quotes_ = false;
}).detach();
}
-void EquityTradingScreen::place_order() {
- if (!is_connected_ && !is_paper_mode_) return;
-
- trading::UnifiedOrder order;
- order.symbol = order_form_.symbol_buf;
- order.exchange = selected_exchange_;
- order.side = order_form_.side;
- order.order_type = order_form_.type;
- order.quantity = order_form_.quantity;
- order.price = order_form_.price;
- order.stop_price = order_form_.stop_price;
- order.product_type = order_form_.product;
- order.stop_loss = order_form_.stop_loss;
- order.take_profit = order_form_.take_profit;
-
- LOG_INFO(TAG, "Placing %s %s order: %s x%.0f @ %.2f",
- trading::order_side_str(order.side),
- trading::order_type_str(order.order_type),
- order.symbol.c_str(), order.quantity, order.price);
-
- if (is_paper_mode_) {
- LOG_INFO(TAG, "Paper order placed");
- return;
- }
-
- if (!active_broker_.has_value()) return;
- auto* broker = trading::BrokerRegistry::instance().get(*active_broker_);
- if (!broker) return;
-
- const auto creds = active_creds_;
- std::thread([broker, creds, order]() {
- auto resp = broker->place_order(creds, order);
- if (resp.success) {
- LOG_INFO(TAG, "Order placed: %s", resp.order_id.c_str());
- core::notify::send("Equity Order Placed",
- std::string(trading::order_side_str(order.side)) + " " + order.symbol,
- core::NotifyLevel::Success);
- } else {
- LOG_WARN(TAG, "Order failed: %s", resp.error.c_str());
- core::notify::send("Equity Order Failed", resp.error, core::NotifyLevel::Error);
- }
+void EquityTradingScreen::modify_order_async(const std::string& oid,
+ double price, double qty, double trigger_price) {
+ if (!connected_ || !active_broker_) { set_status("Not connected."); return; }
+ auto* b = trading::BrokerRegistry::instance().get(*active_broker_);
+ if (!b) { set_status("Broker not found."); return; }
+ json mods;
+ if (price > 0) mods["price"] = price;
+ if (qty > 0) mods["quantity"] = qty;
+ if (trigger_price > 0) mods["trigger_price"] = trigger_price;
+ std::thread([this, b, oid, mods, c=active_creds_]() {
+ auto r = b->modify_order(c, oid, mods);
+ if (r.success) { set_status("Modified: " + oid); refresh_portfolio(); }
+ else set_status("Modify failed: " + r.error);
}).detach();
+ set_status("Modifying...");
}
-void EquityTradingScreen::connect_broker(trading::BrokerId broker_id) {
- LOG_INFO(TAG, "Connecting to broker: %s", trading::broker_id_str(broker_id));
-
- auto* broker = trading::BrokerRegistry::instance().get(broker_id);
- if (!broker) {
- LOG_WARN(TAG, "Broker not found in registry");
- return;
+void EquityTradingScreen::cancel_order_async(const std::string& oid) {
+ if (paper_mode_) {
+ std::thread([oid,this](){ trading::pt_cancel_order(oid); refresh_paper_portfolio(); }).detach();
+ } else if (active_broker_) {
+ auto* b = trading::BrokerRegistry::instance().get(*active_broker_);
+ if (b) std::thread([this,b,oid,c=active_creds_](){ b->cancel_order(c,oid); refresh_portfolio(); }).detach();
}
+ set_status("Cancelling...");
+}
- active_creds_ = broker->load_credentials();
- if (active_creds_.api_key.empty()) {
- LOG_WARN(TAG, "No credentials found for %s — configure in Settings",
- trading::broker_id_str(broker_id));
- return;
- }
+void EquityTradingScreen::exchange_token_async(int idx) {
+ if (connecting_) return;
+ auto* b = trading::BrokerRegistry::instance().get(BROKER_META[idx].id);
+ if (!b) { cred_ui_[idx].err = "Broker unavailable."; return; }
+
+ // For TOTP: secret param = "client_code:pin"
+ std::string secret_param = (BROKER_META[idx].auth_type == BrokerAuthType::TOTP && cred_ui_[idx].user_id[0])
+ ? (std::string(cred_ui_[idx].user_id) + ":" + cred_ui_[idx].api_secret)
+ : cred_ui_[idx].api_secret;
+
+ connecting_ = true;
+ connecting_idx_ = idx;
+ cred_ui_[idx].err.clear();
+ cred_ui_[idx].ok.clear();
+
+ // Network-only future — no shared state touched inside
+ connect_fut_ = std::async(std::launch::async,
+ [b, idx,
+ key = std::string(cred_ui_[idx].api_key),
+ secret = secret_param,
+ code = std::string(cred_ui_[idx].auth_code)]() -> ConnectResult {
+ auto r = b->exchange_token(key, secret, code);
+ if (!r.success) return {false, BROKER_META[idx].id, {}, r.error};
+ json extra = r.additional_data.empty() ? json::object() : json::parse(r.additional_data);
+ extra["token_date"] = today_ist_string();
+ trading::BrokerCredentials creds;
+ creds.broker_id = trading::broker_id_str(BROKER_META[idx].id);
+ creds.api_key = key;
+ creds.api_secret = secret;
+ creds.access_token = r.access_token;
+ creds.user_id = r.user_id;
+ creds.additional_data = extra.dump();
+ b->save_credentials(creds);
+ return {true, BROKER_META[idx].id, creds, ""};
+ });
+}
- active_broker_ = broker_id;
- is_connected_ = true;
- LOG_INFO(TAG, "Connected to %s", trading::broker_id_str(broker_id));
+std::string EquityTradingScreen::generate_oauth_url(trading::BrokerId id, const char* k) {
+ std::string key = k?k:""; if(key.empty()) return "";
+ switch(id){
+ case trading::BrokerId::Fyers: return "https://api-t1.fyers.in/api/v3/generate-authcode?client_id="+key+"&redirect_uri=https://fincept.in/callback&response_type=code&state=fincept";
+ case trading::BrokerId::Zerodha: return "https://kite.trade/connect/login?api_key="+key+"&v=3";
+ case trading::BrokerId::Upstox: return "https://api.upstox.com/v2/login/authorization/dialog?response_type=code&client_id="+key+"&redirect_uri=https://fincept.in/callback";
+ case trading::BrokerId::Dhan: return "https://api.dhan.co/oauth2/authorize?client_id="+key+"&response_type=code&redirect_uri=https://fincept.in/callback";
+ case trading::BrokerId::IIFL: return "https://ttblaze.iifl.com/apiflow/CustomerValidation?apikey="+key;
+ case trading::BrokerId::Groww: return "https://api.groww.in/v1/oauth2/authorize?client_id="+key+"&response_type=code&redirect_uri=https://fincept.in/callback";
+ case trading::BrokerId::IBKR: return "https://www.interactivebrokers.com/authorize?client_id="+key;
+ case trading::BrokerId::Tradier: return "https://api.tradier.com/v1/oauth/authorize?client_id="+key+"&scope=read,write,market,trade&state=fincept";
+ case trading::BrokerId::SaxoBank: return "https://live.logonvalidation.net/authorize?client_id="+key+"&response_type=code&redirect_uri=https://fincept.in/callback";
+ default: return "";
+ }
+}
- fetch_quote();
- refresh_portfolio();
+std::string EquityTradingScreen::today_ist_string() {
+ using namespace std::chrono;
+ auto t = system_clock::to_time_t(system_clock::now() + hours(5) + minutes(30));
+ std::tm tm;
+#ifdef _WIN32
+ gmtime_s(&tm, &t);
+#else
+ gmtime_r(&t, &tm);
+#endif
+ char buf[16]; std::snprintf(buf,sizeof(buf),"%04d-%02d-%02d",tm.tm_year+1900,tm.tm_mon+1,tm.tm_mday);
+ return buf;
}
-void EquityTradingScreen::refresh_portfolio() {
- if (!active_broker_.has_value() || loading_portfolio_) return;
+// ═══════════════════════════════════════════════════════════════════════
+// WebSocket streaming
+// ═══════════════════════════════════════════════════════════════════════
+void EquityTradingScreen::start_ws_stream() {
+ if (!connected_ || !active_broker_) return;
- auto* broker = trading::BrokerRegistry::instance().get(*active_broker_);
- if (!broker) return;
+ auto* b = trading::BrokerRegistry::instance().get(*active_broker_);
+ if (!b) return;
- loading_portfolio_ = true;
- const auto creds = active_creds_;
+ const char* adapter = b->ws_adapter_name();
+ if (!adapter || adapter[0] == '\0') {
+ // Broker has no WS adapter — stay on REST polling
+ ws_streaming_ = false;
+ return;
+ }
- std::thread([this, broker, creds]() {
- auto pos_resp = broker->get_positions(creds);
- if (pos_resp.success && pos_resp.data.has_value()) {
- positions_ = *pos_resp.data;
+ // Build symbol list from watchlist + currently selected symbol
+ std::vector<trading::EquitySymbol> syms;
+ // Always include selected symbol first
+ if (!sel_sym_.empty())
+ syms.push_back({sel_sym_, sel_exch_});
+ for (const auto& w : watchlist_) {
+ bool already = false;
+ for (const auto& s : syms) if (s.symbol == w.symbol) { already = true; break; }
+ if (!already) syms.push_back({w.symbol, w.exchange});
+ }
+
+ auto& esm = trading::EquityStreamManager::instance();
+ esm.stop();
+
+ // Register tick callback — updates quote_ if it's for the selected symbol
+ ws_tick_cb_id_ = esm.on_tick([this](const trading::EquityTick& t) {
+ // Update watchlist entry LTP
+ for (auto& w : watchlist_) {
+ if (w.symbol == t.symbol) {
+ w.ltp = t.ltp;
+ w.change = t.ltp - t.close;
+ w.change_pct = t.close > 0 ? (w.change / t.close * 100.0) : 0.0;
+ }
}
-
- auto hold_resp = broker->get_holdings(creds);
- if (hold_resp.success && hold_resp.data.has_value()) {
- holdings_ = *hold_resp.data;
+ // Update selected quote
+ if (t.symbol == sel_sym_) {
+ quote_.ltp = t.ltp;
+ quote_.open = t.open;
+ quote_.high = t.high;
+ quote_.low = t.low;
+ quote_.bid = t.bid;
+ quote_.ask = t.ask;
+ quote_.volume = t.volume;
+ quote_.change = t.ltp - t.close;
+ quote_.change_pct = t.close > 0 ? (quote_.change / t.close * 100.0) : 0.0;
+ has_quote_ = true;
}
+ });
- auto ord_resp = broker->get_orders(creds);
- if (ord_resp.success && ord_resp.data.has_value()) {
- orders_ = *ord_resp.data;
- }
+ ws_status_cb_id_ = esm.on_status([this](bool conn, const std::string& msg) {
+ if (conn) set_status(std::string("[WS] Connected"));
+ else set_status(std::string("[WS] ") + msg);
+ });
- auto funds_resp = broker->get_funds(creds);
- if (funds_resp.success && funds_resp.data.has_value()) {
- funds_ = *funds_resp.data;
- }
+ esm.start(adapter, active_creds_, syms);
+ ws_streaming_ = true;
+ set_status(std::string("WS stream starting: ") + adapter);
+}
- loading_portfolio_ = false;
- }).detach();
+void EquityTradingScreen::stop_ws_stream() {
+ if (!ws_streaming_) return;
+ auto& esm = trading::EquityStreamManager::instance();
+ if (ws_tick_cb_id_ >= 0) { esm.remove_tick_callback(ws_tick_cb_id_); ws_tick_cb_id_ = -1; }
+ if (ws_status_cb_id_ >= 0) { esm.remove_status_callback(ws_status_cb_id_); ws_status_cb_id_ = -1; }
+ esm.stop();
+ ws_streaming_ = false;
}
} // namespace fincept::equity_trading
diff --git a/fincept-cpp/src/screens/equity_trading/equity_trading_screen.h b/fincept-cpp/src/screens/equity_trading/equity_trading_screen.h
index 0f11b2226..4920d8ce3 100644
--- a/fincept-cpp/src/screens/equity_trading/equity_trading_screen.h
+++ b/fincept-cpp/src/screens/equity_trading/equity_trading_screen.h
@@ -1,14 +1,16 @@
#pragma once
-// Equity Trading Screen — Bloomberg Terminal-style stock trading interface.
-// Multi-panel layout: watchlist | chart + bottom panel | order entry + depth
-
#include "equity_trading_types.h"
#include "trading/broker_registry.h"
#include "trading/broker_interface.h"
+#include "trading/paper_trading.h"
+#include "trading/equity_stream.h"
#include <string>
#include <vector>
#include <future>
#include <optional>
+#include <array>
+#include <chrono>
+#include <nlohmann/json.hpp>
namespace fincept::equity_trading {
@@ -17,79 +19,128 @@ public:
void render();
private:
- void init();
-
- // Panel renderers
- void render_top_nav(float w);
- void render_ticker_bar(float w);
- void render_watchlist_panel(float x, float y, float w, float h);
- void render_chart_panel(float x, float y, float w, float h);
- void render_bottom_panel(float x, float y, float w, float h);
- void render_order_entry(float x, float y, float w, float h);
- void render_order_book(float x, float y, float w, float h);
- void render_status_bar(float w, float total_h);
-
- // Sub-renderers
- void render_positions_table(float w, float h);
- void render_holdings_table(float w, float h);
- void render_orders_table(float w, float h);
- void render_broker_config(float w, float h);
- void render_candle_chart(float w, float h);
+ // Section renderers
+ void section_overview();
+ void section_watchlist();
+ void section_order();
+ void section_positions();
+ void section_orders();
+ void section_funds();
+ void section_brokers();
+
+ // Broker connect result — produced by background thread, consumed on main thread
+ struct ConnectResult {
+ bool success = false;
+ trading::BrokerId broker_id{};
+ trading::BrokerCredentials creds;
+ std::string error;
+ };
// Actions
void select_symbol(const std::string& symbol, const std::string& exchange);
void fetch_quote();
- void fetch_watchlist_quotes();
+ void fetch_candles();
void place_order();
void connect_broker(trading::BrokerId broker_id);
+ void finish_connect(ConnectResult r); // called on main thread after future resolves
void refresh_portfolio();
+ void refresh_paper_portfolio();
+ void cancel_order_async(const std::string& order_id);
+ void modify_order_async(const std::string& order_id, double price, double qty, double trigger_price);
+ void exchange_token_async(int broker_idx);
+ std::string generate_oauth_url(trading::BrokerId id, const char* api_key);
+ static std::string today_ist_string();
+
+ void set_status(std::string msg) {
+ status_msg_ = std::move(msg);
+ status_time_ = std::chrono::steady_clock::now();
+ }
// State
- bool initialized_ = false;
+ bool inited_ = false;
+ int section_ = 0; // active nav section
- // Broker connection
+ // Broker
std::optional<trading::BrokerId> active_broker_;
trading::BrokerCredentials active_creds_;
- bool is_connected_ = false;
- bool is_paper_mode_ = true;
-
- // Selected symbol
- char symbol_buf_[64] = "RELIANCE";
- std::string selected_symbol_ = "RELIANCE";
- std::string selected_exchange_ = "NSE";
- int exchange_idx_ = 0;
-
- // Quote data
- trading::BrokerQuote current_quote_;
- bool has_quote_ = false;
- bool loading_quote_ = false;
- std::future<trading::BrokerQuote> quote_future_;
+ bool connected_ = false;
+ bool paper_mode_ = true;
+ int broker_sel_ = -1;
+ struct CredUI {
+ char api_key[128] = {}, api_secret[128] = {}, user_id[64] = {};
+ char password[64] = {}, totp_secret[64] = {}, auth_code[256] = {};
+ bool show_secret = false, show_pw = false;
+ bool token_valid = false, checking = false;
+ std::string oauth_url, err, ok;
+ };
+ std::array<CredUI, BROKER_META_COUNT> cred_ui_;
+
+ // Paper trading
+ std::string paper_id_;
+
+ // Symbol
+ char sym_buf_[64] = "RELIANCE";
+ std::string sel_sym_ = "RELIANCE";
+ std::string sel_exch_ = "NSE";
+ int exch_idx_ = 0;
+
+ // Quote
+ trading::BrokerQuote quote_;
+ bool has_quote_ = false, loading_quote_ = false;
+ std::future<trading::BrokerQuote> quote_fut_;
// Watchlist
std::vector<WatchlistEntry> watchlist_;
- bool loading_watchlist_ = false;
- // Candle data
+ // Candles
std::vector<trading::BrokerCandle> candles_;
- TimeFrame chart_timeframe_ = TimeFrame::d1;
+ TimeFrame timeframe_ = TimeFrame::d1;
bool loading_candles_ = false;
- std::future<std::vector<trading::BrokerCandle>> candle_future_;
+ std::future<std::vector<trading::BrokerCandle>> candle_fut_;
- // Portfolio data
- std::vector<trading::BrokerPosition> positions_;
- std::vector<trading::BrokerHolding> holdings_;
+ // Portfolio
+ std::vector<trading::BrokerPosition> positions_;
std::vector<trading::BrokerOrderInfo> orders_;
- std::optional<trading::BrokerFunds> funds_;
- bool loading_portfolio_ = false;
+ std::optional<trading::BrokerFunds> funds_;
+ bool loading_port_ = false;
// Order form
OrderFormState order_form_;
- // UI state
- BottomTab bottom_tab_ = BottomTab::positions;
- SidebarView sidebar_view_ = SidebarView::watchlist;
- bool bottom_minimized_ = false;
- char watchlist_search_[64] = {};
+ // Modify order modal state
+ struct ModifyState {
+ bool open = false;
+ std::string order_id;
+ double price = 0.0, qty = 0.0, trigger_price = 0.0;
+ } modify_state_;
+
+ // WebSocket streaming state
+ bool ws_streaming_ = false; // true when WS bridge is running
+ int ws_tick_cb_id_ = -1; // callback ID registered with EquityStreamManager
+ int ws_status_cb_id_ = -1;
+
+ // Start / stop the WS bridge for the current broker + watchlist
+ void start_ws_stream();
+ void stop_ws_stream();
+
+ // Bulk-fetch LTP for all watchlist entries via REST
+ void refresh_watchlist_quotes();
+ bool loading_wl_quotes_ = false;
+ std::chrono::steady_clock::time_point last_wl_refresh_;
+ static constexpr int WL_REFRESH_SECS = 15;
+
+ // Pending broker connect future — polled on main thread
+ std::future<ConnectResult> connect_fut_;
+ bool connecting_ = false;
+ int connecting_idx_ = -1;
+
+ // Status
+ std::string status_msg_;
+ std::chrono::steady_clock::time_point status_time_;
+ std::chrono::steady_clock::time_point last_port_refresh_;
+ std::chrono::steady_clock::time_point last_quote_refresh_;
+ static constexpr int QUOTE_REFRESH_SECS = 5;
+ static constexpr int PORT_REFRESH_SECS = 30;
};
} // namespace fincept::equity_trading
diff --git a/fincept-cpp/src/screens/equity_trading/equity_trading_types.h b/fincept-cpp/src/screens/equity_trading/equity_trading_types.h
index 2b6b6b455..2bc9b45c3 100644
--- a/fincept-cpp/src/screens/equity_trading/equity_trading_types.h
+++ b/fincept-cpp/src/screens/equity_trading/equity_trading_types.h
@@ -7,8 +7,11 @@
namespace fincept::equity_trading {
-// Bottom panel tabs
-enum class BottomTab { positions, holdings, orders, history, brokers };
+// ============================================================================
+// Bottom Panel Tabs
+// ============================================================================
+
+enum class BottomTab { positions, holdings, orders, history, funds, stats, brokers };
inline const char* bottom_tab_label(BottomTab t) {
switch (t) {
@@ -16,6 +19,8 @@ inline const char* bottom_tab_label(BottomTab t) {
case BottomTab::holdings: return "HOLDINGS";
case BottomTab::orders: return "ORDERS";
case BottomTab::history: return "HISTORY";
+ case BottomTab::funds: return "FUNDS";
+ case BottomTab::stats: return "STATS";
case BottomTab::brokers: return "BROKERS";
}
return "POSITIONS";
@@ -24,10 +29,11 @@ inline const char* bottom_tab_label(BottomTab t) {
// Left sidebar view
enum class SidebarView { watchlist, indices };
-// Chart time frame
-enum class TimeFrame {
- m1, m5, m15, m30, h1, h4, d1, w1
-};
+// ============================================================================
+// Chart Time Frame
+// ============================================================================
+
+enum class TimeFrame { m1, m5, m15, m30, h1, h4, d1, w1 };
inline const char* timeframe_label(TimeFrame tf) {
switch (tf) {
@@ -57,30 +63,147 @@ inline const char* timeframe_resolution(TimeFrame tf) {
return "5";
}
+// ============================================================================
+// Order Form Types
+// ============================================================================
+
+enum class OrderValidity { Day, IOC, GTC };
+
+inline const char* validity_label(OrderValidity v) {
+ switch (v) {
+ case OrderValidity::Day: return "DAY";
+ case OrderValidity::IOC: return "IOC";
+ case OrderValidity::GTC: return "GTC";
+ }
+ return "DAY";
+}
+
// Watchlist entry with cached quote data
struct WatchlistEntry {
std::string symbol;
std::string exchange = "NSE";
- double ltp = 0.0;
- double change = 0.0;
+ double ltp = 0.0;
+ double change = 0.0;
double change_pct = 0.0;
- double volume = 0.0;
+ double volume = 0.0;
};
-// Order form state
+// Order form state — all fields for the right-panel order entry form
struct OrderFormState {
- trading::OrderSide side = trading::OrderSide::Buy;
- trading::OrderType type = trading::OrderType::Market;
+ trading::OrderSide side = trading::OrderSide::Buy;
+ trading::OrderType type = trading::OrderType::Market;
trading::ProductType product = trading::ProductType::Intraday;
- char symbol_buf[64] = {};
- double quantity = 1;
- double price = 0.0;
- double stop_price = 0.0;
- double stop_loss = 0.0;
- double take_profit = 0.0;
+ OrderValidity validity = OrderValidity::Day;
+ char symbol_buf[64] = {};
+ double quantity = 1;
+ double price = 0.0;
+ double stop_price = 0.0;
+ double stop_loss = 0.0;
+ double take_profit = 0.0;
+ bool is_amo = false; // After Market Order
+ bool show_bracket = false; // Bracket order expanded
+ double square_off_pts = 0.0; // Bracket profit target in points
+ double bracket_sl_pts = 0.0; // Bracket stop-loss in points
};
-// Stock exchange list
+// ============================================================================
+// Broker Auth Metadata
+// ============================================================================
+
+enum class BrokerAuthType { OAuth, TOTP, ApiKey };
+
+struct BrokerMeta {
+ trading::BrokerId id;
+ const char* name;
+ const char* region;
+ BrokerAuthType auth_type;
+ const char* api_key_label;
+ const char* api_secret_label;
+ const char* api_keys_url;
+ bool needs_user_id;
+ bool needs_totp;
+ bool needs_password;
+ const char* user_id_label;
+ const char* password_label;
+};
+
+inline constexpr BrokerMeta BROKER_META[] = {
+ // Indian — OAuth
+ { trading::BrokerId::Fyers, "Fyers", "India", BrokerAuthType::OAuth,
+ "APP ID", "SECRET KEY",
+ "https://myapi.fyers.in/dashboard",
+ false, false, false, "", "" },
+ { trading::BrokerId::Zerodha, "Zerodha", "India", BrokerAuthType::OAuth,
+ "API KEY", "API SECRET",
+ "https://developers.kite.trade/apps",
+ false, false, false, "", "" },
+ { trading::BrokerId::Upstox, "Upstox", "India", BrokerAuthType::OAuth,
+ "API KEY", "API SECRET",
+ "https://developer.upstox.com/",
+ false, false, false, "", "" },
+ { trading::BrokerId::Dhan, "Dhan", "India", BrokerAuthType::OAuth,
+ "CLIENT ID", "ACCESS TOKEN",
+ "https://dhanhq.co/docs/api/",
+ false, false, false, "", "" },
+ { trading::BrokerId::IIFL, "IIFL", "India", BrokerAuthType::OAuth,
+ "API KEY", "API SECRET",
+ "https://ttblaze.iifl.com/",
+ false, false, false, "", "" },
+ { trading::BrokerId::Groww, "Groww", "India", BrokerAuthType::OAuth,
+ "API KEY", "API SECRET",
+ "https://groww.in/api-docs",
+ false, false, false, "", "" },
+ // Indian — TOTP
+ { trading::BrokerId::AngelOne, "Angel One","India", BrokerAuthType::TOTP,
+ "API KEY", "PIN",
+ "https://smartapi.angelbroking.com/",
+ true, true, false, "Client Code", "" },
+ { trading::BrokerId::Kotak, "Kotak", "India", BrokerAuthType::TOTP,
+ "UCC", "NEO-FIN-KEY",
+ "https://neotradeapi.kotaksecurities.com/",
+ false, false, true, "", "MPIN (6-digit)" },
+ { trading::BrokerId::Shoonya, "Shoonya", "India", BrokerAuthType::TOTP,
+ "USER ID", "PASSWORD",
+ "https://api.shoonya.com/",
+ true, true, false, "User ID", "" },
+ // Indian — ApiKey
+ { trading::BrokerId::AliceBlue,"AliceBlue","India", BrokerAuthType::ApiKey,
+ "USER ID", "API SECRET",
+ "https://ant.aliceblueonline.com/",
+ false, false, true, "User ID", "Enc Key" },
+ { trading::BrokerId::FivePaisa,"5Paisa", "India", BrokerAuthType::ApiKey,
+ "APP KEY", "CLIENT CODE",
+ "https://www.5paisa.com/developerapi",
+ false, false, false, "", "" },
+ { trading::BrokerId::Motilal, "Motilal", "India", BrokerAuthType::ApiKey,
+ "API KEY", "PASSWORD",
+ "https://openapi.motilaloswal.com/",
+ true, false, false, "Client Code", "" },
+ // US
+ { trading::BrokerId::Alpaca, "Alpaca", "US", BrokerAuthType::ApiKey,
+ "API KEY ID", "API SECRET KEY",
+ "https://alpaca.markets/",
+ false, false, false, "", "" },
+ { trading::BrokerId::IBKR, "IBKR", "US", BrokerAuthType::OAuth,
+ "API KEY", "API SECRET",
+ "https://www.interactivebrokers.com/",
+ false, false, false, "", "" },
+ { trading::BrokerId::Tradier, "Tradier", "US", BrokerAuthType::OAuth,
+ "ACCESS TOKEN", "",
+ "https://developer.tradier.com/",
+ false, false, false, "", "" },
+ // EU
+ { trading::BrokerId::SaxoBank, "Saxo Bank","EU", BrokerAuthType::OAuth,
+ "APP KEY", "APP SECRET",
+ "https://www.developer.saxo/",
+ false, false, false, "", "" },
+};
+inline constexpr int BROKER_META_COUNT = 16;
+
+// ============================================================================
+// Stock Exchange List
+// ============================================================================
+
struct ExchangeDef {
const char* code;
const char* name;
diff --git a/fincept-cpp/src/screens/portfolio/views/planning_view.cpp b/fincept-cpp/src/screens/portfolio/views/planning_view.cpp
index bb82d2f5e..4bb33f023 100644
--- a/fincept-cpp/src/screens/portfolio/views/planning_view.cpp
+++ b/fincept-cpp/src/screens/portfolio/views/planning_view.cpp
@@ -1,22 +1,152 @@
-// Planning Panel — Asset allocation, retirement planning
+// Planning Panel — Asset allocation, retirement planning, financial goals
// Port of PlanningPanel.tsx
#include "planning_view.h"
#include "python/python_runner.h"
#include "storage/cache_service.h"
+#include "storage/database.h"
#include "ui/theme.h"
#include "core/logger.h"
#include <imgui.h>
#include <cstdio>
#include <cstdlib>
+#include <cstring>
#include <cmath>
#include <thread>
namespace fincept::portfolio {
+static const char* GOAL_CATEGORIES[] = {"Savings", "Investment", "Debt", "Emergency", "Custom"};
+static const char* GOAL_CATEGORY_KEYS[] = {"savings", "investment", "debt", "emergency", "custom"};
+static constexpr int NUM_GOAL_CATEGORIES = 5;
+
+static const char* GOAL_PRIORITIES[] = {"High", "Medium", "Low"};
+static const char* GOAL_PRIORITY_KEYS[] = {"high", "medium", "low"};
+static constexpr int NUM_GOAL_PRIORITIES = 3;
+
+// ============================================================================
+// Goals — Database setup
+// ============================================================================
+
+void PlanningView::ensure_goals_table() {
+ auto& dbi = db::Database::instance();
+ dbi.exec(R"(
+ CREATE TABLE IF NOT EXISTS financial_goals (
+ id TEXT PRIMARY KEY,
+ portfolio_id TEXT NOT NULL,
+ name TEXT NOT NULL,
+ category TEXT DEFAULT 'savings',
+ target_amount REAL DEFAULT 0.0,
+ current_amount REAL DEFAULT 0.0,
+ deadline TEXT DEFAULT '',
+ priority TEXT DEFAULT 'medium',
+ is_completed INTEGER DEFAULT 0,
+ created_at TEXT DEFAULT (datetime('now')),
+ updated_at TEXT DEFAULT (datetime('now'))
+ )
+ )");
+}
+
+void PlanningView::refresh_goals(const std::string& portfolio_id) {
+ ensure_goals_table();
+ goals_.clear();
+
+ auto& dbi = db::Database::instance();
+ auto stmt = dbi.prepare(
+ "SELECT id, portfolio_id, name, category, target_amount, current_amount, "
+ "deadline, priority, is_completed, created_at, updated_at "
+ "FROM financial_goals WHERE portfolio_id = ? ORDER BY is_completed ASC, priority ASC, deadline ASC");
+ stmt.bind_text(1, portfolio_id);
+
+ while (stmt.step()) {
+ FinancialGoal g;
+ g.id = stmt.col_text(0);
+ g.portfolio_id = stmt.col_text(1);
+ g.name = stmt.col_text(2);
+ g.category = stmt.col_text(3);
+ g.target_amount = stmt.col_double(4);
+ g.current_amount = stmt.col_double(5);
+ g.deadline = stmt.col_text(6);
+ g.priority = stmt.col_text(7);
+ g.is_completed = stmt.col_int(8) != 0;
+ g.created_at = stmt.col_text(9);
+ g.updated_at = stmt.col_text(10);
+ goals_.push_back(g);
+ }
+
+ goals_loaded_ = true;
+}
+
+void PlanningView::create_goal(const std::string& portfolio_id) {
+ auto& dbi = db::Database::instance();
+ std::string id = db::generate_uuid();
+ double target = std::atof(goal_target_);
+ double current = std::atof(goal_current_);
+
+ auto stmt = dbi.prepare(
+ "INSERT INTO financial_goals (id, portfolio_id, name, category, target_amount, "
+ "current_amount, deadline, priority) VALUES (?, ?, ?, ?, ?, ?, ?, ?)");
+ stmt.bind_text(1, id);
+ stmt.bind_text(2, portfolio_id);
+ stmt.bind_text(3, std::string(goal_name_));
+ stmt.bind_text(4, std::string(GOAL_CATEGORY_KEYS[goal_category_idx_]));
+ stmt.bind_double(5, target);
+ stmt.bind_double(6, current);
+ stmt.bind_text(7, std::string(goal_deadline_));
+ stmt.bind_text(8, std::string(GOAL_PRIORITY_KEYS[goal_priority_idx_]));
+ stmt.execute();
+
+ goals_loaded_ = false;
+}
+
+void PlanningView::update_goal() {
+ auto& dbi = db::Database::instance();
+ double target = std::atof(goal_target_);
+ double current = std::atof(goal_current_);
+
+ auto stmt = dbi.prepare(
+ "UPDATE financial_goals SET name = ?, category = ?, target_amount = ?, "
+ "current_amount = ?, deadline = ?, priority = ?, updated_at = datetime('now') WHERE id = ?");
+ stmt.bind_text(1, std::string(goal_name_));
+ stmt.bind_text(2, std::string(GOAL_CATEGORY_KEYS[goal_category_idx_]));
+ stmt.bind_double(3, target);
+ stmt.bind_double(4, current);
+ stmt.bind_text(5, std::string(goal_deadline_));
+ stmt.bind_text(6, std::string(GOAL_PRIORITY_KEYS[goal_priority_idx_]));
+ stmt.bind_text(7, edit_goal_id_);
+ stmt.execute();
+
+ goals_loaded_ = false;
+}
+
+void PlanningView::delete_goal(const std::string& id) {
+ auto& dbi = db::Database::instance();
+ auto stmt = dbi.prepare("DELETE FROM financial_goals WHERE id = ?");
+ stmt.bind_text(1, id);
+ stmt.execute();
+
+ goals_loaded_ = false;
+}
+
+void PlanningView::toggle_goal_complete(const std::string& id, bool completed) {
+ auto& dbi = db::Database::instance();
+ auto stmt = dbi.prepare(
+ "UPDATE financial_goals SET is_completed = ?, updated_at = datetime('now') WHERE id = ?");
+ stmt.bind_int(1, completed ? 1 : 0);
+ stmt.bind_text(2, id);
+ stmt.execute();
+
+ goals_loaded_ = false;
+}
+
+// ============================================================================
+// Main render
+// ============================================================================
+
void PlanningView::render(const PortfolioSummary& summary) {
if (loaded_for_portfolio_ != summary.portfolio.id) {
allocation_loaded_ = false;
+ goals_loaded_ = false;
loaded_for_portfolio_ = summary.portfolio.id;
}
@@ -89,6 +219,12 @@ void PlanningView::render(const PortfolioSummary& summary) {
ImGui::EndTable();
}
}
+
+ ImGui::Spacing();
+ if (theme::SecondaryButton("Refresh")) {
+ allocation_loaded_ = false;
+ fetch_allocation(summary);
+ }
}
} else if (sub_tab_ == 1) {
@@ -172,12 +308,299 @@ void PlanningView::render(const PortfolioSummary& summary) {
}
} else {
- // Goals — placeholder
- theme::SectionHeader("Financial Goals");
- ImGui::TextColored(theme::colors::TEXT_DIM, "Set financial goals and track progress — coming soon.");
+ render_goals(summary);
+ }
+
+ render_goal_modal(summary.portfolio.id);
+}
+
+// ============================================================================
+// Goals tab render
+// ============================================================================
+
+void PlanningView::render_goals(const PortfolioSummary& summary) {
+ if (!goals_loaded_) {
+ refresh_goals(summary.portfolio.id);
+ }
+
+ // Header with create button
+ theme::SectionHeader("Financial Goals");
+ ImGui::SameLine(ImGui::GetContentRegionAvail().x - 100);
+ if (theme::AccentButton("+ New Goal")) {
+ show_create_goal_ = true;
+ show_edit_goal_ = false;
+ std::memset(goal_name_, 0, sizeof(goal_name_));
+ std::memset(goal_target_, 0, sizeof(goal_target_));
+ std::memset(goal_current_, 0, sizeof(goal_current_));
+ std::memset(goal_deadline_, 0, sizeof(goal_deadline_));
+ goal_category_idx_ = 0;
+ goal_priority_idx_ = 1;
+ }
+
+ if (goals_.empty()) {
+ ImGui::Spacing();
+ ImGui::TextColored(theme::colors::TEXT_DIM,
+ "No financial goals yet. Click '+ New Goal' to create one.");
+ ImGui::Spacing();
+ ImGui::TextColored(theme::colors::TEXT_DIM,
+ "Track savings targets, investment milestones, debt payoff, and emergency fund goals.");
+ return;
+ }
+
+ // Summary cards
+ int total_goals = static_cast<int>(goals_.size());
+ int completed = 0;
+ double total_target = 0;
+ double total_current = 0;
+ for (const auto& g : goals_) {
+ if (g.is_completed) completed++;
+ total_target += g.target_amount;
+ total_current += std::min(g.current_amount, g.target_amount);
+ }
+ double overall_progress = total_target > 0 ? (total_current / total_target) * 100.0 : 0.0;
+
+ ImGui::Spacing();
+ ImGui::BeginChild("##goal_summary", ImVec2(0, 50), ImGuiChildFlags_Borders);
+ {
+ char buf[64];
+ ImGui::BeginGroup();
+ ImGui::TextColored(theme::colors::TEXT_DIM, "Goals");
+ std::snprintf(buf, sizeof(buf), "%d / %d", completed, total_goals);
+ ImGui::TextColored(theme::colors::ACCENT, "%s", buf);
+ ImGui::EndGroup();
+
+ ImGui::SameLine(0, 40);
+ ImGui::BeginGroup();
+ ImGui::TextColored(theme::colors::TEXT_DIM, "Target Total");
+ std::snprintf(buf, sizeof(buf), "$%.0f", total_target);
+ ImGui::TextColored(theme::colors::TEXT_PRIMARY, "%s", buf);
+ ImGui::EndGroup();
+
+ ImGui::SameLine(0, 40);
+ ImGui::BeginGroup();
+ ImGui::TextColored(theme::colors::TEXT_DIM, "Current Total");
+ std::snprintf(buf, sizeof(buf), "$%.0f", total_current);
+ ImGui::TextColored(theme::colors::MARKET_GREEN, "%s", buf);
+ ImGui::EndGroup();
+
+ ImGui::SameLine(0, 40);
+ ImGui::BeginGroup();
+ ImGui::TextColored(theme::colors::TEXT_DIM, "Overall Progress");
+ std::snprintf(buf, sizeof(buf), "%.1f%%", overall_progress);
+ ImVec4 prog_col = overall_progress >= 75 ? theme::colors::MARKET_GREEN
+ : overall_progress >= 40 ? ImVec4(1, 0.8f, 0, 1) : theme::colors::MARKET_RED;
+ ImGui::TextColored(prog_col, "%s", buf);
+ ImGui::EndGroup();
+
+ // Link portfolio value
+ ImGui::SameLine(0, 40);
+ ImGui::BeginGroup();
+ ImGui::TextColored(theme::colors::TEXT_DIM, "Portfolio Value");
+ std::snprintf(buf, sizeof(buf), "$%.2f", summary.total_market_value);
+ ImGui::TextColored(theme::colors::ACCENT, "%s", buf);
+ ImGui::EndGroup();
+ }
+ ImGui::EndChild();
+
+ ImGui::Spacing();
+
+ // Goals table
+ if (ImGui::BeginTable("##goals_table", 9,
+ ImGuiTableFlags_RowBg | ImGuiTableFlags_Borders | ImGuiTableFlags_Resizable |
+ ImGuiTableFlags_ScrollY, ImVec2(0, ImGui::GetContentRegionAvail().y - 4))) {
+
+ ImGui::TableSetupColumn("", ImGuiTableColumnFlags_WidthFixed, 24); // checkbox
+ ImGui::TableSetupColumn("Name", ImGuiTableColumnFlags_WidthFixed, 160);
+ ImGui::TableSetupColumn("Category", ImGuiTableColumnFlags_WidthFixed, 90);
+ ImGui::TableSetupColumn("Priority", ImGuiTableColumnFlags_WidthFixed, 60);
+ ImGui::TableSetupColumn("Target", ImGuiTableColumnFlags_WidthFixed, 90);
+ ImGui::TableSetupColumn("Current", ImGuiTableColumnFlags_WidthFixed, 90);
+ ImGui::TableSetupColumn("Progress", ImGuiTableColumnFlags_WidthStretch);
+ ImGui::TableSetupColumn("Deadline", ImGuiTableColumnFlags_WidthFixed, 85);
+ ImGui::TableSetupColumn("Actions", ImGuiTableColumnFlags_WidthFixed, 80);
+ ImGui::TableHeadersRow();
+ ImGui::TableSetupScrollFreeze(0, 1);
+
+ for (const auto& g : goals_) {
+ ImGui::TableNextRow();
+ ImGui::PushID(g.id.c_str());
+
+ // Checkbox
+ ImGui::TableNextColumn();
+ bool completed_flag = g.is_completed;
+ if (ImGui::Checkbox("##done", &completed_flag)) {
+ toggle_goal_complete(g.id, completed_flag);
+ }
+
+ // Name (dimmed if completed)
+ ImGui::TableNextColumn();
+ if (g.is_completed) {
+ ImGui::TextColored(theme::colors::TEXT_DIM, "%s", g.name.c_str());
+ } else {
+ ImGui::TextUnformatted(g.name.c_str());
+ }
+
+ // Category with color
+ ImGui::TableNextColumn();
+ ImVec4 cat_col = theme::colors::TEXT_DIM;
+ if (g.category == "savings") cat_col = ImVec4(0.2f, 0.7f, 0.9f, 1.0f);
+ else if (g.category == "investment") cat_col = theme::colors::MARKET_GREEN;
+ else if (g.category == "debt") cat_col = theme::colors::MARKET_RED;
+ else if (g.category == "emergency") cat_col = ImVec4(1.0f, 0.6f, 0.0f, 1.0f);
+ ImGui::TextColored(cat_col, "%s", g.category.c_str());
+
+ // Priority
+ ImGui::TableNextColumn();
+ ImVec4 pri_col = theme::colors::TEXT_DIM;
+ if (g.priority == "high") pri_col = theme::colors::MARKET_RED;
+ else if (g.priority == "medium") pri_col = ImVec4(1, 0.8f, 0, 1);
+ else if (g.priority == "low") pri_col = theme::colors::MARKET_GREEN;
+ ImGui::TextColored(pri_col, "%s", g.priority.c_str());
+
+ // Target
+ ImGui::TableNextColumn();
+ ImGui::Text("$%.0f", g.target_amount);
+
+ // Current
+ ImGui::TableNextColumn();
+ ImGui::Text("$%.0f", g.current_amount);
+
+ // Progress bar
+ ImGui::TableNextColumn();
+ float progress = g.target_amount > 0
+ ? static_cast<float>(g.current_amount / g.target_amount) : 0.0f;
+ if (progress > 1.0f) progress = 1.0f;
+
+ // Color the progress bar
+ ImVec4 bar_col = progress >= 1.0f ? theme::colors::MARKET_GREEN
+ : progress >= 0.5f ? ImVec4(0.2f, 0.7f, 0.3f, 1.0f)
+ : progress >= 0.25f ? ImVec4(1.0f, 0.8f, 0.0f, 1.0f)
+ : ImVec4(0.9f, 0.3f, 0.2f, 1.0f);
+ ImGui::PushStyleColor(ImGuiCol_PlotHistogram, bar_col);
+ char overlay[32];
+ std::snprintf(overlay, sizeof(overlay), "%.0f%%", progress * 100);
+ ImGui::ProgressBar(progress, ImVec2(-1, 16), overlay);
+ ImGui::PopStyleColor();
+
+ // Deadline
+ ImGui::TableNextColumn();
+ if (!g.deadline.empty()) {
+ ImGui::TextColored(theme::colors::TEXT_DIM, "%s", g.deadline.c_str());
+ } else {
+ ImGui::TextColored(theme::colors::TEXT_DIM, "--");
+ }
+
+ // Actions
+ ImGui::TableNextColumn();
+ if (ImGui::SmallButton("Edit")) {
+ show_edit_goal_ = true;
+ show_create_goal_ = false;
+ edit_goal_id_ = g.id;
+ std::strncpy(goal_name_, g.name.c_str(), sizeof(goal_name_) - 1);
+ std::snprintf(goal_target_, sizeof(goal_target_), "%.0f", g.target_amount);
+ std::snprintf(goal_current_, sizeof(goal_current_), "%.0f", g.current_amount);
+ std::strncpy(goal_deadline_, g.deadline.c_str(), sizeof(goal_deadline_) - 1);
+
+ // Find category index
+ goal_category_idx_ = 0;
+ for (int i = 0; i < NUM_GOAL_CATEGORIES; i++) {
+ if (g.category == GOAL_CATEGORY_KEYS[i]) { goal_category_idx_ = i; break; }
+ }
+ // Find priority index
+ goal_priority_idx_ = 1;
+ for (int i = 0; i < NUM_GOAL_PRIORITIES; i++) {
+ if (g.priority == GOAL_PRIORITY_KEYS[i]) { goal_priority_idx_ = i; break; }
+ }
+ }
+ ImGui::SameLine();
+ ImGui::PushStyleColor(ImGuiCol_Button, ImVec4(0.5f, 0, 0, 1));
+ if (ImGui::SmallButton("X")) {
+ delete_goal(g.id);
+ }
+ ImGui::PopStyleColor();
+
+ ImGui::PopID();
+ }
+ ImGui::EndTable();
}
}
+// ============================================================================
+// Goal create/edit modal
+// ============================================================================
+
+void PlanningView::render_goal_modal(const std::string& portfolio_id) {
+ bool show = show_create_goal_ || show_edit_goal_;
+ if (!show) return;
+
+ const char* title = show_create_goal_ ? "Create Financial Goal" : "Edit Financial Goal";
+ ImGui::OpenPopup(title);
+
+ ImVec2 center = ImGui::GetMainViewport()->GetCenter();
+ ImGui::SetNextWindowPos(center, ImGuiCond_Appearing, ImVec2(0.5f, 0.5f));
+ ImGui::SetNextWindowSize(ImVec2(420, 320));
+
+ bool open = true;
+ if (ImGui::BeginPopupModal(title, &open, ImGuiWindowFlags_NoResize)) {
+ ImGui::Text("Name"); ImGui::SameLine(120);
+ ImGui::SetNextItemWidth(-1);
+ ImGui::InputTextWithHint("##gname", "e.g. Emergency Fund", goal_name_, sizeof(goal_name_));
+
+ ImGui::Text("Category"); ImGui::SameLine(120);
+ ImGui::SetNextItemWidth(-1);
+ ImGui::Combo("##gcat", &goal_category_idx_, GOAL_CATEGORIES, NUM_GOAL_CATEGORIES);
+
+ ImGui::Text("Priority"); ImGui::SameLine(120);
+ ImGui::SetNextItemWidth(-1);
+ ImGui::Combo("##gpri", &goal_priority_idx_, GOAL_PRIORITIES, NUM_GOAL_PRIORITIES);
+
+ ImGui::Text("Target ($)"); ImGui::SameLine(120);
+ ImGui::SetNextItemWidth(-1);
+ ImGui::InputTextWithHint("##gtarget", "50000", goal_target_, sizeof(goal_target_));
+
+ ImGui::Text("Current ($)"); ImGui::SameLine(120);
+ ImGui::SetNextItemWidth(-1);
+ ImGui::InputTextWithHint("##gcurrent", "12000", goal_current_, sizeof(goal_current_));
+
+ ImGui::Text("Deadline"); ImGui::SameLine(120);
+ ImGui::SetNextItemWidth(-1);
+ ImGui::InputTextWithHint("##gdeadline", "2027-12-31", goal_deadline_, sizeof(goal_deadline_));
+
+ ImGui::Spacing();
+ ImGui::Spacing();
+
+ if (theme::AccentButton(show_create_goal_ ? "Create" : "Save")) {
+ if (goal_name_[0] != '\0') {
+ if (show_create_goal_) {
+ create_goal(portfolio_id);
+ } else {
+ update_goal();
+ }
+ show_create_goal_ = false;
+ show_edit_goal_ = false;
+ ImGui::CloseCurrentPopup();
+ }
+ }
+ ImGui::SameLine();
+ if (theme::SecondaryButton("Cancel")) {
+ show_create_goal_ = false;
+ show_edit_goal_ = false;
+ ImGui::CloseCurrentPopup();
+ }
+
+ ImGui::EndPopup();
+ }
+
+ if (!open) {
+ show_create_goal_ = false;
+ show_edit_goal_ = false;
+ }
+}
+
+// ============================================================================
+// Allocation fetch (with fixed error handling)
+// ============================================================================
+
void PlanningView::fetch_allocation(const PortfolioSummary& summary) {
if (loading_) return;
loading_ = true;
@@ -225,17 +648,20 @@ void PlanningView::fetch_allocation(const PortfolioSummary& summary) {
if (!j.is_discarded()) {
if (j.contains("error"))
error_ = j["error"].get<std::string>();
- else
+ else {
allocation_result_ = j;
+ allocation_loaded_ = true;
+ }
}
} else if (error_.empty()) {
error_ = "Script returned empty output";
}
- allocation_loaded_ = true;
+ // On success with data, allocation_loaded_ is already set above.
+ // On error (error_ is non-empty), leave allocation_loaded_ = false so user can retry.
} catch (const std::exception& e) {
error_ = e.what();
LOG_ERROR("PlanningView", "Allocation analysis failed: %s", e.what());
- allocation_loaded_ = true;
+ // Leave allocation_loaded_ = false so the Retry button shows
}
loading_ = false;
}).detach();
diff --git a/fincept-cpp/src/screens/portfolio/views/planning_view.h b/fincept-cpp/src/screens/portfolio/views/planning_view.h
index 61703ff41..e8a0fe638 100644
--- a/fincept-cpp/src/screens/portfolio/views/planning_view.h
+++ b/fincept-cpp/src/screens/portfolio/views/planning_view.h
@@ -1,10 +1,26 @@
#pragma once
#include "portfolio/portfolio_types.h"
#include <string>
+#include <vector>
#include <nlohmann/json.hpp>
namespace fincept::portfolio {
+// Financial goal stored in SQLite
+struct FinancialGoal {
+ std::string id;
+ std::string portfolio_id;
+ std::string name;
+ std::string category; // "savings", "investment", "debt", "emergency", "custom"
+ double target_amount = 0.0;
+ double current_amount = 0.0;
+ std::string deadline; // YYYY-MM-DD
+ std::string priority; // "high", "medium", "low"
+ bool is_completed = false;
+ std::string created_at;
+ std::string updated_at;
+};
+
// Planning Panel — Asset allocation, retirement planning, goal tracking
class PlanningView {
public:
@@ -27,8 +43,31 @@ private:
char expected_return_[8] = "7.0";
char inflation_[8] = "3.0";
+ // Goals state
+ std::vector<FinancialGoal> goals_;
+ bool goals_loaded_ = false;
+ bool show_create_goal_ = false;
+ bool show_edit_goal_ = false;
+ std::string edit_goal_id_;
+ char goal_name_[128] = {};
+ char goal_target_[32] = {};
+ char goal_current_[32] = {};
+ char goal_deadline_[16] = {};
+ int goal_category_idx_ = 0;
+ int goal_priority_idx_ = 1; // default "medium"
+
void fetch_allocation(const PortfolioSummary& summary);
void fetch_retirement();
+
+ // Goals methods
+ void ensure_goals_table();
+ void refresh_goals(const std::string& portfolio_id);
+ void create_goal(const std::string& portfolio_id);
+ void update_goal();
+ void delete_goal(const std::string& id);
+ void toggle_goal_complete(const std::string& id, bool completed);
+ void render_goals(const PortfolioSummary& summary);
+ void render_goal_modal(const std::string& portfolio_id);
};
} // namespace fincept::portfolio
diff --git a/fincept-cpp/src/screens/report_builder/report_builder_screen.cpp b/fincept-cpp/src/screens/report_builder/report_builder_screen.cpp
index f5b3b30e4..f1cd9907d 100644
--- a/fincept-cpp/src/screens/report_builder/report_builder_screen.cpp
+++ b/fincept-cpp/src/screens/report_builder/report_builder_screen.cpp
@@ -8,6 +8,17 @@
#include <cmath>
#include <ctime>
#include <algorithm>
+#include <fstream>
+#include <sstream>
+#include <filesystem>
+
+#ifdef _WIN32
+#include <windows.h>
+#include <commdlg.h>
+#include <shlobj.h>
+#endif
+
+namespace fs = std::filesystem;
namespace fincept::report_builder {
@@ -876,14 +887,23 @@ void ReportBuilderScreen::render_export_dialog() {
if (ImGui::Button("Export", ImVec2(120, 0))) {
export_report(export_format_);
- show_export_dialog_ = false;
- ImGui::CloseCurrentPopup();
+ if (export_success_) {
+ show_export_dialog_ = false;
+ ImGui::CloseCurrentPopup();
+ }
}
ImGui::SameLine();
if (ImGui::Button("Cancel", ImVec2(120, 0))) {
show_export_dialog_ = false;
ImGui::CloseCurrentPopup();
}
+
+ if (export_status_[0] != '\0') {
+ ImGui::Spacing();
+ const ImVec4& col = export_success_ ? theme::colors::SUCCESS : theme::colors::MARKET_RED;
+ ImGui::TextColored(col, "%s", export_status_);
+ }
+
ImGui::EndPopup();
}
}
@@ -1031,12 +1051,862 @@ void ReportBuilderScreen::apply_template_preset(int preset_idx) {
LOG_INFO(TAG, "Applied template: %s", TEMPLATE_PRESETS[preset_idx].name);
}
+// ============================================================================
+// Native Save Dialog
+// ============================================================================
+
+std::string ReportBuilderScreen::native_save_dialog(const char* filter,
+ const char* title,
+ const char* default_ext) {
+#ifdef _WIN32
+ char filename[MAX_PATH] = {};
+ // Pre-fill with document name
+ std::snprintf(filename, MAX_PATH - 1, "%s", document_.name);
+ // Replace spaces with underscores for a safe filename
+ for (char* p = filename; *p; ++p) {
+ if (*p == ' ') *p = '_';
+ }
+
+ OPENFILENAMEA ofn = {};
+ ofn.lStructSize = sizeof(ofn);
+ ofn.hwndOwner = nullptr;
+ ofn.lpstrFilter = filter;
+ ofn.lpstrFile = filename;
+ ofn.nMaxFile = MAX_PATH;
+ ofn.lpstrTitle = title;
+ ofn.lpstrDefExt = default_ext;
+ ofn.Flags = OFN_OVERWRITEPROMPT | OFN_NOCHANGEDIR;
+ if (GetSaveFileNameA(&ofn)) return std::string(filename);
+ return "";
+#else
+ // Fallback: save to Documents or home directory
+ const char* home = std::getenv("HOME");
+ if (!home) home = ".";
+ std::string path = std::string(home) + "/" + document_.name + "." + default_ext;
+ // Replace spaces
+ for (char& c : path) if (c == ' ') c = '_';
+ return path;
+#endif
+}
+
+// ============================================================================
+// HTML Export
+// ============================================================================
+
+static std::string html_escape(const std::string& s) {
+ std::string out;
+ out.reserve(s.size());
+ for (char c : s) {
+ switch (c) {
+ case '&': out += "&amp;"; break;
+ case '<': out += "&lt;"; break;
+ case '>': out += "&gt;"; break;
+ case '"': out += "&quot;"; break;
+ case '\'': out += "&#39;"; break;
+ default: out += c; break;
+ }
+ }
+ return out;
+}
+
+bool ReportBuilderScreen::export_as_html(const std::string& path) {
+ std::ofstream f(path);
+ if (!f.is_open()) return false;
+
+ f << "<!DOCTYPE html>\n<html lang=\"en\">\n<head>\n"
+ << "<meta charset=\"UTF-8\">\n"
+ << "<meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\">\n"
+ << "<title>" << html_escape(document_.name) << "</title>\n"
+ << "<style>\n"
+ << "body{font-family:'Segoe UI',Arial,sans-serif;background:#1a1a1c;color:#e8e8ec;"
+ "max-width:860px;margin:40px auto;padding:0 32px;line-height:1.6}\n"
+ << "h1{font-size:2em;color:#ff730d;border-bottom:2px solid #ff730d;padding-bottom:8px;margin-top:32px}\n"
+ << "h2{font-size:1.4em;color:#c8c8d0;margin-top:24px}\n"
+ << "p{color:#b8b8bf;margin:8px 0}\n"
+ << "blockquote{border-left:4px solid #ff730d;margin:12px 0;padding:8px 16px;"
+ "background:#26262a;color:#b8b8bf}\n"
+ << ".disclaimer{background:#2a2208;border:1px solid #ffc714;padding:10px 16px;"
+ "border-radius:4px;color:#ffc714;font-size:0.85em;margin:12px 0}\n"
+ << "table{border-collapse:collapse;width:100%;margin:12px 0}\n"
+ << "th{background:#2a2a2e;color:#ff730d;padding:8px 12px;text-align:left;"
+ "border:1px solid #3a3a3e}\n"
+ << "td{padding:7px 12px;border:1px solid #2e2e32;color:#b8b8bf}\n"
+ << "tr:nth-child(even) td{background:#1e1e22}\n"
+ << ".kpi-row{display:flex;gap:12px;margin:12px 0;flex-wrap:wrap}\n"
+ << ".kpi{background:#26262a;border:1px solid #3a3a3e;border-radius:6px;"
+ "padding:14px 20px;min-width:120px;flex:1}\n"
+ << ".kpi-label{font-size:0.8em;color:#888891;margin-bottom:4px}\n"
+ << ".kpi-value{font-size:1.5em;font-weight:700;color:#f3f3f5}\n"
+ << ".kpi-change.up{color:#0dd96b}.kpi-change.down{color:#f54040}\n"
+ << ".chart{background:#141416;border:1px solid #3a3a3e;border-radius:4px;"
+ "padding:12px;margin:12px 0;overflow:hidden}\n"
+ << ".bar-chart{display:flex;align-items:flex-end;gap:4px;height:140px;padding:8px 0}\n"
+ << ".bar{background:#ff730d;border-radius:3px 3px 0 0;min-width:20px;"
+ "transition:opacity 0.2s;flex:1}\n"
+ << ".bar.neg{background:#f54040}\n"
+ << ".bar-label{font-size:0.7em;color:#888891;text-align:center;margin-top:4px}\n"
+ << "pre{background:#0e0e10;border:1px solid #2a2a2e;border-radius:4px;"
+ "padding:14px;overflow-x:auto;color:#0dd96b;font-size:0.9em}\n"
+ << ".lang-tag{font-size:0.75em;color:#888891;margin-bottom:4px}\n"
+ << "ul,ol{color:#b8b8bf;padding-left:24px;margin:8px 0}\n"
+ << "li{margin:4px 0}\n"
+ << "hr{border:none;border-top:1px solid #2e2e32;margin:20px 0}\n"
+ << ".page-break{text-align:center;color:#444;font-size:0.8em;margin:20px 0;"
+ "border-top:1px dashed #333;padding-top:8px}\n"
+ << ".header{margin-bottom:32px;padding-bottom:16px;border-bottom:1px solid #2e2e32}\n"
+ << ".meta{color:#888891;font-size:0.85em;margin-top:6px}\n"
+ << "</style>\n</head>\n<body>\n";
+
+ // Document header
+ f << "<div class=\"header\">\n"
+ << "<h1 style=\"border:none;margin:0\">" << html_escape(document_.name) << "</h1>\n";
+ if (document_.author[0] || document_.company[0] || document_.date[0]) {
+ f << "<div class=\"meta\">";
+ if (document_.author[0]) f << html_escape(document_.author);
+ if (document_.author[0] && document_.company[0]) f << " &mdash; ";
+ if (document_.company[0]) f << html_escape(document_.company);
+ if (document_.date[0]) f << " &nbsp;|&nbsp; " << html_escape(document_.date);
+ f << "</div>\n";
+ }
+ f << "</div>\n";
+
+ // Components
+ for (const auto& comp : document_.components) {
+ switch (comp.type) {
+ case ComponentType::heading:
+ f << "<h1>" << html_escape(comp.content) << "</h1>\n";
+ break;
+ case ComponentType::subheading:
+ f << "<h2>" << html_escape(comp.content) << "</h2>\n";
+ break;
+ case ComponentType::text:
+ f << "<p>" << html_escape(comp.content) << "</p>\n";
+ break;
+ case ComponentType::quote:
+ f << "<blockquote>" << html_escape(comp.content) << "</blockquote>\n";
+ break;
+ case ComponentType::disclaimer:
+ f << "<div class=\"disclaimer\">&#9888; " << html_escape(comp.content) << "</div>\n";
+ break;
+ case ComponentType::divider:
+ f << "<hr>\n";
+ break;
+ case ComponentType::page_break:
+ f << "<div class=\"page-break\" style=\"page-break-after:always\">"
+ << "&#8212; Page Break &#8212;</div>\n";
+ break;
+ case ComponentType::table: {
+ const int rows = std::max(1, comp.table_rows);
+ const int cols = std::max(1, comp.table_cols);
+ f << "<table>\n";
+ for (int r = 0; r < rows; ++r) {
+ f << "<tr>";
+ for (int c = 0; c < cols; ++c) {
+ const int idx = r * cols + c;
+ std::string cell;
+ if (idx < static_cast<int>(comp.table_cells.size()))
+ cell = comp.table_cells[idx];
+ if (r == 0)
+ f << "<th>" << html_escape(cell.empty() ? "Header" : cell) << "</th>";
+ else
+ f << "<td>" << html_escape(cell.empty() ? "" : cell) << "</td>";
+ }
+ f << "</tr>\n";
+ }
+ f << "</table>\n";
+ break;
+ }
+ case ComponentType::chart: {
+ f << "<div class=\"chart\">\n";
+ const char* ct = chart_type_label(comp.chart_type);
+ f << "<div style=\"color:#888891;font-size:0.8em;margin-bottom:8px\">"
+ << ct << " Chart</div>\n";
+ if (!comp.chart_data.empty()) {
+ double max_val = 1.0;
+ for (double v : comp.chart_data) max_val = std::max(max_val, std::abs(v));
+ f << "<div class=\"bar-chart\">\n";
+ for (size_t i = 0; i < comp.chart_data.size(); ++i) {
+ const double v = comp.chart_data[i];
+ const int pct = static_cast<int>(std::abs(v) / max_val * 100.0);
+ const char* cls = (v >= 0) ? "bar" : "bar neg";
+ f << "<div style=\"display:flex;flex-direction:column;align-items:center;flex:1\">"
+ << "<div class=\"" << cls << "\" style=\"height:" << pct << "%\"></div>"
+ << "<div class=\"bar-label\">";
+ if (i < comp.chart_labels.size() && !comp.chart_labels[i].empty())
+ f << html_escape(comp.chart_labels[i]);
+ else
+ f << v;
+ f << "</div></div>\n";
+ }
+ f << "</div>\n";
+ } else {
+ f << "<div style=\"color:#555;text-align:center;padding:40px 0\">No data</div>\n";
+ }
+ f << "</div>\n";
+ break;
+ }
+ case ComponentType::kpi: {
+ if (!comp.kpis.empty()) {
+ f << "<div class=\"kpi-row\">\n";
+ for (const auto& k : comp.kpis) {
+ const char* dir = k.trend_up ? "up" : "down";
+ const char* arrow = k.trend_up ? "&#8593;" : "&#8595;";
+ f << "<div class=\"kpi\">"
+ << "<div class=\"kpi-label\">" << html_escape(k.label) << "</div>"
+ << "<div class=\"kpi-value\">" << html_escape(k.value) << "</div>"
+ << "<div class=\"kpi-change " << dir << "\">"
+ << arrow << " ";
+ char chg[32];
+ std::snprintf(chg, sizeof(chg), "%.1f%%", std::abs(k.change));
+ f << chg << "</div></div>\n";
+ }
+ f << "</div>\n";
+ }
+ break;
+ }
+ case ComponentType::code_block:
+ f << "<div class=\"lang-tag\">" << html_escape(comp.language) << "</div>\n"
+ << "<pre>" << html_escape(comp.content) << "</pre>\n";
+ break;
+ case ComponentType::list: {
+ const char* tag = comp.ordered ? "ol" : "ul";
+ f << "<" << tag << ">\n";
+ for (const auto& item : comp.list_items)
+ f << "<li>" << html_escape(item) << "</li>\n";
+ f << "</" << tag << ">\n";
+ break;
+ }
+ case ComponentType::cover_page:
+ f << "<div style=\"text-align:center;padding:60px 0\">"
+ << "<h1 style=\"font-size:2.5em\">" << html_escape(comp.content[0] ? comp.content : document_.name) << "</h1>"
+ << "</div>\n";
+ break;
+ case ComponentType::image:
+ f << "<div style=\"text-align:center;padding:20px;border:1px dashed #444\">"
+ << "[Image: " << html_escape(comp.content) << "]</div>\n";
+ break;
+ }
+ }
+
+ f << "\n</body>\n</html>\n";
+ return f.good();
+}
+
+// ============================================================================
+// Markdown Export
+// ============================================================================
+
+bool ReportBuilderScreen::export_as_markdown(const std::string& path) {
+ std::ofstream f(path);
+ if (!f.is_open()) return false;
+
+ // YAML front matter
+ f << "---\n"
+ << "title: " << document_.name << "\n";
+ if (document_.author[0]) f << "author: " << document_.author << "\n";
+ if (document_.company[0]) f << "company: " << document_.company << "\n";
+ if (document_.date[0]) f << "date: " << document_.date << "\n";
+ f << "---\n\n";
+
+ f << "# " << document_.name << "\n\n";
+
+ for (const auto& comp : document_.components) {
+ switch (comp.type) {
+ case ComponentType::heading:
+ f << "# " << comp.content << "\n\n";
+ break;
+ case ComponentType::subheading:
+ f << "## " << comp.content << "\n\n";
+ break;
+ case ComponentType::text:
+ f << comp.content << "\n\n";
+ break;
+ case ComponentType::quote:
+ f << "> " << comp.content << "\n\n";
+ break;
+ case ComponentType::disclaimer:
+ f << "> **Disclaimer:** " << comp.content << "\n\n";
+ break;
+ case ComponentType::divider:
+ f << "---\n\n";
+ break;
+ case ComponentType::page_break:
+ f << "\n<!-- page break -->\n\n";
+ break;
+ case ComponentType::table: {
+ const int rows = std::max(1, comp.table_rows);
+ const int cols = std::max(1, comp.table_cols);
+ // Header row
+ for (int c = 0; c < cols; ++c) {
+ const int idx = c;
+ std::string cell;
+ if (idx < static_cast<int>(comp.table_cells.size()))
+ cell = comp.table_cells[idx];
+ f << "| " << (cell.empty() ? "Header" : cell) << " ";
+ }
+ f << "|\n";
+ // Separator
+ for (int c = 0; c < cols; ++c) f << "| --- ";
+ f << "|\n";
+ // Data rows
+ for (int r = 1; r < rows; ++r) {
+ for (int c = 0; c < cols; ++c) {
+ const int idx = r * cols + c;
+ std::string cell;
+ if (idx < static_cast<int>(comp.table_cells.size()))
+ cell = comp.table_cells[idx];
+ f << "| " << cell << " ";
+ }
+ f << "|\n";
+ }
+ f << "\n";
+ break;
+ }
+ case ComponentType::chart: {
+ f << "**" << chart_type_label(comp.chart_type) << " Chart**\n\n";
+ if (!comp.chart_data.empty()) {
+ f << "| Index | Value |\n| --- | --- |\n";
+ for (size_t i = 0; i < comp.chart_data.size(); ++i) {
+ std::string label = (i < comp.chart_labels.size()) ? comp.chart_labels[i] : std::to_string(i + 1);
+ f << "| " << label << " | " << comp.chart_data[i] << " |\n";
+ }
+ f << "\n";
+ }
+ break;
+ }
+ case ComponentType::kpi: {
+ if (!comp.kpis.empty()) {
+ f << "| Metric | Value | Change |\n| --- | --- | --- |\n";
+ for (const auto& k : comp.kpis) {
+ char chg[32];
+ std::snprintf(chg, sizeof(chg), "%+.1f%%", k.change);
+ f << "| " << k.label << " | " << k.value << " | " << chg << " |\n";
+ }
+ f << "\n";
+ }
+ break;
+ }
+ case ComponentType::code_block:
+ f << "```" << comp.language << "\n"
+ << comp.content << "\n```\n\n";
+ break;
+ case ComponentType::list:
+ for (size_t i = 0; i < comp.list_items.size(); ++i) {
+ if (comp.ordered)
+ f << (i + 1) << ". " << comp.list_items[i] << "\n";
+ else
+ f << "- " << comp.list_items[i] << "\n";
+ }
+ f << "\n";
+ break;
+ case ComponentType::cover_page:
+ f << "# " << (comp.content[0] ? comp.content : document_.name) << "\n\n";
+ break;
+ case ComponentType::image:
+ f << "![image](" << comp.content << ")\n\n";
+ break;
+ }
+ }
+
+ return f.good();
+}
+
+// ============================================================================
+// CSV Export — flattens all table components; other blocks as comment rows
+// ============================================================================
+
+bool ReportBuilderScreen::export_as_csv(const std::string& path) {
+ std::ofstream f(path);
+ if (!f.is_open()) return false;
+
+ f << "\"Report\",\"" << document_.name << "\"\n";
+ if (document_.author[0]) f << "\"Author\",\"" << document_.author << "\"\n";
+ if (document_.date[0]) f << "\"Date\",\"" << document_.date << "\"\n";
+ f << "\n";
+
+ // Lambda to quote a CSV field
+ auto csv_cell = [](const std::string& s) -> std::string {
+ std::string out = "\"";
+ for (char c : s) {
+ if (c == '"') out += "\"\"";
+ else out += c;
+ }
+ out += '"';
+ return out;
+ };
+
+ for (const auto& comp : document_.components) {
+ switch (comp.type) {
+ case ComponentType::heading:
+ f << csv_cell(std::string("## ") + comp.content) << "\n\n";
+ break;
+ case ComponentType::subheading:
+ f << csv_cell(std::string("### ") + comp.content) << "\n\n";
+ break;
+ case ComponentType::text:
+ case ComponentType::quote:
+ case ComponentType::disclaimer:
+ f << csv_cell(comp.content) << "\n\n";
+ break;
+ case ComponentType::table: {
+ const int rows = std::max(1, comp.table_rows);
+ const int cols = std::max(1, comp.table_cols);
+ for (int r = 0; r < rows; ++r) {
+ for (int c = 0; c < cols; ++c) {
+ if (c > 0) f << ",";
+ const int idx = r * cols + c;
+ std::string cell;
+ if (idx < static_cast<int>(comp.table_cells.size()))
+ cell = comp.table_cells[idx];
+ f << csv_cell(cell);
+ }
+ f << "\n";
+ }
+ f << "\n";
+ break;
+ }
+ case ComponentType::chart: {
+ f << csv_cell(std::string(chart_type_label(comp.chart_type)) + " Chart") << "\n";
+ f << "\"Label\",\"Value\"\n";
+ for (size_t i = 0; i < comp.chart_data.size(); ++i) {
+ std::string label = (i < comp.chart_labels.size()) ? comp.chart_labels[i] : std::to_string(i + 1);
+ f << csv_cell(label) << "," << comp.chart_data[i] << "\n";
+ }
+ f << "\n";
+ break;
+ }
+ case ComponentType::kpi: {
+ f << "\"Metric\",\"Value\",\"Change\"\n";
+ for (const auto& k : comp.kpis) {
+ char chg[32];
+ std::snprintf(chg, sizeof(chg), "%+.1f%%", k.change);
+ f << csv_cell(k.label) << "," << csv_cell(k.value) << "," << csv_cell(chg) << "\n";
+ }
+ f << "\n";
+ break;
+ }
+ case ComponentType::list:
+ for (size_t i = 0; i < comp.list_items.size(); ++i) {
+ if (comp.ordered)
+ f << (i + 1) << "," << csv_cell(comp.list_items[i]) << "\n";
+ else
+ f << csv_cell(comp.list_items[i]) << "\n";
+ }
+ f << "\n";
+ break;
+ default:
+ break;
+ }
+ }
+
+ return f.good();
+}
+
+// ============================================================================
+// PDF Export — minimal valid PDF using stdlib only (no external libs)
+// Generates text-based PDF with basic formatting for all component types
+// ============================================================================
+
+bool ReportBuilderScreen::export_as_pdf(const std::string& path) {
+ // PDF uses points (72pt = 1 inch). A4 = 595 x 842 pt.
+ static constexpr float PAGE_W = 595.0f;
+ static constexpr float PAGE_H = 842.0f;
+ static constexpr float MARGIN = 60.0f;
+ static constexpr float TEXT_W = PAGE_W - 2.0f * MARGIN;
+
+ // We build the PDF in memory so we can compute byte offsets for xref
+ std::vector<std::string> objects; // PDF objects (1-indexed, obj 0 unused)
+ objects.emplace_back(""); // placeholder for obj 0
+
+ // Helper: add object and return its 1-based id
+ auto add_obj = [&](std::string s) -> int {
+ objects.push_back(std::move(s));
+ return static_cast<int>(objects.size()) - 1;
+ };
+
+ // Accumulate page content streams per page
+ // We'll do simple text layout: cursor_y starts at top margin and decrements
+ struct PageContent { std::string stream; };
+ std::vector<PageContent> pages;
+ pages.push_back({});
+
+ float cursor_y = PAGE_H - MARGIN;
+ const float line_h_normal = 14.0f;
+ const float line_h_heading = 22.0f;
+ const float line_h_sub = 18.0f;
+
+ // Escape a string for PDF text (parentheses, backslash, non-ASCII)
+ auto pdf_str = [](const std::string& in) -> std::string {
+ std::string out;
+ out.reserve(in.size() + 16);
+ for (unsigned char c : in) {
+ if (c == '(' || c == ')' || c == '\\') { out += '\\'; out += static_cast<char>(c); }
+ else if (c >= 32 && c < 127) { out += static_cast<char>(c); }
+ else { /* skip non-printable */ }
+ }
+ return out;
+ };
+
+ // Emit text at position (x, y in PDF coordinates — origin bottom-left)
+ auto emit_text = [&](const std::string& text, float x, float y,
+ float font_size, bool bold) -> std::string {
+ std::ostringstream s;
+ s << "BT\n"
+ << "/" << (bold ? "F2" : "F1") << " " << font_size << " Tf\n"
+ << x << " " << y << " Td\n"
+ << "(" << pdf_str(text) << ") Tj\n"
+ << "ET\n";
+ return s.str();
+ };
+
+ // Wrap text into lines of approximately max_chars characters
+ auto wrap_text = [](const std::string& text, int max_chars) -> std::vector<std::string> {
+ std::vector<std::string> lines;
+ if (text.empty()) { lines.emplace_back(""); return lines; }
+ size_t pos = 0;
+ while (pos < text.size()) {
+ size_t end = std::min(pos + static_cast<size_t>(max_chars), text.size());
+ // Try to break at last space
+ if (end < text.size()) {
+ size_t sp = text.rfind(' ', end);
+ if (sp != std::string::npos && sp > pos) end = sp + 1;
+ }
+ lines.push_back(text.substr(pos, end - pos));
+ pos = end;
+ }
+ return lines;
+ };
+
+ // Ensure space on page; start new page if needed
+ auto ensure_space = [&](float needed) {
+ if (cursor_y - needed < MARGIN) {
+ pages.push_back({});
+ cursor_y = PAGE_H - MARGIN;
+ }
+ };
+
+ // Add a line of text to current page
+ auto add_line = [&](const std::string& text, float font_size, bool bold,
+ float indent = 0.0f, float extra_above = 0.0f) {
+ ensure_space(font_size + extra_above + 4.0f);
+ cursor_y -= extra_above;
+ pages.back().stream += emit_text(text, MARGIN + indent, cursor_y, font_size, bold);
+ cursor_y -= (font_size + 2.0f);
+ };
+
+ // Draw a horizontal line
+ auto add_rule = [&]() {
+ ensure_space(10.0f);
+ cursor_y -= 4.0f;
+ std::ostringstream s;
+ s << MARGIN << " " << cursor_y << " m "
+ << (PAGE_W - MARGIN) << " " << cursor_y << " l S\n";
+ pages.back().stream += s.str();
+ cursor_y -= 6.0f;
+ };
+
+ // --- Render document title ---
+ add_line(document_.name, 20.0f, true, 0.0f, 8.0f);
+ if (document_.author[0] || document_.company[0] || document_.date[0]) {
+ std::string meta;
+ if (document_.author[0]) { meta += document_.author; }
+ if (document_.author[0] && document_.company[0]) meta += " - ";
+ if (document_.company[0]) meta += document_.company;
+ if (document_.date[0]) { if (!meta.empty()) meta += " | "; meta += document_.date; }
+ add_line(meta, 9.0f, false);
+ }
+ add_rule();
+
+ // --- Render each component ---
+ for (const auto& comp : document_.components) {
+ switch (comp.type) {
+ case ComponentType::heading:
+ add_line(comp.content[0] ? comp.content : "Heading", line_h_heading, true, 0.0f, 8.0f);
+ add_rule();
+ break;
+ case ComponentType::subheading:
+ add_line(comp.content[0] ? comp.content : "Subheading", line_h_sub, true, 0.0f, 6.0f);
+ break;
+ case ComponentType::text:
+ case ComponentType::disclaimer: {
+ const auto lines = wrap_text(comp.content[0] ? comp.content : "", 85);
+ for (const auto& ln : lines) add_line(ln, line_h_normal, false);
+ cursor_y -= 4.0f;
+ break;
+ }
+ case ComponentType::quote: {
+ const auto lines = wrap_text(comp.content[0] ? comp.content : "", 78);
+ for (const auto& ln : lines) add_line(" " + ln, line_h_normal, false, 8.0f);
+ cursor_y -= 4.0f;
+ break;
+ }
+ case ComponentType::divider:
+ add_rule();
+ break;
+ case ComponentType::page_break:
+ pages.push_back({});
+ cursor_y = PAGE_H - MARGIN;
+ break;
+ case ComponentType::table: {
+ const int rows = std::max(1, comp.table_rows);
+ const int cols = std::max(1, comp.table_cols);
+ const float col_w = TEXT_W / static_cast<float>(cols);
+ const float row_h = 14.0f;
+ ensure_space(static_cast<float>(rows) * row_h + 8.0f);
+ cursor_y -= 4.0f;
+ for (int r = 0; r < rows; ++r) {
+ for (int c = 0; c < cols; ++c) {
+ const int idx = r * cols + c;
+ std::string cell;
+ if (idx < static_cast<int>(comp.table_cells.size()))
+ cell = comp.table_cells[idx];
+ if (cell.empty()) cell = (r == 0) ? "Header" : "";
+ // Truncate to fit column
+ if (cell.size() > 20) cell = cell.substr(0, 17) + "...";
+ const float cx = MARGIN + static_cast<float>(c) * col_w;
+ pages.back().stream += emit_text(cell, cx, cursor_y,
+ line_h_normal - 2.0f, r == 0);
+ }
+ cursor_y -= row_h;
+ // Draw row separator
+ std::ostringstream s;
+ s << MARGIN << " " << cursor_y << " m "
+ << (PAGE_W - MARGIN) << " " << cursor_y << " l S\n";
+ pages.back().stream += s.str();
+ }
+ cursor_y -= 6.0f;
+ break;
+ }
+ case ComponentType::kpi: {
+ if (!comp.kpis.empty()) {
+ add_line("Key Performance Indicators", 11.0f, true, 0.0f, 4.0f);
+ for (const auto& k : comp.kpis) {
+ char buf[128];
+ std::snprintf(buf, sizeof(buf), " %s: %s (%+.1f%%)",
+ k.label, k.value, k.change);
+ add_line(buf, line_h_normal, false);
+ }
+ cursor_y -= 4.0f;
+ }
+ break;
+ }
+ case ComponentType::chart: {
+ add_line(std::string(chart_type_label(comp.chart_type)) + " Chart",
+ 11.0f, true, 0.0f, 4.0f);
+ if (!comp.chart_data.empty()) {
+ // ASCII bar representation
+ double max_val = 1.0;
+ for (double v : comp.chart_data) max_val = std::max(max_val, std::abs(v));
+ for (size_t i = 0; i < comp.chart_data.size(); ++i) {
+ const double v = comp.chart_data[i];
+ const int bars = static_cast<int>(std::abs(v) / max_val * 20.0);
+ std::string bar_str(static_cast<size_t>(bars), '#');
+ char buf[64];
+ std::snprintf(buf, sizeof(buf), " [%2d] %-20s %.2f",
+ static_cast<int>(i + 1), bar_str.c_str(), v);
+ add_line(buf, 9.0f, false);
+ }
+ }
+ cursor_y -= 4.0f;
+ break;
+ }
+ case ComponentType::code_block: {
+ add_line(std::string("[") + comp.language + "]", 9.0f, false, 0.0f, 4.0f);
+ const auto lines = wrap_text(comp.content[0] ? comp.content : "", 80);
+ for (const auto& ln : lines) add_line(ln, 9.0f, false, 8.0f);
+ cursor_y -= 4.0f;
+ break;
+ }
+ case ComponentType::list:
+ for (size_t i = 0; i < comp.list_items.size(); ++i) {
+ std::string prefix = comp.ordered
+ ? std::to_string(i + 1) + ". "
+ : "* ";
+ add_line(prefix + comp.list_items[i], line_h_normal, false, 8.0f);
+ }
+ cursor_y -= 4.0f;
+ break;
+ case ComponentType::cover_page:
+ add_line(comp.content[0] ? comp.content : document_.name,
+ 24.0f, true, 0.0f, 40.0f);
+ break;
+ case ComponentType::image:
+ add_line(std::string("[Image: ") + comp.content + "]",
+ line_h_normal, false, 0.0f, 4.0f);
+ break;
+ }
+ }
+
+ // --- Build PDF objects ---
+ // Obj 1: Catalog
+ add_obj("<< /Type /Catalog /Pages 2 0 R >>");
+ const int catalog_id = static_cast<int>(objects.size()) - 1;
+
+ // Build page content stream objects and collect page ids
+ std::vector<int> page_ids;
+ std::vector<int> content_ids;
+ for (const auto& pg : pages) {
+ const std::string& stream = pg.stream;
+ std::ostringstream content_obj;
+ content_obj << "<< /Length " << stream.size() << " >>\nstream\n"
+ << stream << "\nendstream";
+ content_ids.push_back(add_obj(content_obj.str()));
+ }
+
+ // Obj 2: Pages dictionary (will be updated once we know page count)
+ // We'll write it after building page objects
+ // First build each page object
+ for (int i = 0; i < static_cast<int>(pages.size()); ++i) {
+ std::ostringstream page_obj;
+ page_obj << "<< /Type /Page /Parent 2 0 R "
+ << "/MediaBox [0 0 " << PAGE_W << " " << PAGE_H << "] "
+ << "/Contents " << content_ids[i] << " 0 R "
+ << "/Resources << /Font << "
+ << "/F1 << /Type /Font /Subtype /Type1 /BaseFont /Helvetica >> "
+ << "/F2 << /Type /Font /Subtype /Type1 /BaseFont /Helvetica-Bold >> "
+ << ">> >> >>";
+ page_ids.push_back(add_obj(page_obj.str()));
+ }
+
+ // Pages dictionary
+ std::ostringstream pages_dict;
+ pages_dict << "<< /Type /Pages /Count " << page_ids.size() << " /Kids [";
+ for (int id : page_ids) pages_dict << id << " 0 R ";
+ pages_dict << "] >>";
+ // Insert at position 2 (0-indexed 2 = obj id 2)
+ // We need obj 2 to be the pages dict, but objects are appended.
+ // Simpler: re-number by just placing it correctly.
+ // Actually let's rebuild using sequential numbering:
+ // Reset and build properly with fixed numbering.
+ objects.clear();
+ objects.emplace_back(""); // obj 0 unused
+
+ // Build all content streams first (they don't reference other objects)
+ struct PdfObj { std::string body; };
+ std::vector<PdfObj> pdf_objs;
+ pdf_objs.push_back({""}); // 0 unused
+
+ // Obj 1 = Catalog (references Pages = obj 2)
+ pdf_objs.push_back({"<< /Type /Catalog /Pages 2 0 R >>"});
+
+ // Obj 2 = Pages (placeholder; filled below)
+ pdf_objs.push_back({"PAGES_PLACEHOLDER"});
+
+ // Obj 3..N = content streams
+ int first_content = static_cast<int>(pdf_objs.size());
+ for (const auto& pg : pages) {
+ const std::string& st = pg.stream;
+ std::ostringstream o;
+ o << "<< /Length " << st.size() << " >>\nstream\n" << st << "\nendstream";
+ pdf_objs.push_back({o.str()});
+ }
+
+ // Obj (3+num_pages)..M = page objects
+ int first_page = static_cast<int>(pdf_objs.size());
+ for (int i = 0; i < static_cast<int>(pages.size()); ++i) {
+ const int content_obj_id = first_content + i;
+ std::ostringstream o;
+ o << "<< /Type /Page /Parent 2 0 R "
+ << "/MediaBox [0 0 " << PAGE_W << " " << PAGE_H << "] "
+ << "/Contents " << content_obj_id << " 0 R "
+ << "/Resources << /Font << "
+ << "/F1 << /Type /Font /Subtype /Type1 /BaseFont /Helvetica >> "
+ << "/F2 << /Type /Font /Subtype /Type1 /BaseFont /Helvetica-Bold >> "
+ << ">> >> >>";
+ pdf_objs.push_back({o.str()});
+ }
+
+ // Fill in Pages dict (obj 2)
+ {
+ std::ostringstream o;
+ o << "<< /Type /Pages /Count " << pages.size() << " /Kids [";
+ for (int i = 0; i < static_cast<int>(pages.size()); ++i)
+ o << (first_page + i) << " 0 R ";
+ o << "] >>";
+ pdf_objs[2].body = o.str();
+ }
+
+ // Write PDF to file
+ std::ofstream out(path, std::ios::binary);
+ if (!out.is_open()) return false;
+
+ const int num_objs = static_cast<int>(pdf_objs.size());
+ std::vector<size_t> offsets(static_cast<size_t>(num_objs), 0);
+
+ out << "%PDF-1.4\n";
+ size_t pos = 9; // length of "%PDF-1.4\n"
+
+ for (int i = 1; i < num_objs; ++i) {
+ offsets[static_cast<size_t>(i)] = pos;
+ std::ostringstream obj_str;
+ obj_str << i << " 0 obj\n" << pdf_objs[static_cast<size_t>(i)].body << "\nendobj\n";
+ const std::string s = obj_str.str();
+ out << s;
+ pos += s.size();
+ }
+
+ // xref table
+ const size_t xref_offset = pos;
+ out << "xref\n0 " << num_objs << "\n";
+ out << "0000000000 65535 f \n";
+ for (int i = 1; i < num_objs; ++i) {
+ char entry[21];
+ std::snprintf(entry, sizeof(entry), "%010zu 00000 n \n",
+ offsets[static_cast<size_t>(i)]);
+ out << entry;
+ }
+
+ out << "trailer\n<< /Size " << num_objs
+ << " /Root 1 0 R >>\nstartxref\n" << xref_offset << "\n%%EOF\n";
+
+ return out.good();
+}
+
+// ============================================================================
+// Export dispatcher
+// ============================================================================
+
void ReportBuilderScreen::export_report(ExportFormat format) {
- LOG_INFO(TAG, "Exporting report as %s: %s (%d components)",
- export_format_label(format), document_.name,
- static_cast<int>(document_.components.size()));
- // Export implementation would generate the file here
- // For now, just log the action
+ export_status_[0] = '\0';
+ export_success_ = false;
+
+ const char* filter = nullptr;
+ const char* title = nullptr;
+ const char* ext = nullptr;
+
+ switch (format) {
+ case ExportFormat::pdf: filter = "PDF Files\0*.pdf\0All Files\0*.*\0"; title = "Save PDF"; ext = "pdf"; break;
+ case ExportFormat::html: filter = "HTML Files\0*.html\0All Files\0*.*\0"; title = "Save HTML"; ext = "html"; break;
+ case ExportFormat::csv: filter = "CSV Files\0*.csv\0All Files\0*.*\0"; title = "Save CSV"; ext = "csv"; break;
+ case ExportFormat::markdown: filter = "Markdown Files\0*.md\0All Files\0*.*\0"; title = "Save Markdown"; ext = "md"; break;
+ }
+
+ const std::string save_path = native_save_dialog(filter, title, ext);
+ if (save_path.empty()) {
+ // User cancelled — no error message needed
+ return;
+ }
+
+ bool ok = false;
+ switch (format) {
+ case ExportFormat::pdf: ok = export_as_pdf(save_path); break;
+ case ExportFormat::html: ok = export_as_html(save_path); break;
+ case ExportFormat::csv: ok = export_as_csv(save_path); break;
+ case ExportFormat::markdown: ok = export_as_markdown(save_path); break;
+ }
+
+ if (ok) {
+ export_success_ = true;
+ std::snprintf(export_status_, sizeof(export_status_),
+ "Saved: %s", save_path.c_str());
+ is_dirty_ = false;
+ LOG_INFO(TAG, "Exported report as %s -> %s", export_format_label(format), save_path.c_str());
+ } else {
+ export_success_ = false;
+ std::snprintf(export_status_, sizeof(export_status_),
+ "Error: could not write to %s", save_path.c_str());
+ LOG_ERROR(TAG, "Export failed: %s", save_path.c_str());
+ }
}
} // namespace fincept::report_builder
diff --git a/fincept-cpp/src/screens/report_builder/report_builder_screen.h b/fincept-cpp/src/screens/report_builder/report_builder_screen.h
index 661622968..b6e6788a8 100644
--- a/fincept-cpp/src/screens/report_builder/report_builder_screen.h
+++ b/fincept-cpp/src/screens/report_builder/report_builder_screen.h
@@ -41,6 +41,13 @@ private:
void apply_template_preset(int preset_idx);
void export_report(ExportFormat format);
+ // Export implementation
+ std::string native_save_dialog(const char* filter, const char* title, const char* default_ext);
+ bool export_as_html(const std::string& path);
+ bool export_as_markdown(const std::string& path);
+ bool export_as_csv(const std::string& path);
+ bool export_as_pdf(const std::string& path);
+
// State
bool initialized_ = false;
@@ -56,6 +63,11 @@ private:
// Component palette filter
char component_search_[64] = {};
+
+ // Export status feedback
+ char export_status_[256] = {};
+ bool export_success_ = false;
+ float export_status_timer_ = 0.0f;
};
} // namespace fincept::report_builder
diff --git a/fincept-cpp/src/screens/settings/sections/general_section.cpp b/fincept-cpp/src/screens/settings/sections/general_section.cpp
index 37f32ab7c..777c657b4 100644
--- a/fincept-cpp/src/screens/settings/sections/general_section.cpp
+++ b/fincept-cpp/src/screens/settings/sections/general_section.cpp
@@ -2,8 +2,13 @@
#include "storage/database.h"
#include "ui/theme.h"
#include "core/config.h"
+#include "core/logger.h"
#include <imgui.h>
#include <cstdio>
+#include <fstream>
+#include <nlohmann/json.hpp>
+
+using json = nlohmann::json;
namespace fincept::settings {
@@ -111,12 +116,37 @@ void GeneralSection::render() {
ImGui::Spacing();
if (theme::SecondaryButton("Export Settings")) {
- status_ = "Export not yet implemented";
+ try {
+ auto all = db::ops::get_all_settings();
+ json j;
+ for (auto& s : all) j[s.key] = s.value;
+ std::ofstream f("fincept_settings_export.json");
+ f << j.dump(2);
+ status_ = "Settings exported to fincept_settings_export.json";
+ } catch (const std::exception& e) {
+ status_ = std::string("Export failed: ") + e.what();
+ }
status_time_ = ImGui::GetTime();
}
ImGui::SameLine();
if (theme::SecondaryButton("Import Settings")) {
- status_ = "Import not yet implemented";
+ try {
+ std::ifstream f("fincept_settings_export.json");
+ if (!f.is_open()) {
+ status_ = "Import failed: fincept_settings_export.json not found";
+ } else {
+ json j = json::parse(f);
+ std::vector<std::pair<std::string, std::string>> pairs;
+ for (auto& [k, v] : j.items()) {
+ if (v.is_string()) pairs.emplace_back(k, v.get<std::string>());
+ }
+ db::ops::storage_set_many(pairs);
+ initialized_ = false; // re-init to pick up imported language
+ status_ = "Settings imported (" + std::to_string(pairs.size()) + " keys)";
+ }
+ } catch (const std::exception& e) {
+ status_ = std::string("Import failed: ") + e.what();
+ }
status_time_ = ImGui::GetTime();
}
ImGui::SameLine(0, 40);
@@ -125,13 +155,59 @@ void GeneralSection::render() {
ImGui::PushStyleColor(ImGuiCol_ButtonHovered, ERROR_RED);
ImGui::PushStyleColor(ImGuiCol_Text, ERROR_RED);
if (ImGui::Button("Reset All Settings")) {
- // TODO: confirmation dialog
- status_ = "Reset requires confirmation (not yet implemented)";
- status_time_ = ImGui::GetTime();
+ confirm_reset_open_ = true;
}
ImGui::PopStyleColor(3);
ImGui::EndChild();
+
+ // ── Reset confirmation modal ───────────────────────────────────────────
+ if (confirm_reset_open_) {
+ ImGui::OpenPopup("Reset All Settings");
+ confirm_reset_open_ = false;
+ }
+ ImVec2 center = ImGui::GetMainViewport()->GetCenter();
+ ImGui::SetNextWindowPos(center, ImGuiCond_Appearing, ImVec2(0.5f, 0.5f));
+ if (ImGui::BeginPopupModal("Reset All Settings", nullptr, ImGuiWindowFlags_AlwaysAutoResize)) {
+ ImGui::TextColored(ERROR_RED, "Reset all application settings?");
+ ImGui::Spacing();
+ ImGui::TextColored(TEXT_DIM, "This will clear all settings, credentials,");
+ ImGui::TextColored(TEXT_DIM, "LLM configs, and cached data.");
+ ImGui::TextColored(TEXT_DIM, "This action cannot be undone.");
+ ImGui::Spacing();
+ ImGui::Separator();
+ ImGui::Spacing();
+ ImGui::PushStyleColor(ImGuiCol_Button, ImVec4(ERROR_RED.x, ERROR_RED.y, ERROR_RED.z, 0.8f));
+ ImGui::PushStyleColor(ImGuiCol_ButtonHovered, ERROR_RED);
+ if (ImGui::Button("Yes, Reset Everything")) {
+ try {
+ db::ops::cache_cleanup();
+ db::ops::storage_set_many({}); // no-op but signals intent
+ // Clear settings, LLM configs, credentials via direct DB exec
+ auto& dbref = db::Database::instance();
+ dbref.exec("DELETE FROM settings");
+ dbref.exec("DELETE FROM key_value_storage");
+ dbref.exec("DELETE FROM llm_configs");
+ dbref.exec("DELETE FROM credentials");
+ dbref.exec("UPDATE llm_global_settings SET temperature=0.7, max_tokens=2048, system_prompt='' WHERE id=1");
+ initialized_ = false;
+ selected_language_ = 0;
+ status_ = "All settings have been reset";
+ status_time_ = ImGui::GetTime();
+ LOG_INFO("Settings", "User performed full settings reset");
+ } catch (const std::exception& e) {
+ status_ = std::string("Reset failed: ") + e.what();
+ status_time_ = ImGui::GetTime();
+ }
+ ImGui::CloseCurrentPopup();
+ }
+ ImGui::PopStyleColor(2);
+ ImGui::SameLine();
+ if (theme::SecondaryButton("Cancel")) {
+ ImGui::CloseCurrentPopup();
+ }
+ ImGui::EndPopup();
+ }
}
} // namespace fincept::settings
diff --git a/fincept-cpp/src/screens/settings/sections/general_section.h b/fincept-cpp/src/screens/settings/sections/general_section.h
index cf8126491..84fcb9763 100644
--- a/fincept-cpp/src/screens/settings/sections/general_section.h
+++ b/fincept-cpp/src/screens/settings/sections/general_section.h
@@ -19,6 +19,9 @@ private:
std::string status_;
double status_time_ = 0;
+ // Confirmation modal
+ bool confirm_reset_open_ = false;
+
void init();
};
diff --git a/fincept-cpp/src/screens/settings/sections/llm_config_section.cpp b/fincept-cpp/src/screens/settings/sections/llm_config_section.cpp
index 6cbb6a100..325f54b73 100644
--- a/fincept-cpp/src/screens/settings/sections/llm_config_section.cpp
+++ b/fincept-cpp/src/screens/settings/sections/llm_config_section.cpp
@@ -68,6 +68,17 @@ void LLMConfigSection::populate_edit_buffers() {
}
}
+void LLMConfigSection::delete_provider_config(const std::string& provider) {
+ db::ops::delete_llm_config(provider);
+ load_configs();
+ // If deleted provider was selected, reset selection
+ const auto& providers = llm_providers();
+ if (selected_provider_ >= (int)providers.size())
+ selected_provider_ = 0;
+ status_ = provider + " config deleted";
+ status_time_ = ImGui::GetTime();
+}
+
void LLMConfigSection::save_provider_config() {
const auto& providers = llm_providers();
if (selected_provider_ < 0 || selected_provider_ >= (int)providers.size())
@@ -429,8 +440,8 @@ void LLMConfigSection::render_model_library() {
ImGui::PushStyleColor(ImGuiCol_ButtonHovered, BG_HOVER);
ImGui::PushStyleColor(ImGuiCol_Text, ERROR_RED);
if (ImGui::SmallButton("Delete")) {
- // Delete by saving empty config — or just remove from DB
- // For now, re-save with empty values
+ confirm_delete_provider_ = cfg.provider;
+ confirm_delete_open_ = true;
}
ImGui::PopStyleColor(3);
ImGui::PopID();
@@ -468,6 +479,32 @@ void LLMConfigSection::render() {
case SubPanel::GlobalSettings: render_global_settings(); break;
case SubPanel::ModelLibrary: render_model_library(); break;
}
+
+ // ── Delete confirmation modal ──────────────────────────────────────────
+ if (confirm_delete_open_) {
+ ImGui::OpenPopup("Delete LLM Config");
+ confirm_delete_open_ = false;
+ }
+ ImVec2 center = ImGui::GetMainViewport()->GetCenter();
+ ImGui::SetNextWindowPos(center, ImGuiCond_Appearing, ImVec2(0.5f, 0.5f));
+ if (ImGui::BeginPopupModal("Delete LLM Config", nullptr, ImGuiWindowFlags_AlwaysAutoResize)) {
+ ImGui::TextColored(theme::colors::WARNING, "Delete provider config?");
+ ImGui::Spacing();
+ ImGui::Text("Provider: %s", confirm_delete_provider_.c_str());
+ ImGui::TextColored(theme::colors::TEXT_DIM, "This will remove the API key and model settings.");
+ ImGui::Spacing();
+ ImGui::Separator();
+ ImGui::Spacing();
+ if (theme::AccentButton("Delete")) {
+ delete_provider_config(confirm_delete_provider_);
+ ImGui::CloseCurrentPopup();
+ }
+ ImGui::SameLine();
+ if (theme::SecondaryButton("Cancel")) {
+ ImGui::CloseCurrentPopup();
+ }
+ ImGui::EndPopup();
+ }
}
} // namespace fincept::settings
diff --git a/fincept-cpp/src/screens/settings/sections/llm_config_section.h b/fincept-cpp/src/screens/settings/sections/llm_config_section.h
index e3999cee7..8572e5476 100644
--- a/fincept-cpp/src/screens/settings/sections/llm_config_section.h
+++ b/fincept-cpp/src/screens/settings/sections/llm_config_section.h
@@ -48,8 +48,13 @@ private:
void render_model_library();
void save_provider_config();
+ void delete_provider_config(const std::string& provider);
void save_global_settings();
void ensure_fincept_config();
+
+ // Confirmation modal state
+ bool confirm_delete_open_ = false;
+ std::string confirm_delete_provider_;
};
} // namespace fincept::settings
diff --git a/fincept-cpp/src/screens/surface_analytics/csv_importer.h b/fincept-cpp/src/screens/surface_analytics/csv_importer.h
new file mode 100644
index 000000000..a2be08a87
--- /dev/null
+++ b/fincept-cpp/src/screens/surface_analytics/csv_importer.h
@@ -0,0 +1,59 @@
+#pragma once
+#include "surface_types.h"
+#include <string>
+#include <vector>
+
+namespace fincept::surface {
+
+struct CsvColumn {
+ const char* name;
+ const char* description;
+};
+
+struct CsvSchema {
+ ChartType type;
+ const char* surface_name;
+ std::vector<CsvColumn> columns;
+ const char* example_row;
+};
+
+const CsvSchema& get_csv_schema(ChartType type);
+
+std::vector<std::vector<std::string>> parse_csv_file(
+ const std::string& path,
+ std::string& out_error);
+
+bool load_vol_surface( const std::vector<std::vector<std::string>>& rows, VolatilitySurfaceData& out, std::string& err);
+bool load_greeks_surface( const std::vector<std::vector<std::string>>& rows, GreeksSurfaceData& out, std::string& err, const std::string& greek_name);
+bool load_skew_surface( const std::vector<std::vector<std::string>>& rows, SkewSurfaceData& out, std::string& err);
+bool load_local_vol( const std::vector<std::vector<std::string>>& rows, LocalVolData& out, std::string& err);
+bool load_yield_curve( const std::vector<std::vector<std::string>>& rows, YieldCurveData& out, std::string& err);
+bool load_swaption_vol( const std::vector<std::vector<std::string>>& rows, SwaptionVolData& out, std::string& err);
+bool load_capfloor_vol( const std::vector<std::vector<std::string>>& rows, CapFloorVolData& out, std::string& err);
+bool load_bond_spread( const std::vector<std::vector<std::string>>& rows, BondSpreadData& out, std::string& err);
+bool load_ois_basis( const std::vector<std::vector<std::string>>& rows, OISBasisData& out, std::string& err);
+bool load_real_yield( const std::vector<std::vector<std::string>>& rows, RealYieldData& out, std::string& err);
+bool load_forward_rate( const std::vector<std::vector<std::string>>& rows, ForwardRateData& out, std::string& err);
+bool load_fx_vol( const std::vector<std::vector<std::string>>& rows, FXVolData& out, std::string& err);
+bool load_fx_forward( const std::vector<std::vector<std::string>>& rows, FXForwardPointsData& out, std::string& err);
+bool load_xccy_basis( const std::vector<std::vector<std::string>>& rows, CrossCurrencyBasisData& out,std::string& err);
+bool load_cds_spread( const std::vector<std::vector<std::string>>& rows, CDSSpreadData& out, std::string& err);
+bool load_credit_trans( const std::vector<std::vector<std::string>>& rows, CreditTransitionData& out, std::string& err);
+bool load_recovery_rate( const std::vector<std::vector<std::string>>& rows, RecoveryRateData& out, std::string& err);
+bool load_cmdty_forward( const std::vector<std::vector<std::string>>& rows, CommodityForwardData& out, std::string& err);
+bool load_cmdty_vol( const std::vector<std::vector<std::string>>& rows, CommodityVolData& out, std::string& err);
+bool load_crack_spread( const std::vector<std::vector<std::string>>& rows, CrackSpreadData& out, std::string& err);
+bool load_contango( const std::vector<std::vector<std::string>>& rows, ContangoData& out, std::string& err);
+bool load_correlation( const std::vector<std::vector<std::string>>& rows, CorrelationMatrixData& out, std::string& err);
+bool load_pca( const std::vector<std::vector<std::string>>& rows, PCAData& out, std::string& err);
+bool load_var( const std::vector<std::vector<std::string>>& rows, VaRData& out, std::string& err);
+bool load_stress_test( const std::vector<std::vector<std::string>>& rows, StressTestData& out, std::string& err);
+bool load_factor_exposure(const std::vector<std::vector<std::string>>& rows, FactorExposureData& out, std::string& err);
+bool load_liquidity( const std::vector<std::vector<std::string>>& rows, LiquidityData& out, std::string& err);
+bool load_drawdown( const std::vector<std::vector<std::string>>& rows, DrawdownData& out, std::string& err);
+bool load_beta( const std::vector<std::vector<std::string>>& rows, BetaData& out, std::string& err);
+bool load_implied_div( const std::vector<std::vector<std::string>>& rows, ImpliedDividendData& out, std::string& err);
+bool load_inflation( const std::vector<std::vector<std::string>>& rows, InflationExpData& out, std::string& err);
+bool load_monetary( const std::vector<std::vector<std::string>>& rows, MonetaryPolicyData& out, std::string& err);
+
+} // namespace fincept::surface
diff --git a/fincept-cpp/src/screens/surface_analytics/import_dialog.cpp b/fincept-cpp/src/screens/surface_analytics/import_dialog.cpp
new file mode 100644
index 000000000..d91ba1aac
--- /dev/null
+++ b/fincept-cpp/src/screens/surface_analytics/import_dialog.cpp
@@ -0,0 +1,266 @@
+// SKIP_UNITY_BUILD_INCLUSION — modal dialog for CSV import
+#include "surface_screen.h"
+#include "csv_importer.h"
+#include <imgui.h>
+#include <cstring>
+
+namespace fincept::surface {
+
+using namespace theme::colors;
+
+// ── dispatch_csv_load ─────────────────────────────────────────────────────────
+// Parses the CSV at `path` and routes to the correct per-surface loader.
+bool SurfaceScreen::dispatch_csv_load(const std::string& path, std::string& err)
+{
+ auto rows = parse_csv_file(path, err);
+ if (rows.empty()) return false;
+
+ switch (active_chart_) {
+ case ChartType::Volatility:
+ return load_vol_surface(rows, vol_data_, err);
+ case ChartType::DeltaSurface:
+ return load_greeks_surface(rows, delta_data_, err, "delta");
+ case ChartType::GammaSurface:
+ return load_greeks_surface(rows, gamma_data_, err, "gamma");
+ case ChartType::VegaSurface:
+ return load_greeks_surface(rows, vega_data_, err, "vega");
+ case ChartType::ThetaSurface:
+ return load_greeks_surface(rows, theta_data_, err, "theta");
+ case ChartType::SkewSurface:
+ return load_skew_surface(rows, skew_data_, err);
+ case ChartType::LocalVolSurface:
+ return load_local_vol(rows, local_vol_data_, err);
+ case ChartType::YieldCurve:
+ return load_yield_curve(rows, yield_data_, err);
+ case ChartType::SwaptionVol:
+ return load_swaption_vol(rows, swaption_data_, err);
+ case ChartType::CapFloorVol:
+ return load_capfloor_vol(rows, capfloor_data_, err);
+ case ChartType::BondSpread:
+ return load_bond_spread(rows, bond_spread_data_, err);
+ case ChartType::OISBasis:
+ return load_ois_basis(rows, ois_data_, err);
+ case ChartType::RealYield:
+ return load_real_yield(rows, real_yield_data_, err);
+ case ChartType::ForwardRate:
+ return load_forward_rate(rows, fwd_rate_data_, err);
+ case ChartType::FXVol:
+ return load_fx_vol(rows, fx_vol_data_, err);
+ case ChartType::FXForwardPoints:
+ return load_fx_forward(rows, fx_fwd_data_, err);
+ case ChartType::CrossCurrencyBasis:
+ return load_xccy_basis(rows, xccy_data_, err);
+ case ChartType::CDSSpread:
+ return load_cds_spread(rows, cds_data_, err);
+ case ChartType::CreditTransition:
+ return load_credit_trans(rows, credit_trans_data_, err);
+ case ChartType::RecoveryRate:
+ return load_recovery_rate(rows, recovery_data_, err);
+ case ChartType::CommodityForward:
+ return load_cmdty_forward(rows, cmdty_fwd_data_, err);
+ case ChartType::CommodityVol:
+ return load_cmdty_vol(rows, cmdty_vol_data_, err);
+ case ChartType::CrackSpread:
+ return load_crack_spread(rows, crack_data_, err);
+ case ChartType::ContangoBackwardation:
+ return load_contango(rows, contango_data_, err);
+ case ChartType::Correlation:
+ return load_correlation(rows, corr_data_, err);
+ case ChartType::PCA:
+ return load_pca(rows, pca_data_, err);
+ case ChartType::VaR:
+ return load_var(rows, var_data_, err);
+ case ChartType::StressTestPnL:
+ return load_stress_test(rows, stress_data_, err);
+ case ChartType::FactorExposure:
+ return load_factor_exposure(rows, factor_data_, err);
+ case ChartType::LiquidityHeatmap:
+ return load_liquidity(rows, liquidity_data_, err);
+ case ChartType::Drawdown:
+ return load_drawdown(rows, drawdown_data_, err);
+ case ChartType::BetaSurface:
+ return load_beta(rows, beta_data_, err);
+ case ChartType::ImpliedDividend:
+ return load_implied_div(rows, impl_div_data_, err);
+ case ChartType::InflationExpectations:
+ return load_inflation(rows, inflation_data_, err);
+ case ChartType::MonetaryPolicyPath:
+ return load_monetary(rows, monetary_data_, err);
+ default:
+ err = "No CSV loader for this surface.";
+ return false;
+ }
+}
+
+// ── render_csv_import_dialog ──────────────────────────────────────────────────
+void SurfaceScreen::render_csv_import_dialog()
+{
+ if (!show_import_dialog_) return;
+
+ ImGui::OpenPopup("Import CSV##surface_import");
+
+ ImVec2 center = ImGui::GetMainViewport()->GetCenter();
+ ImGui::SetNextWindowPos(center, ImGuiCond_Always, ImVec2(0.5f, 0.5f));
+ ImGui::SetNextWindowSize(ImVec2(560, 0), ImGuiCond_Always);
+ ImGui::SetNextWindowBgAlpha(0.97f);
+
+ ImGuiWindowFlags modal_flags =
+ ImGuiWindowFlags_NoResize | ImGuiWindowFlags_NoMove |
+ ImGuiWindowFlags_NoSavedSettings;
+
+ if (!ImGui::BeginPopupModal("Import CSV##surface_import", &show_import_dialog_, modal_flags)) {
+ return;
+ }
+
+ const CsvSchema& schema = get_csv_schema(active_chart_);
+ ImDrawList* dl = ImGui::GetWindowDrawList();
+
+ // ── Header ────────────────────────────────────────────────────────────────
+ {
+ ImVec2 p = ImGui::GetCursorScreenPos();
+ float w = ImGui::GetContentRegionAvail().x;
+ dl->AddRectFilled(p, ImVec2(p.x + w, p.y + 32.0f),
+ ImGui::GetColorU32(ImVec4(0.12f, 0.16f, 0.22f, 1.0f)));
+ dl->AddLine(ImVec2(p.x, p.y + 32.0f), ImVec2(p.x + w, p.y + 32.0f),
+ ImGui::GetColorU32(ACCENT), 1.5f);
+ ImGui::Dummy(ImVec2(w, 8.0f));
+ ImGui::SetCursorPosX(ImGui::GetCursorPosX() + 10.0f);
+ ImGui::TextColored(ACCENT, "IMPORT CSV");
+ ImGui::SameLine();
+ ImGui::TextColored(TEXT_DIM, "— %s", schema.surface_name);
+ ImGui::Dummy(ImVec2(w, 4.0f));
+ }
+
+ ImGui::Spacing();
+
+ // ── Schema reference ──────────────────────────────────────────────────────
+ ImGui::TextColored(TEXT_SECONDARY, "Required columns (header row must match exactly):");
+ ImGui::Spacing();
+
+ float col_w = ImGui::GetContentRegionAvail().x;
+ ImVec2 table_origin = ImGui::GetCursorScreenPos();
+ float row_h = ImGui::GetTextLineHeightWithSpacing() + 4.0f;
+ float total_table_h = (float)(schema.columns.size() + 1) * row_h + 4.0f;
+
+ // Table background
+ dl->AddRectFilled(table_origin,
+ ImVec2(table_origin.x + col_w, table_origin.y + total_table_h),
+ ImGui::GetColorU32(ImVec4(0.08f, 0.10f, 0.14f, 1.0f)), 4.0f);
+
+ ImGui::Dummy(ImVec2(col_w, total_table_h));
+ ImGui::SetCursorScreenPos(ImVec2(table_origin.x + 8.0f, table_origin.y + 4.0f));
+
+ // Header row
+ float name_col_x = table_origin.x + 8.0f;
+ float desc_col_x = table_origin.x + col_w * 0.34f;
+ float cur_y = table_origin.y + 4.0f;
+
+ dl->AddText(ImVec2(name_col_x, cur_y), ImGui::GetColorU32(TEXT_DIM), "COLUMN");
+ dl->AddText(ImVec2(desc_col_x, cur_y), ImGui::GetColorU32(TEXT_DIM), "DESCRIPTION");
+ cur_y += row_h;
+ dl->AddLine(ImVec2(table_origin.x + 4.0f, cur_y - 2.0f),
+ ImVec2(table_origin.x + col_w - 4.0f, cur_y - 2.0f),
+ ImGui::GetColorU32(ImVec4(0.25f, 0.25f, 0.30f, 1.0f)));
+
+ // Column rows
+ for (const auto& col : schema.columns) {
+ dl->AddText(ImVec2(name_col_x, cur_y), ImGui::GetColorU32(MARKET_GREEN), col.name);
+ dl->AddText(ImVec2(desc_col_x, cur_y), ImGui::GetColorU32(TEXT_SECONDARY), col.description);
+ cur_y += row_h;
+ }
+
+ ImGui::Spacing();
+
+ // Example row
+ ImGui::TextColored(TEXT_DIM, "Example row: ");
+ ImGui::SameLine();
+ ImGui::TextColored(TEXT_SECONDARY, "%s", schema.example_row);
+
+ ImGui::Spacing();
+ ImGui::Separator();
+ ImGui::Spacing();
+
+ // ── File path input ───────────────────────────────────────────────────────
+ ImGui::TextColored(TEXT_SECONDARY, "CSV file path:");
+ ImGui::SetNextItemWidth(ImGui::GetContentRegionAvail().x);
+ ImGui::PushStyleColor(ImGuiCol_FrameBg, ImGui::GetColorU32(ImVec4(0.10f, 0.12f, 0.16f, 1.0f)));
+ ImGui::PushStyleColor(ImGuiCol_Text, ImGui::GetColorU32(TEXT_PRIMARY));
+ ImGui::InputText("##csv_path", import_path_buf_, sizeof(import_path_buf_));
+ ImGui::PopStyleColor(2);
+
+ ImGui::Spacing();
+
+ // ── Error / success messages ──────────────────────────────────────────────
+ if (!import_error_.empty()) {
+ ImGui::TextColored(MARKET_RED, "Error: %s", import_error_.c_str());
+ ImGui::Spacing();
+ }
+ if (import_success_) {
+ ImGui::TextColored(MARKET_GREEN, "Data loaded successfully.");
+ ImGui::Spacing();
+ }
+
+ // ── Buttons ───────────────────────────────────────────────────────────────
+ float btn_w = 110.0f;
+ float avail = ImGui::GetContentRegionAvail().x;
+
+ // LOAD button
+ {
+ ImVec2 c = ImGui::GetCursorScreenPos();
+ ImVec2 mn = c, mx = ImVec2(c.x + btn_w, c.y + 26.0f);
+ bool hov = ImGui::IsMouseHoveringRect(mn, mx);
+ dl->AddRectFilled(mn, mx,
+ ImGui::GetColorU32(hov ? ImVec4(0.20f, 0.50f, 0.95f, 1.0f)
+ : ImVec4(0.14f, 0.38f, 0.78f, 1.0f)), 3.0f);
+ float tw = ImGui::CalcTextSize("LOAD").x;
+ dl->AddText(ImVec2(mn.x + (btn_w - tw) * 0.5f,
+ mn.y + (26.0f - ImGui::GetTextLineHeight()) * 0.5f),
+ ImGui::GetColorU32(ImVec4(1, 1, 1, 1)), "LOAD");
+ ImGui::InvisibleButton("##csv_load", ImVec2(btn_w, 26.0f));
+ if (ImGui::IsItemClicked()) {
+ import_error_.clear();
+ import_success_ = false;
+ std::string path(import_path_buf_);
+ if (path.empty()) {
+ import_error_ = "Please enter a file path.";
+ } else {
+ std::string err;
+ if (dispatch_csv_load(path, err)) {
+ import_success_ = true;
+ show_import_dialog_ = false;
+ ImGui::CloseCurrentPopup();
+ } else {
+ import_error_ = err;
+ }
+ }
+ }
+ }
+
+ ImGui::SameLine(0, 8);
+
+ // CANCEL button
+ {
+ ImVec2 c = ImGui::GetCursorScreenPos();
+ ImVec2 mn = c, mx = ImVec2(c.x + btn_w, c.y + 26.0f);
+ bool hov = ImGui::IsMouseHoveringRect(mn, mx);
+ dl->AddRectFilled(mn, mx,
+ ImGui::GetColorU32(hov ? ImVec4(0.28f, 0.28f, 0.32f, 1.0f)
+ : ImVec4(0.18f, 0.18f, 0.22f, 1.0f)), 3.0f);
+ float tw = ImGui::CalcTextSize("CANCEL").x;
+ dl->AddText(ImVec2(mn.x + (btn_w - tw) * 0.5f,
+ mn.y + (26.0f - ImGui::GetTextLineHeight()) * 0.5f),
+ ImGui::GetColorU32(TEXT_SECONDARY), "CANCEL");
+ ImGui::InvisibleButton("##csv_cancel", ImVec2(btn_w, 26.0f));
+ if (ImGui::IsItemClicked()) {
+ show_import_dialog_ = false;
+ import_error_.clear();
+ import_success_ = false;
+ ImGui::CloseCurrentPopup();
+ }
+ }
+
+ ImGui::Spacing();
+ ImGui::EndPopup();
+}
+
+} // namespace fincept::surface
diff --git a/fincept-cpp/src/screens/surface_analytics/panels_commodities.cpp b/fincept-cpp/src/screens/surface_analytics/panels_commodities.cpp
index d11286d11..c2ec4b102 100644
--- a/fincept-cpp/src/screens/surface_analytics/panels_commodities.cpp
+++ b/fincept-cpp/src/screens/surface_analytics/panels_commodities.cpp
@@ -9,8 +9,14 @@ namespace fincept::surface {
using namespace theme::colors;
void SurfaceScreen::render_metrics_commodities() {
- float metric_label_w = ImGui::GetContentRegionAvail().x * 0.45f;
- auto row = [metric_label_w](const char* lbl, const char* val, ImVec4 col) {
+ float w = ImGui::GetContentRegionAvail().x;
+ float metric_label_w = w * 0.52f;
+ ImDrawList* dl = ImGui::GetWindowDrawList();
+ auto row = [&](const char* lbl, const char* val, ImVec4 col) {
+ ImVec2 p = ImGui::GetCursorScreenPos();
+ dl->AddCircleFilled(ImVec2(p.x + 4.0f, p.y + ImGui::GetTextLineHeight() * 0.5f + 1.0f),
+ 3.0f, ImGui::GetColorU32(ImVec4(col.x, col.y, col.z, 0.7f)));
+ ImGui::SetCursorPosX(ImGui::GetCursorPosX() + 12.0f);
ImGui::TextColored(TEXT_DIM, "%s", lbl);
ImGui::SameLine(metric_label_w);
ImGui::TextColored(col, "%s", val);
diff --git a/fincept-cpp/src/screens/surface_analytics/panels_credit.cpp b/fincept-cpp/src/screens/surface_analytics/panels_credit.cpp
index 9cc15922d..d6c6c134c 100644
--- a/fincept-cpp/src/screens/surface_analytics/panels_credit.cpp
+++ b/fincept-cpp/src/screens/surface_analytics/panels_credit.cpp
@@ -9,8 +9,14 @@ namespace fincept::surface {
using namespace theme::colors;
void SurfaceScreen::render_metrics_credit() {
- float metric_label_w = ImGui::GetContentRegionAvail().x * 0.45f;
- auto row = [metric_label_w](const char* lbl, const char* val, ImVec4 col) {
+ float w = ImGui::GetContentRegionAvail().x;
+ float metric_label_w = w * 0.52f;
+ ImDrawList* dl = ImGui::GetWindowDrawList();
+ auto row = [&](const char* lbl, const char* val, ImVec4 col) {
+ ImVec2 p = ImGui::GetCursorScreenPos();
+ dl->AddCircleFilled(ImVec2(p.x + 4.0f, p.y + ImGui::GetTextLineHeight() * 0.5f + 1.0f),
+ 3.0f, ImGui::GetColorU32(ImVec4(col.x, col.y, col.z, 0.7f)));
+ ImGui::SetCursorPosX(ImGui::GetCursorPosX() + 12.0f);
ImGui::TextColored(TEXT_DIM, "%s", lbl);
ImGui::SameLine(metric_label_w);
ImGui::TextColored(col, "%s", val);
diff --git a/fincept-cpp/src/screens/surface_analytics/panels_derivatives.cpp b/fincept-cpp/src/screens/surface_analytics/panels_derivatives.cpp
index 21f1a2cc6..41395569a 100644
--- a/fincept-cpp/src/screens/surface_analytics/panels_derivatives.cpp
+++ b/fincept-cpp/src/screens/surface_analytics/panels_derivatives.cpp
@@ -9,8 +9,15 @@ namespace fincept::surface {
using namespace theme::colors;
void SurfaceScreen::render_metrics_derivatives() {
- float metric_label_w = ImGui::GetContentRegionAvail().x * 0.45f;
- auto row = [metric_label_w](const char* lbl, const char* val, ImVec4 col) {
+ float w = ImGui::GetContentRegionAvail().x;
+ float metric_label_w = w * 0.52f;
+ ImDrawList* dl = ImGui::GetWindowDrawList();
+ auto row = [&](const char* lbl, const char* val, ImVec4 col) {
+ // Dot indicator
+ ImVec2 p = ImGui::GetCursorScreenPos();
+ dl->AddCircleFilled(ImVec2(p.x + 4.0f, p.y + ImGui::GetTextLineHeight() * 0.5f + 1.0f),
+ 3.0f, ImGui::GetColorU32(ImVec4(col.x, col.y, col.z, 0.7f)));
+ ImGui::SetCursorPosX(ImGui::GetCursorPosX() + 12.0f);
ImGui::TextColored(TEXT_DIM, "%s", lbl);
ImGui::SameLine(metric_label_w);
ImGui::TextColored(col, "%s", val);
diff --git a/fincept-cpp/src/screens/surface_analytics/panels_fixed_income.cpp b/fincept-cpp/src/screens/surface_analytics/panels_fixed_income.cpp
index 48fd0fa78..059e4754d 100644
--- a/fincept-cpp/src/screens/surface_analytics/panels_fixed_income.cpp
+++ b/fincept-cpp/src/screens/surface_analytics/panels_fixed_income.cpp
@@ -9,8 +9,14 @@ namespace fincept::surface {
using namespace theme::colors;
void SurfaceScreen::render_metrics_fixed_income() {
- float metric_label_w = ImGui::GetContentRegionAvail().x * 0.45f;
- auto row = [metric_label_w](const char* lbl, const char* val, ImVec4 col) {
+ float w = ImGui::GetContentRegionAvail().x;
+ float metric_label_w = w * 0.52f;
+ ImDrawList* dl = ImGui::GetWindowDrawList();
+ auto row = [&](const char* lbl, const char* val, ImVec4 col) {
+ ImVec2 p = ImGui::GetCursorScreenPos();
+ dl->AddCircleFilled(ImVec2(p.x + 4.0f, p.y + ImGui::GetTextLineHeight() * 0.5f + 1.0f),
+ 3.0f, ImGui::GetColorU32(ImVec4(col.x, col.y, col.z, 0.7f)));
+ ImGui::SetCursorPosX(ImGui::GetCursorPosX() + 12.0f);
ImGui::TextColored(TEXT_DIM, "%s", lbl);
ImGui::SameLine(metric_label_w);
ImGui::TextColored(col, "%s", val);
diff --git a/fincept-cpp/src/screens/surface_analytics/panels_fx.cpp b/fincept-cpp/src/screens/surface_analytics/panels_fx.cpp
index 1214ddc89..c51d48d64 100644
--- a/fincept-cpp/src/screens/surface_analytics/panels_fx.cpp
+++ b/fincept-cpp/src/screens/surface_analytics/panels_fx.cpp
@@ -9,8 +9,14 @@ namespace fincept::surface {
using namespace theme::colors;
void SurfaceScreen::render_metrics_fx() {
- float metric_label_w = ImGui::GetContentRegionAvail().x * 0.45f;
- auto row = [metric_label_w](const char* lbl, const char* val, ImVec4 col) {
+ float w = ImGui::GetContentRegionAvail().x;
+ float metric_label_w = w * 0.52f;
+ ImDrawList* dl = ImGui::GetWindowDrawList();
+ auto row = [&](const char* lbl, const char* val, ImVec4 col) {
+ ImVec2 p = ImGui::GetCursorScreenPos();
+ dl->AddCircleFilled(ImVec2(p.x + 4.0f, p.y + ImGui::GetTextLineHeight() * 0.5f + 1.0f),
+ 3.0f, ImGui::GetColorU32(ImVec4(col.x, col.y, col.z, 0.7f)));
+ ImGui::SetCursorPosX(ImGui::GetCursorPosX() + 12.0f);
ImGui::TextColored(TEXT_DIM, "%s", lbl);
ImGui::SameLine(metric_label_w);
ImGui::TextColored(col, "%s", val);
diff --git a/fincept-cpp/src/screens/surface_analytics/panels_macro.cpp b/fincept-cpp/src/screens/surface_analytics/panels_macro.cpp
index ed1abade4..091a38a7f 100644
--- a/fincept-cpp/src/screens/surface_analytics/panels_macro.cpp
+++ b/fincept-cpp/src/screens/surface_analytics/panels_macro.cpp
@@ -9,8 +9,14 @@ namespace fincept::surface {
using namespace theme::colors;
void SurfaceScreen::render_metrics_macro() {
- float metric_label_w = ImGui::GetContentRegionAvail().x * 0.45f;
- auto row = [metric_label_w](const char* lbl, const char* val, ImVec4 col) {
+ float w = ImGui::GetContentRegionAvail().x;
+ float metric_label_w = w * 0.52f;
+ ImDrawList* dl = ImGui::GetWindowDrawList();
+ auto row = [&](const char* lbl, const char* val, ImVec4 col) {
+ ImVec2 p = ImGui::GetCursorScreenPos();
+ dl->AddCircleFilled(ImVec2(p.x + 4.0f, p.y + ImGui::GetTextLineHeight() * 0.5f + 1.0f),
+ 3.0f, ImGui::GetColorU32(ImVec4(col.x, col.y, col.z, 0.7f)));
+ ImGui::SetCursorPosX(ImGui::GetCursorPosX() + 12.0f);
ImGui::TextColored(TEXT_DIM, "%s", lbl);
ImGui::SameLine(metric_label_w);
ImGui::TextColored(col, "%s", val);
diff --git a/fincept-cpp/src/screens/surface_analytics/panels_risk.cpp b/fincept-cpp/src/screens/surface_analytics/panels_risk.cpp
index 851b7703b..037b74d99 100644
--- a/fincept-cpp/src/screens/surface_analytics/panels_risk.cpp
+++ b/fincept-cpp/src/screens/surface_analytics/panels_risk.cpp
@@ -9,8 +9,14 @@ namespace fincept::surface {
using namespace theme::colors;
void SurfaceScreen::render_metrics_risk() {
- float metric_label_w = ImGui::GetContentRegionAvail().x * 0.45f;
- auto row = [metric_label_w](const char* lbl, const char* val, ImVec4 col) {
+ float w = ImGui::GetContentRegionAvail().x;
+ float metric_label_w = w * 0.52f;
+ ImDrawList* dl = ImGui::GetWindowDrawList();
+ auto row = [&](const char* lbl, const char* val, ImVec4 col) {
+ ImVec2 p = ImGui::GetCursorScreenPos();
+ dl->AddCircleFilled(ImVec2(p.x + 4.0f, p.y + ImGui::GetTextLineHeight() * 0.5f + 1.0f),
+ 3.0f, ImGui::GetColorU32(ImVec4(col.x, col.y, col.z, 0.7f)));
+ ImGui::SetCursorPosX(ImGui::GetCursorPosX() + 12.0f);
ImGui::TextColored(TEXT_DIM, "%s", lbl);
ImGui::SameLine(metric_label_w);
ImGui::TextColored(col, "%s", val);
diff --git a/fincept-cpp/src/screens/surface_analytics/surface_3d_renderer.cpp b/fincept-cpp/src/screens/surface_analytics/surface_3d_renderer.cpp
index 80c9fac62..a95fb2b91 100644
--- a/fincept-cpp/src/screens/surface_analytics/surface_3d_renderer.cpp
+++ b/fincept-cpp/src/screens/surface_analytics/surface_3d_renderer.cpp
@@ -73,10 +73,27 @@ void SurfaceScreen::render_3d_surface(
if (grid.empty() || grid[0].empty()) return;
ImVec2 avail = ImGui::GetContentRegionAvail();
+ // Reserve 20px bottom for status strip and 32px top for overlay
+ avail.y -= 20.0f;
ImVec2 origin = ImGui::GetCursorScreenPos();
+ origin.y += 32.0f; // push below the top overlay
+
ImVec2 center(origin.x + avail.x * 0.46f, origin.y + avail.y * 0.52f);
float sc = std::min(avail.x, avail.y) * 0.34f;
+ // Subtle gradient background for the 3D canvas
+ {
+ ImDrawList* bg_dl = ImGui::GetWindowDrawList();
+ ImVec2 bg_min = ImGui::GetWindowPos();
+ bg_min.y += 32.0f;
+ ImVec2 bg_max = ImVec2(bg_min.x + ImGui::GetWindowWidth(), bg_min.y + avail.y);
+ bg_dl->AddRectFilledMultiColor(bg_min, bg_max,
+ ImGui::GetColorU32(ImVec4(0.07f, 0.08f, 0.10f, 1.0f)),
+ ImGui::GetColorU32(ImVec4(0.07f, 0.08f, 0.10f, 1.0f)),
+ ImGui::GetColorU32(ImVec4(0.05f, 0.06f, 0.07f, 1.0f)),
+ ImGui::GetColorU32(ImVec4(0.05f, 0.06f, 0.07f, 1.0f)));
+ }
+
ImGui::InvisibleButton("##3d_interact", avail);
bool hovered = ImGui::IsItemHovered();
@@ -146,11 +163,19 @@ void SurfaceScreen::render_3d_surface(
dl->AddLine(project(v3(-1,-1,gt), center, sc), project(v3(-1,1,gt), center, sc), wall_col);
}
- // ---- Axis labels ----
+ // ---- Axis labels — styled with background pill ----
ImU32 label_col = ImGui::GetColorU32(ImVec4(0.40f, 0.85f, 0.95f, 1.0f));
- dl->AddText(project(v3(0.0f, -1.35f, -1.0f), center, sc), label_col, x_label);
- dl->AddText(project(v3(-1.35f, 0.0f, -1.0f), center, sc), label_col, y_label);
- dl->AddText(project(v3(-1.0f, -1.35f, 0.0f), center, sc), label_col, z_label);
+ ImU32 label_bg = ImGui::GetColorU32(ImVec4(0.10f, 0.22f, 0.28f, 0.82f));
+ auto draw_axis_label = [&](Vec3 pos, const char* text) {
+ ImVec2 tp = project(pos, center, sc);
+ float tw = ImGui::CalcTextSize(text).x;
+ float th = ImGui::GetTextLineHeight();
+ dl->AddRectFilled(ImVec2(tp.x-3, tp.y-2), ImVec2(tp.x+tw+3, tp.y+th+2), label_bg, 2.0f);
+ dl->AddText(tp, label_col, text);
+ };
+ draw_axis_label(v3( 0.0f, -1.45f, -1.0f), x_label);
+ draw_axis_label(v3(-1.50f, 0.0f, -1.0f), y_label);
+ draw_axis_label(v3(-1.0f, -1.45f, 0.0f), z_label);
// ---- Tick labels ----
ImU32 tick_col = ImGui::GetColorU32(ImVec4(0.50f, 0.58f, 0.65f, 0.8f));
@@ -323,32 +348,52 @@ void SurfaceScreen::render_3d_surface(
ImGui::PopStyleColor(2);
}
- // ---- Color bar ----
- float bar_x = origin.x + avail.x - 40;
- float bar_top = origin.y + 30;
- float bar_h = avail.y - 60;
- float bar_w = 16.0f;
+ // ---- Color bar — wider, with gradient border and clean ticks ----
+ float bar_w = 18.0f;
+ float bar_x = origin.x + avail.x - bar_w - 52.0f;
+ float bar_top = origin.y + 36.0f;
+ float bar_h = avail.y - 72.0f;
+ // Draw gradient bar pixel by pixel
for (int ci = 0; ci < (int)bar_h; ci++) {
float ct = 1.0f - (float)ci / bar_h;
ImVec4 cc = surface_color(ct, diverging);
- dl->AddRectFilled(ImVec2(bar_x, bar_top + ci), ImVec2(bar_x + bar_w, bar_top + ci + 1),
- ImGui::GetColorU32(cc));
+ dl->AddRectFilled(
+ ImVec2(bar_x, bar_top + (float)ci),
+ ImVec2(bar_x + bar_w, bar_top + (float)ci + 1.5f),
+ ImGui::GetColorU32(cc));
}
- dl->AddRect(ImVec2(bar_x, bar_top), ImVec2(bar_x + bar_w, bar_top + bar_h),
- ImGui::GetColorU32(ImVec4(0.4f, 0.5f, 0.6f, 0.6f)), 0, 0, 1.0f);
+ // Border
+ dl->AddRect(ImVec2(bar_x - 1, bar_top - 1),
+ ImVec2(bar_x + bar_w + 1, bar_top + bar_h + 1),
+ ImGui::GetColorU32(ImVec4(0.35f, 0.45f, 0.55f, 0.7f)), 0, 0, 1.0f);
+ // Tick marks + labels
+ ImU32 tick_col2 = ImGui::GetColorU32(ImVec4(0.55f, 0.65f, 0.75f, 0.9f));
constexpr int bar_ticks = 6;
for (int bi = 0; bi <= bar_ticks; bi++) {
float frac = (float)bi / (float)bar_ticks;
- float val = max_val - frac * range;
- float py = bar_top + frac * bar_h;
- char bl[16]; std::snprintf(bl, 16, "%.1f", val);
- dl->AddLine(ImVec2(bar_x + bar_w, py), ImVec2(bar_x + bar_w + 4, py),
- ImGui::GetColorU32(ImVec4(0.5f, 0.6f, 0.7f, 0.7f)));
- dl->AddText(ImVec2(bar_x + bar_w + 6, py - 6), ImGui::GetColorU32(ImVec4(0.55f, 0.65f, 0.75f, 0.9f)), bl);
+ float val = max_val - frac * range;
+ float py = bar_top + frac * bar_h;
+ char bl[16]; std::snprintf(bl, 16, "%.2f", val);
+ dl->AddLine(ImVec2(bar_x + bar_w, py),
+ ImVec2(bar_x + bar_w + 5, py),
+ tick_col2, 1.2f);
+ dl->AddText(ImVec2(bar_x + bar_w + 7, py - 6), tick_col2, bl);
}
- dl->AddText(ImVec2(bar_x - 4, bar_top - 16), ImGui::GetColorU32(ImVec4(0.40f, 0.85f, 0.95f, 1.0f)), y_label);
+
+ // Y-axis label above bar
+ ImU32 bar_label_col = ImGui::GetColorU32(ImVec4(0.40f, 0.85f, 0.95f, 1.0f));
+ float yl_tw = ImGui::CalcTextSize(y_label).x;
+ dl->AddText(ImVec2(bar_x + (bar_w - yl_tw) * 0.5f, bar_top - 18.0f), bar_label_col, y_label);
+
+ // Min/Max caps
+ char cap_max[16], cap_min[16];
+ std::snprintf(cap_max, 16, "MAX"); std::snprintf(cap_min, 16, "MIN");
+ dl->AddText(ImVec2(bar_x + bar_w + 7, bar_top - 6),
+ ImGui::GetColorU32(ImVec4(0.40f, 0.85f, 0.95f, 0.7f)), cap_max);
+ dl->AddText(ImVec2(bar_x + bar_w + 7, bar_top + bar_h - 6),
+ ImGui::GetColorU32(ImVec4(0.40f, 0.85f, 0.95f, 0.7f)), cap_min);
}
} // namespace fincept::surface
diff --git a/fincept-cpp/src/screens/surface_analytics/surface_screen.cpp b/fincept-cpp/src/screens/surface_analytics/surface_screen.cpp
index 70b27ddd1..edee935a2 100644
--- a/fincept-cpp/src/screens/surface_analytics/surface_screen.cpp
+++ b/fincept-cpp/src/screens/surface_analytics/surface_screen.cpp
@@ -1,5 +1,6 @@
#include "surface_screen.h"
#include "demo_data.h"
+#include "csv_importer.h"
#include "ui/yoga_helpers.h"
#include <imgui.h>
#include <cstdio>
@@ -14,6 +15,17 @@ static const char* VOL_SYMBOLS[] = {"SPY", "QQQ", "IWM", "AAPL", "TSLA", "NVDA",
static const float VOL_SPOTS[] = {450, 380, 200, 175, 250, 120, 180};
static constexpr int N_SYMBOLS = 7;
+// Category accent colors for visual distinction
+static const ImVec4 CAT_COLORS[] = {
+ {0.20f, 0.60f, 1.00f, 1.0f}, // EQUITY DERIV — blue
+ {0.40f, 0.85f, 0.60f, 1.0f}, // FIXED INCOME — green
+ {1.00f, 0.75f, 0.20f, 1.0f}, // FX — gold
+ {0.90f, 0.35f, 0.35f, 1.0f}, // CREDIT — red
+ {0.75f, 0.55f, 1.00f, 1.0f}, // COMMODITIES — purple
+ {1.00f, 0.55f, 0.15f, 1.0f}, // RISK — orange
+ {0.35f, 0.85f, 0.95f, 1.0f}, // MACRO — cyan
+};
+
// ============================================================================
void SurfaceScreen::load_demo_data() {
srand((unsigned)time(nullptr));
@@ -77,12 +89,12 @@ void SurfaceScreen::render() {
ui::ScreenFrame frame("##surface_analytics", ImVec2(0, 0), BG_DARK);
if (!frame.begin()) { frame.end(); return; }
- auto vstack = ui::vstack_layout(frame.width(), frame.height(), {36, -1});
-
+ // Two-row header: category tabs (28px) + surface chips (28px)
render_control_bar();
float content_w = frame.width();
- float content_h = vstack.heights[1];
+ float header_h = 28.0f + 4.0f + 28.0f + 4.0f; // two rows + gaps
+ float content_h = frame.height() - header_h;
if (frame.is_compact()) {
ImGui::BeginChild("##sa_chart", ImVec2(content_w, content_h), ImGuiChildFlags_Borders);
@@ -103,98 +115,266 @@ void SurfaceScreen::render() {
ImGui::EndChild();
}
+ // CSV import modal (rendered over everything else)
+ render_csv_import_dialog();
+
frame.end();
}
// ============================================================================
void SurfaceScreen::render_control_bar() {
- ImGui::PushStyleColor(ImGuiCol_ChildBg, BG_PANEL);
- ImGui::BeginChild("##sa_ctrl", ImVec2(0, 36), ImGuiChildFlags_Borders);
- ImGui::SetCursorPos(ImVec2(8, 6));
-
const auto categories = get_surface_categories();
+ ImDrawList* dl = ImGui::GetWindowDrawList();
+
+ // ── Row 1: Category tab bar ──────────────────────────────────────────────
+ ImGui::PushStyleColor(ImGuiCol_ChildBg, BG_DARKEST);
+ ImGui::BeginChild("##sa_catbar", ImVec2(0, 28), ImGuiChildFlags_None);
+
+ ImVec2 row1_origin = ImGui::GetCursorScreenPos();
+ ImGui::SetCursorPos(ImVec2(8, 4));
+
+ for (int i = 0; i < (int)categories.size(); i++) {
+ const ImVec4& cat_col = CAT_COLORS[i];
+ bool active = (i == active_category_);
+
+ // Measure label width
+ float lw = ImGui::CalcTextSize(categories[i].name).x;
+ float bw = lw + 18.0f;
+ float bh = 20.0f;
+
+ ImVec2 cursor = ImGui::GetCursorScreenPos();
+ ImVec2 btn_min = cursor;
+ ImVec2 btn_max = ImVec2(cursor.x + bw, cursor.y + bh);
+
+ // Background fill
+ if (active) {
+ dl->AddRectFilled(btn_min, btn_max,
+ ImGui::GetColorU32(ImVec4(cat_col.x*0.18f, cat_col.y*0.18f, cat_col.z*0.18f, 1.0f)));
+ // Active bottom accent line
+ dl->AddLine(ImVec2(btn_min.x, btn_max.y), btn_max,
+ ImGui::GetColorU32(cat_col), 2.5f);
+ } else {
+ bool hov = ImGui::IsMouseHoveringRect(btn_min, btn_max);
+ if (hov)
+ dl->AddRectFilled(btn_min, btn_max, ImGui::GetColorU32(BG_HOVER));
+ }
- // Category dropdown
- ImGui::PushItemWidth(120);
- ImGui::PushStyleColor(ImGuiCol_FrameBg, BG_INPUT);
- if (ImGui::BeginCombo("##cat", categories[active_category_].name, ImGuiComboFlags_NoArrowButton)) {
- for (int i = 0; i < (int)categories.size(); i++) {
- if (ImGui::Selectable(categories[i].name, i == active_category_)) {
- active_category_ = i;
- active_chart_ = categories[i].types[0];
- }
+ // Invisible button for interaction
+ ImGui::InvisibleButton(categories[i].name, ImVec2(bw, bh));
+ if (ImGui::IsItemClicked()) {
+ active_category_ = i;
+ active_chart_ = categories[i].types[0];
+ }
+
+ // Draw text centered in button
+ ImVec4 text_col = active ? cat_col : TEXT_DIM;
+ ImVec2 text_pos = ImVec2(
+ btn_min.x + (bw - ImGui::CalcTextSize(categories[i].name).x) * 0.5f,
+ btn_min.y + (bh - ImGui::GetTextLineHeight()) * 0.5f
+ );
+ dl->AddText(text_pos, ImGui::GetColorU32(text_col), categories[i].name);
+
+ ImGui::SameLine(0, 2);
+ }
+
+ // Right-aligned: IMPORT + view toggle + refresh
+ float avail_x = ImGui::GetContentRegionAvail().x;
+ ImGui::SameLine(0, avail_x - 224);
+
+ // IMPORT button
+ {
+ float iw = ImGui::CalcTextSize("IMPORT").x + 14.0f;
+ ImVec2 ic = ImGui::GetCursorScreenPos();
+ ImVec2 imn = ic, imx = ImVec2(ic.x + iw, ic.y + 20.0f);
+ bool ihov = ImGui::IsMouseHoveringRect(imn, imx);
+ dl->AddRectFilled(imn, imx,
+ ImGui::GetColorU32(ihov ? ImVec4(0.18f, 0.42f, 0.80f, 1.0f)
+ : ImVec4(0.12f, 0.30f, 0.60f, 1.0f)), 2.0f);
+ dl->AddRect(imn, imx, ImGui::GetColorU32(ImVec4(0.25f, 0.55f, 1.0f, 0.6f)), 2.0f);
+ float itw = ImGui::CalcTextSize("IMPORT").x;
+ dl->AddText(ImVec2(imn.x + (iw - itw) * 0.5f,
+ imn.y + (20.0f - ImGui::GetTextLineHeight()) * 0.5f),
+ ImGui::GetColorU32(ImVec4(0.55f, 0.80f, 1.0f, 1.0f)), "IMPORT");
+ ImGui::InvisibleButton("##import_csv", ImVec2(iw, 20.0f));
+ if (ImGui::IsItemClicked()) {
+ show_import_dialog_ = true;
+ import_error_.clear();
+ import_success_ = false;
}
- ImGui::EndCombo();
}
- ImGui::PopStyleColor();
- ImGui::PopItemWidth();
ImGui::SameLine(0, 8);
- ImGui::TextColored(BORDER_BRIGHT, "|");
+ // 3D / TABLE toggle as segmented control
+ auto seg_btn = [&](const char* label, bool selected, ImVec4 accent) {
+ float tw = ImGui::CalcTextSize(label).x + 14.0f;
+ ImVec2 c = ImGui::GetCursorScreenPos();
+ ImVec2 mn = c, mx = ImVec2(c.x + tw, c.y + 20.0f);
+ bool hov = ImGui::IsMouseHoveringRect(mn, mx);
+ ImU32 bg = selected
+ ? ImGui::GetColorU32(ImVec4(accent.x*0.25f, accent.y*0.25f, accent.z*0.25f, 1.0f))
+ : (hov ? ImGui::GetColorU32(BG_HOVER) : ImGui::GetColorU32(BG_WIDGET));
+ dl->AddRectFilled(mn, mx, bg);
+ if (selected)
+ dl->AddRect(mn, mx, ImGui::GetColorU32(ImVec4(accent.x, accent.y, accent.z, 0.5f)));
+ ImVec2 tp = ImVec2(mn.x + (tw - ImGui::CalcTextSize(label).x)*0.5f,
+ mn.y + (20.0f - ImGui::GetTextLineHeight())*0.5f);
+ dl->AddText(tp, ImGui::GetColorU32(selected ? accent : TEXT_DIM), label);
+ ImGui::InvisibleButton(label, ImVec2(tw, 20.0f));
+ return ImGui::IsItemClicked();
+ };
+
+ const ImVec4& cat_accent = CAT_COLORS[active_category_];
+ if (seg_btn("3D", !show_table_, cat_accent)) show_table_ = false;
+ ImGui::SameLine(0, 2);
+ if (seg_btn("TABLE", show_table_, cat_accent)) show_table_ = true;
ImGui::SameLine(0, 8);
- // Surface buttons within category
+ // Refresh button
+ {
+ float rw = ImGui::CalcTextSize("REFRESH").x + 14.0f;
+ ImVec2 rc = ImGui::GetCursorScreenPos();
+ ImVec2 rmn = rc, rmx = ImVec2(rc.x+rw, rc.y+20.0f);
+ bool rhov = ImGui::IsMouseHoveringRect(rmn, rmx);
+ dl->AddRectFilled(rmn, rmx, ImGui::GetColorU32(rhov ? ACCENT_DIM : BG_WIDGET));
+ dl->AddText(ImVec2(rmn.x+7, rmn.y+(20.0f-ImGui::GetTextLineHeight())*0.5f),
+ ImGui::GetColorU32(ACCENT), "REFRESH");
+ ImGui::InvisibleButton("##refresh", ImVec2(rw, 20.0f));
+ if (ImGui::IsItemClicked()) load_demo_data();
+ }
+
+ ImGui::EndChild();
+ ImGui::PopStyleColor();
+
+ // Divider
+ ImGui::Spacing();
+
+ // ── Row 2: Surface chip buttons ─────────────────────────────────────────
+ ImGui::PushStyleColor(ImGuiCol_ChildBg, BG_PANEL);
+ ImGui::BeginChild("##sa_surfbar", ImVec2(0, 28), ImGuiChildFlags_None);
+ ImGui::SetCursorPos(ImVec2(8, 4));
+
const auto& cat = categories[active_category_];
+ const ImVec4& cc = CAT_COLORS[active_category_];
+
for (int i = 0; i < (int)cat.types.size(); i++) {
bool act = (active_chart_ == cat.types[i]);
- ImGui::PushStyleColor(ImGuiCol_Button, act ? ACCENT_DIM : BG_WIDGET);
- ImGui::PushStyleColor(ImGuiCol_Text, act ? ImVec4(1,1,1,1) : TEXT_SECONDARY);
- ImGui::PushStyleColor(ImGuiCol_ButtonHovered, act ? ACCENT : BG_HOVER);
- if (ImGui::SmallButton(chart_type_name(cat.types[i])))
- active_chart_ = cat.types[i];
- ImGui::PopStyleColor(3);
- ImGui::SameLine(0, 4);
- }
+ const char* lbl = chart_type_name(cat.types[i]);
+ float lw2 = ImGui::CalcTextSize(lbl).x + 16.0f;
- ImGui::SameLine(0, 16);
- ImGui::TextColored(BORDER_BRIGHT, "|");
- ImGui::SameLine(0, 8);
+ ImVec2 cur = ImGui::GetCursorScreenPos();
+ ImVec2 mn2 = cur, mx2 = ImVec2(cur.x + lw2, cur.y + 20.0f);
+ bool hov2 = ImGui::IsMouseHoveringRect(mn2, mx2);
- // View toggle
- {
- bool is_fig = !show_table_;
- ImGui::PushStyleColor(ImGuiCol_Button, is_fig ? ACCENT_DIM : BG_WIDGET);
- ImGui::PushStyleColor(ImGuiCol_Text, is_fig ? ImVec4(1,1,1,1) : TEXT_DIM);
- ImGui::PushStyleColor(ImGuiCol_ButtonHovered, BG_HOVER);
- if (ImGui::SmallButton("FIGURE")) show_table_ = false;
- ImGui::PopStyleColor(3);
- ImGui::SameLine(0, 2);
- ImGui::PushStyleColor(ImGuiCol_Button, show_table_ ? ACCENT_DIM : BG_WIDGET);
- ImGui::PushStyleColor(ImGuiCol_Text, show_table_ ? ImVec4(1,1,1,1) : TEXT_DIM);
- ImGui::PushStyleColor(ImGuiCol_ButtonHovered, BG_HOVER);
- if (ImGui::SmallButton("TABLE")) show_table_ = true;
- ImGui::PopStyleColor(3);
- }
+ ImU32 bg2 = act
+ ? ImGui::GetColorU32(ImVec4(cc.x*0.22f, cc.y*0.22f, cc.z*0.22f, 1.0f))
+ : (hov2 ? ImGui::GetColorU32(BG_HOVER) : ImGui::GetColorU32(BG_WIDGET));
+ dl->AddRectFilled(mn2, mx2, bg2, 3.0f);
+ if (act)
+ dl->AddRect(mn2, mx2, ImGui::GetColorU32(ImVec4(cc.x, cc.y, cc.z, 0.7f)), 3.0f, 0, 1.2f);
+
+ ImVec2 tp2 = ImVec2(mn2.x + (lw2 - ImGui::CalcTextSize(lbl).x)*0.5f,
+ mn2.y + (20.0f - ImGui::GetTextLineHeight())*0.5f);
+ ImU32 tc2 = act ? ImGui::GetColorU32(cc) : ImGui::GetColorU32(hov2 ? TEXT_SECONDARY : TEXT_DIM);
+ dl->AddText(tp2, tc2, lbl);
- ImGui::SameLine(0, 12);
- ImGui::PushStyleColor(ImGuiCol_Button, BG_WIDGET);
- ImGui::PushStyleColor(ImGuiCol_ButtonHovered, BG_HOVER);
- ImGui::PushStyleColor(ImGuiCol_Text, ACCENT);
- if (ImGui::SmallButton("REFRESH")) load_demo_data();
- ImGui::PopStyleColor(3);
+ ImGui::InvisibleButton(lbl, ImVec2(lw2, 20.0f));
+ if (ImGui::IsItemClicked()) active_chart_ = cat.types[i];
- ImGui::SameLine(0, 12);
- ImGui::TextColored(TEXT_DIM, "DEMO DATA");
+ ImGui::SameLine(0, 4);
+ }
+
+ // Symbol selector for equity-linked surfaces (right-aligned)
+ bool needs_symbol = (active_category_ == 0); // EQUITY DERIV
+ if (needs_symbol) {
+ float ra = ImGui::GetContentRegionAvail().x;
+ // rough width: combo is ~90px
+ ImGui::SameLine(0, ra - 92.0f);
+ ImGui::PushStyleColor(ImGuiCol_FrameBg, BG_INPUT);
+ ImGui::PushStyleColor(ImGuiCol_Text, TEXT_SECONDARY);
+ ImGui::PushItemWidth(88);
+ int prev = selected_symbol_;
+ if (ImGui::BeginCombo("##sym", VOL_SYMBOLS[selected_symbol_], ImGuiComboFlags_NoArrowButton)) {
+ for (int s = 0; s < N_SYMBOLS; s++) {
+ if (ImGui::Selectable(VOL_SYMBOLS[s], s == selected_symbol_))
+ selected_symbol_ = s;
+ }
+ ImGui::EndCombo();
+ }
+ ImGui::PopItemWidth();
+ ImGui::PopStyleColor(2);
+ if (selected_symbol_ != prev) load_demo_data();
+ }
ImGui::EndChild();
ImGui::PopStyleColor();
}
// ============================================================================
+// Helper: draw a filled badge with text
+static void draw_badge(const char* text, ImVec4 bg_col, ImVec4 text_col) {
+ ImDrawList* dl = ImGui::GetWindowDrawList();
+ ImVec2 cur = ImGui::GetCursorScreenPos();
+ float tw = ImGui::CalcTextSize(text).x;
+ float bw = tw + 10.0f, bh = ImGui::GetTextLineHeight() + 4.0f;
+ dl->AddRectFilled(cur, ImVec2(cur.x + bw, cur.y + bh),
+ ImGui::GetColorU32(bg_col), 3.0f);
+ dl->AddText(ImVec2(cur.x + 5.0f, cur.y + 2.0f),
+ ImGui::GetColorU32(text_col), text);
+ ImGui::Dummy(ImVec2(bw, bh));
+}
+
+// Helper: colored metric row with value badge
+static void metric_row(const char* label, const char* value, ImVec4 val_col, float label_w) {
+ ImGui::TextColored(TEXT_DIM, "%s", label);
+ ImGui::SameLine(label_w);
+ ImGui::TextColored(val_col, "%s", value);
+}
+
+// Helper: thick separator with color tint
+static void colored_separator(ImVec4 col) {
+ ImDrawList* dl = ImGui::GetWindowDrawList();
+ ImVec2 p = ImGui::GetCursorScreenPos();
+ float w = ImGui::GetContentRegionAvail().x;
+ dl->AddLine(p, ImVec2(p.x + w, p.y),
+ ImGui::GetColorU32(ImVec4(col.x, col.y, col.z, 0.45f)), 1.5f);
+ ImGui::Dummy(ImVec2(w, 2.0f));
+}
+
void SurfaceScreen::render_metrics_panel() {
ImGui::PushStyleColor(ImGuiCol_ChildBg, BG_PANEL);
- ImGui::SetCursorPos(ImVec2(8, 8));
- ImGui::TextColored(ACCENT, "%s", chart_type_name(active_chart_));
- ImGui::Spacing(); ImGui::Separator(); ImGui::Spacing();
-
- float metric_label_w = ImGui::GetContentRegionAvail().x * 0.45f;
- auto row = [metric_label_w](const char* lbl, const char* val, ImVec4 col) {
- ImGui::TextColored(TEXT_DIM, "%s", lbl);
- ImGui::SameLine(metric_label_w);
- ImGui::TextColored(col, "%s", val);
- };
+
+ const auto categories = get_surface_categories();
+ const ImVec4& cat_col = CAT_COLORS[active_category_];
+
+ // Panel header — category color accent bar + surface name
+ {
+ ImDrawList* dl = ImGui::GetWindowDrawList();
+ ImVec2 p0 = ImGui::GetCursorScreenPos();
+ float w = ImGui::GetContentRegionAvail().x;
+ // Left accent stripe
+ dl->AddRectFilled(p0, ImVec2(p0.x + 3.0f, p0.y + 48.0f),
+ ImGui::GetColorU32(cat_col));
+ // Header bg
+ dl->AddRectFilled(ImVec2(p0.x + 3.0f, p0.y),
+ ImVec2(p0.x + w, p0.y + 48.0f),
+ ImGui::GetColorU32(ImVec4(cat_col.x*0.08f, cat_col.y*0.08f, cat_col.z*0.08f, 1.0f)));
+ ImGui::Dummy(ImVec2(0, 0));
+ ImGui::SetCursorPosX(ImGui::GetCursorPosX() + 10.0f);
+ ImGui::SetCursorPosY(ImGui::GetCursorPosY() + 6.0f);
+ ImGui::TextColored(cat_col, "%s", categories[active_category_].name);
+ ImGui::SetCursorPosX(ImGui::GetCursorPosX() + 10.0f);
+ ImGui::TextColored(TEXT_PRIMARY, "%s", chart_type_name(active_chart_));
+ ImGui::Dummy(ImVec2(0, 4.0f));
+ }
+
+ colored_separator(cat_col);
+ ImGui::Spacing();
+
+ float panel_w = ImGui::GetContentRegionAvail().x;
+ float label_w = panel_w * 0.50f;
char b[64];
+ // Metric dispatch
switch (active_chart_) {
case ChartType::Volatility: {
if (vol_data_.z.empty()) break;
@@ -202,37 +382,44 @@ void SurfaceScreen::render_metrics_panel() {
float atm = vol_data_.z[me][ms];
int op = (int)(vol_data_.strikes.size()*0.2f), oc = (int)(vol_data_.strikes.size()*0.8f);
float skew = vol_data_.z[me][op] - vol_data_.z[me][oc];
- std::snprintf(b, 64, "%.1f%%", atm); row("ATM VOL", b, TEXT_PRIMARY);
- std::snprintf(b, 64, "%.1f%%", skew); row("SKEW", b, skew > 0 ? MARKET_GREEN : MARKET_RED);
- std::snprintf(b, 64, "$%.2f", vol_data_.spot_price); row("SPOT", b, TEXT_PRIMARY);
- std::snprintf(b, 64, "%d", (int)(vol_data_.strikes.size()*vol_data_.expirations.size()));
- row("POINTS", b, TEXT_SECONDARY);
- ImGui::Spacing(); ImGui::Separator(); ImGui::Spacing();
+
+ std::snprintf(b,64,"%.1f%%",atm); metric_row("ATM VOL",b,TEXT_PRIMARY,label_w);
+ std::snprintf(b,64,"%.1f%%",skew); metric_row("SKEW",b, skew>0?MARKET_GREEN:MARKET_RED, label_w);
+ std::snprintf(b,64,"$%.2f",vol_data_.spot_price); metric_row("SPOT",b,TEXT_PRIMARY,label_w);
+ std::snprintf(b,64,"%d",(int)(vol_data_.strikes.size()*vol_data_.expirations.size()));
+ metric_row("DATA PTS",b,TEXT_SECONDARY,label_w);
+
+ ImGui::Spacing(); colored_separator(cat_col); ImGui::Spacing();
ImGui::TextColored(TEXT_DIM, "UNDERLYING");
- ImGui::TextColored(TEXT_PRIMARY, " %s", vol_data_.underlying.c_str());
- std::snprintf(b, 64, " %.0f - %.0f", vol_data_.strikes.front(), vol_data_.strikes.back());
- ImGui::TextColored(TEXT_DIM, "STRIKES"); ImGui::TextColored(TEXT_PRIMARY, "%s", b);
- std::snprintf(b, 64, " %dD - %dD", vol_data_.expirations.front(), vol_data_.expirations.back());
- ImGui::TextColored(TEXT_DIM, "EXPIRIES"); ImGui::TextColored(TEXT_PRIMARY, "%s", b);
+ ImGui::SameLine(label_w); ImGui::TextColored(cat_col, "%s", vol_data_.underlying.c_str());
+ std::snprintf(b,64,"%.0f - %.0f", vol_data_.strikes.front(), vol_data_.strikes.back());
+ metric_row("STRIKES",b,TEXT_SECONDARY,label_w);
+ std::snprintf(b,64,"%dD - %dD", vol_data_.expirations.front(), vol_data_.expirations.back());
+ metric_row("EXPIRIES",b,TEXT_SECONDARY,label_w);
break;
}
- // Equity Derivatives (excluding Volatility handled above)
case ChartType::DeltaSurface: case ChartType::GammaSurface:
case ChartType::VegaSurface: case ChartType::ThetaSurface:
case ChartType::SkewSurface: case ChartType::LocalVolSurface:
render_metrics_derivatives();
break;
- // Fixed Income
case ChartType::YieldCurve: {
if (yield_data_.z.empty()) break;
const auto& last = yield_data_.z.back();
- float y2=last.size()>4?last[4]:0, y10=last.size()>8?last[8]:0, sp=y10-y2;
- std::snprintf(b,64,"%.2f%%",y2); row("2Y YIELD",b,TEXT_PRIMARY);
- std::snprintf(b,64,"%.2f%%",y10); row("10Y YIELD",b,TEXT_PRIMARY);
- std::snprintf(b,64,"%.2f%%",sp); row("2-10 SPREAD",b, sp<0?MARKET_RED:MARKET_GREEN);
- row("CURVE", sp<0?"INVERTED":"NORMAL", sp<0?MARKET_RED:MARKET_GREEN);
- std::snprintf(b,64,"%d",(int)yield_data_.maturities.size()); row("TENORS",b,TEXT_SECONDARY);
+ float y2=last.size()>4?last[4]:0.0f, y10=last.size()>8?last[8]:0.0f, sp=y10-y2;
+ std::snprintf(b,64,"%.2f%%",y2); metric_row("2Y YIELD",b,TEXT_PRIMARY,label_w);
+ std::snprintf(b,64,"%.2f%%",y10); metric_row("10Y YIELD",b,TEXT_PRIMARY,label_w);
+ std::snprintf(b,64,"%.2f%%",sp); metric_row("2-10 SPREAD",b, sp<0?MARKET_RED:MARKET_GREEN, label_w);
+
+ ImGui::Spacing(); colored_separator(cat_col); ImGui::Spacing();
+ ImGui::TextColored(TEXT_DIM, "SHAPE");
+ ImGui::SameLine(label_w);
+ if (sp < 0) draw_badge("INVERTED", ImVec4(0.5f,0.05f,0.05f,1), MARKET_RED);
+ else if (sp<0.5f) draw_badge("FLAT", ImVec4(0.4f,0.35f,0.0f,1), WARNING);
+ else draw_badge("NORMAL", ImVec4(0.05f,0.3f,0.05f,1), MARKET_GREEN);
+ std::snprintf(b,64,"%d",(int)yield_data_.maturities.size());
+ metric_row("TENORS",b,TEXT_SECONDARY,label_w);
break;
}
case ChartType::SwaptionVol: case ChartType::CapFloorVol:
@@ -241,52 +428,50 @@ void SurfaceScreen::render_metrics_panel() {
render_metrics_fixed_income();
break;
- // FX
case ChartType::FXVol: case ChartType::FXForwardPoints:
case ChartType::CrossCurrencyBasis:
render_metrics_fx();
break;
- // Credit
case ChartType::CDSSpread: case ChartType::CreditTransition:
case ChartType::RecoveryRate:
render_metrics_credit();
break;
- // Commodities
case ChartType::CommodityForward: case ChartType::CommodityVol:
case ChartType::CrackSpread: case ChartType::ContangoBackwardation:
render_metrics_commodities();
break;
- // Risk
case ChartType::Correlation: {
if (corr_data_.z.empty()) break;
const auto& last = corr_data_.z.back();
int n = (int)corr_data_.assets.size();
- float sum=0, mx=-2, mn=2; int cnt=0;
+ float sum=0.0f, cmx=-2.0f, cmn=2.0f; int cnt=0;
for (int i=0;i<n;i++) for (int j=0;j<n;j++) if (i!=j) {
- float c=last[i*n+j]; sum+=c; cnt++; mx=std::max(mx,c); mn=std::min(mn,c);
+ float c=last[i*n+j]; sum+=c; cnt++;
+ cmx = c > cmx ? c : cmx; cmn = c < cmn ? c : cmn;
}
- float avg = cnt>0 ? sum/cnt : 0;
- std::snprintf(b,64,"%.3f",avg); row("AVG CORR",b, avg>0.5f ? MARKET_RED : MARKET_GREEN);
- std::snprintf(b,64,"%.3f",mx); row("MAX CORR",b, mx>0.8f ? MARKET_RED : TEXT_PRIMARY);
- std::snprintf(b,64,"%.3f",mn); row("MIN CORR",b, mn<0 ? INFO : TEXT_PRIMARY);
- std::snprintf(b,64,"%d",n); row("ASSETS",b, TEXT_SECONDARY);
- std::snprintf(b,64,"%dD",corr_data_.window); row("WINDOW",b, TEXT_SECONDARY);
+ float avg = cnt>0 ? sum/(float)cnt : 0.0f;
+ std::snprintf(b,64,"%.3f",avg); metric_row("AVG CORR",b, avg>0.5f?MARKET_RED:MARKET_GREEN, label_w);
+ std::snprintf(b,64,"%.3f",cmx); metric_row("MAX CORR",b, cmx>0.8f?MARKET_RED:TEXT_PRIMARY, label_w);
+ std::snprintf(b,64,"%.3f",cmn); metric_row("MIN CORR",b, cmn<0.0f?INFO:TEXT_PRIMARY, label_w);
+ std::snprintf(b,64,"%d",n); metric_row("ASSETS",b,TEXT_SECONDARY,label_w);
+ std::snprintf(b,64,"%dD",corr_data_.window); metric_row("WINDOW",b,TEXT_SECONDARY,label_w);
break;
}
case ChartType::PCA: {
if (pca_data_.variance_explained.empty()) break;
- for (int i=0;i<std::min(3,(int)pca_data_.variance_explained.size());i++) {
+ int np = (int)pca_data_.variance_explained.size();
+ for (int i=0; i<3 && i<np; i++) {
char lbl[16]; std::snprintf(lbl,16,"PC%d VAR",i+1);
- std::snprintf(b,64,"%.1f%%",pca_data_.variance_explained[i]*100);
- row(lbl, b, i==0?MARKET_GREEN:TEXT_PRIMARY);
+ std::snprintf(b,64,"%.1f%%",pca_data_.variance_explained[i]*100.0f);
+ metric_row(lbl, b, i==0?MARKET_GREEN:TEXT_PRIMARY, label_w);
}
- float tot=0;
- for (int i=0;i<std::min(3,(int)pca_data_.variance_explained.size());i++) tot+=pca_data_.variance_explained[i];
- std::snprintf(b,64,"%.1f%%",tot*100); row("TOP 3",b, tot>0.85f?MARKET_GREEN:WARNING);
- std::snprintf(b,64,"%d",(int)pca_data_.assets.size()); row("ASSETS",b,TEXT_SECONDARY);
+ float tot=0.0f;
+ for (int i=0; i<3 && i<np; i++) tot+=pca_data_.variance_explained[i];
+ std::snprintf(b,64,"%.1f%%",tot*100.0f); metric_row("TOP 3 CUM",b, tot>0.85f?MARKET_GREEN:WARNING, label_w);
+ std::snprintf(b,64,"%d",(int)pca_data_.assets.size()); metric_row("ASSETS",b,TEXT_SECONDARY,label_w);
break;
}
case ChartType::VaR: case ChartType::StressTestPnL:
@@ -296,17 +481,17 @@ void SurfaceScreen::render_metrics_panel() {
render_metrics_risk();
break;
- // Macro
case ChartType::InflationExpectations: case ChartType::MonetaryPolicyPath:
render_metrics_macro();
break;
}
+ // Controls hint (3D mode only) — at bottom of panel
if (!show_table_) {
- ImGui::Spacing(); ImGui::Separator(); ImGui::Spacing();
- ImGui::TextColored(TEXT_DIM, "CONTROLS");
- ImGui::TextColored(TEXT_SECONDARY, " Drag: Rotate");
- ImGui::TextColored(TEXT_SECONDARY, " Scroll: Zoom");
+ ImGui::Spacing(); colored_separator(ImVec4(0.3f,0.3f,0.35f,1)); ImGui::Spacing();
+ ImGui::TextColored(TEXT_DIM, "INTERACT");
+ ImGui::TextColored(TEXT_DISABLED, " Drag Rotate");
+ ImGui::TextColored(TEXT_DISABLED, " Scroll Zoom");
}
ImGui::PopStyleColor();
@@ -314,8 +499,62 @@ void SurfaceScreen::render_metrics_panel() {
// ============================================================================
void SurfaceScreen::render_chart_area() {
+ const auto categories = get_surface_categories();
+ const ImVec4& cat_col = CAT_COLORS[active_category_];
+ ImDrawList* dl = ImGui::GetWindowDrawList();
+ ImVec2 avail = ImGui::GetContentRegionAvail();
+ ImVec2 origin = ImGui::GetCursorScreenPos();
+
+ // Top-left overlay: surface name + category badge
+ {
+ const char* surf_name = chart_type_name(active_chart_);
+ const char* cat_name = categories[active_category_].name;
+ float cat_tw = ImGui::CalcTextSize(cat_name).x + 10.0f;
+ float surf_tw = ImGui::CalcTextSize(surf_name).x;
+
+ // Category pill
+ ImVec2 pill_min = ImVec2(origin.x + 8, origin.y + 8);
+ ImVec2 pill_max = ImVec2(pill_min.x + cat_tw, pill_min.y + 18.0f);
+ dl->AddRectFilled(pill_min, pill_max,
+ ImGui::GetColorU32(ImVec4(cat_col.x*0.25f, cat_col.y*0.25f, cat_col.z*0.25f, 0.95f)), 3.0f);
+ dl->AddRect(pill_min, pill_max,
+ ImGui::GetColorU32(ImVec4(cat_col.x, cat_col.y, cat_col.z, 0.4f)), 3.0f);
+ dl->AddText(ImVec2(pill_min.x + 5.0f, pill_min.y + 2.0f),
+ ImGui::GetColorU32(cat_col), cat_name);
+
+ // Surface name
+ dl->AddText(ImVec2(pill_max.x + 8.0f, pill_min.y + 2.0f),
+ ImGui::GetColorU32(TEXT_PRIMARY), surf_name);
+
+ // View mode badge (top right)
+ const char* view_lbl = show_table_ ? "TABLE VIEW" : "3D SURFACE";
+ float vw = ImGui::CalcTextSize(view_lbl).x + 12.0f;
+ ImVec2 vp_min = ImVec2(origin.x + avail.x - vw - 48.0f, origin.y + 8.0f);
+ ImVec2 vp_max = ImVec2(vp_min.x + vw, vp_min.y + 18.0f);
+ dl->AddRectFilled(vp_min, vp_max, ImGui::GetColorU32(BG_WIDGET), 3.0f);
+ dl->AddText(ImVec2(vp_min.x + 6.0f, vp_min.y + 2.0f),
+ ImGui::GetColorU32(TEXT_DIM), view_lbl);
+ }
+
+ // Bottom status strip
+ {
+ float strip_h = 20.0f;
+ ImVec2 sm = ImVec2(origin.x, origin.y + avail.y - strip_h);
+ ImVec2 sx = ImVec2(origin.x + avail.x, origin.y + avail.y);
+ dl->AddRectFilled(sm, sx, ImGui::GetColorU32(BG_DARKEST));
+ dl->AddLine(sm, ImVec2(sx.x, sm.y),
+ ImGui::GetColorU32(ImVec4(cat_col.x, cat_col.y, cat_col.z, 0.3f)));
+
+ // Status text
+ char status[128];
+ std::snprintf(status, 128, "FINCEPT SURFACE ANALYTICS | %s | %s | DEMO DATA",
+ categories[active_category_].name, chart_type_name(active_chart_));
+ dl->AddText(ImVec2(sm.x + 8.0f, sm.y + 3.0f),
+ ImGui::GetColorU32(TEXT_DISABLED), status);
+ }
+
if (show_table_) {
- ImGui::SetCursorPos(ImVec2(8, 8));
+ ImGui::SetCursorPos(ImVec2(8, 30));
switch (active_chart_) {
case ChartType::Volatility: render_vol_table(); return;
case ChartType::Correlation: render_corr_table(); return;
diff --git a/fincept-cpp/src/screens/surface_analytics/surface_screen.h b/fincept-cpp/src/screens/surface_analytics/surface_screen.h
index dfd94411e..165950e9a 100644
--- a/fincept-cpp/src/screens/surface_analytics/surface_screen.h
+++ b/fincept-cpp/src/screens/surface_analytics/surface_screen.h
@@ -5,6 +5,8 @@
#include "surface_types.h"
#include "ui/theme.h"
#include <imgui.h>
+#include <cstdio>
+#include <string>
namespace fincept::surface {
@@ -119,6 +121,15 @@ private:
// ---- Extended table renderer (in tables_extended.cpp) ----
void render_table_for(ChartType type);
+ // ---- CSV Import state ----
+ bool show_import_dialog_ = false;
+ char import_path_buf_[512] = {};
+ std::string import_error_;
+ bool import_success_ = false;
+
+ void render_csv_import_dialog();
+ bool dispatch_csv_load(const std::string& path, std::string& err);
+
// ---- 3D projection helpers ----
struct Vec3 { float x, y, z; };
ImVec2 project(Vec3 p, ImVec2 center, float scale) const;
diff --git a/fincept-cpp/src/storage/database.h b/fincept-cpp/src/storage/database.h
index 312989a9b..2850fa184 100644
--- a/fincept-cpp/src/storage/database.h
+++ b/fincept-cpp/src/storage/database.h
@@ -378,6 +378,7 @@ void delete_credential(int64_t id);
// --- LLM Config ---
std::vector<LLMConfig> get_llm_configs();
void save_llm_config(const LLMConfig& config);
+void delete_llm_config(const std::string& provider);
LLMGlobalSettings get_llm_global_settings();
void save_llm_global_settings(const LLMGlobalSettings& settings);
void set_active_llm_provider(const std::string& provider);
diff --git a/fincept-cpp/src/trading/broker_interface.h b/fincept-cpp/src/trading/broker_interface.h
index eb2edf8a1..07cfca450 100644
--- a/fincept-cpp/src/trading/broker_interface.h
+++ b/fincept-cpp/src/trading/broker_interface.h
@@ -46,6 +46,11 @@ public:
const std::string& from_date,
const std::string& to_date) = 0;
+ // --- WebSocket streaming (optional — default = not supported) ---
+ // Returns the broker name used to look up the openalgo streaming adapter.
+ // Empty string means no native WS support — fall back to REST polling.
+ virtual const char* ws_adapter_name() const { return ""; }
+
// --- Credential helpers ---
// Load credentials from DB for this broker
BrokerCredentials load_credentials() const;
diff --git a/fincept-cpp/src/trading/broker_types.h b/fincept-cpp/src/trading/broker_types.h
index 83e473941..11dde2e37 100644
--- a/fincept-cpp/src/trading/broker_types.h
+++ b/fincept-cpp/src/trading/broker_types.h
@@ -28,6 +28,7 @@ struct TokenExchangeResponse {
bool success = false;
std::string access_token;
std::string user_id;
+ std::string additional_data; // JSON: feed_token, refresh_token, etc.
std::string error;
};
@@ -100,6 +101,7 @@ struct UnifiedOrder {
std::string validity = "DAY";
double stop_loss = 0;
double take_profit = 0;
+ bool amo = false;
};
// ============================================================================
diff --git a/fincept-cpp/src/trading/brokers/aliceblue_broker.h b/fincept-cpp/src/trading/brokers/aliceblue_broker.h
index 42f0777d6..f4441c920 100644
--- a/fincept-cpp/src/trading/brokers/aliceblue_broker.h
+++ b/fincept-cpp/src/trading/brokers/aliceblue_broker.h
@@ -16,6 +16,7 @@ public:
const char* base_url() const override {
return "https://ant.aliceblueonline.com/rest/AliceBlueAPIService/api";
}
+ const char* ws_adapter_name() const override { return "aliceblue"; }
// AliceBlue uses SHA256 checksum session:
// api_key = user_id, api_secret = api_secret, auth_code = enc_key
diff --git a/fincept-cpp/src/trading/brokers/angelone_broker.cpp b/fincept-cpp/src/trading/brokers/angelone_broker.cpp
index fe7a3acc3..b109a9f2d 100644
--- a/fincept-cpp/src/trading/brokers/angelone_broker.cpp
+++ b/fincept-cpp/src/trading/brokers/angelone_broker.cpp
@@ -2,14 +2,68 @@
#include "http/http_client.h"
#include "core/logger.h"
#include <chrono>
+#include <mutex>
+#include <unordered_map>
namespace fincept::trading {
using namespace fincept::http;
+using json = nlohmann::json;
// ============================================================================
-// Helpers
+// Instrument token cache — lazily loaded from AngelOne's public master JSON
+// Key: "EXCHANGE:SYMBOL" (e.g. "NSE:RELIANCE") → instrument token string
// ============================================================================
+static std::unordered_map<std::string, std::string> s_token_cache;
+static std::once_flag s_token_cache_flag;
+
+static void ensure_token_cache() {
+ std::call_once(s_token_cache_flag, []() {
+ try {
+ auto resp = http::HttpClient::instance().get(
+ "https://margincalculator.angelbroking.com/OpenAPI_File/files/OpenAPIScripMaster.json");
+ if (!resp.success || resp.body.empty()) {
+ LOG_ERROR("AngelOne", "Failed to download instrument master: %s", resp.error.c_str());
+ return;
+ }
+ auto instruments = json::parse(resp.body);
+ for (const auto& inst : instruments) {
+ std::string sym = inst.value("symbol", inst.value("name", ""));
+ std::string exch = inst.value("exch_seg", inst.value("exchange", ""));
+ std::string token = inst.value("token", inst.value("symboltoken", ""));
+ if (!sym.empty() && !exch.empty() && !token.empty()) {
+ // Uppercase keys
+ for (auto& c : sym) c = (char)toupper((unsigned char)c);
+ for (auto& c : exch) c = (char)toupper((unsigned char)c);
+ s_token_cache[exch + ":" + sym] = token;
+ }
+ }
+ LOG_INFO("AngelOne", "Loaded %zu instrument tokens", s_token_cache.size());
+ } catch (const std::exception& e) {
+ LOG_ERROR("AngelOne", "Instrument master parse error: %s", e.what());
+ }
+ });
+}
+
+// Resolve "EXCHANGE:SYMBOL" or "EXCHANGE:TOKEN" → "EXCHANGE:TOKEN"
+// If the part after colon is already numeric, pass through unchanged.
+static std::string resolve_angel_token(const std::string& instrument) {
+ ensure_token_cache();
+ const auto colon = instrument.find(':');
+ if (colon == std::string::npos) return instrument;
+ const std::string part = instrument.substr(colon + 1);
+ // Already a numeric token
+ if (!part.empty() && std::all_of(part.begin(), part.end(), ::isdigit))
+ return instrument;
+ // Look up symbol → token
+ std::string key = instrument;
+ for (auto& c : key) c = (char)toupper((unsigned char)c);
+ auto it = s_token_cache.find(key);
+ if (it != s_token_cache.end())
+ return instrument.substr(0, colon + 1) + it->second;
+ LOG_ERROR("AngelOne", "Token not found for %s", instrument.c_str());
+ return instrument; // return as-is, API will reject it
+}
static int64_t angelone_now_ts() {
const auto now = std::chrono::system_clock::now().time_since_epoch();
@@ -191,15 +245,14 @@ TokenExchangeResponse AngelOneBroker::exchange_token(const std::string& api_key,
const auto jwt_token = data.value("jwtToken", "");
if (!jwt_token.empty()) {
- result.success = true;
+ result.success = true;
result.access_token = jwt_token;
- result.user_id = client_code;
- // Store feed_token and refresh_token in additional_data for later use
+ result.user_id = client_code;
json extra = {
- {"feed_token", data.value("feedToken", "")},
+ {"feed_token", data.value("feedToken", "")},
{"refresh_token", data.value("refreshToken", "")}
};
- // Caller can read these from the TokenExchangeResponse
+ result.additional_data = extra.dump();
} else {
result.error = body.value("message", "Authentication failed");
}
@@ -544,7 +597,8 @@ ApiResponse<std::vector<BrokerQuote>> AngelOneBroker::get_quotes(
// The tokens vector should contain "EXCHANGE:TOKEN" pairs
// Group tokens by exchange
std::map<std::string, json> exchange_tokens;
- for (const auto& token : tokens) {
+ for (const auto& raw_token : tokens) {
+ const std::string token = resolve_angel_token(raw_token);
const auto colon = token.find(':');
std::string exchange = "NSE";
std::string symbol_token = token;
diff --git a/fincept-cpp/src/trading/brokers/angelone_broker.h b/fincept-cpp/src/trading/brokers/angelone_broker.h
index c49400b7b..65cedeb83 100644
--- a/fincept-cpp/src/trading/brokers/angelone_broker.h
+++ b/fincept-cpp/src/trading/brokers/angelone_broker.h
@@ -13,6 +13,7 @@ public:
BrokerId id() const override { return BrokerId::AngelOne; }
const char* name() const override { return "AngelOne"; }
const char* base_url() const override { return "https://apiconnect.angelone.in"; }
+ const char* ws_adapter_name() const override { return "angelone"; }
// AngelOne uses TOTP-based login, not standard OAuth token exchange.
// api_key = API key, api_secret = password (PIN), auth_code = TOTP secret/code
diff --git a/fincept-cpp/src/trading/brokers/dhan_broker.h b/fincept-cpp/src/trading/brokers/dhan_broker.h
index df7c244de..2417c59e9 100644
--- a/fincept-cpp/src/trading/brokers/dhan_broker.h
+++ b/fincept-cpp/src/trading/brokers/dhan_broker.h
@@ -14,6 +14,7 @@ public:
BrokerId id() const override { return BrokerId::Dhan; }
const char* name() const override { return "Dhan"; }
const char* base_url() const override { return "https://api.dhan.co"; }
+ const char* ws_adapter_name() const override { return "dhan"; }
// Dhan uses consent-based OAuth
// api_key = app_id, api_secret = app_secret, auth_code = token_id from consent flow
diff --git a/fincept-cpp/src/trading/brokers/fivepaisa_broker.h b/fincept-cpp/src/trading/brokers/fivepaisa_broker.h
index 2d8d3d6a1..39f6cb8ab 100644
--- a/fincept-cpp/src/trading/brokers/fivepaisa_broker.h
+++ b/fincept-cpp/src/trading/brokers/fivepaisa_broker.h
@@ -15,6 +15,7 @@ public:
BrokerId id() const override { return BrokerId::FivePaisa; }
const char* name() const override { return "5Paisa"; }
const char* base_url() const override { return "https://Openapi.5paisa.com"; }
+ const char* ws_adapter_name() const override { return "fivepaisa"; }
// 5Paisa uses 2-step auth:
// Step 1: TOTP login to get request_token (api_key = app key, api_secret = enc_key, auth_code = "email:pin:totp")
diff --git a/fincept-cpp/src/trading/brokers/fyers_broker.h b/fincept-cpp/src/trading/brokers/fyers_broker.h
index d163ef404..696873a0d 100644
--- a/fincept-cpp/src/trading/brokers/fyers_broker.h
+++ b/fincept-cpp/src/trading/brokers/fyers_broker.h
@@ -12,6 +12,7 @@ public:
BrokerId id() const override { return BrokerId::Fyers; }
const char* name() const override { return "Fyers"; }
const char* base_url() const override { return "https://api-t1.fyers.in"; }
+ const char* ws_adapter_name() const override { return "fyers"; }
TokenExchangeResponse exchange_token(const std::string& api_key,
const std::string& api_secret,
diff --git a/fincept-cpp/src/trading/brokers/groww_broker.h b/fincept-cpp/src/trading/brokers/groww_broker.h
index 9390ce413..2551b2fb8 100644
--- a/fincept-cpp/src/trading/brokers/groww_broker.h
+++ b/fincept-cpp/src/trading/brokers/groww_broker.h
@@ -13,6 +13,7 @@ public:
BrokerId id() const override { return BrokerId::Groww; }
const char* name() const override { return "Groww"; }
const char* base_url() const override { return "https://api.groww.in"; }
+ const char* ws_adapter_name() const override { return "groww"; }
// Groww uses TOTP-based token exchange
// api_key = bearer key for TOTP request, api_secret = TOTP secret (base32), auth_code = unused
diff --git a/fincept-cpp/src/trading/brokers/iifl_broker.h b/fincept-cpp/src/trading/brokers/iifl_broker.h
index 54dccbe8f..80ccb7175 100644
--- a/fincept-cpp/src/trading/brokers/iifl_broker.h
+++ b/fincept-cpp/src/trading/brokers/iifl_broker.h
@@ -14,6 +14,7 @@ public:
BrokerId id() const override { return BrokerId::IIFL; }
const char* name() const override { return "IIFL"; }
const char* base_url() const override { return "https://ttblaze.iifl.com"; }
+ const char* ws_adapter_name() const override { return "iifl"; }
TokenExchangeResponse exchange_token(const std::string& api_key,
const std::string& api_secret,
diff --git a/fincept-cpp/src/trading/brokers/kotak_broker.h b/fincept-cpp/src/trading/brokers/kotak_broker.h
index f06955e9e..8f1516efc 100644
--- a/fincept-cpp/src/trading/brokers/kotak_broker.h
+++ b/fincept-cpp/src/trading/brokers/kotak_broker.h
@@ -15,6 +15,7 @@ public:
BrokerId id() const override { return BrokerId::Kotak; }
const char* name() const override { return "Kotak"; }
const char* base_url() const override { return "https://mis.kotaksecurities.com"; }
+ const char* ws_adapter_name() const override { return "kotak"; }
// Kotak uses a 2-step auth: TOTP login + MPIN validate
// For the unified interface, we combine both steps:
diff --git a/fincept-cpp/src/trading/brokers/motilal_broker.h b/fincept-cpp/src/trading/brokers/motilal_broker.h
index 815aa1685..29c1a5a0e 100644
--- a/fincept-cpp/src/trading/brokers/motilal_broker.h
+++ b/fincept-cpp/src/trading/brokers/motilal_broker.h
@@ -14,6 +14,7 @@ public:
BrokerId id() const override { return BrokerId::Motilal; }
const char* name() const override { return "Motilal"; }
const char* base_url() const override { return "https://openapi.motilaloswal.com/rest"; }
+ const char* ws_adapter_name() const override { return "motilal"; }
TokenExchangeResponse exchange_token(const std::string& api_key,
const std::string& api_secret,
diff --git a/fincept-cpp/src/trading/brokers/shoonya_broker.h b/fincept-cpp/src/trading/brokers/shoonya_broker.h
index 69781d4a5..2e2dc22e6 100644
--- a/fincept-cpp/src/trading/brokers/shoonya_broker.h
+++ b/fincept-cpp/src/trading/brokers/shoonya_broker.h
@@ -14,6 +14,7 @@ public:
BrokerId id() const override { return BrokerId::Shoonya; }
const char* name() const override { return "Shoonya"; }
const char* base_url() const override { return "https://api.shoonya.com/NorenWClientTP"; }
+ const char* ws_adapter_name() const override { return "shoonya"; }
TokenExchangeResponse exchange_token(const std::string& api_key,
const std::string& api_secret,
diff --git a/fincept-cpp/src/trading/brokers/upstox_broker.h b/fincept-cpp/src/trading/brokers/upstox_broker.h
index bc4a7866c..71210d01e 100644
--- a/fincept-cpp/src/trading/brokers/upstox_broker.h
+++ b/fincept-cpp/src/trading/brokers/upstox_broker.h
@@ -14,6 +14,7 @@ public:
BrokerId id() const override { return BrokerId::Upstox; }
const char* name() const override { return "Upstox"; }
const char* base_url() const override { return "https://api.upstox.com/v2"; }
+ const char* ws_adapter_name() const override { return "upstox"; }
// Upstox uses OAuth2 authorization_code flow
// api_key = client_id, api_secret = client_secret, auth_code = authorization code
diff --git a/fincept-cpp/src/trading/brokers/zerodha_broker.h b/fincept-cpp/src/trading/brokers/zerodha_broker.h
index 0b101f3d9..957580f37 100644
--- a/fincept-cpp/src/trading/brokers/zerodha_broker.h
+++ b/fincept-cpp/src/trading/brokers/zerodha_broker.h
@@ -14,6 +14,7 @@ public:
BrokerId id() const override { return BrokerId::Zerodha; }
const char* name() const override { return "Zerodha"; }
const char* base_url() const override { return "https://api.kite.trade"; }
+ const char* ws_adapter_name() const override { return "zerodha"; }
TokenExchangeResponse exchange_token(const std::string& api_key,
const std::string& api_secret,
diff --git a/fincept-cpp/src/trading/equity_stream.cpp b/fincept-cpp/src/trading/equity_stream.cpp
new file mode 100644
index 000000000..621196753
--- /dev/null
+++ b/fincept-cpp/src/trading/equity_stream.cpp
@@ -0,0 +1,383 @@
+// EquityStreamManager — spawns broker_ws_bridge.py subprocess and streams ticks
+
+#include "equity_stream.h"
+#include "python/python_runner.h"
+#include "core/logger.h"
+#include <nlohmann/json.hpp>
+#include <sstream>
+
+#ifndef _WIN32
+#include <unistd.h>
+#include <sys/wait.h>
+#include <signal.h>
+#endif
+
+namespace fincept::trading {
+
+using json = nlohmann::json;
+static const char* ESTAG = "EquityStream";
+
+EquityStreamManager& EquityStreamManager::instance() {
+ static EquityStreamManager s;
+ return s;
+}
+
+// ─────────────────────────────────────────────────────────────────────────────
+// Public API
+// ─────────────────────────────────────────────────────────────────────────────
+
+void EquityStreamManager::start(const std::string& broker_adapter,
+ const BrokerCredentials& creds,
+ const std::vector<EquitySymbol>& symbols) {
+ stop(); // clean up any previous stream
+
+ if (broker_adapter.empty()) {
+ LOG_INFO(ESTAG, "No WS adapter for this broker — REST polling only");
+ return;
+ }
+ if (symbols.empty()) {
+ LOG_INFO(ESTAG, "No symbols to stream");
+ return;
+ }
+
+ running_ = true;
+ connected_ = false;
+
+ spawn_subprocess(broker_adapter, creds, symbols);
+
+ reader_thread_ = std::thread([this]() {
+ LOG_INFO(ESTAG, "Reader thread started");
+ reader_loop();
+ LOG_INFO(ESTAG, "Reader thread exited");
+ });
+}
+
+void EquityStreamManager::stop() {
+ if (!running_) return;
+ running_ = false;
+ connected_ = false;
+
+ kill_subprocess();
+
+ if (reader_thread_.joinable())
+ reader_thread_.join();
+
+ LOG_INFO(ESTAG, "Stream stopped");
+}
+
+bool EquityStreamManager::get_tick(const std::string& symbol, EquityTick& out) const {
+ std::lock_guard<std::mutex> lk(mutex_);
+ auto it = tick_cache_.find(symbol);
+ if (it == tick_cache_.end()) return false;
+ out = it->second;
+ return true;
+}
+
+int EquityStreamManager::on_tick(TickCallback cb) {
+ std::lock_guard<std::mutex> lk(mutex_);
+ int id = next_cb_id_++;
+ tick_cbs_[id] = std::move(cb);
+ return id;
+}
+
+void EquityStreamManager::remove_tick_callback(int id) {
+ std::lock_guard<std::mutex> lk(mutex_);
+ tick_cbs_.erase(id);
+}
+
+int EquityStreamManager::on_status(StatusCallback cb) {
+ std::lock_guard<std::mutex> lk(mutex_);
+ int id = next_cb_id_++;
+ status_cbs_[id] = std::move(cb);
+ return id;
+}
+
+void EquityStreamManager::remove_status_callback(int id) {
+ std::lock_guard<std::mutex> lk(mutex_);
+ status_cbs_.erase(id);
+}
+
+// ─────────────────────────────────────────────────────────────────────────────
+// Subprocess management
+// ─────────────────────────────────────────────────────────────────────────────
+
+void EquityStreamManager::spawn_subprocess(const std::string& broker,
+ const BrokerCredentials& creds,
+ const std::vector<EquitySymbol>& symbols) {
+ auto python = python::resolve_python_path("exchange/broker_ws_bridge.py");
+ if (python.empty()) {
+ LOG_ERROR(ESTAG, "Python not found");
+ running_ = false;
+ return;
+ }
+ auto script = python::resolve_script_path("exchange/broker_ws_bridge.py");
+ if (script.empty()) {
+ LOG_ERROR(ESTAG, "broker_ws_bridge.py not found");
+ running_ = false;
+ return;
+ }
+
+ // Build --symbols args: SYMBOL:EXCHANGE (token unknown at this point → omit)
+ std::string sym_args;
+ for (const auto& s : symbols)
+ sym_args += " " + s.symbol + ":" + s.exchange;
+
+ // Pull credentials
+ const std::string& api_key = creds.api_key;
+ const std::string& access_token = creds.access_token.empty() ? creds.api_secret : creds.access_token;
+ const std::string& user_id = creds.user_id.empty() ? api_key : creds.user_id;
+
+ // Extract feed_token from additional_data (AngelOne stores it there)
+ std::string feed_token;
+ if (!creds.additional_data.empty()) {
+ try {
+ auto j = json::parse(creds.additional_data);
+ feed_token = j.value("feed_token", "");
+ } catch (...) {}
+ }
+ std::string feed_token_arg = feed_token.empty() ? "" : (" --feed-token " + feed_token);
+
+ LOG_INFO(ESTAG, "Starting equity WS bridge: broker=%s symbols=%zu",
+ broker.c_str(), symbols.size());
+
+#ifdef _WIN32
+ // "python -u -B broker_ws_bridge.py <broker> <api_key> <access_token> <user_id> --symbols SYM:EXCH ..."
+ std::string cmd = "\"" + python.string() + "\" -u -B \""
+ + script.string() + "\" "
+ + broker + " "
+ + api_key + " "
+ + access_token + " "
+ + user_id
+ + feed_token_arg
+ + " --symbols" + sym_args;
+
+ SECURITY_ATTRIBUTES sa{};
+ sa.nLength = sizeof(sa);
+ sa.bInheritHandle = TRUE;
+
+ HANDLE hRead = nullptr, hWrite = nullptr;
+ if (!CreatePipe(&hRead, &hWrite, &sa, 0)) {
+ LOG_ERROR(ESTAG, "Failed to create pipe");
+ running_ = false;
+ return;
+ }
+ SetHandleInformation(hRead, HANDLE_FLAG_INHERIT, 0);
+
+ STARTUPINFOA si{};
+ si.cb = sizeof(si);
+ si.hStdOutput = hWrite;
+ si.hStdError = hWrite;
+ si.dwFlags |= STARTF_USESTDHANDLES;
+
+ PROCESS_INFORMATION pi{};
+ BOOL ok = CreateProcessA(nullptr, cmd.data(), nullptr, nullptr,
+ TRUE, CREATE_NO_WINDOW, nullptr, nullptr, &si, &pi);
+ CloseHandle(hWrite);
+
+ if (!ok) {
+ LOG_ERROR(ESTAG, "Failed to spawn broker_ws_bridge.py");
+ CloseHandle(hRead);
+ running_ = false;
+ return;
+ }
+
+ proc_handle_ = pi.hProcess;
+ stdout_rd_ = hRead;
+ CloseHandle(pi.hThread);
+ LOG_INFO(ESTAG, "Bridge subprocess spawned");
+
+#else
+ int pipefd[2];
+ if (pipe(pipefd) < 0) {
+ LOG_ERROR(ESTAG, "Failed to create pipe");
+ running_ = false;
+ return;
+ }
+
+ pid_t pid = fork();
+ if (pid < 0) {
+ LOG_ERROR(ESTAG, "fork() failed");
+ close(pipefd[0]); close(pipefd[1]);
+ running_ = false;
+ return;
+ }
+
+ if (pid == 0) {
+ // Child
+ close(pipefd[0]);
+ dup2(pipefd[1], STDOUT_FILENO);
+ dup2(pipefd[1], STDERR_FILENO);
+ close(pipefd[1]);
+
+ std::vector<const char*> argv;
+ argv.push_back(python.c_str());
+ argv.push_back("-u"); argv.push_back("-B");
+ argv.push_back(script.c_str());
+ argv.push_back(broker.c_str());
+ argv.push_back(api_key.c_str());
+ argv.push_back(access_token.c_str());
+ argv.push_back(user_id.c_str());
+ argv.push_back("--symbols");
+ std::vector<std::string> sym_strs;
+ for (const auto& s : symbols) {
+ sym_strs.push_back(s.symbol + ":" + s.exchange);
+ argv.push_back(sym_strs.back().c_str());
+ }
+ argv.push_back(nullptr);
+ execvp(python.c_str(), const_cast<char* const*>(argv.data()));
+ _exit(1);
+ }
+
+ close(pipefd[1]);
+ proc_pid_ = pid;
+ stdout_fd_ = pipefd[0];
+ LOG_INFO(ESTAG, "Bridge subprocess spawned (PID=%d)", pid);
+#endif
+}
+
+void EquityStreamManager::kill_subprocess() {
+#ifdef _WIN32
+ if (proc_handle_) {
+ TerminateProcess((HANDLE)proc_handle_, 0);
+ WaitForSingleObject((HANDLE)proc_handle_, 3000);
+ CloseHandle((HANDLE)proc_handle_);
+ proc_handle_ = nullptr;
+ }
+ if (stdout_rd_) {
+ CloseHandle((HANDLE)stdout_rd_);
+ stdout_rd_ = nullptr;
+ }
+#else
+ if (proc_pid_ > 0) {
+ kill(proc_pid_, SIGTERM);
+ int st; waitpid(proc_pid_, &st, WNOHANG);
+ proc_pid_ = -1;
+ }
+ if (stdout_fd_ >= 0) {
+ close(stdout_fd_);
+ stdout_fd_ = -1;
+ }
+#endif
+}
+
+// ─────────────────────────────────────────────────────────────────────────────
+// Reader loop — reads stdout line by line, parses JSON
+// ─────────────────────────────────────────────────────────────────────────────
+
+void EquityStreamManager::reader_loop() {
+ std::string buf;
+
+#ifdef _WIN32
+ HANDLE rd = (HANDLE)stdout_rd_;
+ char ch;
+ DWORD n;
+
+ while (running_) {
+ if (!ReadFile(rd, &ch, 1, &n, nullptr) || n == 0) {
+ LOG_INFO(ESTAG, "Bridge pipe closed");
+ break;
+ }
+ if (ch == '\n') {
+ if (!buf.empty()) handle_message(buf);
+ buf.clear();
+ } else if (ch != '\r') {
+ buf += ch;
+ }
+ }
+#else
+ int fd = stdout_fd_;
+ char ch;
+
+ while (running_) {
+ ssize_t n = read(fd, &ch, 1);
+ if (n <= 0) {
+ LOG_INFO(ESTAG, "Bridge pipe closed");
+ break;
+ }
+ if (ch == '\n') {
+ if (!buf.empty()) handle_message(buf);
+ buf.clear();
+ } else if (ch != '\r') {
+ buf += ch;
+ }
+ }
+#endif
+
+ connected_ = false;
+}
+
+// ─────────────────────────────────────────────────────────────────────────────
+// Message handler
+// ─────────────────────────────────────────────────────────────────────────────
+
+void EquityStreamManager::handle_message(const std::string& line) {
+ if (line.empty() || line[0] != '{') {
+ LOG_DEBUG(ESTAG, "Bridge: %s", line.c_str());
+ return;
+ }
+
+ json msg;
+ try {
+ msg = json::parse(line);
+ } catch (...) {
+ LOG_ERROR(ESTAG, "JSON parse error: %.120s", line.c_str());
+ return;
+ }
+
+ const std::string type = msg.value("type", "");
+
+ // ── status ──────────────────────────────────────────────────────────────
+ if (type == "status") {
+ bool conn = msg.value("connected", false);
+ std::string message = msg.value("message", "");
+ connected_ = conn;
+ LOG_INFO(ESTAG, "Bridge status: connected=%s msg=%s",
+ conn ? "true" : "false", message.c_str());
+
+ std::vector<StatusCallback> cbs;
+ {
+ std::lock_guard<std::mutex> lk(mutex_);
+ for (auto& [_, cb] : status_cbs_) cbs.push_back(cb);
+ }
+ for (auto& cb : cbs) try { cb(conn, message); } catch (...) {}
+ return;
+ }
+
+ // ── error ────────────────────────────────────────────────────────────────
+ if (type == "error") {
+ LOG_ERROR(ESTAG, "Bridge error: %s", msg.value("message", "?").c_str());
+ return;
+ }
+
+ // ── tick ─────────────────────────────────────────────────────────────────
+ if (type == "tick") {
+ EquityTick t;
+ t.symbol = msg.value("symbol", "");
+ t.exchange = msg.value("exchange", "");
+ t.ltp = msg.value("ltp", 0.0);
+ t.open = msg.value("open", 0.0);
+ t.high = msg.value("high", 0.0);
+ t.low = msg.value("low", 0.0);
+ t.close = msg.value("close", 0.0);
+ t.volume = msg.value("volume", 0.0);
+ t.bid = msg.value("bid", 0.0);
+ t.ask = msg.value("ask", 0.0);
+ t.timestamp = msg.value("timestamp", int64_t{0});
+
+ if (t.symbol.empty() || t.ltp <= 0.0) return;
+
+ std::vector<TickCallback> cbs;
+ {
+ std::lock_guard<std::mutex> lk(mutex_);
+ tick_cache_[t.symbol] = t;
+ last_tick_time_ = std::chrono::steady_clock::now();
+ for (auto& [_, cb] : tick_cbs_) cbs.push_back(cb);
+ }
+ for (auto& cb : cbs) try { cb(t); } catch (...) {}
+ return;
+ }
+
+ LOG_DEBUG(ESTAG, "Bridge unknown message type: %s", type.c_str());
+}
+
+} // namespace fincept::trading
diff --git a/fincept-cpp/src/trading/equity_stream.h b/fincept-cpp/src/trading/equity_stream.h
new file mode 100644
index 000000000..6ad9ff8bc
--- /dev/null
+++ b/fincept-cpp/src/trading/equity_stream.h
@@ -0,0 +1,118 @@
+#pragma once
+// EquityStreamManager — manages the broker_ws_bridge.py subprocess for live
+// equity price streaming. Same pipe pattern as ExchangeService / ws_stream.py.
+//
+// Usage:
+// auto& esm = EquityStreamManager::instance();
+// esm.start(broker, creds, {{"RELIANCE","NSE"}, {"INFY","NSE"}});
+// esm.on_tick([](const EquityTick& t){ /* update UI */ });
+// esm.stop();
+
+#include "broker_types.h"
+#include <string>
+#include <vector>
+#include <functional>
+#include <thread>
+#include <atomic>
+#include <mutex>
+#include <unordered_map>
+#include <chrono>
+
+#ifdef _WIN32
+#ifndef WIN32_LEAN_AND_MEAN
+#define WIN32_LEAN_AND_MEAN
+#endif
+#ifndef NOMINMAX
+#define NOMINMAX
+#endif
+#include <windows.h>
+#endif
+
+namespace fincept::trading {
+
+struct EquityTick {
+ std::string symbol;
+ std::string exchange;
+ double ltp = 0.0;
+ double open = 0.0;
+ double high = 0.0;
+ double low = 0.0;
+ double close = 0.0;
+ double volume = 0.0;
+ double bid = 0.0;
+ double ask = 0.0;
+ int64_t timestamp = 0;
+};
+
+struct EquitySymbol {
+ std::string symbol;
+ std::string exchange;
+};
+
+using TickCallback = std::function<void(const EquityTick&)>;
+using StatusCallback = std::function<void(bool connected, const std::string& msg)>;
+
+class EquityStreamManager {
+public:
+ static EquityStreamManager& instance();
+
+ // Start streaming for given broker+creds+symbol list.
+ // Stops any existing stream first.
+ void start(const std::string& broker_adapter,
+ const BrokerCredentials& creds,
+ const std::vector<EquitySymbol>& symbols);
+
+ void stop();
+ bool is_connected() const { return connected_; }
+ bool is_running() const { return running_; }
+
+ // Latest cached tick for a symbol (thread-safe)
+ bool get_tick(const std::string& symbol, EquityTick& out) const;
+
+ // Register callbacks (returns ID for removal)
+ int on_tick(TickCallback cb);
+ void remove_tick_callback(int id);
+ int on_status(StatusCallback cb);
+ void remove_status_callback(int id);
+
+ EquityStreamManager(const EquityStreamManager&) = delete;
+ EquityStreamManager& operator=(const EquityStreamManager&) = delete;
+
+private:
+ EquityStreamManager() = default;
+ ~EquityStreamManager() { stop(); }
+
+ void reader_loop();
+ void handle_message(const std::string& line);
+ void spawn_subprocess(const std::string& broker,
+ const BrokerCredentials& creds,
+ const std::vector<EquitySymbol>& symbols);
+ void kill_subprocess();
+
+ // Subprocess handles
+#ifdef _WIN32
+ void* proc_handle_ = nullptr;
+ void* stdout_rd_ = nullptr;
+#else
+ int proc_pid_ = -1;
+ int stdout_fd_ = -1;
+#endif
+
+ std::thread reader_thread_;
+ std::atomic<bool> running_{false};
+ std::atomic<bool> connected_{false};
+
+ // Tick cache
+ mutable std::mutex mutex_;
+ std::unordered_map<std::string, EquityTick> tick_cache_;
+
+ // Callbacks
+ std::unordered_map<int, TickCallback> tick_cbs_;
+ std::unordered_map<int, StatusCallback> status_cbs_;
+ int next_cb_id_ = 1;
+
+ // Last status time (for UI heartbeat display)
+ std::chrono::steady_clock::time_point last_tick_time_;
+};
+
+} // namespace fincept::trading
diff --git a/fincept-cpp/tests/test_equity_ui.cpp b/fincept-cpp/tests/test_equity_ui.cpp
new file mode 100644
index 000000000..dafefaa40
--- /dev/null
+++ b/fincept-cpp/tests/test_equity_ui.cpp
@@ -0,0 +1,166 @@
+// Minimal standalone ImGui test — equity trading broker auth (AngelOne)
+// Build: add to CMakeLists.txt as a separate executable
+// Links against imgui, glfw, opengl, nlohmann_json
+
+#include <imgui.h>
+#include <imgui_impl_glfw.h>
+#include <imgui_impl_opengl3.h>
+#include <GLFW/glfw3.h>
+#include <cstdio>
+#include <cstring>
+#include <string>
+
+// AngelOne credential state
+struct AngelOneCreds {
+ char api_key[128] = {};
+ char client_code[64] = {};
+ char pin[64] = {};
+ char totp_secret[64] = {};
+ bool show_pin = false;
+ bool connected = false;
+ std::string status_msg;
+};
+
+static AngelOneCreds creds;
+static int active_tab = 0; // 0=overview, 1=broker
+
+void render_overview() {
+ ImGui::Text("Equity Trading - Overview");
+ ImGui::Separator();
+ ImGui::Spacing();
+ if (creds.connected) {
+ ImGui::TextColored(ImVec4(0.1f,0.75f,0.35f,1), "Connected to AngelOne");
+ ImGui::Text("Client: %s", creds.client_code);
+ } else {
+ ImGui::TextColored(ImVec4(0.9f,0.7f,0.1f,1), "Paper Trading Mode");
+ ImGui::Spacing();
+ ImGui::Text("Go to Broker Config tab to connect AngelOne.");
+ }
+}
+
+void render_broker_config() {
+ ImGui::Text("AngelOne Configuration");
+ ImGui::TextColored(ImVec4(0.5f,0.5f,0.5f,1), "Auth: TOTP");
+ ImGui::Separator();
+ ImGui::Spacing();
+
+ ImGui::Text("API Key");
+ ImGui::SameLine(120);
+ ImGui::SetNextItemWidth(250);
+ ImGui::InputText("##ak", creds.api_key, sizeof(creds.api_key));
+
+ ImGui::Text("Client Code");
+ ImGui::SameLine(120);
+ ImGui::SetNextItemWidth(250);
+ ImGui::InputText("##cc", creds.client_code, sizeof(creds.client_code));
+
+ ImGui::Text("PIN");
+ ImGui::SameLine(120);
+ ImGui::SetNextItemWidth(250);
+ ImGui::InputText("##pin", creds.pin, sizeof(creds.pin),
+ creds.show_pin ? 0 : ImGuiInputTextFlags_Password);
+ ImGui::SameLine();
+ if (ImGui::SmallButton(creds.show_pin ? "Hide" : "Show"))
+ creds.show_pin = !creds.show_pin;
+
+ ImGui::Text("TOTP Secret");
+ ImGui::SameLine(120);
+ ImGui::SetNextItemWidth(250);
+ ImGui::InputText("##totp", creds.totp_secret, sizeof(creds.totp_secret));
+
+ ImGui::Spacing();
+ ImGui::Separator();
+ ImGui::Spacing();
+
+ if (!creds.connected) {
+ if (ImGui::Button("Connect")) {
+ if (creds.api_key[0] && creds.client_code[0]) {
+ creds.connected = true;
+ creds.status_msg = "Connected to AngelOne!";
+ } else {
+ creds.status_msg = "Fill API Key and Client Code first.";
+ }
+ }
+ } else {
+ ImGui::TextColored(ImVec4(0.1f,0.75f,0.35f,1), "CONNECTED");
+ ImGui::SameLine(0, 12);
+ if (ImGui::Button("Disconnect")) {
+ creds.connected = false;
+ creds.status_msg = "Disconnected.";
+ }
+ }
+
+ if (!creds.status_msg.empty()) {
+ ImGui::Spacing();
+ ImGui::TextColored(
+ creds.connected ? ImVec4(0.1f,0.75f,0.35f,1) : ImVec4(0.85f,0.25f,0.25f,1),
+ "%s", creds.status_msg.c_str());
+ }
+}
+
+int main() {
+ if (!glfwInit()) return 1;
+
+ glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3);
+ glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3);
+ glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);
+
+ GLFWwindow* window = glfwCreateWindow(900, 600, "Equity Trading Test - AngelOne", nullptr, nullptr);
+ if (!window) { glfwTerminate(); return 1; }
+ glfwMakeContextCurrent(window);
+ glfwSwapInterval(1);
+
+ IMGUI_CHECKVERSION();
+ ImGui::CreateContext();
+ ImGuiIO& io = ImGui::GetIO();
+ io.ConfigFlags |= ImGuiConfigFlags_NavEnableKeyboard;
+ ImGui::StyleColorsDark();
+
+ ImGui_ImplGlfw_InitForOpenGL(window, true);
+ ImGui_ImplOpenGL3_Init("#version 330");
+
+ while (!glfwWindowShouldClose(window)) {
+ glfwPollEvents();
+ ImGui_ImplOpenGL3_NewFrame();
+ ImGui_ImplGlfw_NewFrame();
+ ImGui::NewFrame();
+
+ // Fullscreen window
+ ImGuiViewport* vp = ImGui::GetMainViewport();
+ ImGui::SetNextWindowPos(vp->WorkPos);
+ ImGui::SetNextWindowSize(vp->WorkSize);
+ ImGui::Begin("##main", nullptr,
+ ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_NoResize |
+ ImGuiWindowFlags_NoMove | ImGuiWindowFlags_NoCollapse);
+
+ // Nav buttons
+ if (ImGui::Button("Overview")) active_tab = 0;
+ ImGui::SameLine();
+ if (ImGui::Button("Broker Config")) active_tab = 1;
+ ImGui::Separator();
+ ImGui::Spacing();
+
+ switch (active_tab) {
+ case 0: render_overview(); break;
+ case 1: render_broker_config(); break;
+ }
+
+ ImGui::End();
+
+ ImGui::Render();
+ int dw, dh;
+ glfwGetFramebufferSize(window, &dw, &dh);
+ glViewport(0, 0, dw, dh);
+ glClearColor(0.05f, 0.05f, 0.07f, 1.0f);
+ glClear(GL_COLOR_BUFFER_BIT);
+ ImGui_ImplOpenGL3_RenderDrawData(ImGui::GetDrawData());
+ glfwSwapBuffers(window);
+ }
+
+ ImGui_ImplOpenGL3_Shutdown();
+ ImGui_ImplGlfw_Shutdown();
+ ImGui::DestroyContext();
+ glfwDestroyWindow(window);
+ glfwTerminate();
+ return 0;
+}
diff --git a/setup.bat b/setup.bat
new file mode 100644
index 000000000..c3c480993
--- /dev/null
+++ b/setup.bat
@@ -0,0 +1,142 @@
+@echo off
+setlocal EnableDelayedExpansion
+title Fincept Terminal — Setup
+
+:: ── Parse args ──────────────────────────────────────────────
+set CI_MODE=false
+for %%A in (%*) do (
+ if /i "%%A"=="--ci" set CI_MODE=true
+)
+
+echo.
+echo ================================================
+echo Fincept Terminal — Windows Setup
+if "!CI_MODE!"=="true" echo (CI mode -- skipping interactive steps)
+echo ================================================
+echo.
+
+:: ── Check: Git ──────────────────────────────────────────────
+echo [1/6] Checking Git...
+where git >nul 2>&1
+if errorlevel 1 (
+ echo ERROR: Git not found. Install from https://git-scm.com/downloads
+ if "!CI_MODE!"=="false" pause
+ exit /b 1
+)
+echo OK
+
+:: ── Check: CMake ────────────────────────────────────────────
+echo [2/6] Checking CMake...
+where cmake >nul 2>&1
+if errorlevel 1 (
+ if "!CI_MODE!"=="true" (
+ echo ERROR: CMake not found in CI environment.
+ exit /b 1
+ )
+ echo CMake not found. Installing via winget...
+ winget install --id Kitware.CMake -e --silent
+ if errorlevel 1 (
+ echo ERROR: CMake install failed. Install manually from https://cmake.org/download/
+ pause & exit /b 1
+ )
+)
+echo OK
+
+:: ── Check: Ninja ────────────────────────────────────────────
+echo [3/6] Checking Ninja...
+where ninja >nul 2>&1
+if errorlevel 1 (
+ if "!CI_MODE!"=="true" (
+ echo ERROR: Ninja not found in CI environment.
+ exit /b 1
+ )
+ echo Ninja not found. Installing via winget...
+ winget install --id Ninja-build.Ninja -e --silent
+ if errorlevel 1 (
+ echo ERROR: Ninja install failed. Install manually from https://ninja-build.org/
+ pause & exit /b 1
+ )
+)
+echo OK
+
+:: ── Check: Python ───────────────────────────────────────────
+echo [4/6] Checking Python...
+where python >nul 2>&1
+if errorlevel 1 (
+ if "!CI_MODE!"=="true" (
+ echo ERROR: Python not found in CI environment.
+ exit /b 1
+ )
+ echo Python not found. Installing via winget...
+ winget install --id Python.Python.3.11 -e --silent
+ if errorlevel 1 (
+ echo ERROR: Python install failed. Install from https://www.python.org/downloads/
+ pause & exit /b 1
+ )
+)
+echo OK
+
+:: ── Check: MSVC ─────────────────────────────────────────────
+echo [5/6] Checking C++ compiler (MSVC)...
+where cl >nul 2>&1
+if errorlevel 1 (
+ echo MSVC compiler not found in PATH.
+ echo Please install Visual Studio 2022 with "Desktop development with C++" workload:
+ echo https://visualstudio.microsoft.com/
+ echo Then re-run from a "Developer Command Prompt for VS 2022".
+ if "!CI_MODE!"=="false" pause
+ exit /b 1
+)
+echo OK
+
+:: ── vcpkg ───────────────────────────────────────────────────
+echo [6/6] Setting up vcpkg and building...
+if not defined VCPKG_ROOT (
+ set "VCPKG_ROOT=%USERPROFILE%\vcpkg"
+)
+if not exist "%VCPKG_ROOT%\vcpkg.exe" (
+ echo vcpkg not found. Cloning into %VCPKG_ROOT%...
+ git clone https://github.com/microsoft/vcpkg.git "%VCPKG_ROOT%"
+ if errorlevel 1 ( echo ERROR: Failed to clone vcpkg. & exit /b 1 )
+ call "%VCPKG_ROOT%\bootstrap-vcpkg.bat" -disableMetrics
+ if errorlevel 1 ( echo ERROR: vcpkg bootstrap failed. & exit /b 1 )
+ echo vcpkg installed at %VCPKG_ROOT%
+ :: Persist for future sessions (skip in CI — env var already set)
+ if "!CI_MODE!"=="false" (
+ setx VCPKG_ROOT "%VCPKG_ROOT%" >nul
+ )
+) else (
+ echo vcpkg already installed at %VCPKG_ROOT%
+)
+echo OK
+
+:: ── Build ────────────────────────────────────────────────────
+echo.
+echo Configuring (vcpkg downloads dependencies -- may take 10-20 min on first run)...
+cd /d "%~dp0fincept-cpp"
+cmake --preset=default -DCMAKE_TOOLCHAIN_FILE="%VCPKG_ROOT%\scripts\buildsystems\vcpkg.cmake"
+if errorlevel 1 ( echo ERROR: CMake configure failed. & exit /b 1 )
+
+echo Compiling...
+cmake --build build --config Release --parallel
+if errorlevel 1 ( echo ERROR: Build failed. & exit /b 1 )
+
+echo.
+echo ================================================
+echo Build complete!
+echo ================================================
+echo.
+echo Run the terminal:
+echo build\Release\FinceptTerminal.exe
+echo.
+
+:: Skip launch prompt in CI
+if "!CI_MODE!"=="true" goto :done
+
+set /p LAUNCH="Launch now? (y/n): "
+if /i "!LAUNCH!"=="y" (
+ start "" "build\Release\FinceptTerminal.exe"
+)
+
+:done
+endlocal
diff --git a/setup.sh b/setup.sh
new file mode 100644
index 000000000..fcaa8964d
--- /dev/null
+++ b/setup.sh
@@ -0,0 +1,142 @@
+#!/usr/bin/env bash
+set -euo pipefail
+
+# ── Parse args ──────────────────────────────────────────────
+CI_MODE=false
+for arg in "$@"; do
+ case "$arg" in
+ --ci) CI_MODE=true ;;
+ esac
+done
+
+# ── Colours ─────────────────────────────────────────────────
+GREEN='\033[0;32m'
+RED='\033[0;31m'
+YELLOW='\033[1;33m'
+NC='\033[0m'
+
+ok() { echo -e " ${GREEN}OK${NC}"; }
+fail() { echo -e " ${RED}ERROR: $1${NC}"; exit 1; }
+info() { echo -e " ${YELLOW}$1${NC}"; }
+
+echo ""
+echo "================================================"
+echo " Fincept Terminal — Setup"
+[ "$CI_MODE" = true ] && echo " (CI mode — skipping interactive steps)"
+echo "================================================"
+echo ""
+
+# ── Detect OS ───────────────────────────────────────────────
+OS="$(uname -s)"
+case "$OS" in
+ Linux*) PLATFORM="linux" ;;
+ Darwin*) PLATFORM="macos" ;;
+ *) fail "Unsupported OS: $OS" ;;
+esac
+echo "Platform: $OS"
+echo ""
+
+# ── Step 1: System dependencies ─────────────────────────────
+echo "[1/5] Installing system dependencies..."
+if [ "$PLATFORM" = "linux" ]; then
+ if ! command -v apt-get &>/dev/null; then
+ fail "apt-get not found. Please install dependencies manually (see docs/GETTING_STARTED.md)"
+ fi
+ sudo apt-get update -qq
+ sudo apt-get install -y \
+ git cmake ninja-build g++ python3 python3-pip \
+ libxinerama-dev libxcursor-dev xorg-dev libglu1-mesa-dev \
+ libxrandr-dev libxi-dev libxext-dev libxfixes-dev \
+ libwayland-dev libxkbcommon-dev pkg-config \
+ autoconf automake libtool
+elif [ "$PLATFORM" = "macos" ]; then
+ if [ "$CI_MODE" = false ] && ! command -v brew &>/dev/null; then
+ info "Homebrew not found. Installing..."
+ /bin/bash -c "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/HEAD/install.sh)"
+ fi
+ # In CI, brew is pre-installed on macOS runners
+ brew install cmake ninja pkg-config autoconf automake libtool python
+fi
+ok
+
+# ── Step 2: Check C++ compiler ──────────────────────────────
+echo "[2/5] Checking C++ compiler..."
+if [ "$PLATFORM" = "linux" ]; then
+ command -v g++ &>/dev/null || fail "g++ not found. Please check apt output above."
+elif [ "$PLATFORM" = "macos" ]; then
+ command -v clang++ &>/dev/null || fail "clang++ not found. Run: xcode-select --install"
+fi
+ok
+
+# ── Step 3: vcpkg ───────────────────────────────────────────
+echo "[3/5] Setting up vcpkg..."
+VCPKG_ROOT="${VCPKG_ROOT:-$HOME/vcpkg}"
+
+if [ ! -f "$VCPKG_ROOT/vcpkg" ]; then
+ info "vcpkg not found. Cloning into $VCPKG_ROOT..."
+ git clone https://github.com/microsoft/vcpkg.git "$VCPKG_ROOT"
+ "$VCPKG_ROOT/bootstrap-vcpkg.sh" -disableMetrics
+ info "vcpkg installed at $VCPKG_ROOT"
+else
+ info "vcpkg already installed at $VCPKG_ROOT"
+fi
+
+export VCPKG_ROOT
+
+# Persist VCPKG_ROOT in shell profile (skip in CI — env var is already set)
+if [ "$CI_MODE" = false ]; then
+ SHELL_PROFILE=""
+ if [ -f "$HOME/.zshrc" ]; then
+ SHELL_PROFILE="$HOME/.zshrc"
+ elif [ -f "$HOME/.bashrc" ]; then
+ SHELL_PROFILE="$HOME/.bashrc"
+ elif [ -f "$HOME/.bash_profile" ]; then
+ SHELL_PROFILE="$HOME/.bash_profile"
+ fi
+ if [ -n "$SHELL_PROFILE" ]; then
+ if ! grep -q "VCPKG_ROOT" "$SHELL_PROFILE"; then
+ echo "" >> "$SHELL_PROFILE"
+ echo "export VCPKG_ROOT=\"$VCPKG_ROOT\"" >> "$SHELL_PROFILE"
+ info "Added VCPKG_ROOT to $SHELL_PROFILE"
+ fi
+ fi
+fi
+ok
+
+# ── Step 4: Configure ────────────────────────────────────────
+SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
+APP_DIR="$SCRIPT_DIR/fincept-cpp"
+[ -d "$APP_DIR" ] || fail "fincept-cpp directory not found. Make sure you cloned the full repository."
+cd "$APP_DIR"
+
+echo "[4/5] Configuring (vcpkg downloads dependencies — may take 10-20 min on first run)..."
+cmake --preset=default \
+ -DCMAKE_TOOLCHAIN_FILE="$VCPKG_ROOT/scripts/buildsystems/vcpkg.cmake"
+ok
+
+# ── Step 5: Build ────────────────────────────────────────────
+echo "[5/5] Compiling..."
+cmake --build build --config Release --parallel
+ok
+
+# ── Done ─────────────────────────────────────────────────────
+echo ""
+echo "================================================"
+echo " Build complete!"
+echo "================================================"
+echo ""
+echo " Run the terminal:"
+echo " ./build/FinceptTerminal"
+echo ""
+
+# Skip launch prompt in CI
+if [ "$CI_MODE" = false ]; then
+ read -r -p " Launch now? (y/n): " LAUNCH
+ if [[ "$LAUNCH" =~ ^[Yy]$ ]]; then
+ if [ "$PLATFORM" = "macos" ]; then
+ open ./build/FinceptTerminal 2>/dev/null || ./build/FinceptTerminal
+ else
+ ./build/FinceptTerminal
+ fi
+ fi
+fi