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.
C++ ai-agentsalgorithmic-tradingbloomberg-terminalcppfinancefinancial-marketsfintechgood-first-issueinvestmentinvestment-researchmachine-learningopensourcepythonqtquantitative-financestock-markettrading
c/c++ version of the terminal
tilakpatel229a7436c9dcfb
diff --git a/.github/workflows/build-cpp.yml b/.github/workflows/build-cpp.ymlnew file mode 100644index 000000000..940a5471b--- /dev/null+++ b/.github/workflows/build-cpp.yml@@ -0,0 +1,258 @@+name: Build C++ Terminal — All Platforms++on:+ workflow_dispatch:++env:+ BUILD_TYPE: Release+ VCPKG_BINARY_SOURCES: "clear;x-gha,readwrite"++jobs:+ build:+ strategy:+ fail-fast: false+ matrix:+ include:+ # ---- Windows ----+ - os: windows-latest+ triplet: x64-windows+ arch: x64+ platform: Windows+ artifact: FinceptTerminal-Windows-x64+ exe: FinceptTerminal.exe+ cmake_extra: ""++ - os: windows-latest+ triplet: arm64-windows+ arch: arm64+ platform: Windows+ artifact: FinceptTerminal-Windows-arm64+ exe: FinceptTerminal.exe+ cmake_extra: "-A ARM64"++ # ---- Linux ----+ - os: ubuntu-24.04+ triplet: x64-linux+ arch: x64+ platform: Linux+ artifact: FinceptTerminal-Linux-x64+ exe: FinceptTerminal+ cmake_extra: ""++ - os: ubuntu-24.04+ triplet: arm64-linux+ arch: arm64+ platform: Linux+ artifact: FinceptTerminal-Linux-arm64+ exe: FinceptTerminal+ cmake_extra: "-DCMAKE_C_COMPILER=aarch64-linux-gnu-gcc -DCMAKE_CXX_COMPILER=aarch64-linux-gnu-g++ -DCMAKE_SYSTEM_NAME=Linux -DCMAKE_SYSTEM_PROCESSOR=aarch64"++ # ---- macOS ----+ - os: macos-14+ triplet: arm64-osx+ arch: arm64+ platform: macOS+ artifact: FinceptTerminal-macOS-arm64+ exe: FinceptTerminal+ cmake_extra: "-DCMAKE_OSX_ARCHITECTURES=arm64"++ - os: macos-13+ triplet: x64-osx+ arch: x64+ platform: macOS+ artifact: FinceptTerminal-macOS-x64+ exe: FinceptTerminal+ cmake_extra: "-DCMAKE_OSX_ARCHITECTURES=x86_64"++ runs-on: ${{ matrix.os }}+ name: ${{ matrix.platform }} ${{ matrix.arch }}++ steps:+ - name: Checkout+ uses: actions/checkout@v4+ with:+ submodules: recursive++ - 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 || '');++ # ---- System dependencies ----+ - name: Install system dependencies (Linux x64)+ if: runner.os == 'Linux' && matrix.arch == 'x64'+ run: |+ sudo apt-get update+ sudo apt-get 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 autoconf automake libtool \+ python3 python3-pip++ - name: Install system dependencies (Linux arm64 cross-compile)+ if: runner.os == 'Linux' && matrix.arch == 'arm64'+ run: |+ sudo dpkg --add-architecture arm64+ sudo sed -i 's/^deb /deb [arch=amd64] /' /etc/apt/sources.list.d/*.list 2>/dev/null || true+ echo "deb [arch=arm64] http://ports.ubuntu.com/ubuntu-ports $(lsb_release -cs) main restricted universe multiverse" | sudo tee /etc/apt/sources.list.d/arm64.list+ echo "deb [arch=arm64] http://ports.ubuntu.com/ubuntu-ports $(lsb_release -cs)-updates main restricted universe multiverse" | sudo tee -a /etc/apt/sources.list.d/arm64.list+ sudo apt-get update+ sudo apt-get install -y \+ gcc-aarch64-linux-gnu g++-aarch64-linux-gnu \+ pkg-config autoconf automake libtool \+ python3 python3-pip \+ libxinerama-dev:arm64 libxcursor-dev:arm64 libxrandr-dev:arm64 \+ libxi-dev:arm64 libxext-dev:arm64 libxfixes-dev:arm64 \+ libwayland-dev:arm64 libxkbcommon-dev:arm64 \+ libglu1-mesa-dev:arm64 libgl-dev:arm64++ - name: Install system dependencies (macOS)+ if: runner.os == 'macOS'+ run: |+ brew install pkg-config autoconf automake libtool++ # ---- vcpkg ----+ - name: Setup vcpkg+ uses: lukka/run-vcpkg@v11+ with:+ vcpkgDirectory: '${{ github.workspace }}/vcpkg'+ vcpkgGitCommitId: '962e5e39f8a25f42522f51fffc574e05a3efd26b'++ # ---- Configure & Build ----+ - name: Configure CMake+ working-directory: fincept-cpp+ run: |+ cmake -B build \+ -DCMAKE_BUILD_TYPE=${{ env.BUILD_TYPE }} \+ -DCMAKE_TOOLCHAIN_FILE=${{ github.workspace }}/vcpkg/scripts/buildsystems/vcpkg.cmake \+ -DVCPKG_TARGET_TRIPLET=${{ matrix.triplet }} \+ ${{ matrix.cmake_extra }}++ - name: Build+ working-directory: fincept-cpp+ run: cmake --build build --config ${{ env.BUILD_TYPE }} --parallel++ # ---- Collect artifacts ----+ - name: Collect artifacts (Windows)+ if: runner.os == 'Windows'+ working-directory: fincept-cpp+ shell: bash+ run: |+ mkdir -p dist+ cp build/Release/${{ matrix.exe }} dist/+ cp build/Release/*.dll dist/ 2>/dev/null || true+ cp -r fonts dist/fonts 2>/dev/null || true++ - name: Collect artifacts (Linux/macOS)+ if: runner.os != 'Windows'+ working-directory: fincept-cpp+ run: |+ mkdir -p dist+ cp build/${{ matrix.exe }} dist/+ chmod +x dist/${{ matrix.exe }}+ cp -r fonts dist/fonts 2>/dev/null || true++ - name: Upload artifact+ uses: actions/upload-artifact@v4+ with:+ name: ${{ matrix.artifact }}+ path: fincept-cpp/dist/+ retention-days: 30++ # ---- macOS Universal Binary ----+ macos-universal:+ needs: build+ runs-on: macos-14+ name: macOS Universal++ steps:+ - name: Download macOS arm64+ uses: actions/download-artifact@v4+ with:+ name: FinceptTerminal-macOS-arm64+ path: arm64++ - name: Download macOS x64+ uses: actions/download-artifact@v4+ with:+ name: FinceptTerminal-macOS-x64+ path: x64++ - name: Create Universal Binary+ run: |+ mkdir -p dist+ lipo -create arm64/FinceptTerminal x64/FinceptTerminal -output dist/FinceptTerminal+ chmod +x dist/FinceptTerminal+ cp -r arm64/fonts dist/fonts 2>/dev/null || true+ file dist/FinceptTerminal++ - name: Upload Universal artifact+ uses: actions/upload-artifact@v4+ with:+ name: FinceptTerminal-macOS-universal+ path: dist/+ retention-days: 30++ # ---- Release ----+ release:+ needs: [build, macos-universal]+ runs-on: ubuntu-latest+ if: always() && !cancelled() && !contains(needs.*.result, 'failure')+ permissions:+ contents: write++ steps:+ - name: Download all artifacts+ uses: actions/download-artifact@v4+ with:+ path: artifacts++ - name: Package releases+ run: |+ cd artifacts+ for dir in */; do+ name="${dir%/}"+ cd "$name"+ if [[ "$name" == *"Windows"* ]]; then+ zip -r "../../${name}.zip" .+ else+ tar -czf "../../${name}.tar.gz" .+ fi+ cd ..+ done++ - 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 }}"+ body: |+ Automated build from commit ${{ github.sha }}++ ## Downloads++ ### Windows+ - `FinceptTerminal-Windows-x64.zip` — Windows x86_64+ - `FinceptTerminal-Windows-arm64.zip` — Windows ARM64++ ### Linux+ - `FinceptTerminal-Linux-x64.tar.gz` — Linux x86_64+ - `FinceptTerminal-Linux-arm64.tar.gz` — Linux ARM64 (aarch64)++ ### macOS+ - `FinceptTerminal-macOS-arm64.tar.gz` — macOS Apple Silicon (M1/M2/M3/M4)+ - `FinceptTerminal-macOS-x64.tar.gz` — macOS Intel+ - `FinceptTerminal-macOS-universal.tar.gz` — macOS Universal (both architectures)+ files: |+ FinceptTerminal-Windows-x64.zip+ FinceptTerminal-Windows-arm64.zip+ FinceptTerminal-Linux-x64.tar.gz+ FinceptTerminal-Linux-arm64.tar.gz+ FinceptTerminal-macOS-arm64.tar.gz+ FinceptTerminal-macOS-x64.tar.gz+ FinceptTerminal-macOS-universal.tar.gz+ draft: false+ prerelease: truediff --git a/README.md b/README.mdindex 4304bb9fe..538b082ab 100644--- a/README.md+++ b/README.md@@ -1,5 +1,7 @@# Fincept Terminal+> **Migrating to C/C++** — Version 4 will be a pure C++ native application. The current Tauri (React/Rust) build is no longer distributed as a standalone release. To run the Tauri version, clone the repo and use `bun run tauri:dev` from the `fincept-terminal-desktop/` directory.+<div align="center">[](https://github.com/Fincept-Corporation/FinceptTerminal/blob/main/LICENSE)diff --git a/fincept-cpp/.gitignore b/fincept-cpp/.gitignorenew file mode 100644index 000000000..8af5b7d8c--- /dev/null+++ b/fincept-cpp/.gitignore@@ -0,0 +1,24 @@+# Build+build/+cmake-build-*/+out/++# IDE+.vs/+.vscode/+.idea/+*.suo+*.user+*.sln+*.vcxproj*+compile_commands.json++# ImGui layout state+fincept_imgui.ini++# OS+.DS_Store+Thumbs.db++# vcpkg installed packages (managed by vcpkg)+vcpkg_installed/diff --git a/fincept-cpp/CMakeLists.txt b/fincept-cpp/CMakeLists.txtnew file mode 100644index 000000000..f890ccec6--- /dev/null+++ b/fincept-cpp/CMakeLists.txt@@ -0,0 +1,114 @@+cmake_minimum_required(VERSION 3.20)+project(FinceptTerminal VERSION 3.3.1 LANGUAGES CXX)++set(CMAKE_CXX_STANDARD 20)+set(CMAKE_CXX_STANDARD_REQUIRED ON)+set(CMAKE_EXPORT_COMPILE_COMMANDS ON)++# =============================================================================+# Dependencies via vcpkg+# =============================================================================+find_package(glfw3 CONFIG REQUIRED)+find_package(CURL CONFIG REQUIRED)+find_package(nlohmann_json CONFIG REQUIRED)+find_package(unofficial-sqlite3 CONFIG REQUIRED)+find_package(OpenSSL REQUIRED)+find_package(imgui CONFIG REQUIRED)++# OpenGL+find_package(OpenGL REQUIRED)++# =============================================================================+# Sources+# =============================================================================+set(SOURCES+ src/main.cpp+ src/app.cpp+ src/http/http_client.cpp+ src/storage/sqlite_store.cpp+ src/storage/crypto.cpp+ src/auth/auth_api.cpp+ src/auth/auth_manager.cpp+ src/auth/login_screen.cpp+ src/auth/register_screen.cpp+ src/auth/forgot_password.cpp+ src/auth/pricing_screen.cpp+ src/dashboard/dashboard_screen.cpp+ src/dashboard/dashboard_data.cpp+ src/dashboard/stock_ticker.cpp+ src/profile/profile_screen.cpp+ src/news/news_screen.cpp+ src/research/research_data.cpp+ src/research/research_screen.cpp+ src/research/overview_panel.cpp+ src/research/financials_panel.cpp+ src/research/analysis_panel.cpp+ src/research/technicals_panel.cpp+ src/research/news_panel.cpp+ src/markets/markets_data.cpp+ src/markets/markets_screen.cpp+ src/utils/device_id.cpp+)++# =============================================================================+# Executable+# =============================================================================+add_executable(${PROJECT_NAME} ${SOURCES})++target_include_directories(${PROJECT_NAME} PRIVATE+ ${CMAKE_CURRENT_SOURCE_DIR}/src+ ${CMAKE_CURRENT_SOURCE_DIR}/fonts+)++target_link_libraries(${PROJECT_NAME} PRIVATE+ glfw+ OpenGL::GL+ CURL::libcurl+ nlohmann_json::nlohmann_json+ unofficial::sqlite3::sqlite3+ OpenSSL::SSL+ OpenSSL::Crypto+ imgui::imgui+)++# =============================================================================+# Platform-specific+# =============================================================================+if(WIN32)+ target_link_libraries(${PROJECT_NAME} PRIVATE ws2_32 crypt32 wldap32)+ target_compile_definitions(${PROJECT_NAME} PRIVATE NOMINMAX WIN32_LEAN_AND_MEAN)+ # Use console subsystem for now (shows debug output)+ # Switch to WIN32_EXECUTABLE for production release to hide console+elseif(APPLE)+ find_library(COCOA_FRAMEWORK Cocoa)+ find_library(IOKIT_FRAMEWORK IOKit)+ find_library(COREVIDEO_FRAMEWORK CoreVideo)+ target_link_libraries(${PROJECT_NAME} PRIVATE+ ${COCOA_FRAMEWORK}+ ${IOKIT_FRAMEWORK}+ ${COREVIDEO_FRAMEWORK}+ "-framework OpenGL"+ )+elseif(UNIX)+ # Linux+ find_package(PkgConfig REQUIRED)+ target_link_libraries(${PROJECT_NAME} PRIVATE+ pthread+ dl+ )+endif()++# =============================================================================+# Copy fonts to build directory+# =============================================================================+add_custom_command(TARGET ${PROJECT_NAME} POST_BUILD+ COMMAND ${CMAKE_COMMAND} -E copy_directory+ ${CMAKE_CURRENT_SOURCE_DIR}/fonts+ $<TARGET_FILE_DIR:${PROJECT_NAME}>/fonts+)++# =============================================================================+# Install rules (for packaging)+# =============================================================================+install(TARGETS ${PROJECT_NAME} RUNTIME DESTINATION bin)+install(DIRECTORY ${CMAKE_CURRENT_SOURCE_DIR}/fonts DESTINATION bin/fonts)diff --git a/fincept-cpp/CMakePresets.json b/fincept-cpp/CMakePresets.jsonnew file mode 100644index 000000000..7707af132--- /dev/null+++ b/fincept-cpp/CMakePresets.json@@ -0,0 +1,46 @@+{+ "version": 6,+ "cmakeMinimumRequired": { "major": 3, "minor": 20, "patch": 0 },+ "configurePresets": [+ {+ "name": "default",+ "displayName": "Default (vcpkg)",+ "generator": "Ninja",+ "binaryDir": "${sourceDir}/build",+ "cacheVariables": {+ "CMAKE_BUILD_TYPE": "RelWithDebInfo",+ "CMAKE_TOOLCHAIN_FILE": "$env{VCPKG_ROOT}/scripts/buildsystems/vcpkg.cmake"+ }+ },+ {+ "name": "debug",+ "displayName": "Debug",+ "inherits": "default",+ "cacheVariables": {+ "CMAKE_BUILD_TYPE": "Debug"+ }+ },+ {+ "name": "release",+ "displayName": "Release",+ "inherits": "default",+ "cacheVariables": {+ "CMAKE_BUILD_TYPE": "Release"+ }+ }+ ],+ "buildPresets": [+ {+ "name": "default",+ "configurePreset": "default"+ },+ {+ "name": "debug",+ "configurePreset": "debug"+ },+ {+ "name": "release",+ "configurePreset": "release"+ }+ ]+}diff --git a/fincept-cpp/build.bat b/fincept-cpp/build.batnew file mode 100644index 000000000..b6a05d8ee--- /dev/null+++ b/fincept-cpp/build.bat@@ -0,0 +1,48 @@+@echo off+REM Fincept Terminal C++ Build Script (Windows)+REM Prerequisites: CMake, Ninja, vcpkg, Visual Studio Build Tools++echo ================================================+echo Fincept Terminal C++ Build+echo ================================================++REM Check vcpkg+if not defined VCPKG_ROOT (+ echo ERROR: VCPKG_ROOT is not set+ echo Please set VCPKG_ROOT to your vcpkg installation directory+ echo Example: set VCPKG_ROOT=C:\vcpkg+ exit /b 1+)++echo Using vcpkg at: %VCPKG_ROOT%++REM Install dependencies+echo.+echo [1/3] Installing dependencies via vcpkg...+%VCPKG_ROOT%\vcpkg install --triplet x64-windows++REM Configure+echo.+echo [2/3] Configuring with CMake...+cmake --preset default++if %errorlevel% neq 0 (+ echo CMAKE CONFIGURE FAILED+ exit /b 1+)++REM Build+echo.+echo [3/3] Building...+cmake --build build --config RelWithDebInfo++if %errorlevel% neq 0 (+ echo BUILD FAILED+ exit /b 1+)++echo.+echo ================================================+echo Build Complete!+echo Run: build\FinceptTerminal.exe+echo ================================================diff --git a/fincept-cpp/build.sh b/fincept-cpp/build.shnew file mode 100644index 000000000..14a45ee8c--- /dev/null+++ b/fincept-cpp/build.sh@@ -0,0 +1,47 @@+#!/bin/bash+# Fincept Terminal C++ Build Script (macOS/Linux)+# Prerequisites: CMake, Ninja, vcpkg++set -e++echo "================================================"+echo " Fincept Terminal C++ Build"+echo "================================================"++# Check vcpkg+if [ -z "$VCPKG_ROOT" ]; then+ echo "ERROR: VCPKG_ROOT is not set"+ echo "Please set VCPKG_ROOT to your vcpkg installation directory"+ echo "Example: export VCPKG_ROOT=\$HOME/vcpkg"+ exit 1+fi++echo "Using vcpkg at: $VCPKG_ROOT"++# Detect triplet+if [ "$(uname)" = "Darwin" ]; then+ TRIPLET="x64-osx"+else+ TRIPLET="x64-linux"+fi++# Install dependencies+echo ""+echo "[1/3] Installing dependencies via vcpkg..."+$VCPKG_ROOT/vcpkg install --triplet $TRIPLET++# Configure+echo ""+echo "[2/3] Configuring with CMake..."+cmake --preset default++# Build+echo ""+echo "[3/3] Building..."+cmake --build build++echo ""+echo "================================================"+echo " Build Complete!"+echo " Run: ./build/FinceptTerminal"+echo "================================================"diff --git a/fincept-cpp/fonts/JetBrainsMono-Regular.ttf b/fincept-cpp/fonts/JetBrainsMono-Regular.ttfnew file mode 100644index 000000000..07e9e0110Binary files /dev/null and b/fincept-cpp/fonts/JetBrainsMono-Regular.ttf differdiff --git a/fincept-cpp/imgui/.gitkeep b/fincept-cpp/imgui/.gitkeepnew file mode 100644index 000000000..e69de29bbdiff --git a/fincept-cpp/src/app.cpp b/fincept-cpp/src/app.cppnew file mode 100644index 000000000..810b5230a--- /dev/null+++ b/fincept-cpp/src/app.cpp@@ -0,0 +1,491 @@+#include "app.h"+#include "auth/auth_manager.h"+#include "auth/login_screen.h"+#include "auth/register_screen.h"+#include "auth/forgot_password.h"+#include "auth/pricing_screen.h"+#include "dashboard/dashboard_screen.h"+#include "profile/profile_screen.h"+#include "news/news_screen.h"+#include "research/research_screen.h"+#include "markets/markets_screen.h"+#include "theme/bloomberg_theme.h"+#include <imgui.h>+#include <ctime>+#include <cstdio>++namespace fincept {++// Screen instances+static auth::LoginScreen s_login;+static auth::RegisterScreen s_register;+static auth::ForgotPasswordScreen s_forgot_password;+static auth::PricingScreen s_pricing;+static dashboard::DashboardScreen s_dashboard;+static profile::ProfileScreen s_profile;+static news::NewsScreen s_news;+static research::ResearchScreen s_research;+static markets::MarketsScreen s_markets;++void App::initialize() {+ auth::AuthManager::instance().initialize();+ initialized_ = true;+ current_screen_ = AppScreen::Login;+}++void App::shutdown() {}++// =============================================================================+// Top Menu Bar — Bloomberg style (#0A0A0A bg, orange accents)+// Layout: [File|Navigate|View|Help] ... [DateTime | v3.3.1 | FINCEPT] ... [User | Credits | Plan | LOGOUT]+// =============================================================================+void App::render_top_bar() {+ using namespace theme::colors;++ ImGui::PushStyleColor(ImGuiCol_MenuBarBg, BG_DARKEST);+ ImGui::PushStyleColor(ImGuiCol_Text, TEXT_SECONDARY);+ ImGui::PushStyleColor(ImGuiCol_Border, BORDER_DIM);+ ImGui::PushStyleColor(ImGuiCol_PopupBg, BG_PANEL);+ ImGui::PushStyleColor(ImGuiCol_HeaderHovered, BG_HOVER);++ if (ImGui::BeginMainMenuBar()) {++ // === LEFT: Dropdown Menus ===+ if (ImGui::BeginMenu("File")) {+ if (ImGui::MenuItem("New Workspace")) {}+ if (ImGui::MenuItem("Save Workspace")) {}+ ImGui::Separator();+ if (ImGui::MenuItem("Export Data")) {}+ ImGui::Separator();+ if (ImGui::MenuItem("Exit", "Alt+F4")) {}+ ImGui::EndMenu();+ }+ if (ImGui::BeginMenu("Navigate")) {+ if (ImGui::MenuItem("Dashboard", "F1")) {}+ if (ImGui::MenuItem("Markets", "F2")) {}+ if (ImGui::MenuItem("News", "F3")) {}+ if (ImGui::MenuItem("Portfolio", "F4")) {}+ ImGui::Separator();+ if (ImGui::MenuItem("Crypto Trading", "F9")) {}+ if (ImGui::MenuItem("Algo Trading")) {}+ if (ImGui::MenuItem("Backtesting", "F5")) {}+ ImGui::Separator();+ if (ImGui::MenuItem("Settings")) {}+ if (ImGui::MenuItem("Profile", "F12")) {}+ ImGui::EndMenu();+ }+ if (ImGui::BeginMenu("View")) {+ if (ImGui::MenuItem("Fullscreen", "F11")) { toggle_fullscreen(); }+ ImGui::Separator();+ if (ImGui::MenuItem("Reset Layout")) {}+ ImGui::EndMenu();+ }+ if (ImGui::BeginMenu("Help")) {+ if (ImGui::MenuItem("Documentation")) {}+ if (ImGui::MenuItem("Keyboard Shortcuts")) {}+ ImGui::Separator();+ if (ImGui::MenuItem("About Fincept")) {}+ if (ImGui::MenuItem("Support")) {}+ ImGui::EndMenu();+ }++ // === CENTER: DateTime | Version | Brand ===+ {+ time_t now = time(nullptr);+ struct tm* t = localtime(&now);+ char datetime[32];+ std::strftime(datetime, sizeof(datetime), "%Y-%m-%d %H:%M:%S", t);++ const char* ver = "v3.3.1";+ const char* brand = "FINCEPT TERMINAL";++ float dt_w = ImGui::CalcTextSize(datetime).x;+ float pipe_w = ImGui::CalcTextSize("|").x;+ float sp = 6.0f; // spacing on each side of pipe+ float sep_w = pipe_w + sp * 2; // total separator width+ float ver_w = ImGui::CalcTextSize(ver).x;+ float brand_w = ImGui::CalcTextSize(brand).x;+ float center_total = dt_w + sep_w + ver_w + sep_w + brand_w;++ float window_w = ImGui::GetWindowWidth();+ float center_x = (window_w - center_total) * 0.5f;+ float cursor_x = ImGui::GetCursorPosX();+ if (center_x > cursor_x) ImGui::SameLine(center_x);+ else ImGui::SameLine();++ ImGui::TextColored(TEXT_DIM, "%s", datetime);+ ImGui::SameLine(0, 6);+ ImGui::TextColored(BORDER_BRIGHT, "|");+ ImGui::SameLine(0, 6);+ ImGui::TextColored(SUCCESS, "%s", ver);+ ImGui::SameLine(0, 6);+ ImGui::TextColored(BORDER_BRIGHT, "|");+ ImGui::SameLine(0, 6);+ ImGui::TextColored(ACCENT, "%s", brand);+ }++ // === RIGHT: Session Info + Logout ===+ auto& auth = auth::AuthManager::instance();+ if (auth.is_authenticated()) {+ auto& session = auth.session();++ std::string username;+ std::string plan;+ char credits_buf[32] = "";++ if (session.is_registered()) {+ username = session.user_info.username.empty() ? session.user_info.email : session.user_info.username;+ plan = session.user_info.account_type;+ if (!plan.empty()) plan[0] = (char)std::toupper(plan[0]);+ plan += " Plan";+ double cbal = session.user_info.credit_balance;+ if (cbal >= 1000)+ std::snprintf(credits_buf, sizeof(credits_buf), "%.0f Credits", cbal);+ else+ std::snprintf(credits_buf, sizeof(credits_buf), "%.2f Credits", cbal);+ } else {+ username = "Guest";+ plan = "Free";+ }++ float user_w = ImGui::CalcTextSize(username.c_str()).x;+ float rpipe_w = ImGui::CalcTextSize("|").x;+ float rsp = 8.0f;+ float rsep_w = rpipe_w + rsp * 2;+ float cred_w = credits_buf[0] ? ImGui::CalcTextSize(credits_buf).x : 0;+ float plan_w = ImGui::CalcTextSize(plan.c_str()).x;+ float logout_w = ImGui::CalcTextSize("LOGOUT").x + ImGui::GetStyle().FramePadding.x * 2 + 20;+ float right_total = user_w + rsep_w + (cred_w > 0 ? cred_w + rsep_w : 0) + plan_w + rsep_w + logout_w + 16;++ ImGui::SameLine(ImGui::GetWindowWidth() - right_total);++ ImGui::TextColored(WARNING, "%s", username.c_str());+ ImGui::SameLine(0, rsp);+ ImGui::TextColored(BORDER_BRIGHT, "|");+ ImGui::SameLine(0, rsp);++ if (credits_buf[0]) {+ float cbal = session.user_info.credit_balance;+ ImGui::TextColored(cbal > 0 ? MARKET_GREEN : MARKET_RED, "%s", credits_buf);+ ImGui::SameLine(0, rsp);+ ImGui::TextColored(BORDER_BRIGHT, "|");+ ImGui::SameLine(0, rsp);+ }++ // Clickable plan — navigates to Pricing screen+ ImGui::PushStyleColor(ImGuiCol_Button, ImVec4(0, 0, 0, 0));+ ImGui::PushStyleColor(ImGuiCol_ButtonHovered, BG_HOVER);+ ImGui::PushStyleColor(ImGuiCol_ButtonActive, ImVec4(0, 0, 0, 0));+ ImGui::PushStyleColor(ImGuiCol_Text, TEXT_SECONDARY);+ ImGui::PushStyleVar(ImGuiStyleVar_FramePadding, ImVec2(4, 1));+ if (ImGui::SmallButton(plan.c_str())) {+ current_screen_ = AppScreen::Pricing;+ s_pricing.reset();+ }+ ImGui::PopStyleVar();+ ImGui::PopStyleColor(4);+ if (ImGui::IsItemHovered()) ImGui::SetTooltip("View Plans & Pricing");+ ImGui::SameLine(0, rsp);+ ImGui::TextColored(BORDER_BRIGHT, "|");+ ImGui::SameLine(0, rsp);++ // LOGOUT button — Bloomberg red style+ ImGui::PushStyleColor(ImGuiCol_Button, ImVec4(0, 0, 0, 0));+ ImGui::PushStyleColor(ImGuiCol_ButtonHovered, ImVec4(ERROR_RED.x, ERROR_RED.y, ERROR_RED.z, 0.2f));+ ImGui::PushStyleColor(ImGuiCol_Text, ERROR_RED);+ ImGui::PushStyleColor(ImGuiCol_Border, ERROR_RED);+ ImGui::PushStyleVar(ImGuiStyleVar_FramePadding, ImVec2(6, 2));+ ImGui::PushStyleVar(ImGuiStyleVar_FrameBorderSize, 1.0f);+ if (ImGui::SmallButton("LOGOUT")) {+ auth.logout_async();+ current_screen_ = AppScreen::Login;+ came_from_login_ = false;+ has_chosen_free_ = false;+ }+ ImGui::PopStyleVar(2);+ ImGui::PopStyleColor(4);+ }++ ImGui::EndMainMenuBar();+ }++ ImGui::PopStyleColor(5);+}++// =============================================================================+// Tab Navigation Bar — Bloomberg dark, sharp tabs with orange active indicator+// =============================================================================+void App::render_tab_bar() {+ using namespace theme::colors;++ ImGuiViewport* vp = ImGui::GetMainViewport();+ float tab_h = ImGui::GetFrameHeight() + 4;++ ImGui::SetNextWindowPos(ImVec2(vp->WorkPos.x, vp->WorkPos.y));+ ImGui::SetNextWindowSize(ImVec2(vp->WorkSize.x, tab_h));++ ImGui::PushStyleColor(ImGuiCol_WindowBg, BG_DARK);+ ImGui::PushStyleColor(ImGuiCol_Border, BORDER_DIM);+ ImGui::PushStyleVar(ImGuiStyleVar_WindowPadding, ImVec2(4, 2));+ ImGui::PushStyleVar(ImGuiStyleVar_WindowBorderSize, 0);++ ImGui::Begin("##tabbar", nullptr,+ ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_NoResize | ImGuiWindowFlags_NoMove |+ ImGuiWindowFlags_NoScrollbar | ImGuiWindowFlags_NoDocking |+ ImGuiWindowFlags_NoFocusOnAppearing | ImGuiWindowFlags_NoBringToFrontOnFocus);++ if (current_screen_ == AppScreen::Dashboard) {+ struct TabDef { const char* label; const char* shortcut; };+ TabDef tabs[] = {+ {"Dashboard", "F1"}, {"Markets", "F2"}, {"Crypto Trading", "F9"},+ {"Portfolio", "F4"}, {"News", "F3"}, {"AI Chat", "F10"},+ {"Backtesting", "F5"}, {"Algo Trading", nullptr}, {"Node Editor", nullptr},+ {"Code Editor", nullptr}, {"AI Quant Lab", nullptr}, {"QuantLib", nullptr},+ {"Settings", nullptr}, {"Profile", "F12"},+ };+ int n_tabs = sizeof(tabs) / sizeof(tabs[0]);++ ImGui::PushStyleVar(ImGuiStyleVar_FramePadding, ImVec2(8, 3));+ ImGui::PushStyleVar(ImGuiStyleVar_ItemSpacing, ImVec2(2, 0));++ for (int i = 0; i < n_tabs; i++) {+ bool is_active = (i == active_tab_);++ if (is_active) {+ ImGui::PushStyleColor(ImGuiCol_Button, ACCENT_BG);+ ImGui::PushStyleColor(ImGuiCol_ButtonHovered, ACCENT_BG);+ ImGui::PushStyleColor(ImGuiCol_Text, ACCENT);+ ImGui::PushStyleColor(ImGuiCol_Border, ACCENT);+ ImGui::PushStyleVar(ImGuiStyleVar_FrameBorderSize, 1.0f);+ } else {+ ImGui::PushStyleColor(ImGuiCol_Button, ImVec4(0, 0, 0, 0));+ ImGui::PushStyleColor(ImGuiCol_ButtonHovered, BG_HOVER);+ ImGui::PushStyleColor(ImGuiCol_Text, TEXT_DIM);+ ImGui::PushStyleColor(ImGuiCol_Border, ImVec4(0, 0, 0, 0));+ ImGui::PushStyleVar(ImGuiStyleVar_FrameBorderSize, 0.0f);+ }++ if (ImGui::Button(tabs[i].label)) {+ active_tab_ = i;+ }++ if (tabs[i].shortcut && ImGui::IsItemHovered()) {+ ImGui::SetTooltip("%s (%s)", tabs[i].label, tabs[i].shortcut);+ }++ ImGui::PopStyleVar();+ ImGui::PopStyleColor(4);++ if (i < n_tabs - 1) ImGui::SameLine();+ }++ ImGui::PopStyleVar(2);+ }++ ImGui::End();+ ImGui::PopStyleVar(2);+ ImGui::PopStyleColor(2);+}++// =============================================================================+// Footer / Status Bar — Bloomberg style: connection status, session, credits, time+// =============================================================================+void App::render_footer() {+ using namespace theme::colors;++ ImGuiViewport* vp = ImGui::GetMainViewport();+ float bar_h = ImGui::GetFrameHeight();++ ImGui::SetNextWindowPos(ImVec2(vp->WorkPos.x, vp->WorkPos.y + vp->WorkSize.y - bar_h));+ ImGui::SetNextWindowSize(ImVec2(vp->WorkSize.x, bar_h));++ ImGui::PushStyleColor(ImGuiCol_WindowBg, BG_DARKEST);+ ImGui::PushStyleColor(ImGuiCol_Border, BORDER_DIM);+ ImGui::PushStyleVar(ImGuiStyleVar_WindowPadding, ImVec2(8, 2));+ ImGui::PushStyleVar(ImGuiStyleVar_WindowBorderSize, 1.0f);++ ImGui::Begin("##footer", nullptr,+ ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_NoResize | ImGuiWindowFlags_NoMove |+ ImGuiWindowFlags_NoScrollbar | ImGuiWindowFlags_NoDocking |+ ImGuiWindowFlags_NoFocusOnAppearing | ImGuiWindowFlags_NoBringToFrontOnFocus);++ // Left: Connection status+ ImGui::TextColored(MARKET_GREEN, "[*]");+ ImGui::SameLine();+ ImGui::TextColored(TEXT_DIM, "API: Connected");++ ImGui::SameLine(0, 16);+ ImGui::TextColored(BORDER_BRIGHT, "|");++ // Session info+ auto& auth_mgr = auth::AuthManager::instance();+ if (auth_mgr.is_authenticated()) {+ auto& session = auth_mgr.session();+ ImGui::SameLine(0, 16);+ ImGui::TextColored(TEXT_DIM, "Session:");+ ImGui::SameLine(0, 4);+ ImGui::TextColored(session.is_registered() ? SUCCESS : WARNING,+ "%s", session.is_registered() ? "Registered" : "Guest");++ ImGui::SameLine(0, 16);+ ImGui::TextColored(BORDER_BRIGHT, "|");+ ImGui::SameLine(0, 16);+ ImGui::TextColored(TEXT_DIM, "Credits:");+ ImGui::SameLine(0, 4);+ ImGui::TextColored(session.user_info.credit_balance > 0 ? MARKET_GREEN : MARKET_RED,+ "%.2f", session.user_info.credit_balance);++ ImGui::SameLine(0, 16);+ ImGui::TextColored(BORDER_BRIGHT, "|");+ ImGui::SameLine(0, 16);++ // User+ std::string user = session.is_registered()+ ? (session.user_info.username.empty() ? session.user_info.email : session.user_info.username)+ : "Guest";+ ImGui::TextColored(TEXT_SECONDARY, "%s", user.c_str());+ }++ ImGui::SameLine(0, 16);+ ImGui::TextColored(BORDER_BRIGHT, "|");+ ImGui::SameLine(0, 16);++ // Hot reload status+ ImGui::TextColored(TEXT_DIM, "C++ / ImGui");++ // Right: Timestamp+ time_t now = time(nullptr);+ struct tm* t = localtime(&now);+ char tb[32];+ std::strftime(tb, sizeof(tb), "%Y-%m-%d %H:%M:%S", t);++ float time_w = ImGui::CalcTextSize(tb).x + 12;+ ImGui::SameLine(ImGui::GetWindowWidth() - time_w);+ ImGui::TextColored(TEXT_SECONDARY, "%s", tb);++ ImGui::End();+ ImGui::PopStyleVar(2);+ ImGui::PopStyleColor(2);+}++// =============================================================================+void App::render_loading() {+ ImVec2 display = ImGui::GetIO().DisplaySize;+ ImGui::SetNextWindowPos(ImVec2(0, 0));+ ImGui::SetNextWindowSize(display);+ ImGui::PushStyleColor(ImGuiCol_WindowBg, theme::colors::BG_DARKEST);++ ImGui::Begin("##loading", nullptr,+ ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_NoResize | ImGuiWindowFlags_NoMove |+ ImGuiWindowFlags_NoScrollbar | ImGuiWindowFlags_NoDecoration);++ ImVec2 center(display.x / 2, display.y / 2);+ ImGui::SetCursorPos(ImVec2(center.x - 100, center.y - 30));+ ImGui::TextColored(theme::colors::ACCENT, "FINCEPT TERMINAL");+ ImGui::SetCursorPosX(center.x - 80);+ theme::LoadingSpinner("Initializing...");++ ImGui::End();+ ImGui::PopStyleColor();+}++void App::apply_auto_navigation() {+ auto& auth = auth::AuthManager::instance();++ if (auth.is_loading() || auth.is_logging_out()) return;++ if (auth.is_authenticated()) {+ auto& session = auth.session();+ bool has_paid = session.has_paid_plan();++ if (session.is_registered() && has_paid) {+ if (current_screen_ != AppScreen::Dashboard && current_screen_ != AppScreen::Pricing)+ current_screen_ = AppScreen::Dashboard;+ }+ else if (session.is_registered() && !has_paid &&+ current_screen_ != AppScreen::Pricing && current_screen_ != AppScreen::Dashboard &&+ (came_from_login_ || !has_chosen_free_)) {+ current_screen_ = AppScreen::Pricing;+ }+ } else {+ if (current_screen_ == AppScreen::Dashboard || current_screen_ == AppScreen::Pricing) {+ current_screen_ = AppScreen::Login;+ has_chosen_free_ = false;+ came_from_login_ = false;+ }+ }+}++void App::render() {+ auto& auth = auth::AuthManager::instance();++ // F11 fullscreen toggle+ if (ImGui::IsKeyPressed(ImGuiKey_F11)) toggle_fullscreen();++ // Tab navigation keyboard shortcuts (only when on Dashboard screen)+ // Tab indices: 0=Dashboard, 1=Markets, 2=Crypto Trading, 3=Portfolio,+ // 4=News, 5=AI Chat, 6=Backtesting, 7=Algo Trading, 8=Node Editor,+ // 9=Code Editor, 10=AI Quant Lab, 11=QuantLib, 12=Settings, 13=Profile+ if (current_screen_ == AppScreen::Dashboard) {+ if (ImGui::IsKeyPressed(ImGuiKey_F1)) active_tab_ = 0; // Dashboard+ if (ImGui::IsKeyPressed(ImGuiKey_F2)) active_tab_ = 1; // Markets+ if (ImGui::IsKeyPressed(ImGuiKey_F3)) active_tab_ = 4; // News+ if (ImGui::IsKeyPressed(ImGuiKey_F4)) active_tab_ = 3; // Portfolio+ if (ImGui::IsKeyPressed(ImGuiKey_F5)) active_tab_ = 6; // Backtesting+ if (ImGui::IsKeyPressed(ImGuiKey_F9)) active_tab_ = 2; // Crypto Trading+ if (ImGui::IsKeyPressed(ImGuiKey_F10)) active_tab_ = 5; // AI Chat+ if (ImGui::IsKeyPressed(ImGuiKey_F12)) active_tab_ = 13; // Profile+ }++ // Header+ render_top_bar();++ // Tab navigation+ render_tab_bar();++ // Auto-navigate+ if (initialized_ && !auth.is_loading())+ apply_auto_navigation();++ // Loading state+ if (!initialized_ || auth.is_loading() || auth.is_logging_out()) {+ render_loading();+ return;+ }++ next_screen_ = current_screen_;++ switch (current_screen_) {+ case AppScreen::Login: s_login.render(next_screen_); break;+ case AppScreen::Register: s_register.render(next_screen_); break;+ case AppScreen::ForgotPassword: s_forgot_password.render(next_screen_); break;+ case AppScreen::Pricing: s_pricing.render(next_screen_); break;+ case AppScreen::Dashboard:+ // Tab indices: 0=Dashboard, 1=Markets, 2=Crypto Trading, 3=Portfolio,+ // 4=News, 5=AI Chat, 6=Backtesting, 7=Algo Trading, 8=Node Editor,+ // 9=Code Editor, 10=AI Quant Lab, 11=QuantLib, 12=Settings, 13=Profile+ if (active_tab_ == 13) s_profile.render();+ else if (active_tab_ == 4) s_news.render();+ else if (active_tab_ == 1) s_markets.render();+ else s_dashboard.render();+ break;+ default: render_loading(); break;+ }++ // Footer (always visible)+ render_footer();++ // Screen transitions+ if (next_screen_ != current_screen_) {+ if (current_screen_ == AppScreen::Login &&+ (next_screen_ == AppScreen::Dashboard || next_screen_ == AppScreen::Pricing))+ came_from_login_ = true;+ if (next_screen_ == AppScreen::Dashboard && current_screen_ == AppScreen::Pricing) {+ has_chosen_free_ = true;+ came_from_login_ = false;+ }+ current_screen_ = next_screen_;+ }+}++} // namespace finceptdiff --git a/fincept-cpp/src/app.h b/fincept-cpp/src/app.hnew file mode 100644index 000000000..31243f8a2--- /dev/null+++ b/fincept-cpp/src/app.h@@ -0,0 +1,40 @@+#pragma once+// Application state machine — routes between auth screens and dashboard+// Mirrors App.tsx screen routing logic++// Fullscreen toggle (implemented in main.cpp)+void toggle_fullscreen();++namespace fincept {++enum class AppScreen {+ Loading,+ Login,+ Register,+ ForgotPassword,+ Pricing,+ Dashboard+};++class App {+public:+ void initialize();+ void render();+ void shutdown();++private:+ AppScreen current_screen_ = AppScreen::Loading;+ AppScreen next_screen_ = AppScreen::Loading;+ bool initialized_ = false;+ bool came_from_login_ = false;+ bool has_chosen_free_ = false;+ int active_tab_ = 0;++ void render_top_bar();+ void render_tab_bar();+ void render_footer();+ void render_loading();+ void apply_auto_navigation();+};++} // namespace finceptdiff --git a/fincept-cpp/src/auth/auth_api.cpp b/fincept-cpp/src/auth/auth_api.cppnew file mode 100644index 000000000..f66918852--- /dev/null+++ b/fincept-cpp/src/auth/auth_api.cpp@@ -0,0 +1,183 @@+#include "auth_api.h"+#include <iostream>+#include <algorithm>++namespace fincept::auth {++using json = nlohmann::json;++AuthApi& AuthApi::instance() {+ static AuthApi api;+ return api;+}++void AuthApi::set_session_token(const std::string& token) {+ session_token_ = token;+}++void AuthApi::clear_session_token() {+ session_token_.clear();+}++std::string AuthApi::get_session_token() const {+ return session_token_;+}++http::Headers AuthApi::get_auth_headers(const std::string& api_key) const {+ http::Headers headers;+ headers["X-API-Key"] = api_key;+ if (!session_token_.empty()) {+ headers["X-Session-Token"] = session_token_;+ }+ return headers;+}++std::string AuthApi::endpoint(const std::string& path) const {+ return std::string(BASE_URL) + path;+}++// Centralized request handler matching TypeScript's makeApiRequest+api::ApiResponse AuthApi::make_request(const std::string& method, const std::string& path,+ const json& body, const http::Headers& extra_headers) {+ api::ApiResponse result;+ auto& client = http::HttpClient::instance();++ http::Headers headers = extra_headers;+ // Auto-inject session token+ if (!session_token_.empty() && headers.find("X-Session-Token") == headers.end()) {+ headers["X-Session-Token"] = session_token_;+ }++ std::string url = endpoint(path);+ http::HttpResponse resp;++ if (method == "GET") {+ resp = client.get(url, headers);+ } else if (method == "POST") {+ resp = client.post_json(url, body, headers);+ } else if (method == "PUT") {+ resp = client.put_json(url, body, headers);+ } else if (method == "DELETE") {+ resp = client.del(url, body.dump(), headers);+ }++ result.status_code = resp.status_code;++ if (!resp.error.empty() && resp.status_code == 0) {+ // Network error+ result.success = false;+ result.error = "Network error: " + resp.error;+ return result;+ }++ // Parse response+ json response_data;+ try {+ response_data = json::parse(resp.body);+ } catch (...) {+ // Non-JSON response — generate user-friendly error+ result.success = false;+ if (resp.status_code == 401 || resp.status_code == 403) {+ result.error = "Invalid email or password. Please check your credentials and try again.";+ } else if (resp.status_code == 404) {+ result.error = "Account not found. Please check your email or sign up.";+ } else if (resp.status_code >= 500) {+ result.error = "Server error. Please try again later.";+ } else {+ result.error = "Unable to connect to server. Please try again later.";+ }+ return result;+ }++ result.success = resp.success;+ result.data = response_data;++ // Generate user-friendly error messages (matching TypeScript logic)+ if (!resp.success) {+ std::string backend_msg;+ if (response_data.contains("message")) backend_msg = response_data["message"].get<std::string>();+ if (backend_msg.empty() && response_data.contains("error")) backend_msg = response_data["error"].get<std::string>();++ if (resp.status_code == 401 || resp.status_code == 403) {+ std::string lower_msg = backend_msg;+ std::transform(lower_msg.begin(), lower_msg.end(), lower_msg.begin(), ::tolower);+ if (lower_msg.find("password") != std::string::npos) {+ result.error = "Incorrect password. Please try again.";+ } else {+ result.error = "Invalid email or password. Please check your credentials and try again.";+ }+ } else if (resp.status_code == 404) {+ result.error = "Account not found. Please check your email or sign up for a new account.";+ } else if (resp.status_code == 400) {+ result.error = backend_msg.empty() ? "Invalid request. Please check your information." : backend_msg;+ } else if (resp.status_code >= 500) {+ result.error = "Server error. Please try again later.";+ } else {+ result.error = backend_msg.empty() ? ("HTTP " + std::to_string(resp.status_code)) : backend_msg;+ }+ }++ return result;+}++bool AuthApi::check_health() {+ auto result = make_request("GET", "/health");+ return result.success;+}++api::ApiResponse AuthApi::login(const api::LoginRequest& req) {+ return make_request("POST", "/user/login", api::to_json_obj(req));+}++api::ApiResponse AuthApi::register_user(const api::RegisterRequest& req) {+ return make_request("POST", "/user/register", api::to_json_obj(req));+}++api::ApiResponse AuthApi::verify_otp(const api::VerifyOtpRequest& req) {+ return make_request("POST", "/user/verify-otp", api::to_json_obj(req));+}++api::ApiResponse AuthApi::verify_mfa(const std::string& email, const std::string& otp) {+ return make_request("POST", "/user/verify-mfa", {{"email", email}, {"otp", otp}});+}++api::ApiResponse AuthApi::forgot_password(const api::ForgotPasswordRequest& req) {+ return make_request("POST", "/user/forgot-password", api::to_json_obj(req));+}++api::ApiResponse AuthApi::reset_password(const api::ResetPasswordRequest& req) {+ return make_request("POST", "/user/reset-password", api::to_json_obj(req));+}++api::ApiResponse AuthApi::create_guest_session(const api::DeviceRegisterRequest& req) {+ return make_request("POST", "/guest/session", api::to_json_obj(req));+}++api::ApiResponse AuthApi::get_user_profile(const std::string& api_key) {+ return make_request("GET", "/user/profile", {}, {{"X-API-Key", api_key}});+}++api::ApiResponse AuthApi::get_auth_status(const std::string& api_key, const std::string& device_id) {+ http::Headers headers;+ if (!api_key.empty()) headers["X-API-Key"] = api_key;+ if (!device_id.empty()) headers["X-Device-ID"] = device_id;+ return make_request("GET", "/auth/status", {}, headers);+}++api::ApiResponse AuthApi::validate_session_server(const std::string& api_key) {+ return make_request("POST", "/user/validate-session", {}, {{"X-API-Key", api_key}});+}++api::ApiResponse AuthApi::logout(const std::string& api_key) {+ return make_request("POST", "/user/logout", {}, {{"X-API-Key", api_key}});+}++api::ApiResponse AuthApi::get_subscription_plans() {+ return make_request("GET", "/cashfree/plans");+}++api::ApiResponse AuthApi::get_user_subscription(const std::string& api_key) {+ return make_request("GET", "/cashfree/subscription", {}, {{"X-API-Key", api_key}});+}++} // namespace fincept::authdiff --git a/fincept-cpp/src/auth/auth_api.h b/fincept-cpp/src/auth/auth_api.hnew file mode 100644index 000000000..5ed128fc5--- /dev/null+++ b/fincept-cpp/src/auth/auth_api.h@@ -0,0 +1,79 @@+#pragma once+// Auth API service — mirrors AuthApiService from TypeScript exactly+// All endpoints hit api.fincept.in++#include "http/api_types.h"+#include "http/http_client.h"+#include <string>+#include <vector>++namespace fincept::auth {++class AuthApi {+public:+ static AuthApi& instance();++ // Session token management+ void set_session_token(const std::string& token);+ void clear_session_token();+ std::string get_session_token() const;++ // Auth headers for other services to use+ http::Headers get_auth_headers(const std::string& api_key) const;++ // Health check+ bool check_health();++ // Login+ api::ApiResponse login(const api::LoginRequest& req);++ // Register+ api::ApiResponse register_user(const api::RegisterRequest& req);++ // Verify OTP+ api::ApiResponse verify_otp(const api::VerifyOtpRequest& req);++ // Verify MFA+ api::ApiResponse verify_mfa(const std::string& email, const std::string& otp);++ // Forgot password+ api::ApiResponse forgot_password(const api::ForgotPasswordRequest& req);++ // Reset password+ api::ApiResponse reset_password(const api::ResetPasswordRequest& req);++ // Guest session+ api::ApiResponse create_guest_session(const api::DeviceRegisterRequest& req);++ // Get user profile+ api::ApiResponse get_user_profile(const std::string& api_key);++ // Get auth status+ api::ApiResponse get_auth_status(const std::string& api_key, const std::string& device_id);++ // Validate session (server-side)+ api::ApiResponse validate_session_server(const std::string& api_key);++ // Logout+ api::ApiResponse logout(const std::string& api_key);++ // Get subscription plans+ api::ApiResponse get_subscription_plans();++ // Get user subscription+ api::ApiResponse get_user_subscription(const std::string& api_key);++private:+ AuthApi() = default;++ static constexpr const char* BASE_URL = "https://api.fincept.in";++ std::string session_token_;++ std::string endpoint(const std::string& path) const;+ api::ApiResponse make_request(const std::string& method, const std::string& path,+ const api::json& body = {},+ const http::Headers& extra_headers = {});+};++} // namespace fincept::authdiff --git a/fincept-cpp/src/auth/auth_manager.cpp b/fincept-cpp/src/auth/auth_manager.cppnew file mode 100644index 000000000..aa2f10c03--- /dev/null+++ b/fincept-cpp/src/auth/auth_manager.cpp@@ -0,0 +1,574 @@+#include "auth_manager.h"+#include "auth_api.h"+#include "storage/sqlite_store.h"+#include "utils/device_id.h"+#include "utils/validators.h"+#include <iostream>+#include <thread>+#include <cstdio>+#include <ctime>++#ifdef _WIN32+#define WIN32_LEAN_AND_MEAN+#include <windows.h>+#endif++namespace fincept::auth {++using json = nlohmann::json;++static constexpr const char* SESSION_KEY = "fincept_session";++AuthManager& AuthManager::instance() {+ static AuthManager mgr;+ return mgr;+}++void AuthManager::initialize() {+ std::lock_guard<std::mutex> lock(mutex_);+ loading_ = true;++ auto& store = storage::SqliteStore::instance();+ store.initialize();++ if (load_session()) {+ if (session_.is_registered()) {+ // Validate with server in background+ auto validated = validate_session(session_);+ if (validated.authenticated) {+ session_ = validated;+ save_session();+ } else {+ clear_session();+ }+ }+ // Guest sessions are used as-is (checked for expiry in load_session)+ }++ loading_ = false;+ std::cout << "[AuthManager] Initialized — authenticated: " << session_.authenticated+ << ", type: " << session_.user_type << std::endl;+}++// =============================================================================+// State Queries+// =============================================================================++bool AuthManager::is_authenticated() const {+ std::lock_guard<std::mutex> lock(mutex_);+ return session_.authenticated;+}++bool AuthManager::is_loading() const {+ std::lock_guard<std::mutex> lock(mutex_);+ return loading_;+}++bool AuthManager::is_logging_out() const {+ std::lock_guard<std::mutex> lock(mutex_);+ return logging_out_;+}++const api::SessionData& AuthManager::session() const {+ return session_;+}++bool AuthManager::has_session() const {+ std::lock_guard<std::mutex> lock(mutex_);+ return session_.authenticated && !session_.api_key.empty();+}++// =============================================================================+// Session Persistence+// =============================================================================++void AuthManager::save_session() {+ auto& store = storage::SqliteStore::instance();+ store.save_setting(SESSION_KEY, session_.to_json().dump(), "auth");+}++bool AuthManager::load_session() {+ auto& store = storage::SqliteStore::instance();+ auto stored = store.get_setting(SESSION_KEY);+ if (!stored.has_value()) return false;++ try {+ auto j = json::parse(stored.value());+ session_ = api::SessionData::from_json(j);++ // Check guest session expiry (ISO8601 format: "2026-03-14T12:00:00Z")+ if (session_.is_guest() && !session_.expires_at.empty()) {+ // Parse ISO8601 date — extract year/month/day/hour/min/sec+ struct tm expires_tm = {};+ if (std::sscanf(session_.expires_at.c_str(), "%d-%d-%dT%d:%d:%d",+ &expires_tm.tm_year, &expires_tm.tm_mon, &expires_tm.tm_mday,+ &expires_tm.tm_hour, &expires_tm.tm_min, &expires_tm.tm_sec) >= 3) {+ expires_tm.tm_year -= 1900;+ expires_tm.tm_mon -= 1;+ time_t expires_time = mktime(&expires_tm);+ time_t now = time(nullptr);+ if (now > expires_time) {+ std::cerr << "[AuthManager] Guest session expired, clearing" << std::endl;+ clear_session();+ return false;+ }+ }+ }++ return session_.authenticated;+ } catch (const std::exception& e) {+ std::cerr << "[AuthManager] Failed to load session: " << e.what() << std::endl;+ clear_session();+ return false;+ }+}++void AuthManager::clear_session() {+ session_ = api::SessionData{};+ auto& store = storage::SqliteStore::instance();+ store.save_setting(SESSION_KEY, "", "auth");+ store.save_setting("fincept_api_key", "", "auth");+ store.save_setting("fincept_device_id", "", "auth");+}++// =============================================================================+// Internal Helpers+// =============================================================================++api::UserProfile AuthManager::fetch_profile(const std::string& api_key) {+ api::UserProfile profile;+ auto result = AuthApi::instance().get_user_profile(api_key);+ if (result.success && !result.data.is_null()) {+ // Unwrap double-wrapped response+ json profile_data = result.data.contains("data") ? result.data["data"] : result.data;+ api::from_json_obj(profile_data, profile);+ }+ return profile;+}++api::UserSubscription AuthManager::fetch_subscription(const std::string& api_key) {+ api::UserSubscription sub;+ auto result = AuthApi::instance().get_user_subscription(api_key);+ if (result.success && !result.data.is_null()) {+ json sub_data = result.data.contains("data") ? result.data["data"] : result.data;+ api::from_json_obj(sub_data, sub);+ }+ return sub;+}++api::SessionData AuthManager::validate_session(const api::SessionData& saved) {+ auto& api = AuthApi::instance();++ // Restore session token+ if (!saved.session_token.empty()) {+ api.set_session_token(saved.session_token);+ }++ // Validate session token — non-fatal if it fails (session may have expired+ // due to login from another device, but API key may still be valid)+ bool session_token_valid = false;+ if (!saved.session_token.empty()) {+ auto val_result = api.validate_session_server(saved.api_key);+ if (val_result.success) {+ json val_data = val_result.data.contains("data") ? val_result.data["data"] : val_result.data;+ session_token_valid = !val_data.contains("valid") || val_data["valid"].get<bool>();+ }+ if (!session_token_valid) {+ api.clear_session_token();+ }+ }++ // Check auth status — this works with just API key+ auto result = api.get_auth_status(saved.api_key, saved.device_id);+ if (!result.success || result.data.is_null()) {+ return api::SessionData{};+ }++ json auth_data = result.data.contains("data") ? result.data["data"] : result.data;++ if (auth_data.contains("authenticated") && auth_data["authenticated"].get<bool>()) {+ api::SessionData validated;+ validated.authenticated = true;+ validated.user_type = auth_data.value("user_type", "");+ validated.api_key = saved.api_key;+ validated.session_token = session_token_valid ? saved.session_token : "";+ validated.device_id = saved.device_id;++ // Populate user info from auth status response (always available)+ if (auth_data.contains("user") && auth_data["user"].is_object()) {+ auto& u = auth_data["user"];+ validated.user_info.id = u.value("id", 0);+ validated.user_info.username = u.value("username", "");+ validated.user_info.email = u.value("email", "");+ validated.user_info.account_type = u.value("account_type", "");+ validated.user_info.credit_balance = u.value("credit_balance", 0.0);+ validated.user_info.created_at = u.value("created_at", "");+ }++ // Try to fetch full profile and subscription (may fail if session expired)+ if (validated.is_registered()) {+ auto profile = fetch_profile(saved.api_key);+ if (!profile.username.empty()) {+ validated.user_info = profile;+ }+ auto sub = fetch_subscription(saved.api_key);+ if (!sub.account_type.empty()) {+ validated.subscription = sub;+ validated.has_subscription = true;+ } else {+ // Use account_type from auth status as fallback+ validated.subscription.account_type = validated.user_info.account_type;+ validated.subscription.credit_balance = validated.user_info.credit_balance;+ validated.has_subscription = !validated.user_info.account_type.empty();+ }+ }++ return validated;+ }++ return api::SessionData{};+}++// =============================================================================+// Auth Operations+// =============================================================================++AuthResult AuthManager::login(const std::string& email, const std::string& password, bool force_login) {+ std::lock_guard<std::mutex> lock(mutex_);+ loading_ = true;++ auto& api = AuthApi::instance();+ api::LoginRequest req{email, password, force_login};+ auto result = api.login(req);++ // Unwrap double-wrapped response+ json api_data = result.data.contains("data") ? result.data["data"] : result.data;++ // Check active session on another device+ if (api_data.contains("active_session") && api_data["active_session"].get<bool>()) {+ loading_ = false;+ return {false, api_data.value("message", "Already logged in on another device."), false, true};+ }++ // Check MFA required+ if (result.success && api_data.contains("mfa_required") && api_data["mfa_required"].get<bool>()) {+ loading_ = false;+ return {false, "MFA verification required", true, false};+ }++ if (result.success && api_data.contains("api_key")) {+ std::string api_key = api_data["api_key"].get<std::string>();+ std::string session_token = api_data.value("session_token", "");++ api.set_session_token(session_token);++ session_.authenticated = true;+ session_.user_type = "registered";+ session_.api_key = api_key;+ session_.session_token = session_token;+ session_.device_id = utils::generate_device_id();++ // Pre-populate from login response data+ if (api_data.contains("username")) session_.user_info.username = api_data["username"].get<std::string>();+ if (api_data.contains("email")) session_.user_info.email = api_data["email"].get<std::string>();+ if (api_data.contains("credit_balance")) session_.user_info.credit_balance = api_data["credit_balance"].get<double>();++ // Try to fetch full profile and subscription+ auto profile = fetch_profile(api_key);+ if (!profile.username.empty()) {+ session_.user_info = profile;+ }++ auto subscription = fetch_subscription(api_key);+ if (!subscription.account_type.empty()) {+ session_.subscription = subscription;+ session_.has_subscription = true;+ }++ // If profile/subscription fetch failed, get data from auth status+ if (session_.user_info.account_type.empty()) {+ auto auth_status = api.get_auth_status(api_key, session_.device_id);+ if (auth_status.success && !auth_status.data.is_null()) {+ json as_data = auth_status.data.contains("data") ? auth_status.data["data"] : auth_status.data;+ if (as_data.contains("user") && as_data["user"].is_object()) {+ auto& u = as_data["user"];+ if (session_.user_info.account_type.empty())+ session_.user_info.account_type = u.value("account_type", "");+ if (session_.user_info.credit_balance == 0.0)+ session_.user_info.credit_balance = u.value("credit_balance", 0.0);+ if (session_.user_info.id == 0)+ session_.user_info.id = u.value("id", 0);+ }+ }+ }++ // Use account_type as subscription fallback+ if (session_.subscription.account_type.empty() && !session_.user_info.account_type.empty()) {+ session_.subscription.account_type = session_.user_info.account_type;+ session_.subscription.credit_balance = session_.user_info.credit_balance;+ session_.has_subscription = true;+ }++ save_session();++ // Legacy keys+ auto& store = storage::SqliteStore::instance();+ store.save_setting("fincept_api_key", api_key, "auth");+ store.save_setting("fincept_device_id", session_.device_id, "auth");++ loading_ = false;+ std::cout << "[AuthManager] Login success — account_type: " << session_.user_info.account_type << std::endl;+ return {true, ""};+ }++ loading_ = false;+ return {false, result.error.empty() ? "Login failed" : result.error};+}++AuthResult AuthManager::signup(const std::string& username, const std::string& email, const std::string& password,+ const std::string& phone, const std::string& country,+ const std::string& country_code) {+ std::lock_guard<std::mutex> lock(mutex_);+ loading_ = true;++ api::RegisterRequest req;+ req.username = username;+ req.email = email;+ req.password = password;+ req.phone = phone;+ req.country = country;+ req.country_code = country_code;++ auto result = AuthApi::instance().register_user(req);++ loading_ = false;++ if (result.success) {+ return {true, ""};+ }+ return {false, result.error.empty() ? (result.message.empty() ? "Registration failed" : result.message) : result.error};+}++AuthResult AuthManager::verify_otp(const std::string& email, const std::string& otp) {+ std::lock_guard<std::mutex> lock(mutex_);+ loading_ = true;++ auto& api = AuthApi::instance();+ auto result = api.verify_otp({email, otp});+ json api_data = result.data.contains("data") ? result.data["data"] : result.data;++ if (result.success && api_data.contains("api_key")) {+ std::string api_key = api_data["api_key"].get<std::string>();+ std::string session_token = api_data.value("session_token", "");++ api.set_session_token(session_token);+ auto profile = fetch_profile(api_key);++ session_.authenticated = true;+ session_.user_type = "registered";+ session_.api_key = api_key;+ session_.session_token = session_token;+ session_.device_id = utils::generate_device_id();+ session_.user_info = profile;++ save_session();+ loading_ = false;+ return {true, ""};+ }++ loading_ = false;+ return {false, result.error.empty() ? "Verification failed" : result.error};+}++AuthResult AuthManager::verify_mfa(const std::string& email, const std::string& otp) {+ std::lock_guard<std::mutex> lock(mutex_);+ loading_ = true;++ auto& api = AuthApi::instance();+ auto result = api.verify_mfa(email, otp);+ json api_data = result.data.contains("data") ? result.data["data"] : result.data;++ if (result.success && api_data.contains("api_key")) {+ std::string api_key = api_data["api_key"].get<std::string>();+ std::string session_token = api_data.value("session_token", "");++ api.set_session_token(session_token);+ auto profile = fetch_profile(api_key);+ auto subscription = fetch_subscription(api_key);++ session_.authenticated = true;+ session_.user_type = "registered";+ session_.api_key = api_key;+ session_.session_token = session_token;+ session_.device_id = utils::generate_device_id();+ session_.user_info = profile;+ session_.subscription = subscription;+ session_.has_subscription = !subscription.account_type.empty();++ save_session();+ loading_ = false;+ return {true, ""};+ }++ loading_ = false;+ return {false, result.error.empty() ? "MFA verification failed" : result.error};+}++AuthResult AuthManager::setup_guest_access() {+ std::lock_guard<std::mutex> lock(mutex_);+ loading_ = true;++ std::string device_id = utils::generate_device_id();++ api::DeviceRegisterRequest req;+ req.device_id = device_id;+ req.device_name = "Fincept Terminal - Desktop";+ req.platform = "desktop";+ req.hardware_info = {{"cpu_cores", 4}, {"memory_gb", 8}};++#ifdef _WIN32+ SYSTEM_INFO si;+ GetSystemInfo(&si);+ req.hardware_info["cpu_cores"] = (int)si.dwNumberOfProcessors;++ int w = GetSystemMetrics(SM_CXSCREEN);+ int h = GetSystemMetrics(SM_CYSCREEN);+ req.hardware_info["screen_resolution"] = std::to_string(w) + "x" + std::to_string(h);+#elif defined(__APPLE__) || defined(__linux__)+ req.hardware_info["cpu_cores"] = (int)std::thread::hardware_concurrency();+#endif++ auto result = AuthApi::instance().create_guest_session(req);++ if (result.success && !result.data.is_null()) {+ json api_data = result.data.contains("data") ? result.data["data"] : result.data;++ session_.authenticated = true;+ session_.user_type = "guest";+ session_.api_key = api_data.value("api_key", "");+ session_.device_id = device_id;+ session_.expires_at = api_data.value("expires_at", "");+ session_.credit_balance = api_data.value("credit_balance", 0.0);++ save_session();+ loading_ = false;+ return {true, ""};+ }++ loading_ = false;+ return {false, result.error.empty() ? "Failed to setup guest access" : result.error};+}++AuthResult AuthManager::forgot_password(const std::string& email) {+ auto result = AuthApi::instance().forgot_password({email});+ return {result.success, result.error.empty() ? result.message : result.error};+}++AuthResult AuthManager::reset_password(const std::string& email, const std::string& otp, const std::string& new_password) {+ auto result = AuthApi::instance().reset_password({email, otp, new_password});+ return {result.success, result.error.empty() ? result.message : result.error};+}++void AuthManager::logout() {+ {+ std::lock_guard<std::mutex> lock(mutex_);+ if (logging_out_) return;+ logging_out_ = true;+ }++ // Server-side logout (best effort)+ if (!session_.api_key.empty()) {+ try {+ AuthApi::instance().logout(session_.api_key);+ } catch (...) {}+ }++ AuthApi::instance().clear_session_token();++ {+ std::lock_guard<std::mutex> lock(mutex_);+ clear_session();+ logging_out_ = false;+ }++ std::cout << "[AuthManager] Logout completed" << std::endl;+}++void AuthManager::refresh_user_data() {+ if (!session_.authenticated || !session_.is_registered()) return;++ auto profile = fetch_profile(session_.api_key);+ auto subscription = fetch_subscription(session_.api_key);++ std::lock_guard<std::mutex> lock(mutex_);+ if (!profile.username.empty()) {+ session_.user_info = profile;+ }+ session_.subscription = subscription;+ session_.has_subscription = !subscription.account_type.empty();+ save_session();+}++// =============================================================================+// Async Wrappers+// =============================================================================++void AuthManager::run_async(std::function<AuthResult()> fn) {+ result_ready_ = false;+ pending_future_ = std::async(std::launch::async, std::move(fn));+}++bool AuthManager::has_pending_result() const {+ if (result_ready_) return true;+ if (pending_future_.valid()) {+ return pending_future_.wait_for(std::chrono::milliseconds(0)) == std::future_status::ready;+ }+ return false;+}++AuthResult AuthManager::consume_result() {+ if (pending_future_.valid() && pending_future_.wait_for(std::chrono::milliseconds(0)) == std::future_status::ready) {+ last_result_ = pending_future_.get();+ result_ready_ = true;+ }+ result_ready_ = false;+ return last_result_;+}++void AuthManager::login_async(const std::string& email, const std::string& password, bool force_login) {+ run_async([this, email, password, force_login]() { return login(email, password, force_login); });+}++void AuthManager::signup_async(const std::string& username, const std::string& email, const std::string& password,+ const std::string& phone, const std::string& country,+ const std::string& country_code) {+ run_async([this, username, email, password, phone, country, country_code]() {+ return signup(username, email, password, phone, country, country_code);+ });+}++void AuthManager::verify_otp_async(const std::string& email, const std::string& otp) {+ run_async([this, email, otp]() { return verify_otp(email, otp); });+}++void AuthManager::verify_mfa_async(const std::string& email, const std::string& otp) {+ run_async([this, email, otp]() { return verify_mfa(email, otp); });+}++void AuthManager::setup_guest_async() {+ run_async([this]() { return setup_guest_access(); });+}++void AuthManager::forgot_password_async(const std::string& email) {+ run_async([this, email]() { return forgot_password(email); });+}++void AuthManager::reset_password_async(const std::string& email, const std::string& otp, const std::string& new_password) {+ run_async([this, email, otp, new_password]() { return reset_password(email, otp, new_password); });+}++void AuthManager::logout_async() {+ run_async([this]() { logout(); return AuthResult{true, ""}; });+}++} // namespace fincept::authdiff --git a/fincept-cpp/src/auth/auth_manager.h b/fincept-cpp/src/auth/auth_manager.hnew file mode 100644index 000000000..ba3bec883--- /dev/null+++ b/fincept-cpp/src/auth/auth_manager.h@@ -0,0 +1,93 @@+#pragma once+// Auth session manager — mirrors AuthContext from TypeScript+// Manages session lifecycle, persistence, and API auth state++#include "http/api_types.h"+#include <string>+#include <functional>+#include <future>+#include <mutex>++namespace fincept::auth {++// Auth operation result+struct AuthResult {+ bool success = false;+ std::string error;+ bool mfa_required = false;+ bool active_session = false;+};++class AuthManager {+public:+ static AuthManager& instance();++ // Initialize — loads saved session and validates+ void initialize();++ // Auth operations (blocking — call from background thread)+ AuthResult login(const std::string& email, const std::string& password, bool force_login = false);+ AuthResult signup(const std::string& username, const std::string& email, const std::string& password,+ const std::string& phone = "", const std::string& country = "",+ const std::string& country_code = "");+ AuthResult verify_otp(const std::string& email, const std::string& otp);+ AuthResult verify_mfa(const std::string& email, const std::string& otp);+ AuthResult setup_guest_access();+ AuthResult forgot_password(const std::string& email);+ AuthResult reset_password(const std::string& email, const std::string& otp, const std::string& new_password);+ void logout();+ void refresh_user_data();++ // State queries (thread-safe)+ bool is_authenticated() const;+ bool is_loading() const;+ bool is_logging_out() const;+ const api::SessionData& session() const;+ bool has_session() const;++ // Async wrappers — run auth operations off main thread+ void login_async(const std::string& email, const std::string& password, bool force_login = false);+ void signup_async(const std::string& username, const std::string& email, const std::string& password,+ const std::string& phone = "", const std::string& country = "",+ const std::string& country_code = "");+ void verify_otp_async(const std::string& email, const std::string& otp);+ void verify_mfa_async(const std::string& email, const std::string& otp);+ void setup_guest_async();+ void forgot_password_async(const std::string& email);+ void reset_password_async(const std::string& email, const std::string& otp, const std::string& new_password);+ void logout_async();++ // Poll for async result (call from main/render thread)+ bool has_pending_result() const;+ AuthResult consume_result();++ AuthManager(const AuthManager&) = delete;+ AuthManager& operator=(const AuthManager&) = delete;++private:+ AuthManager() = default;++ api::SessionData session_;+ mutable std::mutex mutex_;+ bool loading_ = true;+ bool logging_out_ = false;++ // Async result+ std::future<AuthResult> pending_future_;+ AuthResult last_result_;+ bool result_ready_ = false;++ // Session persistence+ void save_session();+ bool load_session();+ void clear_session();++ // Internal helpers+ api::UserProfile fetch_profile(const std::string& api_key);+ api::UserSubscription fetch_subscription(const std::string& api_key);+ api::SessionData validate_session(const api::SessionData& saved);++ void run_async(std::function<AuthResult()> fn);+};++} // namespace fincept::authdiff --git a/fincept-cpp/src/auth/forgot_password.cpp b/fincept-cpp/src/auth/forgot_password.cppnew file mode 100644index 000000000..05abcfdbd--- /dev/null+++ b/fincept-cpp/src/auth/forgot_password.cpp@@ -0,0 +1,176 @@+#include "forgot_password.h"+#include "auth_manager.h"+#include "theme/bloomberg_theme.h"+#include "utils/validators.h"+#include <imgui.h>+#include <cstring>++namespace fincept::auth {++void ForgotPasswordScreen::reset() {+ step_ = EMAIL;+ std::memset(email_, 0, sizeof(email_));+ std::memset(otp_, 0, sizeof(otp_));+ std::memset(new_password_, 0, sizeof(new_password_));+ std::memset(confirm_password_, 0, sizeof(confirm_password_));+ loading_ = false;+ error_.clear();+ success_msg_.clear();+}++void ForgotPasswordScreen::render(AppScreen& next_screen) {+ auto& auth = AuthManager::instance();++ // Check async results+ if (auth.has_pending_result()) {+ auto result = auth.consume_result();+ loading_ = false;++ if (result.success) {+ if (step_ == EMAIL) {+ step_ = OTP_RESET;+ error_.clear();+ } else if (step_ == OTP_RESET) {+ step_ = SUCCESS;+ success_msg_ = "Password reset successfully. You can now sign in.";+ }+ } else {+ error_ = result.error;+ }+ }++ ImVec2 display = ImGui::GetIO().DisplaySize;+ float panel_w = 420.0f;+ ImGui::SetNextWindowPos(ImVec2((display.x - panel_w) / 2, (display.y - 350) / 2), ImGuiCond_Always);+ ImGui::SetNextWindowSize(ImVec2(panel_w, 0), ImGuiCond_Always);++ ImGui::PushStyleColor(ImGuiCol_WindowBg, theme::colors::BG_PANEL);+ ImGui::PushStyleVar(ImGuiStyleVar_WindowPadding, ImVec2(24, 24));+ ImGui::PushStyleVar(ImGuiStyleVar_WindowBorderSize, 1.0f);+ ImGui::PushStyleColor(ImGuiCol_Border, theme::colors::BORDER);++ ImGui::Begin("##forgot_password_panel", nullptr,+ ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_NoResize | ImGuiWindowFlags_NoMove |+ ImGuiWindowFlags_NoCollapse | ImGuiWindowFlags_AlwaysAutoResize);++ // Back button+ if (theme::SecondaryButton("< Back to Login")) {+ next_screen = AppScreen::Login;+ reset();+ }+ ImGui::Spacing();++ // ========== Success ==========+ if (step_ == SUCCESS) {+ ImGui::TextColored(theme::colors::SUCCESS, "Password Reset Complete");+ ImGui::Spacing();+ ImGui::TextColored(theme::colors::TEXT_SECONDARY, "%s", success_msg_.c_str());+ ImGui::Spacing(); ImGui::Spacing();+ if (theme::AccentButton("Go to Login", ImVec2(-1, 32))) {+ next_screen = AppScreen::Login;+ reset();+ }+ ImGui::End();+ ImGui::PopStyleColor(2);+ ImGui::PopStyleVar(2);+ return;+ }++ // ========== OTP + New Password ==========+ if (step_ == OTP_RESET) {+ ImGui::TextColored(theme::colors::TEXT_PRIMARY, "Reset Password");+ ImGui::Spacing();+ ImGui::TextColored(theme::colors::TEXT_SECONDARY, "Enter the code sent to %s", email_);+ ImGui::Spacing();++ ImGui::PushItemWidth(-1);++ ImGui::TextColored(theme::colors::TEXT_DIM, "VERIFICATION CODE");+ ImGui::PushStyleColor(ImGuiCol_FrameBg, theme::colors::BG_INPUT);+ ImGui::InputText("##reset_otp", otp_, sizeof(otp_));+ ImGui::PopStyleColor();++ ImGui::Spacing();+ ImGui::TextColored(theme::colors::TEXT_DIM, "NEW PASSWORD");+ ImGui::PushStyleColor(ImGuiCol_FrameBg, theme::colors::BG_INPUT);+ ImGui::InputText("##new_password", new_password_, sizeof(new_password_), ImGuiInputTextFlags_Password);+ ImGui::PopStyleColor();++ ImGui::Spacing();+ ImGui::TextColored(theme::colors::TEXT_DIM, "CONFIRM NEW PASSWORD");+ ImGui::PushStyleColor(ImGuiCol_FrameBg, theme::colors::BG_INPUT);+ ImGui::InputText("##confirm_new_password", confirm_password_, sizeof(confirm_password_), ImGuiInputTextFlags_Password);+ ImGui::PopStyleColor();++ ImGui::PopItemWidth();++ if (confirm_password_[0] != '\0' && std::strcmp(new_password_, confirm_password_) != 0) {+ ImGui::TextColored(theme::colors::ERROR_RED, "[X] Passwords do not match");+ }++ ImGui::Spacing();+ theme::ErrorMessage(error_.c_str());++ bool can_submit = otp_[0] != '\0' && new_password_[0] != '\0' &&+ std::strcmp(new_password_, confirm_password_) == 0 &&+ std::strlen(new_password_) >= 8 && !loading_;++ if (!can_submit) ImGui::BeginDisabled();+ if (theme::AccentButton("RESET PASSWORD", ImVec2(-1, 32))) {+ loading_ = true;+ error_.clear();+ std::string sanitized_email = utils::to_lower(utils::sanitize_input(email_));+ auth.reset_password_async(sanitized_email, utils::sanitize_input(otp_), new_password_);+ }+ if (!can_submit) ImGui::EndDisabled();++ if (loading_) {+ ImGui::Spacing();+ theme::LoadingSpinner("Resetting password...");+ }++ ImGui::End();+ ImGui::PopStyleColor(2);+ ImGui::PopStyleVar(2);+ return;+ }++ // ========== Email Step ==========+ ImGui::TextColored(theme::colors::TEXT_PRIMARY, "Forgot Password");+ ImGui::Spacing();+ ImGui::TextColored(theme::colors::TEXT_SECONDARY, "Enter your email to receive a reset code");+ ImGui::Spacing(); ImGui::Spacing();++ ImGui::PushItemWidth(-1);+ ImGui::TextColored(theme::colors::TEXT_DIM, "EMAIL");+ ImGui::PushStyleColor(ImGuiCol_FrameBg, theme::colors::BG_INPUT);+ bool enter_pressed = ImGui::InputText("##forgot_email", email_, sizeof(email_), ImGuiInputTextFlags_EnterReturnsTrue);+ ImGui::PopStyleColor();+ ImGui::PopItemWidth();++ ImGui::Spacing();+ theme::ErrorMessage(error_.c_str());++ bool submit = enter_pressed || theme::AccentButton("SEND RESET CODE", ImVec2(-1, 32));+ if (submit && !loading_ && email_[0] != '\0') {+ auto email_result = utils::validate_email(email_);+ if (!email_result.valid) {+ error_ = email_result.error;+ } else {+ loading_ = true;+ error_.clear();+ auth.forgot_password_async(utils::to_lower(utils::sanitize_input(email_)));+ }+ }++ if (loading_) {+ ImGui::Spacing();+ theme::LoadingSpinner("Sending code...");+ }++ ImGui::End();+ ImGui::PopStyleColor(2);+ ImGui::PopStyleVar(2);+}++} // namespace fincept::authdiff --git a/fincept-cpp/src/auth/forgot_password.h b/fincept-cpp/src/auth/forgot_password.hnew file mode 100644index 000000000..5817b77d2--- /dev/null+++ b/fincept-cpp/src/auth/forgot_password.h@@ -0,0 +1,26 @@+#pragma once+#include "app.h"+#include <string>++namespace fincept::auth {++class ForgotPasswordScreen {+public:+ void render(fincept::AppScreen& next_screen);+ void reset();++private:+ enum Step { EMAIL, OTP_RESET, SUCCESS };+ Step step_ = EMAIL;++ char email_[256] = {};+ char otp_[64] = {};+ char new_password_[256] = {};+ char confirm_password_[256] = {};++ bool loading_ = false;+ std::string error_;+ std::string success_msg_;+};++} // namespace fincept::authdiff --git a/fincept-cpp/src/auth/login_screen.cpp b/fincept-cpp/src/auth/login_screen.cppnew file mode 100644index 000000000..5f82ad9ec--- /dev/null+++ b/fincept-cpp/src/auth/login_screen.cpp@@ -0,0 +1,222 @@+#include "login_screen.h"+#include "auth_manager.h"+#include "theme/bloomberg_theme.h"+#include "utils/validators.h"+#include <imgui.h>+#include <cstring>++namespace fincept::auth {++void LoginScreen::reset() {+ std::memset(email_, 0, sizeof(email_));+ std::memset(password_, 0, sizeof(password_));+ std::memset(mfa_code_, 0, sizeof(mfa_code_));+ show_mfa_ = false;+ show_force_login_ = false;+ loading_ = false;+ error_.clear();+ saved_email_.clear();+}++void LoginScreen::render(AppScreen& next_screen) {+ auto& auth = AuthManager::instance();++ // Check for async results+ if (auth.has_pending_result()) {+ auto result = auth.consume_result();+ loading_ = false;++ if (result.success) {+ if (auth.session().has_paid_plan()) {+ next_screen = AppScreen::Dashboard;+ } else {+ next_screen = AppScreen::Pricing;+ }+ reset();+ return;+ }++ if (result.mfa_required) {+ show_mfa_ = true;+ saved_email_ = email_;+ error_.clear();+ } else if (result.active_session) {+ show_force_login_ = true;+ saved_email_ = email_;+ error_ = result.error;+ } else {+ error_ = result.error;+ }+ }++ // Center the login panel+ ImVec2 display = ImGui::GetIO().DisplaySize;+ float panel_w = 420.0f;+ float panel_h = show_mfa_ ? 320.0f : (show_force_login_ ? 340.0f : 400.0f);+ ImGui::SetNextWindowPos(ImVec2((display.x - panel_w) / 2, (display.y - panel_h) / 2), ImGuiCond_Always);+ ImGui::SetNextWindowSize(ImVec2(panel_w, 0), ImGuiCond_Always);++ ImGui::PushStyleColor(ImGuiCol_WindowBg, theme::colors::BG_PANEL);+ ImGui::PushStyleVar(ImGuiStyleVar_WindowPadding, ImVec2(24, 24));+ ImGui::PushStyleVar(ImGuiStyleVar_WindowBorderSize, 1.0f);+ ImGui::PushStyleColor(ImGuiCol_Border, theme::colors::BORDER);++ ImGui::Begin("##login_panel", nullptr,+ ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_NoResize | ImGuiWindowFlags_NoMove |+ ImGuiWindowFlags_NoCollapse | ImGuiWindowFlags_NoScrollbar | ImGuiWindowFlags_AlwaysAutoResize);++ // ========== MFA Verification ==========+ if (show_mfa_) {+ ImGui::TextColored(theme::colors::TEXT_PRIMARY, "MFA Verification");+ ImGui::Spacing();+ ImGui::TextColored(theme::colors::TEXT_SECONDARY, "Enter the code from your authenticator app");+ ImGui::Spacing(); ImGui::Spacing();++ ImGui::PushItemWidth(-1);+ ImGui::TextColored(theme::colors::TEXT_DIM, "VERIFICATION CODE");+ ImGui::PushStyleColor(ImGuiCol_FrameBg, theme::colors::BG_INPUT);+ bool enter_pressed = ImGui::InputText("##mfa_code", mfa_code_, sizeof(mfa_code_), ImGuiInputTextFlags_EnterReturnsTrue);+ ImGui::PopStyleColor();+ ImGui::PopItemWidth();++ ImGui::Spacing(); ImGui::Spacing();++ theme::ErrorMessage(error_.c_str());++ bool submit = enter_pressed || theme::AccentButton("VERIFY", ImVec2(-1, 32));+ if (submit && !loading_ && mfa_code_[0] != '\0') {+ loading_ = true;+ error_.clear();+ auth.verify_mfa_async(saved_email_, mfa_code_);+ }++ if (loading_) {+ ImGui::Spacing();+ theme::LoadingSpinner("Verifying...");+ }++ ImGui::Spacing();+ if (theme::SecondaryButton("< Back to Login", ImVec2(-1, 28))) {+ show_mfa_ = false;+ std::memset(mfa_code_, 0, sizeof(mfa_code_));+ error_.clear();+ }++ ImGui::End();+ ImGui::PopStyleColor(2);+ ImGui::PopStyleVar(2);+ return;+ }++ // ========== Force Login Prompt ==========+ if (show_force_login_) {+ ImGui::TextColored(theme::colors::TEXT_PRIMARY, "Active Session Detected");+ ImGui::Spacing();+ ImGui::TextWrapped("%s", error_.c_str());+ ImGui::Spacing(); ImGui::Spacing();++ if (theme::AccentButton("Force Login (End Other Session)", ImVec2(-1, 32)) && !loading_) {+ loading_ = true;+ error_.clear();+ show_force_login_ = false;+ auth.login_async(saved_email_, password_, true);+ }++ ImGui::Spacing();+ if (theme::SecondaryButton("Cancel", ImVec2(-1, 28))) {+ show_force_login_ = false;+ error_.clear();+ }++ if (loading_) {+ ImGui::Spacing();+ theme::LoadingSpinner("Logging in...");+ }++ ImGui::End();+ ImGui::PopStyleColor(2);+ ImGui::PopStyleVar(2);+ return;+ }++ // ========== Main Login Form ==========++ // Header+ ImGui::PushFont(nullptr); // Will use default (which should be JetBrains Mono)+ ImGui::TextColored(theme::colors::ACCENT, "FINCEPT TERMINAL");+ ImGui::PopFont();+ ImGui::TextColored(theme::colors::TEXT_SECONDARY, "Sign in to your account");+ ImGui::Spacing(); ImGui::Spacing();++ ImGui::Separator();+ ImGui::Spacing();++ // Email field+ ImGui::PushItemWidth(-1);+ ImGui::TextColored(theme::colors::TEXT_DIM, "EMAIL");+ ImGui::PushStyleColor(ImGuiCol_FrameBg, theme::colors::BG_INPUT);+ ImGui::InputText("##email", email_, sizeof(email_));+ ImGui::PopStyleColor();++ ImGui::Spacing();++ // Password field+ ImGui::TextColored(theme::colors::TEXT_DIM, "PASSWORD");+ ImGui::PushStyleColor(ImGuiCol_FrameBg, theme::colors::BG_INPUT);+ bool enter_pressed = ImGui::InputText("##password", password_, sizeof(password_),+ ImGuiInputTextFlags_Password | ImGuiInputTextFlags_EnterReturnsTrue);+ ImGui::PopStyleColor();+ ImGui::PopItemWidth();++ ImGui::Spacing(); ImGui::Spacing();++ // Error message+ theme::ErrorMessage(error_.c_str());++ // Login button+ bool submit = enter_pressed || theme::AccentButton("SIGN IN", ImVec2(-1, 34));+ if (submit && !loading_ && email_[0] != '\0' && password_[0] != '\0') {+ loading_ = true;+ error_.clear();+ auth.login_async(email_, password_);+ }++ if (loading_) {+ ImGui::Spacing();+ theme::LoadingSpinner("Signing in...");+ }++ ImGui::Spacing(); ImGui::Spacing();++ // Forgot password link+ ImGui::PushStyleColor(ImGuiCol_Button, ImVec4(0, 0, 0, 0));+ ImGui::PushStyleColor(ImGuiCol_ButtonHovered, ImVec4(0, 0, 0, 0));+ ImGui::PushStyleColor(ImGuiCol_ButtonActive, ImVec4(0, 0, 0, 0));+ ImGui::PushStyleColor(ImGuiCol_Text, theme::colors::INFO);+ if (ImGui::Button("Forgot Password?")) {+ next_screen = AppScreen::ForgotPassword;+ }+ ImGui::PopStyleColor(4);++ ImGui::Spacing();+ ImGui::Separator();+ ImGui::Spacing();++ // Register link+ ImGui::TextColored(theme::colors::TEXT_DIM, "Don't have an account?");+ ImGui::SameLine();+ ImGui::PushStyleColor(ImGuiCol_Button, ImVec4(0, 0, 0, 0));+ ImGui::PushStyleColor(ImGuiCol_ButtonHovered, ImVec4(0, 0, 0, 0));+ ImGui::PushStyleColor(ImGuiCol_ButtonActive, ImVec4(0, 0, 0, 0));+ ImGui::PushStyleColor(ImGuiCol_Text, theme::colors::INFO);+ if (ImGui::Button("Sign Up")) {+ next_screen = AppScreen::Register;+ }+ ImGui::PopStyleColor(4);++ ImGui::End();+ ImGui::PopStyleColor(2);+ ImGui::PopStyleVar(2);+}++} // namespace fincept::authdiff --git a/fincept-cpp/src/auth/login_screen.h b/fincept-cpp/src/auth/login_screen.hnew file mode 100644index 000000000..9a51c024b--- /dev/null+++ b/fincept-cpp/src/auth/login_screen.h@@ -0,0 +1,24 @@+#pragma once+#include "app.h"+#include <string>++namespace fincept::auth {++class LoginScreen {+public:+ void render(fincept::AppScreen& next_screen);+ void reset();++private:+ char email_[256] = {};+ char password_[256] = {};+ char mfa_code_[64] = {};++ bool show_mfa_ = false;+ bool show_force_login_ = false;+ bool loading_ = false;+ std::string error_;+ std::string saved_email_;+};++} // namespace fincept::authdiff --git a/fincept-cpp/src/auth/pricing_screen.cpp b/fincept-cpp/src/auth/pricing_screen.cppnew file mode 100644index 000000000..6472807ef--- /dev/null+++ b/fincept-cpp/src/auth/pricing_screen.cpp@@ -0,0 +1,512 @@+#include "pricing_screen.h"+#include "auth_manager.h"+#include "auth_api.h"+#include "theme/bloomberg_theme.h"+#include <imgui.h>+#include <algorithm>+#include <nlohmann/json.hpp>+#include <thread>+#include <cstdio>++#ifdef _WIN32+#include <windows.h>+#include <shellapi.h>+#endif++namespace fincept::auth {++using json = nlohmann::json;++static void open_url(const char* url) {+#ifdef _WIN32+ ShellExecuteA(nullptr, "open", url, nullptr, nullptr, SW_SHOWNORMAL);+#elif __APPLE__+ std::string cmd = std::string("open ") + url;+ system(cmd.c_str());+#else+ std::string cmd = std::string("xdg-open ") + url;+ system(cmd.c_str());+#endif+}++void PricingScreen::reset() {+ plans_.clear();+ loading_ = false;+ fetched_ = false;+ error_.clear();+ payment_error_.clear();+ payment_loading_ = false;+}++void PricingScreen::fetch_plans_async() {+ loading_ = true;+ fetched_ = true;++ fetch_future_ = std::async(std::launch::async, [this]() {+ auto result = AuthApi::instance().get_subscription_plans();++ if (result.success && !result.data.is_null()) {+ json plans_data = result.data;+ if (plans_data.contains("data") && plans_data["data"].is_array()) {+ plans_data = plans_data["data"];+ }+ if (plans_data.is_array()) {+ std::vector<api::SubscriptionPlan> new_plans;+ for (auto& p : plans_data) {+ api::SubscriptionPlan plan;+ api::from_json_obj(p, plan);+ new_plans.push_back(plan);+ }+ std::sort(new_plans.begin(), new_plans.end(),+ [](const api::SubscriptionPlan& a, const api::SubscriptionPlan& b) {+ return a.display_order < b.display_order;+ });+ plans_ = std::move(new_plans);+ }+ } else {+ error_ = result.error.empty() ? "Failed to load plans" : result.error;+ }++ loading_ = false;+ });+}++// ─── Helper: render a single plan card ─────────────────────────────────────────+void PricingScreen::render_plan_card(size_t index, float card_w, float card_h,+ AppScreen& next_screen) {+ using namespace theme::colors;+ auto& auth = AuthManager::instance();+ auto& plan = plans_[index];++ bool is_popular = (plan.name == "Standard" || plan.name == "Pro");+ bool is_current = false;+ if (auth.is_authenticated()) {+ std::string user_plan = auth.session().user_info.account_type;+ for (auto& c : user_plan) c = (char)std::tolower(c);+ // Match against plan_id (e.g. "enterprise") not plan name (e.g. "Enterprise Plan")+ std::string pid = plan.plan_id;+ for (auto& c : pid) c = (char)std::tolower(c);+ is_current = (user_plan == pid);+ }++ // Card background+ ImVec4 card_bg = is_popular ? ImVec4(0.08f, 0.06f, 0.02f, 1.0f) : BG_DARK;+ ImVec4 card_border = is_popular ? ACCENT : (is_current ? SUCCESS : BORDER_DIM);+ float border_sz = is_popular ? 2.0f : 1.0f;++ ImGui::PushStyleColor(ImGuiCol_ChildBg, card_bg);+ ImGui::PushStyleColor(ImGuiCol_Border, card_border);+ ImGui::PushStyleVar(ImGuiStyleVar_ChildBorderSize, border_sz);+ ImGui::PushStyleVar(ImGuiStyleVar_ChildRounding, 4.0f);+ ImGui::PushStyleVar(ImGuiStyleVar_WindowPadding, ImVec2(16, 16));++ std::string child_id = "##plan_card_" + std::to_string(index);+ ImGui::BeginChild(child_id.c_str(), ImVec2(card_w, card_h),+ ImGuiChildFlags_Borders);++ float content_w = ImGui::GetContentRegionAvail().x;++ // ── Popular badge ──+ if (is_popular) {+ float badge_w = ImGui::CalcTextSize("MOST POPULAR").x + 16;+ ImGui::SetCursorPosX((content_w - badge_w) / 2);+ ImGui::PushStyleColor(ImGuiCol_Button, ImVec4(ACCENT.x, ACCENT.y, ACCENT.z, 0.2f));+ ImGui::PushStyleColor(ImGuiCol_Text, ACCENT);+ ImGui::PushStyleVar(ImGuiStyleVar_FrameRounding, 3.0f);+ ImGui::PushStyleVar(ImGuiStyleVar_FramePadding, ImVec2(8, 2));+ ImGui::SmallButton("MOST POPULAR");+ ImGui::PopStyleVar(2);+ ImGui::PopStyleColor(2);+ ImGui::Spacing();+ } else {+ ImGui::Spacing();+ }++ // ── Plan Name (centered, large) ──+ ImGui::SetWindowFontScale(1.3f);+ float name_w = ImGui::CalcTextSize(plan.name.c_str()).x;+ ImGui::SetCursorPosX((content_w - name_w) / 2);+ ImGui::TextColored(TEXT_PRIMARY, "%s", plan.name.c_str());+ ImGui::SetWindowFontScale(1.0f);++ // ── Description (wrapped) ──+ if (!plan.description.empty()) {+ ImGui::PushTextWrapPos(ImGui::GetCursorPosX() + content_w);+ ImGui::TextColored(TEXT_DIM, "%s", plan.description.c_str());+ ImGui::PopTextWrapPos();+ }++ ImGui::Spacing(); ImGui::Spacing();++ // ── Price (centered, prominent) ──+ if (plan.is_free) {+ ImGui::SetWindowFontScale(1.8f);+ float fw = ImGui::CalcTextSize("FREE").x;+ ImGui::SetCursorPosX((content_w - fw) / 2);+ ImGui::TextColored(TEXT_SECONDARY, "FREE");+ ImGui::SetWindowFontScale(1.0f);+ } else {+ char price_buf[32];+ std::snprintf(price_buf, sizeof(price_buf), "$%.0f", plan.price_usd);+ ImGui::SetWindowFontScale(1.8f);+ float pw = ImGui::CalcTextSize(price_buf).x;+ ImGui::SetCursorPosX((content_w - pw) / 2);+ ImGui::TextColored(ACCENT, "%s", price_buf);+ ImGui::SetWindowFontScale(1.0f);++ char period_buf[32];+ std::snprintf(period_buf, sizeof(period_buf), "/ %d days", plan.validity_days);+ float per_w = ImGui::CalcTextSize(period_buf).x;+ ImGui::SetCursorPosX((content_w - per_w) / 2);+ ImGui::TextColored(TEXT_DIM, "%s", period_buf);+ }++ ImGui::Spacing();++ // ── Credits & Support (centered) ──+ char cred_buf[64];+ std::snprintf(cred_buf, sizeof(cred_buf), "%d credits", plan.credits);+ float cw = ImGui::CalcTextSize(cred_buf).x;+ ImGui::SetCursorPosX((content_w - cw) / 2);+ ImGui::TextColored(TEXT_SECONDARY, "%s", cred_buf);++ char sup_buf[64];+ std::snprintf(sup_buf, sizeof(sup_buf), "%s support", plan.support_type.c_str());+ float sw = ImGui::CalcTextSize(sup_buf).x;+ ImGui::SetCursorPosX((content_w - sw) / 2);+ ImGui::TextColored(TEXT_DIM, "%s", sup_buf);++ ImGui::Spacing();++ // ── Separator ──+ ImGui::PushStyleColor(ImGuiCol_Separator, BORDER_DIM);+ ImGui::Separator();+ ImGui::PopStyleColor();++ ImGui::Spacing();++ // ── Features (wrapped) ──+ for (auto& feature : plan.features) {+ ImGui::TextColored(is_popular ? ACCENT : SUCCESS, " +");+ ImGui::SameLine();+ ImGui::PushTextWrapPos(ImGui::GetCursorPosX() + (content_w - ImGui::GetCursorPosX() + ImGui::GetWindowContentRegionMin().x));+ ImGui::TextColored(TEXT_SECONDARY, "%s", feature.c_str());+ ImGui::PopTextWrapPos();+ }++ // Push button to bottom+ float btn_h = 36.0f;+ float cur_y = ImGui::GetCursorPosY();+ float avail_y = ImGui::GetContentRegionAvail().y;+ if (avail_y > btn_h + 8) {+ ImGui::SetCursorPosY(cur_y + avail_y - btn_h - 4);+ } else {+ ImGui::Spacing();+ }++ // ── Action Button ──+ if (is_current) {+ // Highlight border already indicates current; show a subtle active-plan button+ ImGui::PushStyleColor(ImGuiCol_Button, ImVec4(SUCCESS.x, SUCCESS.y, SUCCESS.z, 0.15f));+ ImGui::PushStyleColor(ImGuiCol_ButtonHovered, ImVec4(SUCCESS.x, SUCCESS.y, SUCCESS.z, 0.25f));+ ImGui::PushStyleColor(ImGuiCol_Text, SUCCESS);+ ImGui::PushStyleVar(ImGuiStyleVar_FrameRounding, 4.0f);+ ImGui::Button(("Active##" + std::to_string(index)).c_str(), ImVec2(-1, btn_h));+ ImGui::PopStyleVar();+ ImGui::PopStyleColor(3);+ } else if (plan.is_free) {+ bool has_paid = auth.is_authenticated() && auth.session().has_paid_plan();+ ImGui::PushStyleVar(ImGuiStyleVar_FrameRounding, 4.0f);+ if (has_paid) {+ // User has a paid plan — grey out the free option+ ImGui::PushStyleColor(ImGuiCol_Button, ImVec4(0.15f, 0.15f, 0.15f, 1.0f));+ ImGui::PushStyleColor(ImGuiCol_Text, TEXT_DIM);+ ImGui::Button(("Free Tier##" + std::to_string(index)).c_str(), ImVec2(-1, btn_h));+ ImGui::PopStyleColor(2);+ } else if (theme::SecondaryButton(("Continue Free##" + std::to_string(index)).c_str(), ImVec2(-1, btn_h))) {+ next_screen = AppScreen::Dashboard;+ }+ ImGui::PopStyleVar();+ } else {+ std::string btn_label = payment_loading_+ ? ("Processing...##" + std::to_string(index))+ : ("Select Plan##" + std::to_string(index));++ ImGui::PushStyleVar(ImGuiStyleVar_FrameRounding, 4.0f);+ bool clicked = theme::AccentButton(btn_label.c_str(), ImVec2(-1, btn_h));+ ImGui::PopStyleVar();++ if (clicked && !payment_loading_) {+ payment_loading_ = true;+ payment_error_.clear();++ std::string pid = plan.plan_id;+ std::string api_key = auth.session().api_key;+ std::thread([this, pid, api_key]() {+ auto& api = AuthApi::instance();+ json body;+ body["plan_id"] = pid;+ body["currency"] = "USD";++ auto headers = api.get_auth_headers(api_key);+ auto& client = http::HttpClient::instance();+ auto resp = client.post_json("https://api.fincept.in/cashfree/create-order", body, headers);++ if (resp.success) {+ try {+ auto j = json::parse(resp.body);+ json api_data = j.contains("data") ? j["data"] : j;+ std::string checkout_url;+ if (api_data.contains("payment_session_id")) {+ std::string sid = api_data["payment_session_id"].get<std::string>();+ checkout_url = "https://fincept.in/checkout.html?session=" + sid;+ }+ if (checkout_url.empty() && api_data.contains("checkout_url"))+ checkout_url = api_data["checkout_url"].get<std::string>();+ if (checkout_url.empty() && api_data.contains("url"))+ checkout_url = api_data["url"].get<std::string>();++ if (!checkout_url.empty()) {+ open_url(checkout_url.c_str());+ } else {+ payment_error_ = "No checkout URL received from server";+ }+ } catch (...) {+ payment_error_ = "Failed to parse payment response";+ }+ } else {+ std::string err_msg;+ try {+ auto j = json::parse(resp.body);+ if (j.contains("message")) err_msg = j["message"].get<std::string>();+ if (err_msg.empty() && j.contains("error")) err_msg = j["error"].get<std::string>();+ } catch (...) {}+ payment_error_ = err_msg.empty()+ ? (resp.error.empty() ? "Failed to create payment session" : resp.error)+ : err_msg;+ }+ payment_loading_ = false;+ }).detach();+ }+ }++ ImGui::EndChild();+ ImGui::PopStyleVar(3);+ ImGui::PopStyleColor(2);+}++// ─── Main Render — Fullscreen Layout ────────────────────────────────────────────+void PricingScreen::render(AppScreen& next_screen) {+ using namespace theme::colors;+ auto& auth = AuthManager::instance();++ // Fetch plans on first render (async)+ if (!fetched_ && !loading_) {+ fetch_plans_async();+ }++ // Fullscreen window+ ImGuiViewport* vp = ImGui::GetMainViewport();+ float tab_h = ImGui::GetFrameHeight() + 4;+ float footer_h = ImGui::GetFrameHeight();++ ImGui::SetNextWindowPos(ImVec2(vp->WorkPos.x, vp->WorkPos.y + tab_h));+ ImGui::SetNextWindowSize(ImVec2(vp->WorkSize.x, vp->WorkSize.y - tab_h - footer_h));++ ImGui::PushStyleColor(ImGuiCol_WindowBg, BG_DARK);+ ImGui::PushStyleVar(ImGuiStyleVar_WindowPadding, ImVec2(0, 0));++ ImGui::Begin("##pricing_screen", nullptr,+ ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_NoResize | ImGuiWindowFlags_NoMove |+ ImGuiWindowFlags_NoScrollbar | ImGuiWindowFlags_NoDocking |+ ImGuiWindowFlags_NoFocusOnAppearing | ImGuiWindowFlags_NoBringToFrontOnFocus);++ ImVec2 avail = ImGui::GetContentRegionAvail();++ // ── Scrollable content ──+ ImGui::BeginChild("##pricing_scroll", ImVec2(0, 0), false);++ float content_avail = ImGui::GetContentRegionAvail().x;+ float side_pad = std::max(content_avail * 0.05f, 20.0f);++ ImGui::Spacing(); ImGui::Spacing(); ImGui::Spacing();++ // ── Header Section ──+ {+ ImGui::SetWindowFontScale(1.4f);+ const char* title = "Choose Your Plan";+ float tw = ImGui::CalcTextSize(title).x;+ ImGui::SetCursorPosX((content_avail - tw) / 2);+ ImGui::TextColored(TEXT_PRIMARY, "%s", title);+ ImGui::SetWindowFontScale(1.0f);++ const char* subtitle = "Unlock the full power of Fincept Terminal with a plan that fits your needs";+ float stw = ImGui::CalcTextSize(subtitle).x;+ ImGui::SetCursorPosX((content_avail - stw) / 2);+ ImGui::TextColored(TEXT_DIM, "%s", subtitle);++ // Show current user info and active plan+ if (auth.is_authenticated() && auth.session().is_registered()) {+ ImGui::Spacing();+ auto& session = auth.session();+ std::string info = "Logged in as " + (session.user_info.email.empty() ? session.user_info.username : session.user_info.email);+ char cred[64];+ std::snprintf(cred, sizeof(cred), " | %.0f credits remaining", session.user_info.credit_balance);+ info += cred;+ float iw = ImGui::CalcTextSize(info.c_str()).x;+ ImGui::SetCursorPosX((content_avail - iw) / 2);+ ImGui::TextColored(TEXT_SECONDARY, "%s", info.c_str());++ // Current plan badge+ if (session.has_paid_plan()) {+ ImGui::Spacing();+ std::string plan_name = session.user_info.account_type;+ if (!plan_name.empty()) plan_name[0] = (char)std::toupper(plan_name[0]);++ std::string plan_label = "Current Plan: " + plan_name;+ float pw = ImGui::CalcTextSize(plan_label.c_str()).x + 24;+ ImGui::SetCursorPosX((content_avail - pw) / 2);++ ImGui::PushStyleColor(ImGuiCol_Button, ImVec4(SUCCESS.x, SUCCESS.y, SUCCESS.z, 0.15f));+ ImGui::PushStyleColor(ImGuiCol_ButtonHovered, ImVec4(SUCCESS.x, SUCCESS.y, SUCCESS.z, 0.15f));+ ImGui::PushStyleColor(ImGuiCol_ButtonActive, ImVec4(SUCCESS.x, SUCCESS.y, SUCCESS.z, 0.15f));+ ImGui::PushStyleColor(ImGuiCol_Text, SUCCESS);+ ImGui::PushStyleVar(ImGuiStyleVar_FrameRounding, 4.0f);+ ImGui::PushStyleVar(ImGuiStyleVar_FramePadding, ImVec2(12, 4));+ ImGui::Button(plan_label.c_str());+ ImGui::PopStyleVar(2);+ ImGui::PopStyleColor(4);+ }+ }+ }++ ImGui::Spacing(); ImGui::Spacing(); ImGui::Spacing();++ // ── Loading / Error / Plans ──+ if (loading_) {+ ImGui::Spacing(); ImGui::Spacing();+ float spinner_x = (content_avail - 100) / 2;+ ImGui::SetCursorPosX(spinner_x);+ theme::LoadingSpinner("Loading plans...");+ } else if (!error_.empty()) {+ ImGui::SetCursorPosX(side_pad);+ theme::ErrorMessage(error_.c_str());+ ImGui::Spacing();+ ImGui::SetCursorPosX(side_pad);+ if (theme::SecondaryButton("Retry")) {+ fetched_ = false;+ error_.clear();+ }+ } else if (!plans_.empty()) {+ // Responsive grid: compute card size based on available width+ int num_plans = (int)plans_.size();+ float usable_w = content_avail - side_pad * 2;+ float gap = 16.0f;++ // Determine columns: try to fit all in one row, else wrap+ int cols = num_plans;+ float card_w = (usable_w - (cols - 1) * gap) / cols;++ // If cards are too narrow, reduce columns+ float min_card_w = 260.0f;+ if (card_w < min_card_w && cols > 3) { cols = 3; card_w = (usable_w - (cols - 1) * gap) / cols; }+ if (card_w < min_card_w && cols > 2) { cols = 2; card_w = (usable_w - (cols - 1) * gap) / cols; }+ if (card_w < min_card_w) { cols = 1; card_w = usable_w; }++ // Cap card width for aesthetics+ if (card_w > 380 && cols > 1) card_w = 380;++ // Card height — uniform for all cards, bigger to fit wrapped text+ float card_h = std::max(avail.y * 0.78f, 480.0f);+ if (card_h > 640) card_h = 640;++ // Center the row of cards+ float total_row_w = cols * card_w + (cols - 1) * gap;+ float start_x = (content_avail - total_row_w) / 2;++ int col = 0;+ for (size_t i = 0; i < plans_.size(); i++) {+ if (col == 0) {+ ImGui::SetCursorPosX(start_x);+ } else {+ ImGui::SameLine(0, gap);+ }++ render_plan_card(i, card_w, card_h, next_screen);++ col++;+ if (col >= cols) col = 0;+ }++ // Payment error+ if (!payment_error_.empty()) {+ ImGui::Spacing(); ImGui::Spacing();+ ImGui::SetCursorPosX(side_pad);+ theme::ErrorMessage(payment_error_.c_str());+ }+ } else {+ ImGui::Spacing(); ImGui::Spacing();+ const char* msg = "No plans available.";+ float mw = ImGui::CalcTextSize(msg).x;+ ImGui::SetCursorPosX((content_avail - mw) / 2);+ ImGui::TextColored(TEXT_DIM, "%s", msg);+ }++ ImGui::Spacing(); ImGui::Spacing(); ImGui::Spacing();++ // ── Footer ──+ {+ ImGui::PushStyleColor(ImGuiCol_Separator, BORDER_DIM);+ ImGui::Separator();+ ImGui::PopStyleColor();+ ImGui::Spacing();++ // Show "Continue with Free Plan" only if user has no paid plan+ bool user_has_paid = auth.is_authenticated() && auth.session().has_paid_plan();++ if (user_has_paid) {+ // User already has a plan — show "Back to Dashboard"+ const char* back_btn = "Back to Dashboard";+ float bw = ImGui::CalcTextSize(back_btn).x;+ ImGui::SetCursorPosX((content_avail - bw) / 2);++ ImGui::PushStyleColor(ImGuiCol_Button, ImVec4(0, 0, 0, 0));+ ImGui::PushStyleColor(ImGuiCol_ButtonHovered, ImVec4(0, 0, 0, 0));+ ImGui::PushStyleColor(ImGuiCol_ButtonActive, ImVec4(0, 0, 0, 0));+ ImGui::PushStyleColor(ImGuiCol_Text, INFO);+ if (ImGui::Button(back_btn)) {+ next_screen = AppScreen::Dashboard;+ }+ ImGui::PopStyleColor(4);+ } else {+ const char* explore = "Want to explore first?";+ const char* free_btn = "Continue with Free Plan";+ float ew = ImGui::CalcTextSize(explore).x;+ float bw = ImGui::CalcTextSize(free_btn).x;+ float total = ew + 8 + bw;+ ImGui::SetCursorPosX((content_avail - total) / 2);++ ImGui::TextColored(TEXT_DIM, "%s", explore);+ ImGui::SameLine(0, 8);++ ImGui::PushStyleColor(ImGuiCol_Button, ImVec4(0, 0, 0, 0));+ ImGui::PushStyleColor(ImGuiCol_ButtonHovered, ImVec4(0, 0, 0, 0));+ ImGui::PushStyleColor(ImGuiCol_ButtonActive, ImVec4(0, 0, 0, 0));+ ImGui::PushStyleColor(ImGuiCol_Text, INFO);+ if (ImGui::Button(free_btn)) {+ next_screen = AppScreen::Dashboard;+ }+ ImGui::PopStyleColor(4);+ }++ ImGui::Spacing();+ }++ ImGui::EndChild(); // pricing_scroll++ ImGui::End();+ ImGui::PopStyleVar();+ ImGui::PopStyleColor();+}++} // namespace fincept::authdiff --git a/fincept-cpp/src/auth/pricing_screen.h b/fincept-cpp/src/auth/pricing_screen.hnew file mode 100644index 000000000..378f13543--- /dev/null+++ b/fincept-cpp/src/auth/pricing_screen.h@@ -0,0 +1,35 @@+#pragma once+#include "app.h"+#include "http/api_types.h"+#include <vector>+#include <string>+#include <future>+#include <atomic>++namespace fincept::auth {++class PricingScreen {+public:+ void render(fincept::AppScreen& next_screen);+ void reset();++private:+ std::vector<api::SubscriptionPlan> plans_;+ std::atomic<bool> loading_{false};+ bool fetched_ = false;+ std::string error_;++ // Async plan fetching+ std::future<void> fetch_future_;+ void fetch_plans_async();++ // Payment+ std::string payment_error_;+ bool payment_loading_ = false;++ // Card rendering helper+ void render_plan_card(size_t index, float card_w, float card_h,+ fincept::AppScreen& next_screen);+};++} // namespace fincept::authdiff --git a/fincept-cpp/src/auth/register_screen.cpp b/fincept-cpp/src/auth/register_screen.cppnew file mode 100644index 000000000..e52c4b56d--- /dev/null+++ b/fincept-cpp/src/auth/register_screen.cpp@@ -0,0 +1,317 @@+#include "register_screen.h"+#include "auth_manager.h"+#include "theme/bloomberg_theme.h"+#include <imgui.h>+#include <cstring>+#include <algorithm>++namespace fincept::auth {++void RegisterScreen::reset() {+ step_ = FORM;+ std::memset(first_name_, 0, sizeof(first_name_));+ std::memset(last_name_, 0, sizeof(last_name_));+ std::memset(email_, 0, sizeof(email_));+ std::memset(phone_, 0, sizeof(phone_));+ std::memset(password_, 0, sizeof(password_));+ std::memset(confirm_password_, 0, sizeof(confirm_password_));+ std::memset(otp_, 0, sizeof(otp_));+ std::strncpy(country_code_, "+1", sizeof(country_code_) - 1);+ loading_ = false;+ error_.clear();+ pw_strength_ = {};+ passwords_match_ = true;+}++void RegisterScreen::render(AppScreen& next_screen) {+ auto& auth = AuthManager::instance();++ // Check async results+ if (auth.has_pending_result()) {+ auto result = auth.consume_result();+ loading_ = false;++ if (result.success) {+ if (step_ == FORM) {+ step_ = OTP_VERIFICATION;+ error_.clear();+ } else if (step_ == OTP_VERIFICATION) {+ step_ = COMPLETE;+ // Navigate based on plan+ if (auth.session().has_paid_plan()) {+ next_screen = AppScreen::Dashboard;+ } else {+ next_screen = AppScreen::Pricing;+ }+ reset();+ return;+ }+ } else {+ error_ = result.error;+ }+ }++ // Center panel+ ImVec2 display = ImGui::GetIO().DisplaySize;+ float panel_w = 460.0f;+ ImGui::SetNextWindowPos(ImVec2((display.x - panel_w) / 2, display.y * 0.1f), ImGuiCond_Always);+ ImGui::SetNextWindowSize(ImVec2(panel_w, 0), ImGuiCond_Always);++ ImGui::PushStyleColor(ImGuiCol_WindowBg, theme::colors::BG_PANEL);+ ImGui::PushStyleVar(ImGuiStyleVar_WindowPadding, ImVec2(24, 24));+ ImGui::PushStyleVar(ImGuiStyleVar_WindowBorderSize, 1.0f);+ ImGui::PushStyleColor(ImGuiCol_Border, theme::colors::BORDER);++ ImGui::Begin("##register_panel", nullptr,+ ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_NoResize | ImGuiWindowFlags_NoMove |+ ImGuiWindowFlags_NoCollapse | ImGuiWindowFlags_AlwaysAutoResize);++ // ========== OTP Verification Step ==========+ if (step_ == OTP_VERIFICATION) {+ // Back button+ if (theme::SecondaryButton("< Back")) {+ step_ = FORM;+ std::memset(otp_, 0, sizeof(otp_));+ error_.clear();+ }+ ImGui::SameLine();+ ImGui::TextColored(theme::colors::TEXT_PRIMARY, "Verify Your Email");+ ImGui::Spacing();++ ImGui::TextColored(theme::colors::TEXT_SECONDARY, "We sent a verification code to");+ ImGui::TextColored(theme::colors::TEXT_PRIMARY, "%s", email_);+ ImGui::TextColored(theme::colors::TEXT_DIM, "Check your spam folder if you don't see it.");+ ImGui::Spacing(); ImGui::Spacing();++ ImGui::PushItemWidth(-1);+ ImGui::TextColored(theme::colors::TEXT_DIM, "VERIFICATION CODE");+ ImGui::PushStyleColor(ImGuiCol_FrameBg, theme::colors::BG_INPUT);+ bool enter_pressed = ImGui::InputText("##otp", otp_, sizeof(otp_), ImGuiInputTextFlags_EnterReturnsTrue);+ ImGui::PopStyleColor();+ ImGui::PopItemWidth();++ ImGui::Spacing();+ theme::ErrorMessage(error_.c_str());++ bool submit = enter_pressed || theme::AccentButton("VERIFY", ImVec2(-1, 32));+ if (submit && !loading_ && otp_[0] != '\0') {+ loading_ = true;+ error_.clear();+ std::string sanitized_email = utils::sanitize_input(email_);+ std::transform(sanitized_email.begin(), sanitized_email.end(), sanitized_email.begin(), ::tolower);+ auth.verify_otp_async(sanitized_email, utils::sanitize_input(otp_));+ }++ if (loading_) {+ ImGui::Spacing();+ theme::LoadingSpinner("Verifying...");+ }++ ImGui::Spacing();+ ImGui::Separator();+ ImGui::Spacing();++ // Resend OTP+ ImGui::PushStyleColor(ImGuiCol_Button, ImVec4(0, 0, 0, 0));+ ImGui::PushStyleColor(ImGuiCol_ButtonHovered, ImVec4(0, 0, 0, 0));+ ImGui::PushStyleColor(ImGuiCol_ButtonActive, ImVec4(0, 0, 0, 0));+ ImGui::PushStyleColor(ImGuiCol_Text, theme::colors::INFO);+ if (ImGui::Button("Resend Code") && !loading_) {+ loading_ = true;+ error_.clear();+ std::string username = utils::to_lower(utils::sanitize_input(std::string(first_name_) + std::string(last_name_)));+ std::string sanitized_email = utils::to_lower(utils::sanitize_input(email_));+ auth.signup_async(username, sanitized_email, password_, phone_, "", country_code_);+ }+ ImGui::PopStyleColor(4);++ ImGui::End();+ ImGui::PopStyleColor(2);+ ImGui::PopStyleVar(2);+ return;+ }++ // ========== Registration Form ==========++ // Back button + Header+ if (theme::SecondaryButton("< Back")) {+ next_screen = AppScreen::Login;+ }+ ImGui::SameLine();+ ImGui::TextColored(theme::colors::TEXT_PRIMARY, "Create Account");+ ImGui::Spacing();+ ImGui::TextColored(theme::colors::TEXT_SECONDARY, "Join Fincept Terminal");+ ImGui::Spacing();+ ImGui::Separator();+ ImGui::Spacing();++ float half_width = (ImGui::GetContentRegionAvail().x - 8) / 2;++ // First + Last name (side by side)+ ImGui::BeginGroup();+ ImGui::PushItemWidth(half_width);+ ImGui::TextColored(theme::colors::TEXT_DIM, "FIRST NAME");+ ImGui::PushStyleColor(ImGuiCol_FrameBg, theme::colors::BG_INPUT);+ ImGui::InputText("##first_name", first_name_, sizeof(first_name_));+ ImGui::PopStyleColor();+ ImGui::PopItemWidth();+ ImGui::EndGroup();++ ImGui::SameLine(0, 8);++ ImGui::BeginGroup();+ ImGui::PushItemWidth(half_width);+ ImGui::TextColored(theme::colors::TEXT_DIM, "LAST NAME");+ ImGui::PushStyleColor(ImGuiCol_FrameBg, theme::colors::BG_INPUT);+ ImGui::InputText("##last_name", last_name_, sizeof(last_name_));+ ImGui::PopStyleColor();+ ImGui::PopItemWidth();+ ImGui::EndGroup();++ // Username validation+ std::string username = utils::to_lower(utils::sanitize_input(std::string(first_name_) + std::string(last_name_)));+ if (!username.empty()) {+ bool valid = username.size() >= 3 && username.size() <= 50;+ ImGui::TextColored(valid ? theme::colors::SUCCESS : theme::colors::WARNING,+ "%s Username: %s (%zu chars)", valid ? "[OK]" : "[!]", username.c_str(), username.size());+ }++ ImGui::Spacing();++ ImGui::PushItemWidth(-1);+ ImGui::TextColored(theme::colors::TEXT_DIM, "EMAIL");+ ImGui::PushStyleColor(ImGuiCol_FrameBg, theme::colors::BG_INPUT);+ ImGui::InputText("##reg_email", email_, sizeof(email_));+ ImGui::PopStyleColor();+ ImGui::PopItemWidth();++ // Email validation+ if (email_[0] != '\0') {+ auto email_result = utils::validate_email(email_);+ if (!email_result.valid) {+ ImGui::TextColored(theme::colors::ERROR_RED, "[X] %s", email_result.error.c_str());+ }+ }++ ImGui::Spacing();++ // Phone (country code + number side by side)+ ImGui::BeginGroup();+ ImGui::PushItemWidth(60);+ ImGui::TextColored(theme::colors::TEXT_DIM, "CODE");+ ImGui::PushStyleColor(ImGuiCol_FrameBg, theme::colors::BG_INPUT);+ ImGui::InputText("##country_code", country_code_, sizeof(country_code_));+ ImGui::PopStyleColor();+ ImGui::PopItemWidth();+ ImGui::EndGroup();++ ImGui::SameLine(0, 8);++ ImGui::BeginGroup();+ ImGui::PushItemWidth(ImGui::GetContentRegionAvail().x);+ ImGui::TextColored(theme::colors::TEXT_DIM, "PHONE NUMBER");+ ImGui::PushStyleColor(ImGuiCol_FrameBg, theme::colors::BG_INPUT);+ ImGui::InputText("##phone", phone_, sizeof(phone_));+ ImGui::PopStyleColor();+ ImGui::PopItemWidth();+ ImGui::EndGroup();++ ImGui::Spacing();++ // Password+ ImGui::PushItemWidth(-1);+ ImGui::TextColored(theme::colors::TEXT_DIM, "PASSWORD");+ ImGui::PushStyleColor(ImGuiCol_FrameBg, theme::colors::BG_INPUT);+ if (ImGui::InputText("##reg_password", password_, sizeof(password_), ImGuiInputTextFlags_Password)) {+ pw_strength_ = utils::validate_password(password_);+ }+ ImGui::PopStyleColor();+ ImGui::PopItemWidth();++ // Password strength indicators+ if (password_[0] != '\0') {+ auto indicator = [](bool ok, const char* label) {+ ImGui::TextColored(ok ? theme::colors::SUCCESS : theme::colors::TEXT_DISABLED,+ "%s %s", ok ? "[OK]" : "[ ]", label);+ };+ indicator(pw_strength_.min_length, "8+ characters");+ indicator(pw_strength_.has_upper, "Uppercase letter");+ indicator(pw_strength_.has_lower, "Lowercase letter");+ indicator(pw_strength_.has_number, "Number");+ indicator(pw_strength_.has_special, "Special character");+ }++ ImGui::Spacing();++ // Confirm password+ ImGui::PushItemWidth(-1);+ ImGui::TextColored(theme::colors::TEXT_DIM, "CONFIRM PASSWORD");+ ImGui::PushStyleColor(ImGuiCol_FrameBg, theme::colors::BG_INPUT);+ if (ImGui::InputText("##confirm_password", confirm_password_, sizeof(confirm_password_), ImGuiInputTextFlags_Password)) {+ passwords_match_ = (std::strcmp(password_, confirm_password_) == 0);+ }+ ImGui::PopStyleColor();+ ImGui::PopItemWidth();++ if (confirm_password_[0] != '\0' && !passwords_match_) {+ ImGui::TextColored(theme::colors::ERROR_RED, "[X] Passwords do not match");+ }++ ImGui::Spacing(); ImGui::Spacing();++ // Error+ theme::ErrorMessage(error_.c_str());++ // Submit+ bool can_submit = first_name_[0] != '\0' && last_name_[0] != '\0' &&+ email_[0] != '\0' && password_[0] != '\0' &&+ confirm_password_[0] != '\0' && passwords_match_ &&+ pw_strength_.is_valid() && !loading_;++ if (!can_submit) ImGui::BeginDisabled();+ bool submit = theme::AccentButton("CREATE ACCOUNT", ImVec2(-1, 34));+ if (!can_submit) ImGui::EndDisabled();++ if (submit && can_submit) {+ loading_ = true;+ error_.clear();++ std::string uname = utils::to_lower(utils::sanitize_input(std::string(first_name_) + std::string(last_name_)));+ std::string sanitized_email = utils::to_lower(utils::sanitize_input(email_));++ if (uname.size() < 3 || uname.size() > 50) {+ error_ = "Username must be between 3 and 50 characters.";+ loading_ = false;+ } else {+ auth.signup_async(uname, sanitized_email, password_, phone_, "", country_code_);+ }+ }++ if (loading_) {+ ImGui::Spacing();+ theme::LoadingSpinner("Creating account...");+ }++ ImGui::Spacing();+ ImGui::Separator();+ ImGui::Spacing();++ // Login link+ ImGui::TextColored(theme::colors::TEXT_DIM, "Already have an account?");+ ImGui::SameLine();+ ImGui::PushStyleColor(ImGuiCol_Button, ImVec4(0, 0, 0, 0));+ ImGui::PushStyleColor(ImGuiCol_ButtonHovered, ImVec4(0, 0, 0, 0));+ ImGui::PushStyleColor(ImGuiCol_ButtonActive, ImVec4(0, 0, 0, 0));+ ImGui::PushStyleColor(ImGuiCol_Text, theme::colors::INFO);+ if (ImGui::Button("Sign In")) {+ next_screen = AppScreen::Login;+ }+ ImGui::PopStyleColor(4);++ ImGui::End();+ ImGui::PopStyleColor(2);+ ImGui::PopStyleVar(2);+}++} // namespace fincept::authdiff --git a/fincept-cpp/src/auth/register_screen.h b/fincept-cpp/src/auth/register_screen.hnew file mode 100644index 000000000..183ebebf6--- /dev/null+++ b/fincept-cpp/src/auth/register_screen.h@@ -0,0 +1,33 @@+#pragma once+#include "app.h"+#include "utils/validators.h"+#include <string>++namespace fincept::auth {++class RegisterScreen {+public:+ void render(fincept::AppScreen& next_screen);+ void reset();++private:+ enum Step { FORM, OTP_VERIFICATION, COMPLETE };+ Step step_ = FORM;++ char first_name_[128] = {};+ char last_name_[128] = {};+ char email_[256] = {};+ char phone_[64] = {};+ char country_code_[16] = {'+', '1', '\0'};+ char password_[256] = {};+ char confirm_password_[256] = {};+ char otp_[64] = {};++ bool loading_ = false;+ std::string error_;++ utils::PasswordStrength pw_strength_;+ bool passwords_match_ = true;+};++} // namespace fincept::authdiff --git a/fincept-cpp/src/dashboard/dashboard_data.cpp b/fincept-cpp/src/dashboard/dashboard_data.cppnew file mode 100644index 000000000..483889b97--- /dev/null+++ b/fincept-cpp/src/dashboard/dashboard_data.cpp@@ -0,0 +1,475 @@+#include "dashboard_data.h"+#include <nlohmann/json.hpp>+#include <thread>+#include <sstream>+#include <ctime>+#include <cstdio>++#ifdef _WIN32+#include <windows.h>+#endif++using json = nlohmann::json;++namespace fincept::dashboard {++// Python paths (same as markets_data.cpp)+static const char* PYTHON_EXE = "C:/ProgramData/miniconda3/python.exe";+static const char* YFINANCE_SCRIPT =+ "C:/windowsdisk/finceptTerminal/fincept-terminal-desktop/"+ "src-tauri/resources/scripts/yfinance_data.py";++DashboardData& DashboardData::instance() {+ static DashboardData s;+ return s;+}++// =============================================================================+// Symbol lists — matching React's widget configurations exactly+// =============================================================================+std::vector<std::string> DashboardData::symbols_for(DataCategory cat) {+ switch (cat) {+ case DataCategory::Indices:+ return {+ "^GSPC", "^DJI", "^IXIC", "^RUT", "^FTSE",+ "^GDAXI", "^FCHI", "^N225", "^HSI", "000001.SS",+ "^BSESN", "^NSEI", "^STOXX50E", "^AXJO"+ };+ case DataCategory::Forex:+ return {+ "EURUSD=X", "GBPUSD=X", "USDJPY=X", "USDCHF=X",+ "USDCAD=X", "AUDUSD=X", "NZDUSD=X", "EURGBP=X",+ "EURJPY=X", "GBPJPY=X", "USDCNY=X", "USDINR=X"+ };+ case DataCategory::Commodities:+ return {+ "GC=F", "SI=F", "PL=F", "HG=F",+ "CL=F", "BZ=F", "NG=F",+ "ZC=F", "ZW=F", "ZS=F"+ };+ case DataCategory::Crypto:+ return {+ "BTC-USD", "ETH-USD", "BNB-USD", "SOL-USD",+ "XRP-USD", "ADA-USD", "DOGE-USD", "LINK-USD",+ "DOT-USD", "AVAX-USD", "UNI-USD", "ATOM-USD"+ };+ case DataCategory::SectorETFs:+ return {+ "XLK", "XLV", "XLF", "XLE", "XLI",+ "XLB", "XLU", "XLRE", "XLC", "XLP", "XLY"+ };+ case DataCategory::TopMovers:+ return {+ "SMCI", "PLTR", "MSTR", "NVDA", "AMD", "TSLA",+ "INTC", "PFE", "BA", "NKE", "DIS", "PYPL"+ };+ case DataCategory::Ticker:+ return {+ "^GSPC", "^DJI", "^IXIC", "^RUT", "^FTSE", "^GDAXI", "^N225", "^HSI",+ "AAPL", "MSFT", "GOOGL", "AMZN", "NVDA", "TSLA",+ "BTC-USD", "ETH-USD",+ "GC=F", "CL=F",+ "EURUSD=X", "GBPUSD=X", "USDJPY=X"+ };+ case DataCategory::MarketPulse:+ return {+ "^VIX", "^TNX", "DX-Y.NYB", "GC=F", "CL=F", "BTC-USD"+ };+ default:+ return {};+ }+}++std::map<std::string, std::string> DashboardData::labels_for(DataCategory cat) {+ switch (cat) {+ case DataCategory::Indices:+ return {+ {"^GSPC", "S&P 500"}, {"^DJI", "DOW JONES"}, {"^IXIC", "NASDAQ"},+ {"^RUT", "RUSSELL 2000"}, {"^FTSE", "FTSE 100"}, {"^GDAXI", "DAX"},+ {"^FCHI", "CAC 40"}, {"^N225", "NIKKEI 225"}, {"^HSI", "HANG SENG"},+ {"000001.SS", "SHANGHAI"}, {"^BSESN", "SENSEX"}, {"^NSEI", "NIFTY 50"},+ {"^STOXX50E", "EURO STOXX"}, {"^AXJO", "ASX 200"}+ };+ case DataCategory::Forex:+ return {+ {"EURUSD=X", "EUR/USD"}, {"GBPUSD=X", "GBP/USD"}, {"USDJPY=X", "USD/JPY"},+ {"USDCHF=X", "USD/CHF"}, {"USDCAD=X", "USD/CAD"}, {"AUDUSD=X", "AUD/USD"},+ {"NZDUSD=X", "NZD/USD"}, {"EURGBP=X", "EUR/GBP"}, {"EURJPY=X", "EUR/JPY"},+ {"GBPJPY=X", "GBP/JPY"}, {"USDCNY=X", "USD/CNY"}, {"USDINR=X", "USD/INR"}+ };+ case DataCategory::Commodities:+ return {+ {"GC=F", "Gold"}, {"SI=F", "Silver"}, {"PL=F", "Platinum"}, {"HG=F", "Copper"},+ {"CL=F", "WTI Crude"}, {"BZ=F", "Brent Crude"}, {"NG=F", "Natural Gas"},+ {"ZC=F", "Corn"}, {"ZW=F", "Wheat"}, {"ZS=F", "Soybeans"}+ };+ case DataCategory::Crypto:+ return {+ {"BTC-USD", "Bitcoin"}, {"ETH-USD", "Ethereum"}, {"BNB-USD", "BNB"},+ {"SOL-USD", "Solana"}, {"XRP-USD", "XRP"}, {"ADA-USD", "Cardano"},+ {"DOGE-USD", "Dogecoin"}, {"LINK-USD", "Chainlink"},+ {"DOT-USD", "Polkadot"}, {"AVAX-USD", "Avalanche"},+ {"UNI-USD", "Uniswap"}, {"ATOM-USD", "Cosmos"}+ };+ case DataCategory::SectorETFs:+ return {+ {"XLK", "Technology"}, {"XLV", "Healthcare"}, {"XLF", "Financials"},+ {"XLE", "Energy"}, {"XLI", "Industrials"}, {"XLB", "Materials"},+ {"XLU", "Utilities"}, {"XLRE", "Real Estate"}, {"XLC", "Comm. Services"},+ {"XLP", "Consumer Staples"}, {"XLY", "Consumer Disc."}+ };+ case DataCategory::TopMovers:+ return {+ {"SMCI", "Super Micro"}, {"PLTR", "Palantir"}, {"MSTR", "MicroStrategy"},+ {"NVDA", "NVIDIA"}, {"AMD", "AMD"}, {"TSLA", "Tesla"},+ {"INTC", "Intel"}, {"PFE", "Pfizer"}, {"BA", "Boeing"},+ {"NKE", "Nike"}, {"DIS", "Disney"}, {"PYPL", "PayPal"}+ };+ case DataCategory::Ticker:+ return {+ {"^GSPC", "S&P 500"}, {"^DJI", "DOW"}, {"^IXIC", "NASDAQ"},+ {"^RUT", "RUSSELL"}, {"^FTSE", "FTSE"}, {"^GDAXI", "DAX"},+ {"^N225", "NIKKEI"}, {"^HSI", "HANG SENG"},+ {"AAPL", "AAPL"}, {"MSFT", "MSFT"}, {"GOOGL", "GOOGL"},+ {"AMZN", "AMZN"}, {"NVDA", "NVDA"}, {"TSLA", "TSLA"},+ {"BTC-USD", "BTC"}, {"ETH-USD", "ETH"},+ {"GC=F", "GOLD"}, {"CL=F", "CRUDE"},+ {"EURUSD=X", "EUR/USD"}, {"GBPUSD=X", "GBP/USD"}, {"USDJPY=X", "USD/JPY"}+ };+ case DataCategory::MarketPulse:+ return {+ {"^VIX", "VIX"}, {"^TNX", "US 10Y"}, {"DX-Y.NYB", "DXY"},+ {"GC=F", "Gold"}, {"CL=F", "Oil"}, {"BTC-USD", "BTC"}+ };+ default:+ return {};+ }+}++// =============================================================================+// Python subprocess runner (same pattern as markets_data.cpp)+// =============================================================================+std::string DashboardData::run_yfinance(const std::string& args) {+ std::string cmd = std::string("\"") + PYTHON_EXE + "\" \""+ + YFINANCE_SCRIPT + "\" " + args;++#ifdef _WIN32+ SECURITY_ATTRIBUTES sa{};+ sa.nLength = sizeof(sa);+ sa.bInheritHandle = TRUE;++ HANDLE hRead = nullptr, hWrite = nullptr;+ CreatePipe(&hRead, &hWrite, &sa, 0);+ 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{};+ std::string cmd_line = cmd;++ BOOL ok = CreateProcessA(+ nullptr, cmd_line.data(), nullptr, nullptr, TRUE,+ CREATE_NO_WINDOW, nullptr, nullptr, &si, &pi+ );+ CloseHandle(hWrite);++ if (!ok) {+ CloseHandle(hRead);+ return "";+ }++ std::string output;+ char buffer[4096];+ DWORD bytesRead;+ while (ReadFile(hRead, buffer, sizeof(buffer) - 1, &bytesRead, nullptr) && bytesRead > 0) {+ buffer[bytesRead] = '\0';+ output += buffer;+ }+ CloseHandle(hRead);+ WaitForSingleObject(pi.hProcess, 60000);+ CloseHandle(pi.hProcess);+ CloseHandle(pi.hThread);++ // Extract last JSON line+ std::string json_line;+ std::istringstream stream(output);+ std::string line;+ while (std::getline(stream, line)) {+ size_t start = line.find_first_not_of(" \t\r\n");+ if (start == std::string::npos) continue;+ char first = line[start];+ if (first == '{' || first == '[') json_line = line;+ }+ return json_line;+#else+ FILE* pipe = popen(cmd.c_str(), "r");+ if (!pipe) return "";+ std::string output;+ char buffer[4096];+ while (fgets(buffer, sizeof(buffer), pipe)) output += buffer;+ pclose(pipe);++ std::string json_line;+ std::istringstream stream(output);+ std::string line;+ while (std::getline(stream, line)) {+ size_t start = line.find_first_not_of(" \t\r\n");+ if (start == std::string::npos) continue;+ char first = line[start];+ if (first == '{' || first == '[') json_line = line;+ }+ return json_line;+#endif+}++// =============================================================================+// Parse yfinance JSON array into QuoteEntry vector+// =============================================================================+std::vector<QuoteEntry> DashboardData::parse_quotes(+ const std::string& json_str,+ const std::map<std::string, std::string>& labels)+{+ std::vector<QuoteEntry> result;+ try {+ auto j = json::parse(json_str);+ if (!j.is_array()) return result;+ for (auto& item : j) {+ QuoteEntry q;+ q.symbol = item.value("symbol", "");+ q.price = item.value("price", 0.0);+ q.change = item.value("change", 0.0);+ q.change_percent = item.value("change_percent", 0.0);+ q.high = item.value("high", 0.0);+ q.low = item.value("low", 0.0);+ q.open = item.value("open", 0.0);+ q.previous_close = item.value("previous_close", 0.0);+ q.volume = item.value("volume", 0.0);++ // Apply label+ auto it = labels.find(q.symbol);+ q.label = (it != labels.end()) ? it->second : q.symbol;++ if (!q.symbol.empty() && q.price > 0)+ result.push_back(q);+ }+ } catch (...) {+ // parse error — return empty+ }+ return result;+}++// =============================================================================+// Lifecycle+// =============================================================================+void DashboardData::initialize() {+ if (initialized_) return;+ initialized_ = true;++ // Stagger initial fetches to avoid hammering Python all at once+ // Categories with shorter timers will fire first+ for (int i = 0; i < static_cast<int>(DataCategory::Count); i++) {+ categories_[i].timer = refresh_interval_ + 1.0f; // trigger immediately+ }+ news_timer_ = refresh_interval_ + 1.0f;+}++void DashboardData::update(float dt) {+ if (!initialized_) return;++ // Update timers and trigger fetches+ for (int i = 0; i < static_cast<int>(DataCategory::Count); i++) {+ auto& state = categories_[i];+ state.timer += dt;+ if (state.timer >= refresh_interval_ && !state.loading.load()) {+ state.timer = 0;+ fetch_category(static_cast<DataCategory>(i));+ }+ }++ news_timer_ += dt;+ if (news_timer_ >= refresh_interval_ && !news_loading_.load()) {+ news_timer_ = 0;+ fetch_news_feeds();+ }+}++void DashboardData::refresh_all() {+ for (int i = 0; i < static_cast<int>(DataCategory::Count); i++) {+ categories_[i].timer = refresh_interval_ + 1.0f;+ }+ news_timer_ = refresh_interval_ + 1.0f;+}++void DashboardData::refresh(DataCategory cat) {+ int idx = static_cast<int>(cat);+ if (idx >= 0 && idx < static_cast<int>(DataCategory::Count)) {+ categories_[idx].timer = refresh_interval_ + 1.0f;+ }+}++// =============================================================================+// Data access+// =============================================================================+std::vector<QuoteEntry> DashboardData::get_quotes(DataCategory cat) const {+ int idx = static_cast<int>(cat);+ if (idx < 0 || idx >= static_cast<int>(DataCategory::Count)) return {};+ std::lock_guard<std::mutex> lock(mutex_);+ return categories_[idx].quotes;+}++std::vector<NewsItem> DashboardData::get_news() const {+ std::lock_guard<std::mutex> lock(mutex_);+ return news_;+}++bool DashboardData::is_loading(DataCategory cat) const {+ int idx = static_cast<int>(cat);+ if (idx < 0 || idx >= static_cast<int>(DataCategory::Count)) return false;+ return categories_[idx].loading.load();+}++bool DashboardData::has_data(DataCategory cat) const {+ int idx = static_cast<int>(cat);+ if (idx < 0 || idx >= static_cast<int>(DataCategory::Count)) return false;+ std::lock_guard<std::mutex> lock(mutex_);+ return categories_[idx].has_data;+}++std::string DashboardData::get_error(DataCategory cat) const {+ int idx = static_cast<int>(cat);+ if (idx < 0 || idx >= static_cast<int>(DataCategory::Count)) return "";+ std::lock_guard<std::mutex> lock(mutex_);+ return categories_[idx].error;+}++float DashboardData::time_since_refresh(DataCategory cat) const {+ int idx = static_cast<int>(cat);+ if (idx < 0 || idx >= static_cast<int>(DataCategory::Count)) return 999.0f;+ auto elapsed = std::chrono::steady_clock::now() - categories_[idx].last_fetch;+ return (float)std::chrono::duration_cast<std::chrono::seconds>(elapsed).count();+}++std::string DashboardData::last_refresh_str(DataCategory cat) const {+ int idx = static_cast<int>(cat);+ if (idx < 0 || idx >= static_cast<int>(DataCategory::Count)) return "Never";+ auto tp = categories_[idx].last_fetch;+ if (tp == std::chrono::steady_clock::time_point{}) return "Never";+ float secs = time_since_refresh(cat);+ if (secs < 60) return std::to_string((int)secs) + "s ago";+ if (secs < 3600) return std::to_string((int)(secs / 60)) + "m ago";+ return std::to_string((int)(secs / 3600)) + "h ago";+}++void DashboardData::set_refresh_interval(float seconds) {+ refresh_interval_ = seconds;+}++// =============================================================================+// Background fetch+// =============================================================================+void DashboardData::fetch_category(DataCategory cat) {+ int idx = static_cast<int>(cat);+ auto& state = categories_[idx];+ if (state.loading.load()) return;+ state.loading = true;++ auto syms = symbols_for(cat);+ auto lbls = labels_for(cat);++ std::thread([this, idx, syms, lbls]() {+ // Build command: "batch_quotes SYM1 SYM2 ..."+ std::string args = "batch_quotes";+ for (auto& s : syms) args += " " + s;++ std::string output = run_yfinance(args);+ auto parsed = parse_quotes(output, lbls);++ {+ std::lock_guard<std::mutex> lock(mutex_);+ if (!parsed.empty()) {+ categories_[idx].quotes = std::move(parsed);+ categories_[idx].error.clear();+ } else if (categories_[idx].quotes.empty()) {+ categories_[idx].error = "Failed to fetch data";+ }+ // Keep stale data if fetch fails but we had data before+ categories_[idx].has_data = !categories_[idx].quotes.empty();+ categories_[idx].last_fetch = std::chrono::steady_clock::now();+ }+ categories_[idx].loading = false;+ }).detach();+}++void DashboardData::fetch_news_feeds() {+ if (news_loading_.load()) return;+ news_loading_ = true;++ // For now, news comes from hardcoded headlines with real timestamps+ // In a future iteration, this will call RSS feeds like NewsScreen does+ std::thread([this]() {+ // Placeholder: generate timestamped news items+ // Real implementation would reuse NewsScreen::fetch_news() RSS parsing+ std::vector<NewsItem> items;++ // We'll use the news from the existing news screen infrastructure+ // For the dashboard widget, we provide recent market headlines+ // This will be connected to the real RSS system in the next iteration+ time_t now = time(nullptr);++ const char* headlines[] = {+ "Fed officials signal cautious approach to rate decisions amid mixed economic signals",+ "Tech sector leads market rally as AI spending accelerates across enterprise",+ "Oil prices stabilize following OPEC+ production agreement extension",+ "Treasury yields edge higher on stronger-than-expected employment data",+ "Consumer spending shows resilience despite elevated inflation readings",+ "European Central Bank maintains rates, signals data-dependent approach",+ "Semiconductor stocks surge on robust demand forecasts for AI chips",+ "Cryptocurrency markets gain as institutional adoption continues to expand",+ "Manufacturing PMI crosses expansion threshold for first time in months",+ "Emerging market currencies strengthen as dollar index pulls back",+ "Housing starts decline as mortgage rates remain elevated above 6.5%",+ "Corporate earnings season shows mixed results across financial sector",+ };++ const char* sources[] = {+ "Reuters", "Bloomberg", "CNBC", "FT", "WSJ",+ "MarketWatch", "Reuters", "CoinDesk", "ISM",+ "Reuters", "NAR", "Bloomberg"+ };++ const char* cats[] = {+ "ECONOMIC", "MARKETS", "ENERGY", "MARKETS", "ECONOMIC",+ "ECONOMIC", "MARKETS", "CRYPTO", "ECONOMIC",+ "MARKETS", "ECONOMIC", "MARKETS"+ };++ for (int i = 0; i < 12; i++) {+ NewsItem item;+ item.headline = headlines[i];+ item.source = sources[i];+ item.category = cats[i];+ item.sort_ts = now - i * 900; // 15 min apart+ item.priority = (i < 2) ? 1 : 3;++ struct tm* t = localtime(&item.sort_ts);+ char buf[32];+ std::strftime(buf, sizeof(buf), "%H:%M", t);+ item.time_str = buf;++ items.push_back(item);+ }++ {+ std::lock_guard<std::mutex> lock(mutex_);+ news_ = std::move(items);+ news_has_data_ = true;+ }+ news_loading_ = false;+ }).detach();+}++} // namespace fincept::dashboarddiff --git a/fincept-cpp/src/dashboard/dashboard_data.h b/fincept-cpp/src/dashboard/dashboard_data.hnew file mode 100644index 000000000..8962074af--- /dev/null+++ b/fincept-cpp/src/dashboard/dashboard_data.h@@ -0,0 +1,140 @@+#pragma once+// DashboardData — singleton data service for the dashboard+// Fetches real market data via yfinance Python subprocess in background threads+// Thread-safe: all data access through mutex-locked getters++#include <string>+#include <vector>+#include <map>+#include <mutex>+#include <atomic>+#include <chrono>+#include <functional>++namespace fincept::dashboard {++struct QuoteEntry {+ std::string symbol;+ std::string label; // display name+ double price = 0;+ double change = 0;+ double change_percent = 0;+ double high = 0;+ double low = 0;+ double open = 0;+ double previous_close = 0;+ double volume = 0;+};++struct NewsItem {+ std::string headline;+ std::string source;+ std::string category;+ std::string time_str;+ int64_t sort_ts = 0;+ int priority = 3; // 0=flash, 1=urgent, 2=breaking, 3=routine+};++// Category IDs+enum class DataCategory {+ Indices,+ Forex,+ Commodities,+ Crypto,+ SectorETFs,+ TopMovers,+ Ticker, // aggregated ticker bar data+ MarketPulse, // VIX, TNX, DXY, Gold, Oil, BTC+ Count+};++inline const char* category_name(DataCategory c) {+ switch (c) {+ case DataCategory::Indices: return "Indices";+ case DataCategory::Forex: return "Forex";+ case DataCategory::Commodities: return "Commodities";+ case DataCategory::Crypto: return "Crypto";+ case DataCategory::SectorETFs: return "SectorETFs";+ case DataCategory::TopMovers: return "TopMovers";+ case DataCategory::Ticker: return "Ticker";+ case DataCategory::MarketPulse: return "MarketPulse";+ default: return "Unknown";+ }+}++class DashboardData {+public:+ static DashboardData& instance();++ // Initialize and start first fetch+ void initialize();++ // Call each frame — checks timers and triggers refresh if needed+ void update(float dt);++ // Force refresh all categories now+ void refresh_all();++ // Force refresh one category+ void refresh(DataCategory cat);++ // Data access (thread-safe copies)+ std::vector<QuoteEntry> get_quotes(DataCategory cat) const;+ std::vector<NewsItem> get_news() const;++ // Status+ bool is_loading(DataCategory cat) const;+ bool has_data(DataCategory cat) const;+ std::string get_error(DataCategory cat) const;+ float time_since_refresh(DataCategory cat) const;++ // Configuration+ void set_refresh_interval(float seconds);+ float get_refresh_interval() const { return refresh_interval_; }++ // Timestamp of last successful fetch for display+ std::string last_refresh_str(DataCategory cat) const;++ DashboardData(const DashboardData&) = delete;+ DashboardData& operator=(const DashboardData&) = delete;++private:+ DashboardData() = default;++ struct CategoryState {+ std::vector<QuoteEntry> quotes;+ std::atomic<bool> loading{false};+ bool has_data = false;+ std::string error;+ float timer = 0;+ std::chrono::steady_clock::time_point last_fetch{};+ };++ mutable std::mutex mutex_;+ CategoryState categories_[static_cast<int>(DataCategory::Count)];++ std::vector<NewsItem> news_;+ std::atomic<bool> news_loading_{false};+ bool news_has_data_ = false;+ float news_timer_ = 0;++ float refresh_interval_ = 600.0f; // 10 minutes default+ bool initialized_ = false;++ // Symbol lists (matching React originals)+ static std::vector<std::string> symbols_for(DataCategory cat);+ static std::map<std::string, std::string> labels_for(DataCategory cat);++ // Background fetch+ void fetch_category(DataCategory cat);+ void fetch_news_feeds();++ // Python subprocess runner+ static std::string run_yfinance(const std::string& args);++ // Parse yfinance JSON output into QuoteEntry vector+ static std::vector<QuoteEntry> parse_quotes(const std::string& json_str,+ const std::map<std::string, std::string>& labels);+};++} // namespace fincept::dashboarddiff --git a/fincept-cpp/src/dashboard/dashboard_screen.cpp b/fincept-cpp/src/dashboard/dashboard_screen.cppnew file mode 100644index 000000000..09ed0f710--- /dev/null+++ b/fincept-cpp/src/dashboard/dashboard_screen.cpp@@ -0,0 +1,1258 @@+#include "dashboard_screen.h"+#include "auth/auth_manager.h"+#include "theme/bloomberg_theme.h"+#include "storage/sqlite_store.h"+#include <imgui.h>+#include <cstdio>+#include <cmath>+#include <algorithm>+#include <ctime>+#include <cstring>++namespace fincept::dashboard {++// ============================================================================+// Bloomberg color palette+// ============================================================================+static const ImVec4 FC_ORANGE = ImVec4(1.0f, 0.533f, 0.0f, 1.0f);+static const ImVec4 FC_GREEN = ImVec4(0.0f, 0.84f, 0.435f, 1.0f);+static const ImVec4 FC_RED = ImVec4(1.0f, 0.231f, 0.231f, 1.0f);+static const ImVec4 FC_CYAN = ImVec4(0.0f, 0.898f, 1.0f, 1.0f);+static const ImVec4 FC_YELLOW = ImVec4(1.0f, 0.843f, 0.0f, 1.0f);+static const ImVec4 FC_GRAY = ImVec4(0.47f, 0.47f, 0.47f, 1.0f);+static const ImVec4 FC_MUTED = ImVec4(0.29f, 0.29f, 0.29f, 1.0f);+static const ImVec4 FC_WHITE = ImVec4(1.0f, 1.0f, 1.0f, 1.0f);+static const ImVec4 FC_PANEL = ImVec4(0.059f, 0.059f, 0.059f, 1.0f);+static const ImVec4 FC_HEADER = ImVec4(0.102f, 0.102f, 0.102f, 1.0f);+static const ImVec4 FC_BORDER = ImVec4(0.165f, 0.165f, 0.165f, 1.0f);+static const ImVec4 FC_DARK = ImVec4(0.0f, 0.0f, 0.0f, 1.0f);+static const ImVec4 FC_BLUE = ImVec4(0.0f, 0.533f, 1.0f, 1.0f);+static const ImVec4 FC_PURPLE = ImVec4(0.616f, 0.306f, 0.867f, 1.0f);++static ImVec4 chg_col(double v) { return v > 0 ? FC_GREEN : (v < 0 ? FC_RED : FC_GRAY); }++static std::string fmt_price(double v, int decimals = 2) {+ char b[32];+ if (v == 0) return "--";+ if (std::abs(v) >= 1e6) std::snprintf(b, sizeof(b), "%.2fM", v / 1e6);+ else if (std::abs(v) >= 1e4) std::snprintf(b, sizeof(b), "%.*fK", decimals > 0 ? 1 : 0, v / 1e3);+ else std::snprintf(b, sizeof(b), "%.*f", decimals, v);+ return b;+}++static std::string fmt_volume(double v) {+ char b[32];+ if (v >= 1e9) std::snprintf(b, sizeof(b), "%.1fB", v / 1e9);+ else if (v >= 1e6) std::snprintf(b, sizeof(b), "%.1fM", v / 1e6);+ else if (v >= 1e3) std::snprintf(b, sizeof(b), "%.1fK", v / 1e3);+ else std::snprintf(b, sizeof(b), "%.0f", v);+ return b;+}++// Helper: small styled button+static bool mini_button(const char* label, ImVec4 text_col) {+ ImGui::PushStyleColor(ImGuiCol_Button, ImVec4(0.1f, 0.1f, 0.1f, 1.0f));+ ImGui::PushStyleColor(ImGuiCol_ButtonHovered, ImVec4(0.2f, 0.12f, 0.0f, 1.0f));+ ImGui::PushStyleColor(ImGuiCol_ButtonActive, ImVec4(0.15f, 0.08f, 0.0f, 1.0f));+ ImGui::PushStyleColor(ImGuiCol_Text, text_col);+ ImGui::PushStyleVar(ImGuiStyleVar_FramePadding, ImVec2(6, 2));+ bool clicked = ImGui::SmallButton(label);+ ImGui::PopStyleVar();+ ImGui::PopStyleColor(4);+ return clicked;+}++// ============================================================================+// Accent color per widget type+// ============================================================================+ImVec4 DashboardScreen::accent_for(WidgetType type) {+ switch (type) {+ case WidgetType::GlobalIndices: return FC_ORANGE;+ case WidgetType::Forex: return FC_YELLOW;+ case WidgetType::Commodities: return FC_ORANGE;+ case WidgetType::Crypto: return FC_CYAN;+ case WidgetType::SectorHeatmap: return FC_CYAN;+ case WidgetType::News: return FC_WHITE;+ case WidgetType::EconomicIndicators: return FC_YELLOW;+ case WidgetType::GeopoliticalRisk: return FC_RED;+ case WidgetType::Performance: return FC_GREEN;+ case WidgetType::TopMovers: return FC_PURPLE;+ case WidgetType::MarketData: return FC_BLUE;+ default: return FC_ORANGE;+ }+}++const char* DashboardScreen::loading_text(bool loading, bool has_data) {+ if (loading && !has_data) return "Loading...";+ if (loading && has_data) return nullptr;+ if (!has_data) return "No data";+ return nullptr;+}++// ============================================================================+// Init+// ============================================================================+void DashboardScreen::init() {+ if (initialized_) return;+ session_start_ = std::chrono::steady_clock::now();+ DashboardData::instance().initialize();+ load_layout();+ if (layout_.widgets.empty()) layout_ = default_layout();+ init_static_data();+ initialized_ = true;+}++void DashboardScreen::init_static_data() {+ econ_data_ = {+ {"US 10Y Treasury", 4.35f, 0.05f}, {"US GDP Growth", 2.8f, 0.1f},+ {"US Unemployment", 3.6f, -0.1f}, {"US CPI YoY", 3.2f, -0.1f},+ {"Fed Funds Rate", 5.50f, 0.0f}, {"PMI Manufacturing", 50.3f, 0.5f},+ {"Consumer Confidence", 104.7f, 2.3f}, {"Retail Sales MoM", 0.6f, 0.3f},+ };+ geo_data_ = {+ {"Global Risk", 62.5f, 2.3f}, {"US-China", 78.3f, -1.5f},+ {"Europe", 45.2f, 0.8f}, {"Middle East", 82.7f, 5.2f},+ {"Asia-Pacific", 38.5f, -0.3f}, {"Latin America", 52.1f, 1.1f},+ {"Africa", 58.4f, 0.6f}, {"Cyber Risk", 71.2f, 3.8f},+ };+ perf_data_ = {+ {"Total Return", 0.0f, 8.67f}, {"Day P/L", 15243.56f, 1.23f},+ {"Week P/L", 42567.89f, 3.45f}, {"Month P/L", 125678.90f, 8.12f},+ {"Sharpe Ratio", 1.85f, 0.0f}, {"Max Drawdown", -5.23f, 0.0f},+ };+}++// ============================================================================+// Layout persistence+// ============================================================================+void DashboardScreen::save_layout() {+ try {+ auto j = layout_.to_json();+ fincept::storage::SqliteStore::instance().save_setting("dashboard_layout", j.dump(), "dashboard");+ } catch (...) {}+}++void DashboardScreen::load_layout() {+ try {+ auto opt = fincept::storage::SqliteStore::instance().get_setting("dashboard_layout");+ if (opt.has_value() && !opt->empty()) {+ auto j = nlohmann::json::parse(*opt);+ layout_ = DashboardLayout::from_json(j);+ }+ } catch (...) {}+}++// ============================================================================+// Widget management+// ============================================================================+void DashboardScreen::add_widget(WidgetType type) {+ WidgetInstance w;+ w.id = generate_widget_id();+ w.type = type;+ w.title = widget_type_name(type);+ int max_row = 0;+ for (auto& existing : layout_.widgets) {+ int end_row = existing.row + existing.row_span;+ if (end_row > max_row) max_row = end_row;+ }+ w.col = 0; w.row = max_row; w.col_span = 1; w.row_span = 1;+ layout_.widgets.push_back(w);+ save_layout();+}++void DashboardScreen::remove_widget(const std::string& id) {+ layout_.widgets.erase(+ std::remove_if(layout_.widgets.begin(), layout_.widgets.end(),+ [&id](const WidgetInstance& w) { return w.id == id; }),+ layout_.widgets.end());+ save_layout();+}++void DashboardScreen::apply_template(const std::string& template_id) {+ for (auto& t : get_all_templates()) {+ if (t.id == template_id) { layout_ = t.create(); save_layout(); return; }+ }+}++// ============================================================================+// HEADER BAR — single row: branding + status + actions + session+// ============================================================================+void DashboardScreen::render_header_bar(float width) {+ ImGui::PushStyleColor(ImGuiCol_ChildBg, FC_HEADER);+ ImGui::BeginChild("##dash_header", ImVec2(width, 30), false);++ ImGui::SetCursorPos(ImVec2(8, 6));++ // Left: Branding+ ImGui::TextColored(FC_ORANGE, "FINCEPT");+ ImGui::SameLine(0, 4);+ ImGui::TextColored(FC_MUTED, "TERMINAL");+ ImGui::SameLine(0, 10);+ ImGui::TextColored(FC_BORDER, "|");+ ImGui::SameLine(0, 10);++ // Live status+ bool has_any = DashboardData::instance().has_data(DataCategory::Indices);+ bool loading = DashboardData::instance().is_loading(DataCategory::Indices);+ if (has_any) ImGui::TextColored(FC_GREEN, "[*] LIVE");+ else if (loading) ImGui::TextColored(FC_YELLOW, "[~] LOADING");+ else ImGui::TextColored(FC_RED, "[!] OFFLINE");++ ImGui::SameLine(0, 10);+ ImGui::TextColored(FC_BORDER, "|");+ ImGui::SameLine(0, 10);++ // Clock+ time_t now = time(nullptr);+ struct tm* t = localtime(&now);+ char tb[32];+ std::strftime(tb, sizeof(tb), "%H:%M:%S", t);+ ImGui::TextColored(FC_YELLOW, "%s", tb);++ ImGui::SameLine(0, 10);+ ImGui::TextColored(FC_BORDER, "|");+ ImGui::SameLine(0, 10);++ // Widget count+ int visible = 0;+ for (auto& w : layout_.widgets) if (w.visible) visible++;+ ImGui::TextColored(FC_CYAN, "%d WIDGETS", visible);++ ImGui::SameLine(0, 10);+ ImGui::TextColored(FC_BORDER, "|");+ ImGui::SameLine(0, 6);++ // ---- Actions in the header row ----+ if (mini_button("[+] ADD", FC_ORANGE)) show_add_widget_modal_ = true;+ ImGui::SameLine(0, 4);+ if (mini_button("TEMPLATE", FC_CYAN)) show_template_picker_ = true;+ ImGui::SameLine(0, 4);+ if (mini_button("REFRESH", FC_GREEN)) DashboardData::instance().refresh_all();+ ImGui::SameLine(0, 4);++ // Refresh interval combo+ ImGui::PushItemWidth(48);+ ImGui::PushStyleColor(ImGuiCol_FrameBg, ImVec4(0.08f, 0.08f, 0.08f, 1.0f));+ ImGui::PushStyleColor(ImGuiCol_Text, FC_GRAY);+ const char* intervals[] = {"1m", "5m", "10m", "30m"};+ float interval_secs[] = {60.0f, 300.0f, 600.0f, 1800.0f};+ if (ImGui::Combo("##iv", &refresh_interval_idx_, intervals, 4)) {+ DashboardData::instance().set_refresh_interval(interval_secs[refresh_interval_idx_]);+ }+ ImGui::PopStyleColor(2);+ ImGui::PopItemWidth();++ ImGui::SameLine(0, 4);+ ImGui::TextColored(FC_BORDER, "|");+ ImGui::SameLine(0, 4);++ // Market Pulse toggle+ if (mini_button(layout_.market_pulse_open ? "PULSE [ON]" : "PULSE [OFF]",+ layout_.market_pulse_open ? FC_ORANGE : FC_GRAY)) {+ layout_.market_pulse_open = !layout_.market_pulse_open;+ save_layout();+ }++ // Right: session uptime (push to far right)+ auto elapsed = std::chrono::steady_clock::now() - session_start_;+ int secs = (int)std::chrono::duration_cast<std::chrono::seconds>(elapsed).count();+ char uptime[16];+ std::snprintf(uptime, sizeof(uptime), "%02d:%02d:%02d", secs / 3600, (secs % 3600) / 60, secs % 60);++ float uptxt_w = ImGui::CalcTextSize("00:00:00").x + ImGui::CalcTextSize("SESSION:").x + 12;+ float cur_x = ImGui::GetCursorPosX();+ float right_x = width - uptxt_w - 8;+ if (right_x > cur_x + 8) {+ ImGui::SameLine(right_x);+ ImGui::TextColored(FC_GRAY, "SESSION:");+ ImGui::SameLine(0, 4);+ ImGui::TextColored(FC_CYAN, "%s", uptime);+ }++ ImGui::EndChild();+ ImGui::PopStyleColor();+}++// ============================================================================+// Ticker Bar — Real scrolling market data+// ============================================================================+void DashboardScreen::render_ticker_bar(float width) {+ ImGui::PushStyleColor(ImGuiCol_ChildBg, ImVec4(0.02f, 0.02f, 0.02f, 1.0f));+ ImGui::BeginChild("##ticker_bar", ImVec2(width, 20), false);++ auto ticker_quotes = DashboardData::instance().get_quotes(DataCategory::Ticker);++ if (ticker_quotes.empty()) {+ ImGui::SetCursorPos(ImVec2(width / 2 - 60, 2));+ ImGui::TextColored(FC_MUTED, "Loading market data...");+ ImGui::EndChild();+ ImGui::PopStyleColor();+ return;+ }++ ticker_offset_ -= ImGui::GetIO().DeltaTime * 55.0f;++ float total_w = 0;+ for (auto& q : ticker_quotes) {+ char buf[64];+ std::snprintf(buf, sizeof(buf), "%s %.2f %+.2f%% ", q.label.c_str(), q.price, q.change_percent);+ total_w += ImGui::CalcTextSize(buf).x;+ }+ if (total_w > 0 && ticker_offset_ < -total_w) ticker_offset_ = width;++ ImGui::SetCursorPos(ImVec2(0, 2));++ float cur_x = ticker_offset_;+ for (auto& q : ticker_quotes) {+ if (cur_x > width + 200) break;+ if (cur_x > -200) {+ ImGui::SetCursorPosX(cur_x);+ ImGui::TextColored(FC_WHITE, "%s", q.label.c_str());+ ImGui::SameLine(0, 3);+ ImGui::TextColored(FC_GRAY, "%s", fmt_price(q.price).c_str());+ ImGui::SameLine(0, 3);+ ImGui::TextColored(chg_col(q.change_percent), "%+.2f%%", q.change_percent);+ ImGui::SameLine(0, 14);+ cur_x = ImGui::GetCursorPosX();+ } else {+ char buf[64];+ std::snprintf(buf, sizeof(buf), "%s %.2f %+.2f%%", q.label.c_str(), q.price, q.change_percent);+ cur_x += ImGui::CalcTextSize(buf).x + 18;+ }+ }++ ImGui::EndChild();+ ImGui::PopStyleColor();+}++// ============================================================================+// F-Key Bar (removed separate toolbar — merged Add Widget into header)+// ============================================================================+void DashboardScreen::render_fkey_bar(float width) {+ // Skip F-key bar if window too narrow+ if (width < 600) return;++ ImGui::PushStyleColor(ImGuiCol_ChildBg, ImVec4(0.03f, 0.03f, 0.03f, 1.0f));+ ImGui::BeginChild("##fkey_bar", ImVec2(width, 22), false);+ ImGui::SetCursorPos(ImVec2(4, 2));++ struct FKey { const char* label; ImVec4 color; };+ FKey keys[] = {+ {"F1:HELP", FC_GRAY}, {"F2:MKT", FC_ORANGE}, {"F3:NEWS", FC_ORANGE},+ {"F4:PORT", FC_GREEN}, {"F5:MOV", FC_PURPLE}, {"F6:ECON", FC_YELLOW},+ {"F7:CHT", FC_CYAN}, {"F8:TRD", FC_GREEN}, {"F9:CRY", FC_CYAN},+ {"F10:FX", FC_YELLOW}, {"F11:CMD", FC_ORANGE}, {"F12:SET", FC_GRAY}+ };++ float avail = width - 8;+ float btn_w = avail / 12.0f - 2.0f;+ if (btn_w < 30) btn_w = 30;++ for (int i = 0; i < 12; i++) {+ float used = ImGui::GetCursorPosX();+ if (used + btn_w > width - 4) break; // stop if overflow++ ImGui::PushStyleColor(ImGuiCol_Button, ImVec4(0.06f, 0.06f, 0.06f, 1.0f));+ ImGui::PushStyleColor(ImGuiCol_ButtonHovered, ImVec4(0.12f, 0.12f, 0.12f, 1.0f));+ ImGui::PushStyleColor(ImGuiCol_Text, keys[i].color);+ ImGui::PushStyleVar(ImGuiStyleVar_FramePadding, ImVec2(2, 1));++ ImGui::Button(keys[i].label, ImVec2(btn_w, 17));++ ImGui::PopStyleVar();+ ImGui::PopStyleColor(3);+ if (i < 11) ImGui::SameLine(0, 2);+ }++ ImGui::EndChild();+ ImGui::PopStyleColor();+}++// ============================================================================+// Toolbar — now empty stub (merged into header)+// ============================================================================+void DashboardScreen::render_toolbar(float /*width*/) {+ // All toolbar actions moved to header bar+}++// ============================================================================+// Generic quote table renderer+// ============================================================================+void DashboardScreen::render_quote_table(+ const char* table_id,+ const std::vector<QuoteEntry>& quotes,+ const char* col1, const char* col2, const char* col3,+ bool show_volume, int price_decimals)+{+ int num_cols = show_volume ? 4 : 3;+ ImGuiTableFlags flags = ImGuiTableFlags_RowBg | ImGuiTableFlags_ScrollY |+ ImGuiTableFlags_SizingStretchProp;++ if (ImGui::BeginTable(table_id, num_cols, flags,+ ImVec2(0, ImGui::GetContentRegionAvail().y))) {+ ImGui::TableSetupColumn(col1, 0, 2.0f);+ ImGui::TableSetupColumn(col2, 0, 1.5f);+ ImGui::TableSetupColumn(col3, 0, 1.0f);+ if (show_volume) ImGui::TableSetupColumn("Vol", 0, 1.0f);+ ImGui::TableSetupScrollFreeze(0, 1);+ ImGui::TableHeadersRow();++ for (auto& q : quotes) {+ ImGui::TableNextRow();+ ImGui::TableNextColumn();+ ImGui::TextColored(FC_WHITE, "%s", q.label.c_str());+ ImGui::TableNextColumn();+ ImGui::Text("%s", fmt_price(q.price, price_decimals).c_str());+ ImGui::TableNextColumn();+ ImGui::TextColored(chg_col(q.change_percent), "%+.2f%%", q.change_percent);+ if (show_volume) {+ ImGui::TableNextColumn();+ ImGui::TextColored(FC_MUTED, "%s", fmt_volume(q.volume).c_str());+ }+ }+ ImGui::EndTable();+ }+}++// ============================================================================+// Individual widget content renderers+// ============================================================================+void DashboardScreen::widget_global_indices(float w, float h) {+ auto quotes = DashboardData::instance().get_quotes(DataCategory::Indices);+ if (auto* msg = loading_text(DashboardData::instance().is_loading(DataCategory::Indices), !quotes.empty())) {+ ImGui::TextColored(FC_MUTED, "%s", msg); return;+ }+ render_quote_table("##idx", quotes, "Index", "Value", "Chg%", false, 2);+}++void DashboardScreen::widget_forex(float w, float h) {+ auto quotes = DashboardData::instance().get_quotes(DataCategory::Forex);+ if (auto* msg = loading_text(DashboardData::instance().is_loading(DataCategory::Forex), !quotes.empty())) {+ ImGui::TextColored(FC_MUTED, "%s", msg); return;+ }+ render_quote_table("##fx", quotes, "Pair", "Rate", "Chg%", false, 4);+}++void DashboardScreen::widget_commodities(float w, float h) {+ auto quotes = DashboardData::instance().get_quotes(DataCategory::Commodities);+ if (auto* msg = loading_text(DashboardData::instance().is_loading(DataCategory::Commodities), !quotes.empty())) {+ ImGui::TextColored(FC_MUTED, "%s", msg); return;+ }+ render_quote_table("##cmd", quotes, "Commodity", "Price", "Chg%", false, 2);+}++void DashboardScreen::widget_crypto(float w, float h) {+ auto quotes = DashboardData::instance().get_quotes(DataCategory::Crypto);+ if (auto* msg = loading_text(DashboardData::instance().is_loading(DataCategory::Crypto), !quotes.empty())) {+ ImGui::TextColored(FC_MUTED, "%s", msg); return;+ }+ render_quote_table("##cry", quotes, "Token", "Price", "Chg%", true, 2);+}++void DashboardScreen::widget_sector_heatmap(float w, float h) {+ auto quotes = DashboardData::instance().get_quotes(DataCategory::SectorETFs);+ bool is_load = DashboardData::instance().is_loading(DataCategory::SectorETFs);+ if (quotes.empty()) {+ ImGui::TextColored(FC_MUTED, is_load ? "Loading sectors..." : "No sector data");+ return;+ }++ ImVec2 avail = ImGui::GetContentRegionAvail();+ if (avail.x < 20 || avail.y < 20) return;++ int n = (int)quotes.size();++ // Adaptive grid: prefer wider cells on wide widgets, more rows on tall widgets+ int cols, rows;+ if (avail.x > avail.y * 1.5f) {+ // Wide widget — more columns+ cols = std::min(n, std::max(3, (int)(avail.x / 90.0f)));+ rows = (n + cols - 1) / cols;+ } else {+ // Square or tall — balanced+ cols = std::max(2, (int)std::ceil(std::sqrt((double)n * avail.x / std::max(1.0f, avail.y))));+ cols = std::min(cols, n);+ rows = (n + cols - 1) / cols;+ }++ float gap = 2.0f;+ float cell_w = std::max(40.0f, (avail.x - (cols - 1) * gap) / cols);+ float cell_h = std::max(30.0f, (avail.y - (rows - 1) * gap) / rows);++ ImVec2 origin = ImGui::GetCursorScreenPos();+ ImDrawList* dl = ImGui::GetWindowDrawList();++ for (int i = 0; i < n; i++) {+ int r = i / cols, c = i % cols;+ float x = origin.x + c * (cell_w + gap);+ float y = origin.y + r * (cell_h + gap);+ auto& q = quotes[i];++ // Bloomberg-style heatmap colors: deeper saturation+ float pct = (float)q.change_percent;+ float intensity = std::min(std::abs(pct) / 3.5f, 1.0f);+ ImU32 bg;+ if (pct > 0) {+ // Green gradient: dark green → bright green+ int g_val = (int)(40 + 170 * intensity);+ int r_val = (int)(10 * (1.0f - intensity));+ bg = IM_COL32(r_val, g_val, (int)(15 * intensity), 230);+ } else if (pct < 0) {+ // Red gradient: dark red → bright red+ int r_val = (int)(50 + 170 * intensity);+ int g_val = (int)(10 * (1.0f - intensity));+ bg = IM_COL32(r_val, g_val, 0, 230);+ } else {+ bg = IM_COL32(45, 45, 45, 230);+ }++ dl->AddRectFilled(ImVec2(x, y), ImVec2(x + cell_w, y + cell_h), bg, 3.0f);++ // Subtle border+ ImU32 border_col = pct > 0 ? IM_COL32(0, 180, 80, 60) :+ (pct < 0 ? IM_COL32(180, 40, 40, 60) : IM_COL32(60, 60, 60, 80));+ dl->AddRect(ImVec2(x, y), ImVec2(x + cell_w, y + cell_h), border_col, 3.0f);++ // Compute font size so full label text fits the cell width+ float default_fs = ImGui::GetFontSize();+ float max_text_w = cell_w - 6.0f;++ const char* lbl = q.label.c_str();+ ImVec2 ts_full = ImGui::CalcTextSize(lbl);+ // Scale font down if label is wider than cell, minimum 8px+ float lbl_fs = default_fs;+ if (ts_full.x > max_text_w && ts_full.x > 0) {+ lbl_fs = default_fs * (max_text_w / ts_full.x);+ if (lbl_fs < 8.0f) lbl_fs = 8.0f;+ }+ float lbl_h = lbl_fs; // approx line height at this font size++ // Change percent text — always at default or slightly smaller+ char val[16];+ std::snprintf(val, sizeof(val), "%+.2f%%", pct);+ ImVec2 vs_full = ImGui::CalcTextSize(val);+ float val_fs = default_fs;+ if (vs_full.x > max_text_w && vs_full.x > 0) {+ val_fs = default_fs * (max_text_w / vs_full.x);+ if (val_fs < 8.0f) val_fs = 8.0f;+ }+ float val_h = val_fs;++ // Price line (optional third line)+ char price_buf[24] = {};+ float price_fs = 0, price_h = 0;+ bool show_price = false;+ if (q.price > 0) {+ std::snprintf(price_buf, sizeof(price_buf), "$%s", fmt_price(q.price).c_str());+ ImVec2 ps_full = ImGui::CalcTextSize(price_buf);+ price_fs = default_fs * 0.85f;+ if (ps_full.x * (price_fs / default_fs) > max_text_w && ps_full.x > 0) {+ price_fs = default_fs * (max_text_w / ps_full.x);+ if (price_fs < 7.0f) price_fs = 7.0f;+ }+ price_h = price_fs;+ // Only show price if cell is tall enough for 3 lines+ show_price = cell_h >= (lbl_h + val_h + price_h + 8.0f);+ }++ // Vertically center all lines+ float gap_between = 2.0f;+ float total_h = lbl_h + gap_between + val_h;+ if (show_price) total_h += gap_between + price_h;+ float text_y = y + std::max(2.0f, (cell_h - total_h) / 2.0f);++ // Draw label — scaled font, centered+ ImFont* font = ImGui::GetFont();+ float lbl_w = ts_full.x * (lbl_fs / default_fs);+ float tx = x + std::max(3.0f, (cell_w - lbl_w) / 2.0f);+ dl->AddText(font, lbl_fs, ImVec2(tx, text_y),+ IM_COL32(255, 255, 255, 240), lbl);++ // Draw change% — scaled font, centered, colored+ float val_w = vs_full.x * (val_fs / default_fs);+ float vx = x + std::max(3.0f, (cell_w - val_w) / 2.0f);+ ImU32 tc = pct > 0 ? IM_COL32(100, 255, 160, 255) :+ (pct < 0 ? IM_COL32(255, 120, 120, 255) : IM_COL32(140, 140, 140, 255));+ dl->AddText(font, val_fs, ImVec2(vx, text_y + lbl_h + gap_between), tc, val);++ // Draw price if space allows+ if (show_price) {+ ImVec2 ps_full2 = ImGui::CalcTextSize(price_buf);+ float pw = ps_full2.x * (price_fs / default_fs);+ float px = x + std::max(3.0f, (cell_w - pw) / 2.0f);+ dl->AddText(font, price_fs,+ ImVec2(px, text_y + lbl_h + gap_between + val_h + gap_between),+ IM_COL32(180, 180, 180, 180), price_buf);+ }+ }+ ImGui::Dummy(avail);+}++void DashboardScreen::widget_news(float w, float h) {+ auto news = DashboardData::instance().get_news();+ if (news.empty()) { ImGui::TextColored(FC_MUTED, "Loading news..."); return; }++ ImGuiTableFlags flags = ImGuiTableFlags_RowBg | ImGuiTableFlags_ScrollY |+ ImGuiTableFlags_SizingFixedFit | ImGuiTableFlags_PadOuterX;++ float avail_h = ImGui::GetContentRegionAvail().y;+ if (avail_h < 20) avail_h = 20;++ if (ImGui::BeginTable("##news_tbl", 3, flags, ImVec2(0, avail_h))) {+ ImGui::TableSetupColumn("Time", ImGuiTableColumnFlags_WidthFixed, 42.0f);+ ImGui::TableSetupColumn("Source", ImGuiTableColumnFlags_WidthFixed, 70.0f);+ ImGui::TableSetupColumn("Headline", ImGuiTableColumnFlags_WidthStretch);+ ImGui::TableSetupScrollFreeze(0, 1);+ ImGui::TableHeadersRow();++ for (size_t i = 0; i < news.size(); i++) {+ auto& item = news[i];+ ImGui::TableNextRow();++ // Time column+ ImGui::TableNextColumn();+ ImGui::TextColored(FC_MUTED, "%s", item.time_str.c_str());++ // Source column+ ImGui::TableNextColumn();+ if (item.priority <= 1) {+ ImGui::TextColored(FC_RED, "[!]");+ ImGui::SameLine(0, 2);+ }+ ImGui::TextColored(FC_ORANGE, "%s", item.source.c_str());++ // Headline column — wraps to available width+ ImGui::TableNextColumn();+ ImGui::PushTextWrapPos(ImGui::GetCursorPosX() + ImGui::GetContentRegionAvail().x);+ ImGui::TextColored(FC_WHITE, "%s", item.headline.c_str());+ ImGui::PopTextWrapPos();+ }+ ImGui::EndTable();+ }+}++void DashboardScreen::widget_economic(float w, float h) {+ if (ImGui::BeginTable("##eco", 3, ImGuiTableFlags_RowBg | ImGuiTableFlags_ScrollY |+ ImGuiTableFlags_SizingStretchProp, ImVec2(0, ImGui::GetContentRegionAvail().y))) {+ ImGui::TableSetupColumn("Indicator", 0, 2.5f);+ ImGui::TableSetupColumn("Value", 0, 1.0f);+ ImGui::TableSetupColumn("Chg", 0, 1.0f);+ ImGui::TableSetupScrollFreeze(0, 1);+ ImGui::TableHeadersRow();+ for (auto& e : econ_data_) {+ ImGui::TableNextRow();+ ImGui::TableNextColumn(); ImGui::TextColored(FC_WHITE, "%s", e.name.c_str());+ ImGui::TableNextColumn(); ImGui::Text("%.2f", e.value);+ ImGui::TableNextColumn(); ImGui::TextColored(chg_col(e.change), "%+.2f", e.change);+ }+ ImGui::EndTable();+ }+}++void DashboardScreen::widget_geopolitics(float w, float h) {+ if (ImGui::BeginTable("##geo", 3, ImGuiTableFlags_RowBg | ImGuiTableFlags_ScrollY |+ ImGuiTableFlags_SizingStretchProp, ImVec2(0, ImGui::GetContentRegionAvail().y))) {+ ImGui::TableSetupColumn("Region", 0, 1.8f);+ ImGui::TableSetupColumn("Risk", 0, 1.0f);+ ImGui::TableSetupColumn("Trend", 0, 1.0f);+ ImGui::TableSetupScrollFreeze(0, 1);+ ImGui::TableHeadersRow();+ for (auto& g : geo_data_) {+ ImGui::TableNextRow();+ ImGui::TableNextColumn(); ImGui::TextColored(FC_WHITE, "%s", g.region.c_str());+ ImGui::TableNextColumn();+ ImVec4 rc = g.risk > 70 ? FC_RED : (g.risk > 50 ? FC_YELLOW : FC_GREEN);+ ImGui::TextColored(rc, "%.1f", g.risk);+ ImGui::TableNextColumn();+ ImGui::TextColored(chg_col(g.trend), "%+.1f", g.trend);+ }+ ImGui::EndTable();+ }+}++void DashboardScreen::widget_performance(float w, float h) {+ if (ImGui::BeginTable("##perf", 2, ImGuiTableFlags_RowBg | ImGuiTableFlags_ScrollY |+ ImGuiTableFlags_SizingStretchProp, ImVec2(0, ImGui::GetContentRegionAvail().y))) {+ ImGui::TableSetupColumn("Metric", 0, 2.0f);+ ImGui::TableSetupColumn("Value", 0, 1.5f);+ ImGui::TableSetupScrollFreeze(0, 1);+ ImGui::TableHeadersRow();+ for (auto& p : perf_data_) {+ ImGui::TableNextRow();+ ImGui::TableNextColumn(); ImGui::TextColored(FC_WHITE, "%s", p.metric.c_str());+ ImGui::TableNextColumn();+ if (p.value != 0)+ ImGui::TextColored(chg_col(p.change), "$%s (%+.2f%%)", fmt_price(p.value).c_str(), p.change);+ else+ ImGui::TextColored(chg_col(p.change), "%+.2f%%", p.change);+ }+ ImGui::EndTable();+ }+}++void DashboardScreen::widget_top_movers(float w, float h) {+ auto quotes = DashboardData::instance().get_quotes(DataCategory::TopMovers);+ if (auto* msg = loading_text(DashboardData::instance().is_loading(DataCategory::TopMovers), !quotes.empty())) {+ ImGui::TextColored(FC_MUTED, "%s", msg); return;+ }+ auto sorted = quotes;+ std::sort(sorted.begin(), sorted.end(), [](const QuoteEntry& a, const QuoteEntry& b) {+ return std::abs(a.change_percent) > std::abs(b.change_percent);+ });+ render_quote_table("##movers", sorted, "Stock", "Price", "Chg%", true, 2);+}++void DashboardScreen::widget_market_data(float w, float h) {+ auto quotes = DashboardData::instance().get_quotes(DataCategory::Indices);+ render_quote_table("##mktdata", quotes, "Symbol", "Price", "Chg%", true, 2);+}++// ============================================================================+// Widget Frame+// ============================================================================+void DashboardScreen::render_widget_frame(const char* title, const ImVec4& accent,+ float w, float h, WidgetType type) {+ if (w < 20 || h < 20) return; // skip too-small widgets++ ImGui::PushStyleColor(ImGuiCol_ChildBg, FC_PANEL);+ ImGui::PushStyleColor(ImGuiCol_Border, FC_BORDER);+ ImGui::PushStyleVar(ImGuiStyleVar_ChildBorderSize, 1.0f);+ ImGui::PushStyleVar(ImGuiStyleVar_ChildRounding, 2.0f);++ std::string id = std::string("##wf_") + title;+ ImGui::BeginChild(id.c_str(), ImVec2(w, h), ImGuiChildFlags_Borders);++ float hdr_h = 22.0f;+ ImVec2 hdr_start = ImGui::GetCursorScreenPos();+ ImDrawList* dl = ImGui::GetWindowDrawList();++ // Header bg+ dl->AddRectFilled(hdr_start, ImVec2(hdr_start.x + w, hdr_start.y + hdr_h),+ ImGui::ColorConvertFloat4ToU32(FC_HEADER));+ // Accent line+ dl->AddRectFilled(hdr_start, ImVec2(hdr_start.x + w, hdr_start.y + 2),+ ImGui::ColorConvertFloat4ToU32(accent));++ // Title+ ImGui::SetCursorPosX(6);+ ImGui::SetCursorPosY(4);+ ImGui::TextColored(accent, "%s", title);++ // Loading indicator+ DataCategory data_cat = DataCategory::Indices;+ switch (type) {+ case WidgetType::GlobalIndices: data_cat = DataCategory::Indices; break;+ case WidgetType::Forex: data_cat = DataCategory::Forex; break;+ case WidgetType::Commodities: data_cat = DataCategory::Commodities; break;+ case WidgetType::Crypto: data_cat = DataCategory::Crypto; break;+ case WidgetType::SectorHeatmap: data_cat = DataCategory::SectorETFs; break;+ case WidgetType::TopMovers: data_cat = DataCategory::TopMovers; break;+ default: break;+ }+ if (DashboardData::instance().is_loading(data_cat)) {+ ImGui::SameLine(0, 6);+ ImGui::TextColored(FC_YELLOW, "(...)");+ }++ // Close button+ float close_x = w - 18;+ if (close_x > ImGui::GetCursorPosX() + 20) {+ ImGui::SameLine(close_x);+ ImGui::SetCursorPosY(3);+ ImGui::PushStyleColor(ImGuiCol_Button, ImVec4(0, 0, 0, 0));+ ImGui::PushStyleColor(ImGuiCol_ButtonHovered, ImVec4(1, 0, 0, 0.3f));+ ImGui::PushStyleColor(ImGuiCol_Text, FC_MUTED);+ std::string close_id = std::string("x##c_") + title;+ if (ImGui::SmallButton(close_id.c_str())) {+ for (auto& wi : layout_.widgets) {+ if (wi.title == title) { remove_widget(wi.id); break; }+ }+ }+ ImGui::PopStyleColor(3);+ }++ // Content+ ImGui::SetCursorPosY(hdr_h + 2);+ float content_h = h - hdr_h - 4;+ if (content_h < 10) content_h = 10;++ ImGui::PushStyleVar(ImGuiStyleVar_WindowPadding, ImVec2(4, 2));+ ImGui::BeginChild((std::string("##wc_") + title).c_str(), ImVec2(w - 2, content_h), false);++ switch (type) {+ case WidgetType::GlobalIndices: widget_global_indices(w, content_h); break;+ case WidgetType::Forex: widget_forex(w, content_h); break;+ case WidgetType::Commodities: widget_commodities(w, content_h); break;+ case WidgetType::Crypto: widget_crypto(w, content_h); break;+ case WidgetType::SectorHeatmap: widget_sector_heatmap(w, content_h); break;+ case WidgetType::News: widget_news(w, content_h); break;+ case WidgetType::EconomicIndicators: widget_economic(w, content_h); break;+ case WidgetType::GeopoliticalRisk: widget_geopolitics(w, content_h); break;+ case WidgetType::Performance: widget_performance(w, content_h); break;+ case WidgetType::TopMovers: widget_top_movers(w, content_h); break;+ case WidgetType::MarketData: widget_market_data(w, content_h); break;+ default: ImGui::TextColored(FC_MUTED, "Unknown widget"); break;+ }++ ImGui::EndChild();+ ImGui::PopStyleVar();++ ImGui::EndChild();+ ImGui::PopStyleVar(2);+ ImGui::PopStyleColor(2);+}++// ============================================================================+// Market Pulse Panel (Right Sidebar) — responsive to width+// ============================================================================+void DashboardScreen::render_market_pulse(float width, float height) {+ ImGui::PushStyleColor(ImGuiCol_ChildBg, ImVec4(0.04f, 0.04f, 0.04f, 1.0f));+ ImGui::PushStyleColor(ImGuiCol_Border, FC_BORDER);+ ImGui::PushStyleVar(ImGuiStyleVar_ChildBorderSize, 1.0f);+ ImGui::BeginChild("##market_pulse", ImVec2(width, height), ImGuiChildFlags_Borders);++ float pad = 8.0f;+ float inner_w = width - pad * 2;++ // Title+ ImGui::SetCursorPos(ImVec2(pad, 4));+ ImGui::TextColored(FC_ORANGE, "MARKET PULSE");+ ImGui::Spacing();+ ImGui::PushStyleColor(ImGuiCol_Separator, FC_BORDER);+ ImGui::Separator();+ ImGui::PopStyleColor();++ // ---- Fear & Greed Gauge ----+ ImGui::Spacing();+ ImGui::SetCursorPosX(pad);+ ImGui::TextColored(FC_GRAY, "FEAR & GREED");++ auto pulse_quotes = DashboardData::instance().get_quotes(DataCategory::MarketPulse);+ float vix_val = 0;+ for (auto& q : pulse_quotes) {+ if (q.symbol == "^VIX") { vix_val = (float)q.price; break; }+ }++ float fear_greed = vix_val > 0 ?+ std::max(0.0f, std::min(100.0f, 100.0f - (vix_val - 10.0f) * 3.0f)) : 55.0f;++ // Gradient bar+ ImVec2 bar_start = ImGui::GetCursorScreenPos();+ bar_start.x += pad;+ float bar_w = inner_w;+ float bar_h = 6.0f;+ ImDrawList* dl = ImGui::GetWindowDrawList();++ for (int i = 0; i < (int)bar_w; i++) {+ float t = (float)i / bar_w;+ int r, g;+ if (t < 0.5f) { r = 255; g = (int)(t * 2 * 255); }+ else { r = (int)((1.0f - (t - 0.5f) * 2) * 255); g = 255; }+ dl->AddRectFilled(+ ImVec2(bar_start.x + i, bar_start.y),+ ImVec2(bar_start.x + i + 1, bar_start.y + bar_h),+ IM_COL32(r, g, 0, 180));+ }++ float ptr_x = bar_start.x + (fear_greed / 100.0f) * bar_w;+ dl->AddTriangleFilled(+ ImVec2(ptr_x - 3, bar_start.y + bar_h + 1),+ ImVec2(ptr_x + 3, bar_start.y + bar_h + 1),+ ImVec2(ptr_x, bar_start.y + bar_h - 2),+ IM_COL32(255, 255, 255, 220));++ ImGui::Dummy(ImVec2(bar_w, bar_h + 6));++ const char* fg_label = fear_greed <= 25 ? "FEAR" : fear_greed <= 50 ? "CAUTIOUS" :+ fear_greed <= 75 ? "NEUTRAL" : "GREED";+ ImVec4 fg_color = fear_greed <= 25 ? FC_RED : fear_greed <= 50 ? FC_ORANGE :+ fear_greed <= 75 ? FC_YELLOW : FC_GREEN;++ ImGui::SetCursorPosX(pad);+ ImGui::TextColored(fg_color, "%.0f %s", fear_greed, fg_label);++ ImGui::Spacing();+ ImGui::PushStyleColor(ImGuiCol_Separator, FC_BORDER); ImGui::Separator(); ImGui::PopStyleColor();++ // ---- Global Snapshot ----+ ImGui::Spacing();+ ImGui::SetCursorPosX(pad);+ ImGui::TextColored(FC_GRAY, "GLOBAL SNAPSHOT");+ ImGui::Spacing();++ if (!pulse_quotes.empty()) {+ // Use a table for proper alignment+ if (ImGui::BeginTable("##pulse_snap", 3, ImGuiTableFlags_SizingStretchProp,+ ImVec2(inner_w, 0))) {+ ImGui::TableSetupColumn("Name", 0, 1.2f);+ ImGui::TableSetupColumn("Price", 0, 1.0f);+ ImGui::TableSetupColumn("Chg", 0, 0.9f);+ for (auto& q : pulse_quotes) {+ ImGui::TableNextRow();+ ImGui::TableNextColumn(); ImGui::TextColored(FC_WHITE, "%s", q.label.c_str());+ ImGui::TableNextColumn(); ImGui::Text("%s", fmt_price(q.price).c_str());+ ImGui::TableNextColumn(); ImGui::TextColored(chg_col(q.change_percent), "%+.2f%%", q.change_percent);+ }+ ImGui::EndTable();+ }+ } else {+ ImGui::SetCursorPosX(pad);+ ImGui::TextColored(FC_MUTED, "Loading...");+ }++ ImGui::Spacing();+ ImGui::PushStyleColor(ImGuiCol_Separator, FC_BORDER); ImGui::Separator(); ImGui::PopStyleColor();++ // ---- Top Movers ----+ ImGui::Spacing();+ ImGui::SetCursorPosX(pad);+ ImGui::TextColored(FC_GRAY, "TOP MOVERS");+ ImGui::Spacing();++ auto movers = DashboardData::instance().get_quotes(DataCategory::TopMovers);+ if (!movers.empty()) {+ auto sorted = movers;+ std::sort(sorted.begin(), sorted.end(), [](const QuoteEntry& a, const QuoteEntry& b) {+ return std::abs(a.change_percent) > std::abs(b.change_percent);+ });+ int show = std::min(6, (int)sorted.size());++ if (ImGui::BeginTable("##pulse_movers", 3, ImGuiTableFlags_SizingStretchProp,+ ImVec2(inner_w, 0))) {+ ImGui::TableSetupColumn("Dir", 0, 0.8f);+ ImGui::TableSetupColumn("Name", 0, 1.5f);+ ImGui::TableSetupColumn("Price", 0, 1.0f);+ for (int i = 0; i < show; i++) {+ auto& q = sorted[i];+ ImGui::TableNextRow();+ ImGui::TableNextColumn();+ ImGui::TextColored(chg_col(q.change_percent), "%s%+.1f%%",+ q.change_percent >= 0 ? "+" : "", q.change_percent);+ ImGui::TableNextColumn();+ ImGui::TextColored(FC_WHITE, "%s", q.label.c_str());+ ImGui::TableNextColumn();+ ImGui::TextColored(FC_GRAY, "$%s", fmt_price(q.price).c_str());+ }+ ImGui::EndTable();+ }+ } else {+ ImGui::SetCursorPosX(pad);+ ImGui::TextColored(FC_MUTED, "Loading...");+ }++ ImGui::Spacing();+ ImGui::PushStyleColor(ImGuiCol_Separator, FC_BORDER); ImGui::Separator(); ImGui::PopStyleColor();++ // ---- Market Breadth ----+ ImGui::Spacing();+ ImGui::SetCursorPosX(pad);+ ImGui::TextColored(FC_GRAY, "MARKET BREADTH");+ ImGui::Spacing();++ auto indices = DashboardData::instance().get_quotes(DataCategory::Indices);+ if (!indices.empty()) {+ int advancing = 0, declining = 0;+ for (auto& q : indices) {+ if (q.change_percent > 0) advancing++;+ else if (q.change_percent < 0) declining++;+ }+ int total = (int)indices.size();++ ImGui::SetCursorPosX(pad);+ ImGui::TextColored(FC_GREEN, "Adv: %d", advancing);+ ImGui::SameLine(0, 8);+ ImGui::TextColored(FC_RED, "Dec: %d", declining);+ ImGui::SameLine(0, 8);+ ImGui::TextColored(FC_GRAY, "Unch: %d", total - advancing - declining);++ if (total > 0) {+ float adv_pct = (float)advancing / total;+ ImVec2 p = ImGui::GetCursorScreenPos();+ p.x += pad;+ float bw = inner_w;+ dl = ImGui::GetWindowDrawList();+ dl->AddRectFilled(ImVec2(p.x, p.y), ImVec2(p.x + bw * adv_pct, p.y + 5),+ ImGui::ColorConvertFloat4ToU32(FC_GREEN), 2.0f);+ dl->AddRectFilled(ImVec2(p.x + bw * adv_pct, p.y), ImVec2(p.x + bw, p.y + 5),+ ImGui::ColorConvertFloat4ToU32(FC_RED), 2.0f);+ ImGui::Dummy(ImVec2(bw, 8));+ }+ }++ ImGui::EndChild();+ ImGui::PopStyleVar();+ ImGui::PopStyleColor(2);+}++// ============================================================================+// Widget Grid — positions widgets using absolute cursor positions+// ============================================================================+void DashboardScreen::render_widget_grid(float width, float height) {+ float gap = 4.0f;++ // Find grid dimensions from layout+ int max_col = 0, max_row = 0;+ for (auto& w : layout_.widgets) {+ if (!w.visible) continue;+ max_col = std::max(max_col, w.col + w.col_span);+ max_row = std::max(max_row, w.row + w.row_span);+ }+ if (max_col == 0) max_col = layout_.grid_cols;+ if (max_row == 0) max_row = layout_.grid_rows;++ float cell_w = (width - (max_col + 1) * gap) / max_col;+ float cell_h = (height - (max_row + 1) * gap) / max_row;++ // Ensure minimum sizes+ cell_w = std::max(100.0f, cell_w);+ cell_h = std::max(60.0f, cell_h);++ // Allow scrolling if content overflows+ bool needs_scroll = (max_row * (cell_h + gap) + gap) > height;+ ImGuiWindowFlags flags = needs_scroll ? 0 : ImGuiWindowFlags_NoScrollbar;++ ImGui::BeginChild("##grid", ImVec2(width, height), false, flags);++ for (auto& w : layout_.widgets) {+ if (!w.visible) continue;++ float wx = gap + w.col * (cell_w + gap);+ float wy = gap + w.row * (cell_h + gap);+ float ww = w.col_span * cell_w + (w.col_span - 1) * gap;+ float wh = w.row_span * cell_h + (w.row_span - 1) * gap;++ ImGui::SetCursorPos(ImVec2(wx, wy));+ render_widget_frame(w.title.c_str(), accent_for(w.type), ww, wh, w.type);+ }++ ImGui::EndChild();+}++// ============================================================================+// Add Widget Modal+// ============================================================================+void DashboardScreen::render_add_widget_modal() {+ if (!show_add_widget_modal_) return;++ ImVec2 center = ImGui::GetMainViewport()->GetCenter();+ ImGui::SetNextWindowPos(center, ImGuiCond_Appearing, ImVec2(0.5f, 0.5f));+ ImGui::SetNextWindowSize(ImVec2(420, 380), ImGuiCond_FirstUseEver);++ ImGui::PushStyleColor(ImGuiCol_WindowBg, ImVec4(0.06f, 0.06f, 0.06f, 0.97f));+ ImGui::PushStyleColor(ImGuiCol_TitleBgActive, FC_HEADER);++ if (ImGui::Begin("Add Widget##modal", &show_add_widget_modal_,+ ImGuiWindowFlags_NoCollapse | ImGuiWindowFlags_NoDocking)) {++ ImGui::TextColored(FC_ORANGE, "Select widget to add:");+ ImGui::Spacing();+ ImGui::Separator();+ ImGui::Spacing();++ for (int i = 0; i < static_cast<int>(WidgetType::Count); i++) {+ auto type = static_cast<WidgetType>(i);+ ImVec4 accent = accent_for(type);++ ImGui::PushStyleColor(ImGuiCol_Button, ImVec4(0.08f, 0.08f, 0.08f, 1.0f));+ ImGui::PushStyleColor(ImGuiCol_ButtonHovered,+ ImVec4(accent.x * 0.3f, accent.y * 0.3f, accent.z * 0.3f, 1.0f));+ ImGui::PushStyleColor(ImGuiCol_Text, accent);++ if (ImGui::Button(widget_type_name(type), ImVec2(-1, 26))) {+ add_widget(type);+ show_add_widget_modal_ = false;+ }+ ImGui::PopStyleColor(3);+ }+ }+ ImGui::End();+ ImGui::PopStyleColor(2);+}++// ============================================================================+// Template Picker Modal+// ============================================================================+void DashboardScreen::render_template_picker_modal() {+ if (!show_template_picker_) return;++ ImVec2 center = ImGui::GetMainViewport()->GetCenter();+ ImGui::SetNextWindowPos(center, ImGuiCond_Appearing, ImVec2(0.5f, 0.5f));+ ImGui::SetNextWindowSize(ImVec2(500, 340), ImGuiCond_FirstUseEver);++ ImGui::PushStyleColor(ImGuiCol_WindowBg, ImVec4(0.06f, 0.06f, 0.06f, 0.97f));+ ImGui::PushStyleColor(ImGuiCol_TitleBgActive, FC_HEADER);++ if (ImGui::Begin("Dashboard Templates##modal", &show_template_picker_,+ ImGuiWindowFlags_NoCollapse | ImGuiWindowFlags_NoDocking)) {++ ImGui::TextColored(FC_ORANGE, "Choose a layout:");+ ImGui::Spacing();+ ImGui::Separator();+ ImGui::Spacing();++ for (auto& t : get_all_templates()) {+ bool is_current = (layout_.template_id == t.id);+ ImGui::PushStyleColor(ImGuiCol_Button,+ is_current ? ImVec4(0.15f, 0.08f, 0.0f, 1.0f) : ImVec4(0.08f, 0.08f, 0.08f, 1.0f));+ ImGui::PushStyleColor(ImGuiCol_ButtonHovered, ImVec4(0.2f, 0.12f, 0.0f, 1.0f));++ std::string label = std::string("[") + t.tag + "] " + t.name;+ if (is_current) label += " (ACTIVE)";++ if (ImGui::Button(label.c_str(), ImVec2(-1, 0))) {+ apply_template(t.id);+ show_template_picker_ = false;+ }+ ImGui::PopStyleColor(2);++ ImGui::PushStyleColor(ImGuiCol_Text, FC_GRAY);+ ImGui::TextWrapped(" %s", t.description.c_str());+ ImGui::PopStyleColor();+ ImGui::Spacing();+ }+ }+ ImGui::End();+ ImGui::PopStyleColor(2);+}++// ============================================================================+// Status Bar+// ============================================================================+void DashboardScreen::render_status_bar(float width) {+ ImGui::PushStyleColor(ImGuiCol_ChildBg, FC_HEADER);+ ImGui::BeginChild("##dash_status", ImVec2(width, 20), false);++ ImGui::SetCursorPos(ImVec2(8, 3));++ ImGui::TextColored(FC_ORANGE, "v3.3.1");+ ImGui::SameLine(0, 8);+ ImGui::TextColored(FC_BORDER, "|");+ ImGui::SameLine(0, 8);+ ImGui::TextColored(FC_GRAY, "LAYOUT:");+ ImGui::SameLine(0, 3);+ ImGui::TextColored(FC_GREEN, "%s", layout_.template_id.c_str());+ ImGui::SameLine(0, 8);+ ImGui::TextColored(FC_BORDER, "|");+ ImGui::SameLine(0, 8);++ // Feed indicators+ struct FeedInfo { const char* label; DataCategory cat; };+ FeedInfo feeds[] = {+ {"EQ", DataCategory::Indices}, {"FX", DataCategory::Forex},+ {"CM", DataCategory::Commodities}, {"CR", DataCategory::Crypto},+ {"SC", DataCategory::SectorETFs}+ };+ for (int i = 0; i < 5; i++) {+ bool has = DashboardData::instance().has_data(feeds[i].cat);+ bool ld = DashboardData::instance().is_loading(feeds[i].cat);+ ImVec4 col = has ? FC_GREEN : (ld ? FC_YELLOW : FC_RED);+ ImGui::TextColored(col, "[*]%s", feeds[i].label);+ if (i < 4) ImGui::SameLine(0, 3);+ }++ // Right: status+ float right_x = width - 60;+ float cur = ImGui::GetCursorPosX();+ if (right_x > cur + 10) {+ ImGui::SameLine(right_x);+ bool ok = DashboardData::instance().has_data(DataCategory::Indices);+ ImGui::TextColored(ok ? FC_GREEN : FC_YELLOW, ok ? "READY" : "LOADING");+ }++ ImGui::EndChild();+ ImGui::PopStyleColor();+}++// ============================================================================+// MAIN RENDER+// ============================================================================+void DashboardScreen::render() {+ init();++ DashboardData::instance().update(ImGui::GetIO().DeltaTime);++ ImGuiViewport* vp = ImGui::GetMainViewport();+ float tab_bar_h = ImGui::GetFrameHeight() + 4;+ float footer_h = ImGui::GetFrameHeight();++ float work_y = vp->WorkPos.y + tab_bar_h;+ float work_h = vp->WorkSize.y - tab_bar_h - footer_h;+ float work_w = vp->WorkSize.x;++ ImGui::SetNextWindowPos(ImVec2(vp->WorkPos.x, work_y));+ ImGui::SetNextWindowSize(ImVec2(work_w, work_h));++ ImGui::PushStyleVar(ImGuiStyleVar_WindowPadding, ImVec2(0, 0));+ ImGui::PushStyleVar(ImGuiStyleVar_WindowBorderSize, 0);+ ImGui::PushStyleColor(ImGuiCol_WindowBg, FC_DARK);++ ImGui::Begin("##dash", nullptr,+ ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_NoResize | ImGuiWindowFlags_NoMove |+ ImGuiWindowFlags_NoCollapse | ImGuiWindowFlags_NoDocking |+ ImGuiWindowFlags_NoBringToFrontOnFocus | ImGuiWindowFlags_NoScrollbar |+ ImGuiWindowFlags_NoScrollWithMouse);++ float content_w = ImGui::GetContentRegionAvail().x;++ // Fixed heights+ float header_h = 30;+ float accent_h = 2;+ float fkey_h = 0; // F-key bar removed+ float ticker_h = 20;+ float status_h = 0; // status bar removed — app-level footer handles session/API info++ // Header bar (with Add Widget, Template, Refresh, Pulse toggle)+ render_header_bar(content_w);++ // Orange accent line+ {+ ImVec2 p = ImGui::GetCursorScreenPos();+ ImGui::GetWindowDrawList()->AddRectFilled(p, ImVec2(p.x + content_w, p.y + accent_h),+ ImGui::ColorConvertFloat4ToU32(FC_ORANGE));+ ImGui::Dummy(ImVec2(content_w, accent_h));+ }++ // Ticker bar+ render_ticker_bar(content_w);++ // Main area: widget grid + market pulse+ float grid_area_h = ImGui::GetContentRegionAvail().y - status_h;+ if (grid_area_h < 100) grid_area_h = 100;++ float pulse_w = layout_.market_pulse_open ? std::max(280.0f, std::min(340.0f, content_w * 0.25f)) : 0.0f;+ float grid_w = content_w - pulse_w;++ // Use a table layout for proper side-by-side+ if (ImGui::BeginTable("##main_layout", layout_.market_pulse_open ? 2 : 1,+ ImGuiTableFlags_SizingFixedFit | ImGuiTableFlags_NoHostExtendX,+ ImVec2(content_w, grid_area_h))) {+ if (layout_.market_pulse_open) {+ ImGui::TableSetupColumn("grid", ImGuiTableColumnFlags_WidthFixed, grid_w);+ ImGui::TableSetupColumn("pulse", ImGuiTableColumnFlags_WidthFixed, pulse_w);+ } else {+ ImGui::TableSetupColumn("grid", ImGuiTableColumnFlags_WidthFixed, content_w);+ }++ ImGui::TableNextRow(0, grid_area_h);++ ImGui::TableNextColumn();+ render_widget_grid(grid_w, grid_area_h);++ if (layout_.market_pulse_open) {+ ImGui::TableNextColumn();+ render_market_pulse(pulse_w, grid_area_h);+ }++ ImGui::EndTable();+ }++ ImGui::End();+ ImGui::PopStyleColor();+ ImGui::PopStyleVar(2);++ // Modals (rendered outside main window)+ render_add_widget_modal();+ render_template_picker_modal();+}++} // namespace fincept::dashboarddiff --git a/fincept-cpp/src/dashboard/dashboard_screen.h b/fincept-cpp/src/dashboard/dashboard_screen.hnew file mode 100644index 000000000..8906651a5--- /dev/null+++ b/fincept-cpp/src/dashboard/dashboard_screen.h@@ -0,0 +1,96 @@+#pragma once+// Fincept Terminal Dashboard — Production Bloomberg-style widget grid+// Real data via yfinance, resizable widgets, Market Pulse sidebar, template system+// Layout: Header | F-Key Bar | Ticker | [Widget Grid + Market Pulse] | Status++#include "dashboard_data.h"+#include "widget_registry.h"+#include <imgui.h>+#include <string>+#include <vector>+#include <chrono>++namespace fincept::dashboard {++class DashboardScreen {+public:+ void render();++private:+ bool initialized_ = false;+ std::chrono::steady_clock::time_point session_start_;+ float ticker_offset_ = 0;++ // Layout state+ DashboardLayout layout_;+ bool show_add_widget_modal_ = false;+ bool show_template_picker_ = false;+ bool first_run_ = true;+ int refresh_interval_idx_ = 2; // 0=1m, 1=5m, 2=10m, 3=30m++ // Economic indicator data (hardcoded for now — FRED integration later)+ struct EconEntry { std::string name; float value; float change; };+ std::vector<EconEntry> econ_data_;++ // Geopolitics risk data (hardcoded for now — API integration later)+ struct GeoEntry { std::string region; float risk; float trend; };+ std::vector<GeoEntry> geo_data_;++ // Performance data (hardcoded for now — portfolio integration later)+ struct PerfEntry { std::string metric; float value; float change; };+ std::vector<PerfEntry> perf_data_;++ void init();+ void init_static_data(); // econ, geo, perf (until APIs are connected)++ // Top-level layout sections+ void render_header_bar(float width);+ void render_fkey_bar(float width);+ void render_ticker_bar(float width);+ void render_toolbar(float width);+ void render_widget_grid(float width, float height);+ void render_market_pulse(float width, float height);+ void render_status_bar(float width);++ // Widget frame — wraps any widget with header, accent, close button+ void render_widget_frame(const char* title, const ImVec4& accent,+ float w, float h, WidgetType type);++ // Individual widget renderers (read from DashboardData)+ void widget_global_indices(float w, float h);+ void widget_forex(float w, float h);+ void widget_commodities(float w, float h);+ void widget_crypto(float w, float h);+ void widget_sector_heatmap(float w, float h);+ void widget_news(float w, float h);+ void widget_economic(float w, float h);+ void widget_geopolitics(float w, float h);+ void widget_performance(float w, float h);+ void widget_top_movers(float w, float h);+ void widget_market_data(float w, float h);++ // Render a generic quote table (reused by many widgets)+ void render_quote_table(const char* table_id,+ const std::vector<QuoteEntry>& quotes,+ const char* col1, const char* col2, const char* col3,+ bool show_volume, int price_decimals);++ // Modals+ void render_add_widget_modal();+ void render_template_picker_modal();++ // Widget management+ void add_widget(WidgetType type);+ void remove_widget(const std::string& id);+ void apply_template(const std::string& template_id);++ // Layout persistence+ void save_layout();+ void load_layout();++ // Helpers+ static ImVec4 accent_for(WidgetType type);+ static const char* loading_text(bool loading, bool has_data);+};++} // namespace fincept::dashboarddiff --git a/fincept-cpp/src/dashboard/sidebar.cpp b/fincept-cpp/src/dashboard/sidebar.cppnew file mode 100644index 000000000..0d4bc58fe--- /dev/null+++ b/fincept-cpp/src/dashboard/sidebar.cpp@@ -0,0 +1,87 @@+#include "sidebar.h"+#include "theme/bloomberg_theme.h"+#include <imgui.h>++namespace fincept::dashboard {++void Sidebar::render() {+ ImGui::PushStyleColor(ImGuiCol_WindowBg, theme::colors::BG_DARK);+ ImGui::PushStyleVar(ImGuiStyleVar_WindowPadding, ImVec2(8, 8));++ if (ImGui::Begin("Navigation")) {+ // Bloomberg-style navigation sections+ ImGui::TextColored(theme::colors::ACCENT, "TERMINAL");+ ImGui::Spacing();++ struct NavItem {+ const char* label;+ const char* shortcut;+ bool separator_after;+ };++ NavItem core_items[] = {+ {"Dashboard", "F1", false},+ {"Markets", "F2", false},+ {"News", "F3", false},+ {"Watchlist", "F4", true},+ };++ NavItem trading_items[] = {+ {"Crypto Trading", nullptr, false},+ {"Equity Trading", nullptr, false},+ {"Algo Trading", nullptr, false},+ {"Backtesting", nullptr, true},+ };++ NavItem research_items[] = {+ {"Equity Research", nullptr, false},+ {"Screener", nullptr, false},+ {"Analytics", nullptr, false},+ {"Portfolio", nullptr, false},+ {"Derivatives", nullptr, true},+ };++ NavItem tools_items[] = {+ {"Code Editor", nullptr, false},+ {"Node Editor", nullptr, false},+ {"Excel", nullptr, false},+ {"Settings", nullptr, false},+ };++ // Render nav section+ auto render_section = [](const char* title, NavItem* items, int count) {+ ImGui::Spacing();+ ImGui::TextColored(theme::colors::TEXT_DIM, "%s", title);+ ImGui::Spacing();++ for (int i = 0; i < count; i++) {+ ImGui::PushStyleColor(ImGuiCol_Header, theme::colors::BG_WIDGET);+ ImGui::PushStyleColor(ImGuiCol_HeaderHovered, theme::colors::BG_HOVER);++ bool selected = ImGui::Selectable(items[i].label);+ if (items[i].shortcut) {+ ImGui::SameLine(ImGui::GetContentRegionAvail().x - 20);+ ImGui::TextColored(theme::colors::TEXT_DISABLED, "%s", items[i].shortcut);+ }++ ImGui::PopStyleColor(2);++ if (items[i].separator_after) {+ ImGui::Spacing();+ ImGui::Separator();+ }+ }+ };++ render_section("CORE", core_items, 4);+ render_section("TRADING", trading_items, 4);+ render_section("RESEARCH", research_items, 5);+ render_section("TOOLS", tools_items, 4);+ }+ ImGui::End();++ ImGui::PopStyleVar();+ ImGui::PopStyleColor();+}++} // namespace fincept::dashboarddiff --git a/fincept-cpp/src/dashboard/sidebar.h b/fincept-cpp/src/dashboard/sidebar.hnew file mode 100644index 000000000..1d5a012cb--- /dev/null+++ b/fincept-cpp/src/dashboard/sidebar.h@@ -0,0 +1,10 @@+#pragma once++namespace fincept::dashboard {++class Sidebar {+public:+ static void render();+};++} // namespace fincept::dashboarddiff --git a/fincept-cpp/src/dashboard/status_bar.cpp b/fincept-cpp/src/dashboard/status_bar.cppnew file mode 100644index 000000000..8eea530ab--- /dev/null+++ b/fincept-cpp/src/dashboard/status_bar.cpp@@ -0,0 +1,69 @@+#include "status_bar.h"+#include "auth/auth_manager.h"+#include "theme/bloomberg_theme.h"+#include <imgui.h>+#include <ctime>+#include <cstdio>++namespace fincept::dashboard {++void StatusBar::render() {+ ImGuiViewport* viewport = ImGui::GetMainViewport();+ float bar_height = 24.0f;++ ImGui::SetNextWindowPos(ImVec2(viewport->WorkPos.x,+ viewport->WorkPos.y + viewport->WorkSize.y - bar_height));+ ImGui::SetNextWindowSize(ImVec2(viewport->WorkSize.x, bar_height));++ ImGui::PushStyleVar(ImGuiStyleVar_WindowPadding, ImVec2(8, 3));+ ImGui::PushStyleVar(ImGuiStyleVar_WindowBorderSize, 1.0f);+ ImGui::PushStyleColor(ImGuiCol_WindowBg, theme::colors::BG_DARKEST);+ ImGui::PushStyleColor(ImGuiCol_Border, theme::colors::BORDER_DIM);++ ImGui::Begin("##StatusBar", nullptr,+ ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_NoResize | ImGuiWindowFlags_NoMove |+ ImGuiWindowFlags_NoScrollbar | ImGuiWindowFlags_NoScrollWithMouse |+ ImGuiWindowFlags_NoDocking | ImGuiWindowFlags_NoNavFocus);++ auto& auth = auth::AuthManager::instance();+ auto& session = auth.session();++ // Left: Connection status+ theme::StatusIndicator("API", true);++ ImGui::SameLine(0, 16);+ ImGui::TextColored(theme::colors::BORDER, "|");+ ImGui::SameLine(0, 16);++ // Credits+ ImGui::TextColored(theme::colors::TEXT_DIM, "Credits:");+ ImGui::SameLine(0, 4);+ ImGui::TextColored(theme::colors::MARKET_GREEN, "%.0f", session.user_info.credit_balance);++ ImGui::SameLine(0, 16);+ ImGui::TextColored(theme::colors::BORDER, "|");+ ImGui::SameLine(0, 16);++ // Session type+ ImGui::TextColored(theme::colors::TEXT_DIM, "Session:");+ ImGui::SameLine(0, 4);+ ImGui::TextColored(session.is_registered() ? theme::colors::SUCCESS : theme::colors::WARNING,+ "%s", session.is_registered() ? "Registered" : "Guest");++ // Right: Clock+ time_t now = time(nullptr);+ struct tm* tm_info = localtime(&now);+ char time_buf[32];+ std::snprintf(time_buf, sizeof(time_buf), "%02d:%02d:%02d", tm_info->tm_hour, tm_info->tm_min, tm_info->tm_sec);++ float time_width = ImGui::CalcTextSize(time_buf).x + 16;+ ImGui::SameLine(ImGui::GetWindowWidth() - time_width);+ ImGui::TextColored(theme::colors::TEXT_SECONDARY, "%s", time_buf);++ ImGui::End();++ ImGui::PopStyleColor(2);+ ImGui::PopStyleVar(2);+}++} // namespace fincept::dashboarddiff --git a/fincept-cpp/src/dashboard/status_bar.h b/fincept-cpp/src/dashboard/status_bar.hnew file mode 100644index 000000000..bf04ee742--- /dev/null+++ b/fincept-cpp/src/dashboard/status_bar.h@@ -0,0 +1,10 @@+#pragma once++namespace fincept::dashboard {++class StatusBar {+public:+ static void render();+};++} // namespace fincept::dashboarddiff --git a/fincept-cpp/src/dashboard/stock_ticker.cpp b/fincept-cpp/src/dashboard/stock_ticker.cppnew file mode 100644index 000000000..e7e67165a--- /dev/null+++ b/fincept-cpp/src/dashboard/stock_ticker.cpp@@ -0,0 +1,421 @@+#include "stock_ticker.h"+#include "theme/bloomberg_theme.h"+#include <imgui.h>+#include <nlohmann/json.hpp>+#include <cstdio>+#include <chrono>+#include <cmath>+#include <filesystem>+#include <sstream>+#include <array>++#ifdef _WIN32+#define WIN32_LEAN_AND_MEAN+#define NOMINMAX+#include <windows.h>+#elif defined(__APPLE__)+#include <mach-o/dyld.h>+#endif++namespace fincept::dashboard {++using json = nlohmann::json;++// Tickers to display — major indices, stocks, crypto, commodities+static const std::vector<std::pair<std::string, std::string>> TICKER_SYMBOLS = {+ {"^GSPC", "S&P 500"},+ {"^DJI", "DOW"},+ {"^IXIC", "NASDAQ"},+ {"^FTSE", "FTSE 100"},+ {"^N225", "NIKKEI"},+ {"AAPL", "AAPL"},+ {"MSFT", "MSFT"},+ {"GOOGL", "GOOGL"},+ {"AMZN", "AMZN"},+ {"NVDA", "NVDA"},+ {"TSLA", "TSLA"},+ {"META", "META"},+ {"BTC-USD", "BTC"},+ {"ETH-USD", "ETH"},+ {"GC=F", "GOLD"},+ {"CL=F", "CRUDE"},+ {"^TNX", "US10Y"},+ {"EURUSD=X", "EUR/USD"},+ {"^VIX", "VIX"},+ {"^NSEI", "NIFTY"},+};++// Find the yfinance_data.py script path+static std::string find_script_path() {+ // Try paths relative to the exe+#ifdef _WIN32+ char exe_buf[MAX_PATH];+ GetModuleFileNameA(nullptr, exe_buf, MAX_PATH);+ std::filesystem::path exe_dir = std::filesystem::path(exe_buf).parent_path();+#elif defined(__APPLE__)+ // macOS: use _NSGetExecutablePath or /proc/self/exe fallback+ char exe_buf[4096];+ uint32_t bufsize = sizeof(exe_buf);+ std::filesystem::path exe_dir;+ if (_NSGetExecutablePath(exe_buf, &bufsize) == 0) {+ exe_dir = std::filesystem::path(exe_buf).parent_path();+ } else {+ exe_dir = std::filesystem::current_path();+ }+#else+ // Linux: /proc/self/exe+ std::filesystem::path exe_dir;+ try {+ exe_dir = std::filesystem::read_symlink("/proc/self/exe").parent_path();+ } catch (...) {+ exe_dir = std::filesystem::current_path();+ }+#endif++ // Search candidates+ std::vector<std::string> candidates = {+ // Relative to exe (build/Release/ on Windows, build/ on Linux/macOS)+ (exe_dir / ".." / ".." / ".." / "fincept-terminal-desktop" / "src-tauri" / "resources" / "scripts" / "yfinance_data.py").string(),+ (exe_dir / ".." / ".." / "fincept-terminal-desktop" / "src-tauri" / "resources" / "scripts" / "yfinance_data.py").string(),+ // From project root+ (exe_dir / ".." / ".." / ".." / ".." / "fincept-terminal-desktop" / "src-tauri" / "resources" / "scripts" / "yfinance_data.py").string(),+ };++ for (auto& path : candidates) {+ if (std::filesystem::exists(path)) {+ auto canonical = std::filesystem::canonical(path).string();+ std::printf("[StockTicker] Found script: %s\n", canonical.c_str());+ return canonical;+ }+ }++ std::printf("[StockTicker] yfinance_data.py not found!\n");+ return "";+}++// Run python script and capture stdout+static std::string run_python(const std::string& script_path, const std::string& args) {+#ifdef _WIN32+ const char* python_cmd = "python";+ const char* null_dev = "NUL";+#else+ const char* python_cmd = "python3";+ const char* null_dev = "/dev/null";+#endif++ std::printf("[StockTicker] Running: %s \"%s\" %s\n", python_cmd, script_path.c_str(), args.c_str());++#ifdef _WIN32+ // Use CreateProcess with pipes for cleaner capture+ SECURITY_ATTRIBUTES sa;+ sa.nLength = sizeof(SECURITY_ATTRIBUTES);+ sa.bInheritHandle = TRUE;+ sa.lpSecurityDescriptor = nullptr;++ HANDLE hReadPipe, hWritePipe;+ if (!CreatePipe(&hReadPipe, &hWritePipe, &sa, 0)) {+ std::printf("[StockTicker] CreatePipe failed\n");+ return "";+ }+ SetHandleInformation(hReadPipe, HANDLE_FLAG_INHERIT, 0);++ // Also redirect stderr to NUL to suppress yfinance warnings+ HANDLE hNul = CreateFileA("NUL", GENERIC_WRITE, FILE_SHARE_WRITE, &sa, OPEN_EXISTING, 0, nullptr);++ STARTUPINFOA si = {};+ si.cb = sizeof(si);+ si.hStdOutput = hWritePipe;+ si.hStdError = hNul;+ si.dwFlags = STARTF_USESTDHANDLES;++ PROCESS_INFORMATION pi = {};+ std::string full_cmd = std::string(python_cmd) + " \"" + script_path + "\" " + args;+ char cmd_buf[4096];+ strncpy_s(cmd_buf, full_cmd.c_str(), sizeof(cmd_buf) - 1);++ if (!CreateProcessA(nullptr, cmd_buf, nullptr, nullptr, TRUE, CREATE_NO_WINDOW, nullptr, nullptr, &si, &pi)) {+ std::printf("[StockTicker] CreateProcess failed (error %lu)\n", GetLastError());+ CloseHandle(hReadPipe);+ CloseHandle(hWritePipe);+ if (hNul != INVALID_HANDLE_VALUE) CloseHandle(hNul);+ return "";+ }++ CloseHandle(hWritePipe);+ if (hNul != INVALID_HANDLE_VALUE) CloseHandle(hNul);++ // Read output+ std::string output;+ char buffer[4096];+ DWORD bytesRead;+ while (ReadFile(hReadPipe, buffer, sizeof(buffer) - 1, &bytesRead, nullptr) && bytesRead > 0) {+ buffer[bytesRead] = '\0';+ output += buffer;+ }++ WaitForSingleObject(pi.hProcess, 60000); // 60s timeout+ CloseHandle(pi.hProcess);+ CloseHandle(pi.hThread);+ CloseHandle(hReadPipe);++ return output;+#else+ std::string cmd = std::string(python_cmd) + " \"" + script_path + "\" " + args + " 2>" + null_dev;+ FILE* pipe = popen(cmd.c_str(), "r");+ if (!pipe) return "";++ std::string output;+ char buffer[4096];+ while (fgets(buffer, sizeof(buffer), pipe)) {+ output += buffer;+ }+ pclose(pipe);+ return output;+#endif+}++StockTicker& StockTicker::instance() {+ static StockTicker ticker;+ return ticker;+}++void StockTicker::initialize() {+ if (running_) return;++ // Initialize with placeholder data+ {+ std::lock_guard<std::mutex> lock(mutex_);+ items_.clear();+ for (auto& [sym, name] : TICKER_SYMBOLS) {+ TickerItem item;+ item.symbol = sym;+ item.name = name;+ items_.push_back(item);+ }+ }++ running_ = true;+ fetch_thread_ = std::thread(&StockTicker::fetch_loop, this);+ std::printf("[StockTicker] Initialized with %zu symbols\n", TICKER_SYMBOLS.size());+}++void StockTicker::shutdown() {+ running_ = false;+ if (fetch_thread_.joinable()) {+ fetch_thread_.join();+ }+}++void StockTicker::fetch_prices() {+ std::string script = find_script_path();+ if (script.empty()) {+ std::printf("[StockTicker] Cannot fetch — script not found\n");+ return;+ }++ // Build args: batch_quotes SYM1 SYM2 SYM3 ...+ std::string args = "batch_quotes";+ for (auto& [sym, name] : TICKER_SYMBOLS) {+ args += " " + sym;+ }++ std::string output = run_python(script, args);++ if (output.empty()) {+ std::printf("[StockTicker] No output from python script\n");+ return;+ }++ // Find the JSON in the output (last line starting with [ or {)+ std::string json_str;+ std::istringstream stream(output);+ std::string line;+ while (std::getline(stream, line)) {+ // Trim whitespace+ size_t start = line.find_first_not_of(" \t\r\n");+ if (start == std::string::npos) continue;+ char first = line[start];+ if (first == '[' || first == '{') {+ json_str = line.substr(start);+ }+ }++ if (json_str.empty()) {+ std::printf("[StockTicker] No JSON found in output. Raw output:\n%s\n", output.c_str());+ return;+ }++ try {+ auto data = json::parse(json_str);++ if (data.is_array()) {+ std::lock_guard<std::mutex> lock(mutex_);+ int matched = 0;+ for (auto& entry : data) {+ std::string sym = entry.value("symbol", "");+ for (auto& item : items_) {+ if (item.symbol == sym) {+ item.price = entry.value("price", 0.0f);+ item.change = entry.value("change", 0.0f);+ item.change_pct = entry.value("change_percent", 0.0f);+ item.valid = item.price > 0;+ matched++;+ break;+ }+ }+ }+ fetched_ = true;+ std::printf("[StockTicker] Loaded %d/%zu prices from yfinance\n", matched, TICKER_SYMBOLS.size());+ } else if (data.contains("error")) {+ std::printf("[StockTicker] Script error: %s\n", data["error"].get<std::string>().c_str());+ }+ } catch (const std::exception& e) {+ std::printf("[StockTicker] JSON parse error: %s\nRaw: %.200s\n", e.what(), json_str.c_str());+ }+}++void StockTicker::fetch_loop() {+ // Initial fetch immediately+ fetch_prices();++ while (running_) {+ // Refresh every 60 seconds (yfinance has rate limits)+ for (int i = 0; i < 60 && running_; i++) {+ std::this_thread::sleep_for(std::chrono::seconds(1));+ }+ if (running_) {+ fetch_prices();+ }+ }+}++void StockTicker::render(float bar_height) {+ ImGuiIO& io = ImGui::GetIO();+ float window_width = io.DisplaySize.x;++ // Position just below the main menu bar using viewport WorkPos+ ImGuiViewport* vp = ImGui::GetMainViewport();+ float ticker_y = vp->WorkPos.y;+ ImGui::SetNextWindowPos(ImVec2(vp->WorkPos.x, ticker_y));+ ImGui::SetNextWindowSize(ImVec2(window_width, bar_height));++ ImGui::PushStyleColor(ImGuiCol_WindowBg, ImVec4(0.02f, 0.02f, 0.05f, 1.0f));+ ImGui::PushStyleColor(ImGuiCol_Border, theme::colors::BORDER_DIM);+ ImGui::PushStyleVar(ImGuiStyleVar_WindowPadding, ImVec2(0, 2));+ ImGui::PushStyleVar(ImGuiStyleVar_WindowBorderSize, 1.0f);++ ImGui::Begin("##stock_ticker", nullptr,+ ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_NoResize | ImGuiWindowFlags_NoMove |+ ImGuiWindowFlags_NoScrollbar | ImGuiWindowFlags_NoScrollWithMouse |+ ImGuiWindowFlags_NoCollapse | ImGuiWindowFlags_NoDocking |+ ImGuiWindowFlags_NoFocusOnAppearing | ImGuiWindowFlags_NoBringToFrontOnFocus);++ // Calculate total content width+ std::lock_guard<std::mutex> lock(mutex_);++ float spacing = 32.0f;+ float total_width = 0.0f;++ // Pre-calculate widths+ struct RenderItem {+ std::string text;+ float width;+ ImVec4 change_color;+ std::string change_text;+ float change_width;+ };+ std::vector<RenderItem> render_items;++ for (auto& item : items_) {+ RenderItem ri;++ if (item.valid) {+ // Format price based on magnitude+ char price_buf[32];+ if (item.price >= 10000.0f) {+ std::snprintf(price_buf, sizeof(price_buf), "%.0f", item.price);+ } else if (item.price >= 100.0f) {+ std::snprintf(price_buf, sizeof(price_buf), "%.1f", item.price);+ } else if (item.price >= 1.0f) {+ std::snprintf(price_buf, sizeof(price_buf), "%.2f", item.price);+ } else {+ std::snprintf(price_buf, sizeof(price_buf), "%.4f", item.price);+ }++ ri.text = item.name + " " + price_buf;++ char change_buf[32];+ std::snprintf(change_buf, sizeof(change_buf), "%s%.2f%%",+ item.change_pct >= 0 ? "+" : "", item.change_pct);+ ri.change_text = change_buf;++ ri.change_color = item.change_pct >= 0 ? theme::colors::SUCCESS : theme::colors::ERROR_RED;+ } else {+ ri.text = item.name + " ---";+ ri.change_text = "";+ ri.change_color = theme::colors::TEXT_DISABLED;+ }++ ri.width = ImGui::CalcTextSize(ri.text.c_str()).x;+ ri.change_width = ri.change_text.empty() ? 0 : ImGui::CalcTextSize(ri.change_text.c_str()).x;++ float item_width = ri.width + (ri.change_width > 0 ? ri.change_width + 8.0f : 0) + spacing;+ total_width += item_width;+ render_items.push_back(ri);+ }++ if (total_width < 1.0f) total_width = 1.0f;++ // Scroll speed — pixels per second+ float scroll_speed = 40.0f;+ scroll_offset_ += scroll_speed * io.DeltaTime;++ // Wrap around when we've scrolled past the full content+ if (scroll_offset_ >= total_width) {+ scroll_offset_ -= total_width;+ }++ // Render two copies for seamless looping+ float y_center = (bar_height - ImGui::GetTextLineHeight()) * 0.5f;++ for (int copy = 0; copy < 2; copy++) {+ float x = -scroll_offset_ + copy * total_width;++ for (auto& ri : render_items) {+ float item_end = x + ri.width + ri.change_width + 8.0f + spacing;++ // Only render if visible (fully on screen)+ if (item_end > 0 && x < window_width && x >= -ri.width) {+ float draw_x = std::max(x, 0.0f);++ // Symbol + Price+ if (x >= 0) {+ ImGui::SetCursorPos(ImVec2(draw_x, y_center));+ ImGui::TextColored(theme::colors::TEXT_PRIMARY, "%s", ri.text.c_str());+ }++ // Change percentage+ float chg_x = x + ri.width + 8.0f;+ if (!ri.change_text.empty() && chg_x >= 0 && chg_x < window_width) {+ ImGui::SetCursorPos(ImVec2(chg_x, y_center));+ ImGui::TextColored(ri.change_color, "%s", ri.change_text.c_str());+ }++ // Separator+ float sep_x = x + ri.width + (ri.change_width > 0 ? ri.change_width + 8.0f : 0) + spacing * 0.5f - 4.0f;+ if (sep_x >= 0 && sep_x < window_width) {+ ImGui::SetCursorPos(ImVec2(sep_x, y_center));+ ImGui::TextColored(theme::colors::BORDER_DIM, "|");+ }+ }++ x += ri.width + (ri.change_width > 0 ? ri.change_width + 8.0f : 0) + spacing;+ }+ }++ ImGui::End();+ ImGui::PopStyleVar(2);+ ImGui::PopStyleColor(2);+}++} // namespace fincept::dashboarddiff --git a/fincept-cpp/src/dashboard/stock_ticker.h b/fincept-cpp/src/dashboard/stock_ticker.hnew file mode 100644index 000000000..0af49701f--- /dev/null+++ b/fincept-cpp/src/dashboard/stock_ticker.h@@ -0,0 +1,49 @@+#pragma once+// Bloomberg-style scrolling stock ticker bar+// Fetches real market data and renders a smooth horizontal scroll++#include <string>+#include <vector>+#include <mutex>+#include <atomic>+#include <thread>++namespace fincept::dashboard {++struct TickerItem {+ std::string symbol;+ std::string name;+ float price = 0.0f;+ float change = 0.0f;+ float change_pct = 0.0f;+ bool valid = false;+};++class StockTicker {+public:+ static StockTicker& instance();++ void initialize();+ void shutdown();+ void render(float bar_height = 24.0f);++ StockTicker(const StockTicker&) = delete;+ StockTicker& operator=(const StockTicker&) = delete;++private:+ StockTicker() = default;+ ~StockTicker() = default;++ void fetch_prices();+ void fetch_loop();++ std::vector<TickerItem> items_;+ std::mutex mutex_;+ std::atomic<bool> running_{false};+ std::thread fetch_thread_;+ float scroll_offset_ = 0.0f;+ bool fetched_ = false;+ double last_fetch_time_ = 0.0;+};++} // namespace fincept::dashboarddiff --git a/fincept-cpp/src/dashboard/widget_registry.h b/fincept-cpp/src/dashboard/widget_registry.hnew file mode 100644index 000000000..ac9be3897--- /dev/null+++ b/fincept-cpp/src/dashboard/widget_registry.h@@ -0,0 +1,247 @@+#pragma once+// Widget type system and layout persistence for the dashboard+// Supports adding/removing widgets, drag-resize, and SQLite persistence++#include <string>+#include <vector>+#include <nlohmann/json.hpp>++namespace fincept::dashboard {++// All available widget types+enum class WidgetType {+ GlobalIndices,+ Forex,+ Commodities,+ Crypto,+ SectorHeatmap,+ News,+ EconomicIndicators,+ GeopoliticalRisk,+ Performance,+ TopMovers,+ MarketData, // generic quote table+ Count+};++inline const char* widget_type_name(WidgetType t) {+ switch (t) {+ case WidgetType::GlobalIndices: return "Global Indices";+ case WidgetType::Forex: return "Forex";+ case WidgetType::Commodities: return "Commodities";+ case WidgetType::Crypto: return "Crypto";+ case WidgetType::SectorHeatmap: return "Sector Heatmap";+ case WidgetType::News: return "Market News";+ case WidgetType::EconomicIndicators: return "Economic Indicators";+ case WidgetType::GeopoliticalRisk: return "Geopolitical Risk";+ case WidgetType::Performance: return "Performance";+ case WidgetType::TopMovers: return "Top Movers";+ case WidgetType::MarketData: return "Market Data";+ default: return "Unknown";+ }+}++inline const char* widget_type_id(WidgetType t) {+ switch (t) {+ case WidgetType::GlobalIndices: return "indices";+ case WidgetType::Forex: return "forex";+ case WidgetType::Commodities: return "commodities";+ case WidgetType::Crypto: return "crypto";+ case WidgetType::SectorHeatmap: return "heatmap";+ case WidgetType::News: return "news";+ case WidgetType::EconomicIndicators: return "economic";+ case WidgetType::GeopoliticalRisk: return "geopolitics";+ case WidgetType::Performance: return "performance";+ case WidgetType::TopMovers: return "topmovers";+ case WidgetType::MarketData: return "marketdata";+ default: return "unknown";+ }+}++inline WidgetType widget_type_from_id(const std::string& id) {+ if (id == "indices") return WidgetType::GlobalIndices;+ if (id == "forex") return WidgetType::Forex;+ if (id == "commodities") return WidgetType::Commodities;+ if (id == "crypto") return WidgetType::Crypto;+ if (id == "heatmap") return WidgetType::SectorHeatmap;+ if (id == "news") return WidgetType::News;+ if (id == "economic") return WidgetType::EconomicIndicators;+ if (id == "geopolitics") return WidgetType::GeopoliticalRisk;+ if (id == "performance") return WidgetType::Performance;+ if (id == "topmovers") return WidgetType::TopMovers;+ if (id == "marketdata") return WidgetType::MarketData;+ return WidgetType::GlobalIndices;+}++// A single widget instance in the grid+struct WidgetInstance {+ std::string id; // unique instance id+ WidgetType type;+ std::string title; // user-customizable title+ int col = 0; // grid column (0-based)+ int row = 0; // grid row (0-based)+ int col_span = 1; // how many columns wide+ int row_span = 1; // how many rows tall+ bool visible = true;++ nlohmann::json to_json() const {+ return {+ {"id", id}, {"type", widget_type_id(type)}, {"title", title},+ {"col", col}, {"row", row}, {"col_span", col_span}, {"row_span", row_span},+ {"visible", visible}+ };+ }++ static WidgetInstance from_json(const nlohmann::json& j) {+ WidgetInstance w;+ w.id = j.value("id", "");+ w.type = widget_type_from_id(j.value("type", "indices"));+ w.title = j.value("title", "");+ w.col = j.value("col", 0);+ w.row = j.value("row", 0);+ w.col_span = j.value("col_span", 1);+ w.row_span = j.value("row_span", 1);+ w.visible = j.value("visible", true);+ if (w.title.empty()) w.title = widget_type_name(w.type);+ return w;+ }+};++// Complete dashboard layout+struct DashboardLayout {+ std::string template_id = "default";+ int grid_cols = 3;+ int grid_rows = 3;+ bool market_pulse_open = true;+ std::vector<WidgetInstance> widgets;++ nlohmann::json to_json() const {+ nlohmann::json j;+ j["template_id"] = template_id;+ j["grid_cols"] = grid_cols;+ j["grid_rows"] = grid_rows;+ j["market_pulse_open"] = market_pulse_open;+ j["widgets"] = nlohmann::json::array();+ for (auto& w : widgets) j["widgets"].push_back(w.to_json());+ return j;+ }++ static DashboardLayout from_json(const nlohmann::json& j) {+ DashboardLayout l;+ l.template_id = j.value("template_id", "default");+ l.grid_cols = j.value("grid_cols", 3);+ l.grid_rows = j.value("grid_rows", 3);+ l.market_pulse_open = j.value("market_pulse_open", true);+ if (j.contains("widgets") && j["widgets"].is_array()) {+ for (auto& wj : j["widgets"]) {+ l.widgets.push_back(WidgetInstance::from_json(wj));+ }+ }+ return l;+ }+};++// =============================================================================+// Default templates+// =============================================================================+inline DashboardLayout default_layout() {+ DashboardLayout l;+ l.template_id = "default";+ l.grid_cols = 3;+ l.grid_rows = 3;+ l.market_pulse_open = true;+ l.widgets = {+ {"w-idx", WidgetType::GlobalIndices, "GLOBAL INDICES", 0, 0, 1, 1, true},+ {"w-heat", WidgetType::SectorHeatmap, "SECTOR HEATMAP", 1, 0, 1, 1, true},+ {"w-perf", WidgetType::Performance, "PERFORMANCE", 2, 0, 1, 1, true},+ {"w-fx", WidgetType::Forex, "FOREX", 0, 1, 1, 1, true},+ {"w-cmd", WidgetType::Commodities, "COMMODITIES", 1, 1, 1, 1, true},+ {"w-cry", WidgetType::Crypto, "CRYPTO", 2, 1, 1, 1, true},+ {"w-news", WidgetType::News, "MARKET NEWS", 0, 2, 1, 1, true},+ {"w-eco", WidgetType::EconomicIndicators, "ECONOMIC INDICATORS", 1, 2, 1, 1, true},+ {"w-geo", WidgetType::GeopoliticalRisk, "GEOPOLITICAL RISK", 2, 2, 1, 1, true},+ };+ return l;+}++inline DashboardLayout crypto_trader_layout() {+ DashboardLayout l;+ l.template_id = "crypto-trader";+ l.grid_cols = 3;+ l.grid_rows = 3;+ l.market_pulse_open = true;+ l.widgets = {+ {"w-cry", WidgetType::Crypto, "CRYPTO MARKETS", 0, 0, 2, 1, true},+ {"w-movers",WidgetType::TopMovers, "TOP MOVERS", 2, 0, 1, 1, true},+ {"w-fx", WidgetType::Forex, "FOREX", 0, 1, 1, 1, true},+ {"w-cmd", WidgetType::Commodities, "COMMODITIES", 1, 1, 1, 1, true},+ {"w-idx", WidgetType::GlobalIndices, "INDICES", 2, 1, 1, 1, true},+ {"w-news", WidgetType::News, "CRYPTO NEWS", 0, 2, 2, 1, true},+ {"w-eco", WidgetType::EconomicIndicators, "ECONOMIC", 2, 2, 1, 1, true},+ };+ return l;+}++inline DashboardLayout macro_economist_layout() {+ DashboardLayout l;+ l.template_id = "macro-economist";+ l.grid_cols = 3;+ l.grid_rows = 3;+ l.market_pulse_open = true;+ l.widgets = {+ {"w-eco", WidgetType::EconomicIndicators, "ECONOMIC INDICATORS", 0, 0, 1, 1, true},+ {"w-idx", WidgetType::GlobalIndices, "GLOBAL INDICES", 1, 0, 1, 1, true},+ {"w-fx", WidgetType::Forex, "FOREX MAJOR PAIRS", 2, 0, 1, 1, true},+ {"w-cmd", WidgetType::Commodities, "COMMODITIES", 0, 1, 1, 1, true},+ {"w-heat", WidgetType::SectorHeatmap, "SECTOR HEATMAP", 1, 1, 1, 1, true},+ {"w-geo", WidgetType::GeopoliticalRisk, "GEOPOLITICAL RISK", 2, 1, 1, 1, true},+ {"w-news", WidgetType::News, "ECONOMIC NEWS", 0, 2, 2, 1, true},+ {"w-cry", WidgetType::Crypto, "CRYPTO", 2, 2, 1, 1, true},+ };+ return l;+}++inline DashboardLayout equity_trader_layout() {+ DashboardLayout l;+ l.template_id = "equity-trader";+ l.grid_cols = 3;+ l.grid_rows = 3;+ l.market_pulse_open = true;+ l.widgets = {+ {"w-idx", WidgetType::GlobalIndices, "MARKET INDICES", 0, 0, 1, 1, true},+ {"w-movers",WidgetType::TopMovers, "TOP MOVERS", 1, 0, 1, 1, true},+ {"w-heat", WidgetType::SectorHeatmap, "SECTOR HEATMAP", 2, 0, 1, 1, true},+ {"w-perf", WidgetType::Performance, "PERFORMANCE", 0, 1, 1, 1, true},+ {"w-fx", WidgetType::Forex, "FOREX", 1, 1, 1, 1, true},+ {"w-cmd", WidgetType::Commodities, "COMMODITIES", 2, 1, 1, 1, true},+ {"w-news", WidgetType::News, "MARKETS NEWS", 0, 2, 2, 1, true},+ {"w-eco", WidgetType::EconomicIndicators, "ECONOMIC", 2, 2, 1, 1, true},+ };+ return l;+}++// Template registry+struct TemplateInfo {+ std::string id;+ std::string name;+ std::string description;+ std::string tag;+ DashboardLayout (*create)();+};++inline std::vector<TemplateInfo> get_all_templates() {+ return {+ {"default", "Default Terminal", "Bloomberg-style 3x3 grid with all major asset classes", "TERMINAL", default_layout},+ {"crypto-trader", "Crypto Trader", "Focus on crypto markets, top movers, and forex", "CRYPTO", crypto_trader_layout},+ {"macro-economist","Macro Economist", "Economic indicators, indices, commodities, and geo risk","MACRO", macro_economist_layout},+ {"equity-trader", "Equity Trader", "Stock indices, top movers, sectors, and performance", "EQUITY", equity_trader_layout},+ };+}++// Generate a unique widget ID+inline std::string generate_widget_id() {+ static int counter = 100;+ return "w-" + std::to_string(++counter);+}++} // namespace fincept::dashboarddiff --git a/fincept-cpp/src/dashboard/widgets/account_info.cpp b/fincept-cpp/src/dashboard/widgets/account_info.cppnew file mode 100644index 000000000..e28bd897f--- /dev/null+++ b/fincept-cpp/src/dashboard/widgets/account_info.cpp@@ -0,0 +1,64 @@+#include "account_info.h"+#include "auth/auth_manager.h"+#include "theme/bloomberg_theme.h"+#include <imgui.h>++namespace fincept::dashboard::widgets {++void AccountInfo::render() {+ if (ImGui::Begin("Account")) {+ auto& session = auth::AuthManager::instance().session();++ theme::SectionHeader("ACCOUNT INFO");+ ImGui::Spacing();++ auto info_row = [](const char* label, const char* value, ImVec4 color = theme::colors::TEXT_SECONDARY) {+ ImGui::TextColored(theme::colors::TEXT_DIM, "%s", label);+ ImGui::SameLine(120);+ ImGui::TextColored(color, "%s", value);+ };++ if (session.is_registered()) {+ info_row("Username", session.user_info.username.c_str(), theme::colors::TEXT_PRIMARY);+ info_row("Email", session.user_info.email.c_str());++ std::string at = session.user_info.account_type;+ for (auto& c : at) c = (char)std::toupper(c);+ info_row("Plan", at.c_str(), theme::colors::ACCENT);++ char credits[32];+ std::snprintf(credits, sizeof(credits), "%.0f", session.user_info.credit_balance);+ info_row("Credits", credits, theme::colors::MARKET_GREEN);++ info_row("Verified", session.user_info.is_verified ? "Yes" : "No",+ session.user_info.is_verified ? theme::colors::SUCCESS : theme::colors::WARNING);++ info_row("MFA", session.user_info.mfa_enabled ? "Enabled" : "Disabled",+ session.user_info.mfa_enabled ? theme::colors::SUCCESS : theme::colors::TEXT_DIM);++ if (!session.user_info.country.empty()) {+ info_row("Country", session.user_info.country.c_str());+ }++ ImGui::Spacing();+ ImGui::Separator();+ ImGui::Spacing();++ if (!session.user_info.created_at.empty()) {+ info_row("Member Since", session.user_info.created_at.substr(0, 10).c_str());+ }+ if (!session.user_info.last_login_at.empty()) {+ info_row("Last Login", session.user_info.last_login_at.substr(0, 10).c_str());+ }+ } else {+ info_row("Session", "Guest", theme::colors::WARNING);+ info_row("Credits", "Limited", theme::colors::TEXT_DIM);++ ImGui::Spacing(); ImGui::Spacing();+ ImGui::TextColored(theme::colors::TEXT_DIM, "Sign up for full access");+ }+ }+ ImGui::End();+}++} // namespace fincept::dashboard::widgetsdiff --git a/fincept-cpp/src/dashboard/widgets/account_info.h b/fincept-cpp/src/dashboard/widgets/account_info.hnew file mode 100644index 000000000..41c7e2f76--- /dev/null+++ b/fincept-cpp/src/dashboard/widgets/account_info.h@@ -0,0 +1,10 @@+#pragma once++namespace fincept::dashboard::widgets {++class AccountInfo {+public:+ static void render();+};++} // namespace fincept::dashboard::widgetsdiff --git a/fincept-cpp/src/dashboard/widgets/market_overview.cpp b/fincept-cpp/src/dashboard/widgets/market_overview.cppnew file mode 100644index 000000000..38eb43b21--- /dev/null+++ b/fincept-cpp/src/dashboard/widgets/market_overview.cpp@@ -0,0 +1,97 @@+#include "market_overview.h"+#include "theme/bloomberg_theme.h"+#include <imgui.h>+#include <cmath>++namespace fincept::dashboard::widgets {++void MarketOverview::render() {+ if (ImGui::Begin("Market Overview")) {+ theme::SectionHeader("INDICES");+ ImGui::Spacing();++ if (ImGui::BeginTable("##indices", 4,+ ImGuiTableFlags_Borders | ImGuiTableFlags_RowBg | ImGuiTableFlags_SizingStretchSame)) {++ ImGui::TableSetupColumn("Index", ImGuiTableColumnFlags_WidthStretch);+ ImGui::TableSetupColumn("Last", ImGuiTableColumnFlags_WidthFixed, 80);+ ImGui::TableSetupColumn("Change", ImGuiTableColumnFlags_WidthFixed, 80);+ ImGui::TableSetupColumn("%Chg", ImGuiTableColumnFlags_WidthFixed, 70);+ ImGui::TableHeadersRow();++ struct IndexData { const char* name; float last; float change; };+ IndexData indices[] = {+ {"S&P 500", 5234.18f, +28.72f},+ {"DJIA", 39512.84f, +125.08f},+ {"NASDAQ", 16384.47f, +85.32f},+ {"Russell 2000", 2084.15f, -12.43f},+ {"VIX", 13.42f, -0.28f},+ {"DXY", 104.28f, +0.15f},+ };++ for (auto& idx : indices) {+ ImGui::TableNextRow();++ ImGui::TableNextColumn();+ ImGui::TextColored(theme::colors::TEXT_PRIMARY, "%s", idx.name);++ ImGui::TableNextColumn();+ ImGui::TextColored(theme::colors::TEXT_SECONDARY, "%.2f", idx.last);++ ImGui::TableNextColumn();+ bool positive = idx.change >= 0;+ ImGui::TextColored(positive ? theme::colors::MARKET_GREEN : theme::colors::MARKET_RED,+ "%s%.2f", positive ? "+" : "", idx.change);++ ImGui::TableNextColumn();+ float pct = (idx.change / idx.last) * 100.0f;+ ImGui::TextColored(positive ? theme::colors::MARKET_GREEN : theme::colors::MARKET_RED,+ "%s%.2f%%", pct >= 0 ? "+" : "", pct);+ }++ ImGui::EndTable();+ }++ ImGui::Spacing(); ImGui::Spacing();++ theme::SectionHeader("COMMODITIES");+ ImGui::Spacing();++ if (ImGui::BeginTable("##commodities", 3,+ ImGuiTableFlags_Borders | ImGuiTableFlags_RowBg | ImGuiTableFlags_SizingStretchSame)) {++ ImGui::TableSetupColumn("Commodity");+ ImGui::TableSetupColumn("Price");+ ImGui::TableSetupColumn("Change");+ ImGui::TableHeadersRow();++ struct CommodityData { const char* name; const char* price; const char* change; bool pos; };+ CommodityData commodities[] = {+ {"Gold", "$2,178.30", "+$12.40", true},+ {"Silver", "$24.85", "-$0.32", false},+ {"WTI Oil","$78.42", "+$1.15", true},+ {"Nat Gas","$1.72", "-$0.08", false},+ {"Copper", "$3.92", "+$0.05", true},+ };++ for (auto& c : commodities) {+ ImGui::TableNextRow();+ ImGui::TableNextColumn();+ ImGui::TextColored(theme::colors::TEXT_PRIMARY, "%s", c.name);+ ImGui::TableNextColumn();+ ImGui::TextColored(theme::colors::TEXT_SECONDARY, "%s", c.price);+ ImGui::TableNextColumn();+ ImGui::TextColored(c.pos ? theme::colors::MARKET_GREEN : theme::colors::MARKET_RED,+ "%s", c.change);+ }++ ImGui::EndTable();+ }++ ImGui::Spacing();+ ImGui::TextColored(theme::colors::TEXT_DIM, "Sample data - connect to live market feed");+ }+ ImGui::End();+}++} // namespace fincept::dashboard::widgetsdiff --git a/fincept-cpp/src/dashboard/widgets/market_overview.h b/fincept-cpp/src/dashboard/widgets/market_overview.hnew file mode 100644index 000000000..ef5fb6327--- /dev/null+++ b/fincept-cpp/src/dashboard/widgets/market_overview.h@@ -0,0 +1,10 @@+#pragma once++namespace fincept::dashboard::widgets {++class MarketOverview {+public:+ static void render();+};++} // namespace fincept::dashboard::widgetsdiff --git a/fincept-cpp/src/http/api_types.h b/fincept-cpp/src/http/api_types.hnew file mode 100644index 000000000..4327e6491--- /dev/null+++ b/fincept-cpp/src/http/api_types.h@@ -0,0 +1,298 @@+#pragma once+// API request/response types mirroring the TypeScript interfaces exactly++#include <nlohmann/json.hpp>+#include <string>+#include <optional>+#include <vector>++namespace fincept::api {++using json = nlohmann::json;++// =============================================================================+// Generic API Response+// =============================================================================+struct ApiResponse {+ bool success = false;+ json data;+ std::string message;+ std::string error;+ int status_code = 0;+};++// =============================================================================+// Auth Request Types+// =============================================================================+struct LoginRequest {+ std::string email;+ std::string password;+ bool force_login = false;+};++inline json to_json_obj(const LoginRequest& r) {+ json j;+ j["email"] = r.email;+ j["password"] = r.password;+ if (r.force_login) j["force_login"] = true;+ return j;+}++struct RegisterRequest {+ std::string username;+ std::string email;+ std::string password;+ std::string phone;+ std::string country;+ std::string country_code;+ std::string preferred_currency = "USD";+};++inline json to_json_obj(const RegisterRequest& r) {+ json j;+ j["username"] = r.username;+ j["email"] = r.email;+ j["password"] = r.password;+ if (!r.phone.empty()) j["phone"] = r.phone;+ if (!r.country.empty()) j["country"] = r.country;+ j["country_code"] = r.country_code;+ j["preferred_currency"] = r.preferred_currency;+ return j;+}++struct VerifyOtpRequest {+ std::string email;+ std::string otp;+};++inline json to_json_obj(const VerifyOtpRequest& r) {+ return {{"email", r.email}, {"otp", r.otp}};+}++struct ForgotPasswordRequest {+ std::string email;+};++inline json to_json_obj(const ForgotPasswordRequest& r) {+ return {{"email", r.email}};+}++struct ResetPasswordRequest {+ std::string email;+ std::string otp;+ std::string new_password;+};++inline json to_json_obj(const ResetPasswordRequest& r) {+ return {{"email", r.email}, {"otp", r.otp}, {"new_password", r.new_password}};+}++struct DeviceRegisterRequest {+ std::string device_id;+ std::string device_name;+ std::string platform = "desktop";+ json hardware_info;+};++inline json to_json_obj(const DeviceRegisterRequest& r) {+ return {+ {"device_id", r.device_id},+ {"device_name", r.device_name},+ {"platform", r.platform},+ {"hardware_info", r.hardware_info}+ };+}++// =============================================================================+// Auth Response Types+// =============================================================================+struct LoginResponse {+ std::string api_key;+ std::string session_token;+ std::string message;+ std::string username;+ std::string email;+ double credit_balance = 0.0;+ bool mfa_required = false;+ bool active_session = false;+};++inline void from_json_obj(const json& j, LoginResponse& r) {+ if (j.contains("api_key")) r.api_key = j["api_key"].get<std::string>();+ if (j.contains("session_token")) r.session_token = j["session_token"].get<std::string>();+ if (j.contains("message")) r.message = j["message"].get<std::string>();+ if (j.contains("username")) r.username = j["username"].get<std::string>();+ if (j.contains("email")) r.email = j["email"].get<std::string>();+ if (j.contains("credit_balance")) r.credit_balance = j["credit_balance"].get<double>();+ if (j.contains("mfa_required")) r.mfa_required = j["mfa_required"].get<bool>();+ if (j.contains("active_session")) r.active_session = j["active_session"].get<bool>();+}++struct UserProfile {+ int id = 0;+ std::string username;+ std::string email;+ std::string account_type;+ double credit_balance = 0.0;+ bool is_verified = false;+ bool is_admin = false;+ bool mfa_enabled = false;+ std::string phone;+ std::string country_code;+ std::string country;+ std::string created_at;+ std::string last_login_at;+};++inline void from_json_obj(const json& j, UserProfile& p) {+ if (j.contains("id")) p.id = j["id"].get<int>();+ if (j.contains("username")) p.username = j["username"].get<std::string>();+ if (j.contains("email")) p.email = j["email"].get<std::string>();+ if (j.contains("account_type")) p.account_type = j["account_type"].get<std::string>();+ if (j.contains("credit_balance")) p.credit_balance = j["credit_balance"].get<double>();+ if (j.contains("is_verified")) p.is_verified = j["is_verified"].get<bool>();+ if (j.contains("is_admin")) p.is_admin = j["is_admin"].get<bool>();+ if (j.contains("mfa_enabled")) p.mfa_enabled = j["mfa_enabled"].get<bool>();+ if (j.contains("phone") && !j["phone"].is_null()) p.phone = j["phone"].get<std::string>();+ if (j.contains("country_code") && !j["country_code"].is_null()) p.country_code = j["country_code"].get<std::string>();+ if (j.contains("country") && !j["country"].is_null()) p.country = j["country"].get<std::string>();+ if (j.contains("created_at")) p.created_at = j["created_at"].get<std::string>();+ if (j.contains("last_login_at")) p.last_login_at = j["last_login_at"].get<std::string>();+}++struct UserSubscription {+ int user_id = 0;+ std::string account_type;+ double credit_balance = 0.0;+ std::string credits_expire_at;+ std::string support_type;+ std::string last_credit_purchase_at;+ std::string created_at;+};++inline void from_json_obj(const json& j, UserSubscription& s) {+ if (j.contains("user_id")) s.user_id = j["user_id"].get<int>();+ if (j.contains("account_type")) s.account_type = j["account_type"].get<std::string>();+ if (j.contains("credit_balance")) s.credit_balance = j["credit_balance"].get<double>();+ if (j.contains("credits_expire_at") && !j["credits_expire_at"].is_null()) s.credits_expire_at = j["credits_expire_at"].get<std::string>();+ if (j.contains("support_type")) s.support_type = j["support_type"].get<std::string>();+ if (j.contains("last_credit_purchase_at") && !j["last_credit_purchase_at"].is_null()) s.last_credit_purchase_at = j["last_credit_purchase_at"].get<std::string>();+ if (j.contains("created_at")) s.created_at = j["created_at"].get<std::string>();+}++struct SubscriptionPlan {+ std::string plan_id;+ std::string name;+ std::string description;+ double price_usd = 0.0;+ std::string currency;+ int credits = 0;+ std::string support_type;+ int validity_days = 0;+ std::vector<std::string> features;+ bool is_free = false;+ int display_order = 0;+};++inline void from_json_obj(const json& j, SubscriptionPlan& p) {+ if (j.contains("plan_id")) p.plan_id = j["plan_id"].get<std::string>();+ if (j.contains("name")) p.name = j["name"].get<std::string>();+ if (j.contains("description")) p.description = j["description"].get<std::string>();+ if (j.contains("price_usd")) p.price_usd = j["price_usd"].get<double>();+ if (j.contains("currency")) p.currency = j["currency"].get<std::string>();+ if (j.contains("credits")) p.credits = j["credits"].get<int>();+ if (j.contains("support_type")) p.support_type = j["support_type"].get<std::string>();+ if (j.contains("validity_days")) p.validity_days = j["validity_days"].get<int>();+ if (j.contains("features") && j["features"].is_array()) {+ for (auto& f : j["features"]) p.features.push_back(f.get<std::string>());+ }+ if (j.contains("is_free")) p.is_free = j["is_free"].get<bool>();+ if (j.contains("display_order")) p.display_order = j["display_order"].get<int>();+}++// =============================================================================+// Session Data (mirrors TypeScript SessionData exactly)+// =============================================================================+struct SessionData {+ bool authenticated = false;+ std::string user_type; // "guest" | "registered"+ std::string api_key;+ std::string session_token;+ std::string device_id;+ UserProfile user_info;+ std::string expires_at;+ double credit_balance = 0.0;+ int requests_today = 0;+ UserSubscription subscription;+ bool has_subscription = false;++ bool is_registered() const { return user_type == "registered"; }+ bool is_guest() const { return user_type == "guest"; }++ bool has_paid_plan() const {+ std::string at = user_info.account_type;+ // lowercase+ for (auto& c : at) c = (char)std::tolower(c);+ return at == "basic" || at == "standard" || at == "pro" || at == "enterprise";+ }++ json to_json() const {+ json j;+ j["authenticated"] = authenticated;+ j["user_type"] = user_type;+ j["api_key"] = api_key;+ j["session_token"] = session_token;+ j["device_id"] = device_id;+ j["expires_at"] = expires_at;+ j["credit_balance"] = credit_balance;+ j["requests_today"] = requests_today;+ j["has_subscription"] = has_subscription;++ json ui;+ ui["username"] = user_info.username;+ ui["email"] = user_info.email;+ ui["account_type"] = user_info.account_type;+ ui["credit_balance"] = user_info.credit_balance;+ ui["is_verified"] = user_info.is_verified;+ ui["mfa_enabled"] = user_info.mfa_enabled;+ ui["phone"] = user_info.phone;+ ui["country"] = user_info.country;+ ui["country_code"] = user_info.country_code;+ j["user_info"] = ui;++ json sub;+ sub["user_id"] = subscription.user_id;+ sub["account_type"] = subscription.account_type;+ sub["credit_balance"] = subscription.credit_balance;+ sub["credits_expire_at"] = subscription.credits_expire_at;+ sub["support_type"] = subscription.support_type;+ sub["last_credit_purchase_at"] = subscription.last_credit_purchase_at;+ sub["created_at"] = subscription.created_at;+ j["subscription"] = sub;++ return j;+ }++ static SessionData from_json(const json& j) {+ SessionData s;+ if (j.contains("authenticated")) s.authenticated = j["authenticated"].get<bool>();+ if (j.contains("user_type")) s.user_type = j["user_type"].get<std::string>();+ if (j.contains("api_key")) s.api_key = j["api_key"].get<std::string>();+ if (j.contains("session_token")) s.session_token = j["session_token"].get<std::string>();+ if (j.contains("device_id")) s.device_id = j["device_id"].get<std::string>();+ if (j.contains("expires_at")) s.expires_at = j["expires_at"].get<std::string>();+ if (j.contains("credit_balance")) s.credit_balance = j["credit_balance"].get<double>();+ if (j.contains("requests_today")) s.requests_today = j["requests_today"].get<int>();+ if (j.contains("has_subscription")) s.has_subscription = j["has_subscription"].get<bool>();+ if (j.contains("user_info")) {+ from_json_obj(j["user_info"], s.user_info);+ }+ if (j.contains("subscription") && j["subscription"].is_object()) {+ from_json_obj(j["subscription"], s.subscription);+ s.has_subscription = !s.subscription.account_type.empty();+ }+ return s;+ }+};++} // namespace fincept::apidiff --git a/fincept-cpp/src/http/http_client.cpp b/fincept-cpp/src/http/http_client.cppnew file mode 100644index 000000000..56b51ca1e--- /dev/null+++ b/fincept-cpp/src/http/http_client.cpp@@ -0,0 +1,171 @@+// Production HTTP client implementation using libcurl+// Thread-safe with connection reuse and proper error handling++#include "http_client.h"+#include <curl/curl.h>+#include <stdexcept>+#include <cstring>++namespace fincept::http {++// libcurl write callback+static size_t write_callback(char* ptr, size_t size, size_t nmemb, void* userdata) {+ auto* response_body = static_cast<std::string*>(userdata);+ size_t total = size * nmemb;+ response_body->append(ptr, total);+ return total;+}++// Global curl init/cleanup+struct CurlGlobalInit {+ CurlGlobalInit() { curl_global_init(CURL_GLOBAL_ALL); }+ ~CurlGlobalInit() { curl_global_cleanup(); }+};+static CurlGlobalInit g_curl_init;++HttpClient& HttpClient::instance() {+ static HttpClient client;+ return client;+}++HttpClient::HttpClient() = default;+HttpClient::~HttpClient() = default;++void HttpClient::set_timeout(long timeout_seconds) {+ std::lock_guard<std::mutex> lock(mutex_);+ timeout_seconds_ = timeout_seconds;+}++void HttpClient::set_connect_timeout(long timeout_seconds) {+ std::lock_guard<std::mutex> lock(mutex_);+ connect_timeout_seconds_ = timeout_seconds;+}++HttpResponse HttpClient::perform(const std::string& method, const std::string& url,+ const std::string& body, const Headers& headers) {+ HttpResponse response;++ CURL* curl = curl_easy_init();+ if (!curl) {+ response.error = "Failed to initialize CURL";+ return response;+ }++ std::string response_body;++ // URL+ curl_easy_setopt(curl, CURLOPT_URL, url.c_str());++ // Method+ if (method == "POST") {+ curl_easy_setopt(curl, CURLOPT_POST, 1L);+ curl_easy_setopt(curl, CURLOPT_POSTFIELDS, body.c_str());+ curl_easy_setopt(curl, CURLOPT_POSTFIELDSIZE, (long)body.size());+ } else if (method == "PUT") {+ curl_easy_setopt(curl, CURLOPT_CUSTOMREQUEST, "PUT");+ curl_easy_setopt(curl, CURLOPT_POSTFIELDS, body.c_str());+ curl_easy_setopt(curl, CURLOPT_POSTFIELDSIZE, (long)body.size());+ } else if (method == "DELETE") {+ curl_easy_setopt(curl, CURLOPT_CUSTOMREQUEST, "DELETE");+ if (!body.empty()) {+ curl_easy_setopt(curl, CURLOPT_POSTFIELDS, body.c_str());+ curl_easy_setopt(curl, CURLOPT_POSTFIELDSIZE, (long)body.size());+ }+ }+ // GET is default++ // Headers+ struct curl_slist* header_list = nullptr;+ header_list = curl_slist_append(header_list, "Content-Type: application/json");+ header_list = curl_slist_append(header_list, "Accept: application/json");+ for (const auto& [key, value] : headers) {+ std::string header = key + ": " + value;+ header_list = curl_slist_append(header_list, header.c_str());+ }+ curl_easy_setopt(curl, CURLOPT_HTTPHEADER, header_list);++ // Response+ curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, write_callback);+ curl_easy_setopt(curl, CURLOPT_WRITEDATA, &response_body);++ // Timeouts+ curl_easy_setopt(curl, CURLOPT_TIMEOUT, timeout_seconds_);+ curl_easy_setopt(curl, CURLOPT_CONNECTTIMEOUT, connect_timeout_seconds_);++ // SSL+ curl_easy_setopt(curl, CURLOPT_SSL_VERIFYPEER, 1L);+ curl_easy_setopt(curl, CURLOPT_SSL_VERIFYHOST, 2L);++ // Follow redirects+ curl_easy_setopt(curl, CURLOPT_FOLLOWLOCATION, 1L);+ curl_easy_setopt(curl, CURLOPT_MAXREDIRS, 5L);++ // Connection reuse+ curl_easy_setopt(curl, CURLOPT_TCP_KEEPALIVE, 1L);++ // User agent+ curl_easy_setopt(curl, CURLOPT_USERAGENT, "FinceptTerminal/3.3.1");++ // Perform+ CURLcode res = curl_easy_perform(curl);++ if (res != CURLE_OK) {+ response.error = curl_easy_strerror(res);+ if (res == CURLE_OPERATION_TIMEDOUT) {+ response.error = "Request timed out";+ } else if (res == CURLE_COULDNT_CONNECT) {+ response.error = "Could not connect to server";+ } else if (res == CURLE_COULDNT_RESOLVE_HOST) {+ response.error = "Could not resolve host";+ }+ } else {+ long http_code = 0;+ curl_easy_getinfo(curl, CURLINFO_RESPONSE_CODE, &http_code);+ response.status_code = (int)http_code;+ response.body = std::move(response_body);+ response.success = (http_code >= 200 && http_code < 300);+ }++ curl_slist_free_all(header_list);+ curl_easy_cleanup(curl);++ return response;+}++HttpResponse HttpClient::get(const std::string& url, const Headers& headers) {+ return perform("GET", url, "", headers);+}++HttpResponse HttpClient::post(const std::string& url, const std::string& body, const Headers& headers) {+ return perform("POST", url, body, headers);+}++HttpResponse HttpClient::put(const std::string& url, const std::string& body, const Headers& headers) {+ return perform("PUT", url, body, headers);+}++HttpResponse HttpClient::del(const std::string& url, const std::string& body, const Headers& headers) {+ return perform("DELETE", url, body, headers);+}++HttpResponse HttpClient::post_json(const std::string& url, const json& body, const Headers& headers) {+ return perform("POST", url, body.dump(), headers);+}++HttpResponse HttpClient::put_json(const std::string& url, const json& body, const Headers& headers) {+ return perform("PUT", url, body.dump(), headers);+}++std::future<HttpResponse> HttpClient::get_async(const std::string& url, const Headers& headers) {+ return std::async(std::launch::async, [this, url, headers]() {+ return this->get(url, headers);+ });+}++std::future<HttpResponse> HttpClient::post_json_async(const std::string& url, const json& body, const Headers& headers) {+ return std::async(std::launch::async, [this, url, body, headers]() {+ return this->post_json(url, body, headers);+ });+}++} // namespace fincept::httpdiff --git a/fincept-cpp/src/http/http_client.h b/fincept-cpp/src/http/http_client.hnew file mode 100644index 000000000..d4024a077--- /dev/null+++ b/fincept-cpp/src/http/http_client.h@@ -0,0 +1,70 @@+#pragma once+// Production-grade HTTP client wrapping libcurl+// Thread-safe, connection pooling, timeout handling, async support++#include <string>+#include <map>+#include <functional>+#include <future>+#include <mutex>+#include <nlohmann/json.hpp>++namespace fincept::http {++using json = nlohmann::json;++struct HttpResponse {+ int status_code = 0;+ std::string body;+ bool success = false;+ std::string error;++ json json_body() const {+ try {+ return json::parse(body);+ } catch (...) {+ return json();+ }+ }+};++using Headers = std::map<std::string, std::string>;++class HttpClient {+public:+ static HttpClient& instance();++ // Synchronous requests+ HttpResponse get(const std::string& url, const Headers& headers = {});+ HttpResponse post(const std::string& url, const std::string& body = "", const Headers& headers = {});+ HttpResponse put(const std::string& url, const std::string& body = "", const Headers& headers = {});+ HttpResponse del(const std::string& url, const std::string& body = "", const Headers& headers = {});++ // JSON convenience+ HttpResponse post_json(const std::string& url, const json& body, const Headers& headers = {});+ HttpResponse put_json(const std::string& url, const json& body, const Headers& headers = {});++ // Async requests (returns future)+ std::future<HttpResponse> get_async(const std::string& url, const Headers& headers = {});+ std::future<HttpResponse> post_json_async(const std::string& url, const json& body, const Headers& headers = {});++ // Configuration+ void set_timeout(long timeout_seconds);+ void set_connect_timeout(long timeout_seconds);++ HttpClient(const HttpClient&) = delete;+ HttpClient& operator=(const HttpClient&) = delete;++private:+ HttpClient();+ ~HttpClient();++ HttpResponse perform(const std::string& method, const std::string& url,+ const std::string& body, const Headers& headers);++ long timeout_seconds_ = 30;+ long connect_timeout_seconds_ = 10;+ std::mutex mutex_;+};++} // namespace fincept::httpdiff --git a/fincept-cpp/src/main.cpp b/fincept-cpp/src/main.cppnew file mode 100644index 000000000..109cbfced--- /dev/null+++ b/fincept-cpp/src/main.cpp@@ -0,0 +1,592 @@+// Fincept Terminal — C++ / ImGui Desktop Application+// Entry point: GLFW + OpenGL3 + Dear ImGui (Docking)+// Hot reload: watches source files → auto-recompile → auto-relaunch++// Platform headers FIRST (before GLFW native)+#ifdef _WIN32+#define WIN32_LEAN_AND_MEAN+#define NOMINMAX+#include <windows.h>+#include <shellapi.h>+#elif defined(__APPLE__)+#include <mach-o/dyld.h>+#include <unistd.h>+#elif defined(__linux__)+#include <unistd.h>+#endif++#include <imgui.h>+#include <imgui_impl_glfw.h>+#include <imgui_impl_opengl3.h>++#include <GLFW/glfw3.h>+#ifdef _WIN32+#define GLFW_EXPOSE_NATIVE_WIN32+#include <GLFW/glfw3native.h>+#endif++#include "app.h"+#include "theme/bloomberg_theme.h"++#include <cstdio>+#include <cstdlib>+#include <string>+#include <filesystem>+#include <vector>+#include <thread>+#include <atomic>+#include <chrono>+#include <mutex>++// =============================================================================+// Fullscreen Toggle — uses Win32 API on Windows, GLFW on others+// =============================================================================+static GLFWwindow* g_window = nullptr;+static bool g_fullscreen = false;++#ifdef _WIN32+static LONG g_saved_style = 0;+static LONG g_saved_exstyle = 0;+static RECT g_saved_rect = {};++void toggle_fullscreen() {+ if (!g_window) return;++ HWND hwnd = glfwGetWin32Window(g_window);+ if (!hwnd) return;++ if (!g_fullscreen) {+ // Save current window style and position+ g_saved_style = GetWindowLong(hwnd, GWL_STYLE);+ g_saved_exstyle = GetWindowLong(hwnd, GWL_EXSTYLE);+ GetWindowRect(hwnd, &g_saved_rect);++ // Remove title bar, borders, etc.+ SetWindowLong(hwnd, GWL_STYLE, g_saved_style & ~(WS_CAPTION | WS_THICKFRAME));+ SetWindowLong(hwnd, GWL_EXSTYLE, g_saved_exstyle & ~(WS_EX_DLGMODALFRAME | WS_EX_WINDOWEDGE | WS_EX_CLIENTEDGE | WS_EX_STATICEDGE));++ // Get monitor info for the monitor the window is on+ MONITORINFO mi = { sizeof(mi) };+ GetMonitorInfo(MonitorFromWindow(hwnd, MONITOR_DEFAULTTONEAREST), &mi);++ // Resize to cover the full monitor+ SetWindowPos(hwnd, HWND_TOP,+ mi.rcMonitor.left, mi.rcMonitor.top,+ mi.rcMonitor.right - mi.rcMonitor.left,+ mi.rcMonitor.bottom - mi.rcMonitor.top,+ SWP_NOZORDER | SWP_NOACTIVATE | SWP_FRAMECHANGED);++ g_fullscreen = true;+ std::printf("[Fullscreen] Entered fullscreen\n");+ } else {+ // Restore window style+ SetWindowLong(hwnd, GWL_STYLE, g_saved_style);+ SetWindowLong(hwnd, GWL_EXSTYLE, g_saved_exstyle);++ // Restore position and size+ SetWindowPos(hwnd, nullptr,+ g_saved_rect.left, g_saved_rect.top,+ g_saved_rect.right - g_saved_rect.left,+ g_saved_rect.bottom - g_saved_rect.top,+ SWP_NOZORDER | SWP_NOACTIVATE | SWP_FRAMECHANGED);++ g_fullscreen = false;+ std::printf("[Fullscreen] Exited fullscreen\n");+ }+}+#else+static int g_windowed_x = 0, g_windowed_y = 0, g_windowed_w = 1600, g_windowed_h = 900;++void toggle_fullscreen() {+ if (!g_window) return;+ if (!g_fullscreen) {+ glfwGetWindowPos(g_window, &g_windowed_x, &g_windowed_y);+ glfwGetWindowSize(g_window, &g_windowed_w, &g_windowed_h);+ GLFWmonitor* monitor = glfwGetPrimaryMonitor();+ const GLFWvidmode* mode = glfwGetVideoMode(monitor);+ glfwSetWindowMonitor(g_window, monitor, 0, 0, mode->width, mode->height, mode->refreshRate);+ g_fullscreen = true;+ } else {+ glfwSetWindowMonitor(g_window, nullptr, g_windowed_x, g_windowed_y, g_windowed_w, g_windowed_h, 0);+ glfwMaximizeWindow(g_window);+ g_fullscreen = false;+ }+}+#endif++// =============================================================================+// GLFW Error Callback+// =============================================================================+static void glfw_error_callback(int error, const char* description) {+ std::fprintf(stderr, "[GLFW Error %d] %s\n", error, description);+}++// =============================================================================+// Font Loading+// =============================================================================+static void load_fonts(float dpi_scale) {+ ImGuiIO& io = ImGui::GetIO();+ io.Fonts->Clear();++ float font_size = 16.0f * dpi_scale;++ // Font candidates in priority order per platform+ const char* font_candidates[] = {+ "fonts/JetBrainsMono-Regular.ttf", // Bundled (best for terminal)+ "../fonts/JetBrainsMono-Regular.ttf", // Build directory offset+#ifdef _WIN32+ "C:/Windows/Fonts/segoeui.ttf", // Segoe UI — Windows default+ "C:/Windows/Fonts/consola.ttf", // Consolas — monospace fallback+ "C:/Windows/Fonts/arial.ttf", // Arial — universally readable+#elif defined(__APPLE__)+ "/System/Library/Fonts/SFNSMono.ttf", // SF Mono+ "/System/Library/Fonts/Menlo.ttc", // Menlo+ "/System/Library/Fonts/Helvetica.ttc", // Helvetica+ "/Library/Fonts/Arial.ttf", // Arial+#else+ "/usr/share/fonts/truetype/dejavu/DejaVuSansMono.ttf", // DejaVu Mono+ "/usr/share/fonts/truetype/liberation/LiberationMono-Regular.ttf",+ "/usr/share/fonts/truetype/ubuntu/UbuntuMono-R.ttf",+ "/usr/share/fonts/TTF/DejaVuSansMono.ttf", // Arch Linux+#endif+ };++ ImFontConfig config;+ config.OversampleH = 3;+ config.OversampleV = 3;+ config.PixelSnapH = true;+ config.RasterizerDensity = dpi_scale;++ bool loaded = false;+ for (const char* path : font_candidates) {+ if (std::filesystem::exists(path)) {+ io.FontDefault = io.Fonts->AddFontFromFileTTF(path, font_size, &config);+ if (io.FontDefault) {+ std::printf("[Font] Loaded: %s at %.0fpx\n", path, font_size);+ loaded = true;+ break;+ }+ }+ }++ if (!loaded) {+ ImFontConfig fallback_config;+ fallback_config.SizePixels = font_size;+ io.FontDefault = io.Fonts->AddFontDefault(&fallback_config);+ std::printf("[Font] Using ImGui default font at %.0fpx\n", font_size);+ }++ io.Fonts->Build();+}++// =============================================================================+// Hot Reload: Watch source files → recompile → relaunch+// =============================================================================+namespace hot_reload {++struct WatchedFile {+ std::string path;+ std::filesystem::file_time_type last_write;+};++static std::vector<WatchedFile> watched_files_;+static std::atomic<bool> rebuild_needed_{false};+static std::atomic<bool> rebuild_in_progress_{false};+static std::atomic<bool> rebuild_succeeded_{false};+static std::atomic<bool> watcher_running_{false};+static std::thread watcher_thread_;+static std::string src_dir_;+static std::string build_dir_;+static std::string exe_path_;+static std::mutex status_mutex_;+static std::string status_message_ = "Idle";++static void scan_source_files() {+ watched_files_.clear();+ for (auto& entry : std::filesystem::recursive_directory_iterator(src_dir_)) {+ if (!entry.is_regular_file()) continue;+ auto ext = entry.path().extension().string();+ if (ext == ".cpp" || ext == ".h" || ext == ".hpp") {+ watched_files_.push_back({+ entry.path().string(),+ entry.last_write_time()+ });+ }+ }+ // Also watch CMakeLists.txt+ std::string cmake_path = src_dir_ + "/../CMakeLists.txt";+ if (std::filesystem::exists(cmake_path)) {+ watched_files_.push_back({+ cmake_path,+ std::filesystem::last_write_time(cmake_path)+ });+ }+ std::printf("[HotReload] Watching %zu source files\n", watched_files_.size());+}++static bool check_source_changes() {+ bool changed = false;+ for (auto& wf : watched_files_) {+ try {+ if (!std::filesystem::exists(wf.path)) continue;+ auto current = std::filesystem::last_write_time(wf.path);+ if (current != wf.last_write) {+ std::printf("[HotReload] Changed: %s\n", wf.path.c_str());+ wf.last_write = current;+ changed = true;+ }+ } catch (...) {}+ }+ // Also check for new files+ if (changed) {+ scan_source_files();+ }+ return changed;+}++static void run_rebuild() {+ rebuild_in_progress_ = true;+ rebuild_succeeded_ = false;+ {+ std::lock_guard<std::mutex> lock(status_mutex_);+ status_message_ = "Compiling...";+ }+ std::printf("[HotReload] === Rebuilding... ===\n");++#ifdef _WIN32+ // Windows: running exe is locked by the linker. Rename it out of the way first.+ // Windows allows renaming a running executable, but not overwriting it.+ std::string old_exe = exe_path_ + ".old";+ // Remove any previous .old file+ std::filesystem::remove(old_exe);+ // Rename the running exe so the linker can create a fresh one+ std::error_code ec;+ std::filesystem::rename(exe_path_, old_exe, ec);+ if (ec) {+ std::printf("[HotReload] Warning: could not rename running exe: %s\n", ec.message().c_str());+ } else {+ std::printf("[HotReload] Renamed running exe to .old\n");+ }+#endif++ // Run cmake --build+ std::string cmd = "cmake --build \"" + build_dir_ + "\" --config Release 2>&1";++#ifdef _WIN32+ FILE* pipe = _popen(cmd.c_str(), "r");+#else+ FILE* pipe = popen(cmd.c_str(), "r");+#endif++ bool success = false;+ if (pipe) {+ char buffer[512];+ std::string output;+ while (fgets(buffer, sizeof(buffer), pipe)) {+ output += buffer;+ std::printf("[Build] %s", buffer);+ }+#ifdef _WIN32+ int ret = _pclose(pipe);+#else+ int ret = pclose(pipe);+#endif+ success = (ret == 0);+ }++#ifdef _WIN32+ // If build failed, rename back so the exe still exists for next attempt+ if (!success && !ec) {+ std::filesystem::rename(old_exe, exe_path_, ec);+ if (!ec) std::printf("[HotReload] Restored original exe\n");+ }+#endif++ rebuild_in_progress_ = false;++ if (success) {+ rebuild_succeeded_ = true;+ {+ std::lock_guard<std::mutex> lock(status_mutex_);+ status_message_ = "Build OK — restarting...";+ }+ std::printf("[HotReload] === Build succeeded — will relaunch ===\n");+ } else {+ {+ std::lock_guard<std::mutex> lock(status_mutex_);+ status_message_ = "Build FAILED — check console";+ }+ std::printf("[HotReload] === Build FAILED ===\n");+ }+}++static void watcher_loop() {+ while (watcher_running_) {+ std::this_thread::sleep_for(std::chrono::milliseconds(1000));+ if (!watcher_running_) break;+ if (rebuild_in_progress_) continue;++ if (check_source_changes()) {+ // Debounce: wait 500ms for more changes+ std::this_thread::sleep_for(std::chrono::milliseconds(500));+ if (!watcher_running_) break;+ // Check again to catch rapid saves+ check_source_changes();++ run_rebuild();+ }+ }+}++void initialize() {+#ifdef _WIN32+ char path_buf[MAX_PATH];+ GetModuleFileNameA(nullptr, path_buf, MAX_PATH);+ exe_path_ = path_buf;+#elif defined(__APPLE__)+ char path_buf[4096];+ uint32_t bufsize = sizeof(path_buf);+ if (_NSGetExecutablePath(path_buf, &bufsize) == 0) {+ exe_path_ = path_buf;+ }+#elif defined(__linux__)+ try {+ exe_path_ = std::filesystem::read_symlink("/proc/self/exe").string();+ } catch (...) {}+#endif++ // Determine source and build directories relative to exe+ std::filesystem::path exe_p(exe_path_);+ // exe is at build/Release/FinceptTerminal.exe+ // build dir is build/+ // source dir is src/+ build_dir_ = exe_p.parent_path().parent_path().string();+ src_dir_ = (exe_p.parent_path().parent_path().parent_path() / "src").string();++ if (!std::filesystem::exists(src_dir_)) {+ std::printf("[HotReload] Source dir not found: %s — hot reload disabled\n", src_dir_.c_str());+ return;+ }++ std::printf("[HotReload] Source dir: %s\n", src_dir_.c_str());+ std::printf("[HotReload] Build dir: %s\n", build_dir_.c_str());++ scan_source_files();++ watcher_running_ = true;+ watcher_thread_ = std::thread(watcher_loop);++ std::printf("[HotReload] Watcher started — edit any .cpp/.h file to trigger rebuild\n");+}++bool should_relaunch() {+ return rebuild_succeeded_.load();+}++void relaunch() {+ std::printf("[HotReload] Relaunching %s...\n", exe_path_.c_str());++#ifdef _WIN32+ STARTUPINFOA si = {};+ si.cb = sizeof(si);+ PROCESS_INFORMATION pi = {};++ if (CreateProcessA(+ exe_path_.c_str(),+ nullptr,+ nullptr, nullptr,+ FALSE,+ 0,+ nullptr,+ nullptr,+ &si, &pi+ )) {+ CloseHandle(pi.hProcess);+ CloseHandle(pi.hThread);+ std::printf("[HotReload] New process started (PID %lu)\n", pi.dwProcessId);+ } else {+ std::printf("[HotReload] Failed to relaunch (error %lu)\n", GetLastError());+ }+#else+ // Unix: fork + exec+ pid_t pid = fork();+ if (pid == 0) {+ execl(exe_path_.c_str(), exe_path_.c_str(), nullptr);+ _exit(1); // exec failed+ } else if (pid > 0) {+ std::printf("[HotReload] New process started (PID %d)\n", pid);+ } else {+ std::printf("[HotReload] Fork failed\n");+ }+#endif+}++void shutdown() {+ watcher_running_ = false;+ if (watcher_thread_.joinable()) {+ watcher_thread_.join();+ }+}++std::string get_status() {+ std::lock_guard<std::mutex> lock(status_mutex_);+ return status_message_;+}++bool is_rebuilding() {+ return rebuild_in_progress_.load();+}++} // namespace hot_reload++// =============================================================================+// Main+// =============================================================================+int main(int /*argc*/, char** /*argv*/) {+ glfwSetErrorCallback(glfw_error_callback);+ if (!glfwInit()) {+ std::fprintf(stderr, "Failed to initialize GLFW\n");+ return 1;+ }++ // OpenGL 3.3 Core+ glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3);+ glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3);+ glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);+#ifdef __APPLE__+ glfwWindowHint(GLFW_OPENGL_FORWARD_COMPAT, GL_TRUE);+#endif++ // Window hints+ glfwWindowHint(GLFW_MAXIMIZED, GLFW_TRUE);+ glfwWindowHint(GLFW_DECORATED, GLFW_TRUE);+ glfwWindowHint(GLFW_RESIZABLE, GLFW_TRUE);++ // Create window+ GLFWwindow* window = glfwCreateWindow(1600, 900, "Fincept Terminal v3.3.1", nullptr, nullptr);+ if (!window) {+ std::fprintf(stderr, "Failed to create GLFW window\n");+ glfwTerminate();+ return 1;+ }+ g_window = window;+ glfwMakeContextCurrent(window);+ glfwSwapInterval(1); // VSync++ // ImGui setup+ IMGUI_CHECKVERSION();+ ImGui::CreateContext();+ ImGuiIO& io = ImGui::GetIO();++ // Enable docking and viewports+ io.ConfigFlags |= ImGuiConfigFlags_DockingEnable;+ // io.ConfigFlags |= ImGuiConfigFlags_ViewportsEnable; // Multi-viewport (optional)++ // Keyboard nav+ io.ConfigFlags |= ImGuiConfigFlags_NavEnableKeyboard;++ // INI file for layout persistence+ io.IniFilename = "fincept_imgui.ini";++ // Apply Bloomberg theme+ fincept::theme::ApplyBloombergTheme();++ // DPI awareness+ float xscale = 1.0f, yscale = 1.0f;+ glfwGetWindowContentScale(window, &xscale, &yscale);+ float dpi_scale = (xscale + yscale) / 2.0f;++ // Scale style for DPI+ ImGui::GetStyle().ScaleAllSizes(dpi_scale);++ // Init backends FIRST (before loading fonts — OpenGL needs to upload font atlas)+ ImGui_ImplGlfw_InitForOpenGL(window, true);+ const char* glsl_version = "#version 330 core";+ ImGui_ImplOpenGL3_Init(glsl_version);++ // Load fonts AFTER backend init+ load_fonts(dpi_scale);++ // Initialize application+ fincept::App app;++ // Initialize in a thread to avoid blocking the window+ bool app_initialized = false;+ std::printf("[Main] Starting Fincept Terminal...\n");++ // Initialize hot reload+ hot_reload::initialize();++ // ========================================================================+ // Main Loop+ // ========================================================================+ while (!glfwWindowShouldClose(window)) {+ glfwPollEvents();++ // Hot reload: if rebuild succeeded, relaunch+ if (hot_reload::should_relaunch()) {+ // Clean shutdown before relaunch+ app.shutdown();+ ImGui_ImplOpenGL3_Shutdown();+ ImGui_ImplGlfw_Shutdown();+ ImGui::DestroyContext();+ glfwDestroyWindow(window);+ glfwTerminate();+ hot_reload::relaunch();+ hot_reload::shutdown();+ return 0;+ }++ // Initialize app on first frame (after OpenGL context is ready)+ if (!app_initialized) {+ app.initialize();+ app_initialized = true;+ }++ // Start ImGui frame+ ImGui_ImplOpenGL3_NewFrame();+ ImGui_ImplGlfw_NewFrame();+ ImGui::NewFrame();++ // Render application+ app.render();++ // Render ImGui+ ImGui::Render();+ int display_w, display_h;+ glfwGetFramebufferSize(window, &display_w, &display_h);+ glViewport(0, 0, display_w, display_h);++ // Clear with Bloomberg dark background+ glClearColor(0.039f, 0.039f, 0.039f, 1.0f);+ glClear(GL_COLOR_BUFFER_BIT);++ ImGui_ImplOpenGL3_RenderDrawData(ImGui::GetDrawData());++ // Multi-viewport support (if enabled)+ if (io.ConfigFlags & ImGuiConfigFlags_ViewportsEnable) {+ GLFWwindow* backup_context = glfwGetCurrentContext();+ ImGui::UpdatePlatformWindows();+ ImGui::RenderPlatformWindowsDefault();+ glfwMakeContextCurrent(backup_context);+ }++ glfwSwapBuffers(window);+ }++ // ========================================================================+ // Cleanup+ // ========================================================================+ hot_reload::shutdown();+ app.shutdown();++ ImGui_ImplOpenGL3_Shutdown();+ ImGui_ImplGlfw_Shutdown();+ ImGui::DestroyContext();++ glfwDestroyWindow(window);+ glfwTerminate();++ std::printf("[Main] Fincept Terminal shutdown complete\n");+ return 0;+}diff --git a/fincept-cpp/src/markets/markets_data.cpp b/fincept-cpp/src/markets/markets_data.cppnew file mode 100644index 000000000..96ccc4f9f--- /dev/null+++ b/fincept-cpp/src/markets/markets_data.cpp@@ -0,0 +1,181 @@+#include "markets_data.h"+#include <nlohmann/json.hpp>+#include <thread>+#include <sstream>++#ifdef _WIN32+#include <windows.h>+#endif++using json = nlohmann::json;++namespace fincept::markets {++const std::string MarketsData::empty_string_;+const std::vector<MarketQuote> MarketsData::empty_quotes_;++static const char* PYTHON_EXE = "C:/ProgramData/miniconda3/python.exe";+static const char* YFINANCE_SCRIPT =+ "C:/windowsdisk/finceptTerminal/fincept-terminal-desktop/"+ "src-tauri/resources/scripts/yfinance_data.py";++// Run python and capture stdout (same as research_data.cpp)+static std::string run_python(const std::string& args) {+ std::string cmd = std::string("\"") + PYTHON_EXE + "\" \""+ + YFINANCE_SCRIPT + "\" " + args;++#ifdef _WIN32+ SECURITY_ATTRIBUTES sa{};+ sa.nLength = sizeof(sa);+ sa.bInheritHandle = TRUE;++ HANDLE hRead = nullptr, hWrite = nullptr;+ CreatePipe(&hRead, &hWrite, &sa, 0);+ 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{};+ std::string cmd_line = cmd;++ BOOL ok = CreateProcessA(+ nullptr, cmd_line.data(), nullptr, nullptr, TRUE,+ CREATE_NO_WINDOW, nullptr, nullptr, &si, &pi+ );+ CloseHandle(hWrite);++ if (!ok) {+ CloseHandle(hRead);+ return "";+ }++ std::string output;+ char buffer[4096];+ DWORD bytesRead;+ while (ReadFile(hRead, buffer, sizeof(buffer) - 1, &bytesRead, nullptr) && bytesRead > 0) {+ buffer[bytesRead] = '\0';+ output += buffer;+ }+ CloseHandle(hRead);+ WaitForSingleObject(pi.hProcess, 60000);+ CloseHandle(pi.hProcess);+ CloseHandle(pi.hThread);++ // Extract last JSON line+ std::string json_line;+ std::istringstream stream(output);+ std::string line;+ while (std::getline(stream, line)) {+ size_t start = line.find_first_not_of(" \t\r\n");+ if (start == std::string::npos) continue;+ char first = line[start];+ if (first == '{' || first == '[') json_line = line;+ }+ return json_line;+#else+ FILE* pipe = popen(cmd.c_str(), "r");+ if (!pipe) return "";+ std::string output;+ char buffer[4096];+ while (fgets(buffer, sizeof(buffer), pipe)) output += buffer;+ pclose(pipe);++ std::string json_line;+ std::istringstream stream(output);+ std::string line;+ while (std::getline(stream, line)) {+ size_t start = line.find_first_not_of(" \t\r\n");+ if (start == std::string::npos) continue;+ char first = line[start];+ if (first == '{' || first == '[') json_line = line;+ }+ return json_line;+#endif+}++bool MarketsData::is_loading(const std::string& category) const {+ auto it = categories_.find(category);+ if (it == categories_.end()) return false;+ return it->second.loading.load();+}++bool MarketsData::has_data(const std::string& category) const {+ auto it = categories_.find(category);+ if (it == categories_.end()) return false;+ return it->second.has_data;+}++const std::string& MarketsData::error(const std::string& category) const {+ auto it = categories_.find(category);+ if (it == categories_.end()) return empty_string_;+ return it->second.error;+}++const std::vector<MarketQuote>& MarketsData::quotes(const std::string& category) const {+ auto it = categories_.find(category);+ if (it == categories_.end()) return empty_quotes_;+ return it->second.quotes;+}++void MarketsData::fetch_category(const std::string& category, const std::vector<std::string>& symbols) {+ auto& state = categories_[category];+ if (state.loading.load()) return;+ state.loading = true;+ state.error.clear();++ // Build symbol args: "batch_quotes SYM1 SYM2 SYM3..."+ std::string args = "batch_quotes";+ for (auto& s : symbols) args += " " + s;++ std::string cat = category;+ std::thread([this, cat, args]() {+ std::string out = run_python(args);+ if (!out.empty()) {+ std::lock_guard<std::mutex> lock(mutex_);+ parse_quotes(cat, out);+ } else {+ std::lock_guard<std::mutex> lock(mutex_);+ categories_[cat].error = "Failed to fetch data";+ }+ categories_[cat].has_data = true;+ categories_[cat].loading = false;+ }).detach();+}++void MarketsData::fetch_all(const std::vector<MarketCategory>& categories) {+ for (auto& cat : categories) {+ fetch_category(cat.title, cat.symbols);+ }+}++void MarketsData::parse_quotes(const std::string& category, const std::string& json_str) {+ auto& state = categories_[category];+ state.quotes.clear();+ try {+ auto j = json::parse(json_str);+ if (j.is_array()) {+ for (auto& item : j) {+ MarketQuote q;+ q.symbol = item.value("symbol", "");+ q.price = item.value("price", 0.0);+ q.change = item.value("change", 0.0);+ q.change_percent = item.value("change_percent", 0.0);+ q.high = item.value("high", 0.0);+ q.low = item.value("low", 0.0);+ q.open = item.value("open", 0.0);+ q.previous_close = item.value("previous_close", 0.0);+ q.volume = item.value("volume", 0.0);+ if (!q.symbol.empty())+ state.quotes.push_back(q);+ }+ }+ } catch (...) {+ state.error = "Parse error";+ }+}++} // namespace fincept::marketsdiff --git a/fincept-cpp/src/markets/markets_data.h b/fincept-cpp/src/markets/markets_data.hnew file mode 100644index 000000000..caa330ba9--- /dev/null+++ b/fincept-cpp/src/markets/markets_data.h@@ -0,0 +1,48 @@+#pragma once+// Markets tab — data fetching layer+// Uses yfinance batch_quotes to fetch quotes for multiple symbols++#include "markets_types.h"+#include <mutex>+#include <atomic>+#include <string>+#include <vector>+#include <map>++namespace fincept::markets {++class MarketsData {+public:+ // Fetch quotes for a category (runs in background thread)+ void fetch_category(const std::string& category, const std::vector<std::string>& symbols);++ // Fetch all categories at once+ void fetch_all(const std::vector<MarketCategory>& categories);++ std::mutex& mutex() { return mutex_; }++ bool is_loading(const std::string& category) const;+ bool has_data(const std::string& category) const;+ const std::string& error(const std::string& category) const;++ // Get quotes for a category+ const std::vector<MarketQuote>& quotes(const std::string& category) const;++private:+ std::mutex mutex_;++ struct CategoryState {+ std::atomic<bool> loading{false};+ bool has_data = false;+ std::string error;+ std::vector<MarketQuote> quotes;+ };++ mutable std::map<std::string, CategoryState> categories_;+ static const std::string empty_string_;+ static const std::vector<MarketQuote> empty_quotes_;++ void parse_quotes(const std::string& category, const std::string& json_str);+};++} // namespace fincept::marketsdiff --git a/fincept-cpp/src/markets/markets_screen.cpp b/fincept-cpp/src/markets/markets_screen.cppnew file mode 100644index 000000000..e47b35a0f--- /dev/null+++ b/fincept-cpp/src/markets/markets_screen.cpp@@ -0,0 +1,384 @@+#include "markets_screen.h"+#include "../theme/bloomberg_theme.h"+#include <imgui.h>+#include <cstdio>+#include <cstring>+#include <ctime>+#include <cmath>++namespace fincept::markets {++using namespace theme::colors;++// ─── Formatting helpers ─────────────────────────────────────────────────────+static const char* fmt_change(char* buf, size_t sz, double v) {+ std::snprintf(buf, sz, "%s%.2f", v >= 0 ? "+" : "", v);+ return buf;+}++static const char* fmt_pct(char* buf, size_t sz, double v) {+ std::snprintf(buf, sz, "%s%.2f%%", v >= 0 ? "+" : "", v);+ return buf;+}++// ─────────────────────────────────────────────────────────────────────────────+void MarketsScreen::init() {+ global_markets_ = default_global_markets();+ regional_markets_ = default_regional_markets();+ refresh_all();+ initialized_ = true;+}++void MarketsScreen::refresh_all() {+ data_.fetch_all(global_markets_);+ data_.fetch_all(regional_markets_);+ last_refresh_ = time(nullptr);+}++// ─────────────────────────────────────────────────────────────────────────────+void MarketsScreen::render() {+ if (!initialized_) init();++ ImGuiViewport* vp = ImGui::GetMainViewport();+ float tab_h = ImGui::GetFrameHeight() + 4;+ float footer_h = ImGui::GetFrameHeight();++ ImGui::SetNextWindowPos(ImVec2(vp->WorkPos.x, vp->WorkPos.y + tab_h));+ ImGui::SetNextWindowSize(ImVec2(vp->WorkSize.x, vp->WorkSize.y - tab_h - footer_h));++ ImGui::PushStyleColor(ImGuiCol_WindowBg, BG_DARK);+ ImGui::PushStyleVar(ImGuiStyleVar_WindowPadding, ImVec2(0, 0));++ ImGui::Begin("##markets_screen", nullptr,+ ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_NoResize | ImGuiWindowFlags_NoMove |+ ImGuiWindowFlags_NoScrollbar | ImGuiWindowFlags_NoDocking |+ ImGuiWindowFlags_NoFocusOnAppearing | ImGuiWindowFlags_NoBringToFrontOnFocus);++ render_header();+ render_controls();++ // Scrollable content area+ ImGui::BeginChild("##markets_content", ImVec2(0, 0), false);+ render_panels();+ ImGui::EndChild();++ ImGui::End();+ ImGui::PopStyleVar();+ ImGui::PopStyleColor();++ // Auto-update timer+ if (auto_update_) {+ update_timer_ += ImGui::GetIO().DeltaTime;+ if (update_timer_ >= update_interval_) {+ update_timer_ = 0;+ refresh_all();+ }+ }+}++// ─────────────────────────────────────────────────────────────────────────────+void MarketsScreen::render_header() {+ ImGui::PushStyleColor(ImGuiCol_ChildBg, BG_PANEL);+ ImGui::BeginChild("##mkt_header", ImVec2(0, 32), true);++ ImGui::TextColored(ACCENT, "FINCEPT");+ ImGui::SameLine(0, 8);+ ImGui::TextColored(TEXT_PRIMARY, "MARKET TERMINAL");+ ImGui::SameLine(0, 8);+ ImGui::TextColored(MARKET_GREEN, "LIVE");++ ImGui::SameLine(0, 16);+ ImGui::TextColored(BORDER_BRIGHT, "|");+ ImGui::SameLine(0, 16);++ // Timestamp+ time_t now = time(nullptr);+ struct tm* t = localtime(&now);+ char tb[32];+ std::strftime(tb, sizeof(tb), "%Y-%m-%d %H:%M:%S", t);+ ImGui::TextColored(TEXT_DIM, "%s", tb);++ // Right side: last refresh info+ ImGui::SameLine(ImGui::GetContentRegionAvail().x - 200);+ if (last_refresh_ > 0) {+ int elapsed = (int)difftime(now, last_refresh_);+ if (elapsed < 60)+ ImGui::TextColored(TEXT_DIM, "Updated %ds ago", elapsed);+ else+ ImGui::TextColored(TEXT_DIM, "Updated %dm ago", elapsed / 60);+ }++ ImGui::EndChild();+ ImGui::PopStyleColor();+}++// ─────────────────────────────────────────────────────────────────────────────+void MarketsScreen::render_controls() {+ ImGui::PushStyleColor(ImGuiCol_ChildBg, BG_PANEL);+ ImGui::BeginChild("##mkt_controls", ImVec2(0, 30), true);++ // Refresh button+ if (theme::AccentButton("REFRESH ALL")) {+ refresh_all();+ }++ ImGui::SameLine(0, 12);++ // Auto-update toggle+ ImVec4 auto_col = auto_update_ ? MARKET_GREEN : TEXT_DIM;+ ImGui::PushStyleColor(ImGuiCol_Button, auto_update_ ? ImVec4(0.0f, 0.5f, 0.2f, 1.0f) : BG_WIDGET);+ ImGui::PushStyleColor(ImGuiCol_Text, auto_update_ ? TEXT_PRIMARY : TEXT_DIM);+ char auto_label[32];+ std::snprintf(auto_label, sizeof(auto_label), "AUTO %s", auto_update_ ? "ON" : "OFF");+ if (ImGui::Button(auto_label)) {+ auto_update_ = !auto_update_;+ update_timer_ = 0;+ }+ ImGui::PopStyleColor(2);++ ImGui::SameLine(0, 8);++ // Interval selector+ static const char* intervals[] = {"10 min", "15 min", "30 min", "1 hour"};+ static const float interval_vals[] = {600.0f, 900.0f, 1800.0f, 3600.0f};++ ImGui::PushItemWidth(80);+ ImGui::PushStyleColor(ImGuiCol_FrameBg, BG_INPUT);+ ImGui::PushStyleColor(ImGuiCol_Text, TEXT_PRIMARY);+ if (ImGui::Combo("##interval", &interval_index_, intervals, 4)) {+ update_interval_ = interval_vals[interval_index_];+ update_timer_ = 0;+ }+ ImGui::PopStyleColor(2);+ ImGui::PopItemWidth();++ ImGui::SameLine(0, 16);+ ImGui::TextColored(BORDER_BRIGHT, "|");+ ImGui::SameLine(0, 16);++ // Count panels and symbols+ int total_panels = (int)global_markets_.size() + (int)regional_markets_.size();+ int total_symbols = 0;+ for (auto& m : global_markets_) total_symbols += (int)m.symbols.size();+ for (auto& m : regional_markets_) total_symbols += (int)m.symbols.size();+ ImGui::TextColored(TEXT_DIM, "%d panels | %d symbols", total_panels, total_symbols);++ // Loading indicator+ bool any_loading = false;+ for (auto& m : global_markets_) if (data_.is_loading(m.title)) any_loading = true;+ for (auto& m : regional_markets_) if (data_.is_loading(m.title)) any_loading = true;+ if (any_loading) {+ ImGui::SameLine(0, 12);+ ImGui::TextColored(WARNING, "[LOADING...]");+ }++ ImGui::EndChild();+ ImGui::PopStyleColor();+}++// ─────────────────────────────────────────────────────────────────────────────+void MarketsScreen::render_panels() {+ ImGui::PushStyleVar(ImGuiStyleVar_WindowPadding, ImVec2(8, 8));++ // ── Global Markets ──+ ImGui::Spacing();+ ImGui::PushStyleColor(ImGuiCol_Text, ACCENT);+ ImGui::SetWindowFontScale(1.1f);+ ImGui::TextUnformatted(" GLOBAL MARKETS");+ ImGui::SetWindowFontScale(1.0f);+ ImGui::PopStyleColor();+ ImGui::PushStyleColor(ImGuiCol_Separator, BORDER_DIM);+ ImGui::Separator();+ ImGui::PopStyleColor();+ ImGui::Spacing();++ // Render global panels in a grid (3 columns)+ float avail_w = ImGui::GetContentRegionAvail().x;+ float panel_w = (avail_w - 24) / 3.0f;+ if (panel_w < 280) panel_w = (avail_w - 16) / 2.0f;+ if (panel_w < 280) panel_w = avail_w - 8;++ int col = 0;+ int max_cols = (int)((avail_w + 8) / (panel_w + 8));+ if (max_cols < 1) max_cols = 1;++ for (size_t i = 0; i < global_markets_.size(); i++) {+ if (col > 0) ImGui::SameLine(0, 8);+ ImGui::BeginChild(("##gp_" + std::to_string(i)).c_str(),+ ImVec2(panel_w, 280), true);+ render_panel(global_markets_[i]);+ ImGui::EndChild();++ col++;+ if (col >= max_cols) col = 0;+ }++ ImGui::Spacing(); ImGui::Spacing();++ // ── Regional Markets ──+ ImGui::PushStyleColor(ImGuiCol_Text, ACCENT);+ ImGui::SetWindowFontScale(1.1f);+ ImGui::TextUnformatted(" REGIONAL MARKETS - LIVE DATA");+ ImGui::SetWindowFontScale(1.0f);+ ImGui::PopStyleColor();+ ImGui::PushStyleColor(ImGuiCol_Separator, BORDER_DIM);+ ImGui::Separator();+ ImGui::PopStyleColor();+ ImGui::Spacing();++ col = 0;+ for (size_t i = 0; i < regional_markets_.size(); i++) {+ if (col > 0) ImGui::SameLine(0, 8);+ ImGui::BeginChild(("##rp_" + std::to_string(i)).c_str(),+ ImVec2(panel_w, 300), true);+ render_panel(regional_markets_[i]);+ ImGui::EndChild();++ col++;+ if (col >= max_cols) col = 0;+ }++ ImGui::Spacing();+ ImGui::PopStyleVar();+}++// ─────────────────────────────────────────────────────────────────────────────+void MarketsScreen::render_panel(const MarketCategory& cat) {+ std::lock_guard<std::mutex> lock(data_.mutex());++ bool loading = data_.is_loading(cat.title);+ auto& quotes = data_.quotes(cat.title);+ auto& err = data_.error(cat.title);++ // ── Panel Header ──+ ImGui::PushStyleColor(ImGuiCol_ChildBg, BG_DARKEST);+ ImGui::BeginChild(("##ph_" + cat.title).c_str(), ImVec2(0, 24), true);++ ImGui::TextColored(ACCENT, "%s", cat.title.c_str());+ if (cat.show_name) {+ ImGui::SameLine(0, 8);+ ImGui::TextColored(MARKET_GREEN, "LIVE");+ }++ if (loading) {+ ImGui::SameLine(ImGui::GetContentRegionAvail().x - 40);+ ImGui::TextColored(WARNING, "[...]");+ }++ // Refresh single panel+ ImGui::SameLine(ImGui::GetContentRegionAvail().x - 12);+ ImGui::PushStyleColor(ImGuiCol_Button, ImVec4(0, 0, 0, 0));+ ImGui::PushStyleColor(ImGuiCol_Text, TEXT_DIM);+ if (ImGui::SmallButton(("R##" + cat.title).c_str())) {+ data_.fetch_category(cat.title, cat.symbols);+ }+ ImGui::PopStyleColor(2);++ ImGui::EndChild();+ ImGui::PopStyleColor();++ // ── Error banner ──+ if (!err.empty()) {+ ImGui::PushStyleColor(ImGuiCol_ChildBg, ImVec4(0.3f, 0.05f, 0.05f, 1.0f));+ ImGui::BeginChild(("##err_" + cat.title).c_str(), ImVec2(0, 18), false);+ ImGui::TextColored(MARKET_RED, " %s", err.c_str());+ ImGui::EndChild();+ ImGui::PopStyleColor();+ }++ // ── Table ──+ ImGuiTableFlags flags = ImGuiTableFlags_RowBg | ImGuiTableFlags_BordersInnerH |+ ImGuiTableFlags_SizingStretchProp | ImGuiTableFlags_ScrollY;++ int num_cols = cat.show_name ? 5 : 6;+ if (ImGui::BeginTable(cat.title.c_str(), num_cols, flags)) {+ // Header+ ImGui::TableSetupColumn("SYMBOL", ImGuiTableColumnFlags_WidthStretch, cat.show_name ? 1.2f : 1.5f);+ if (cat.show_name)+ ImGui::TableSetupColumn("NAME", ImGuiTableColumnFlags_WidthStretch, 2.0f);+ ImGui::TableSetupColumn("PRICE", ImGuiTableColumnFlags_WidthStretch, 1.0f);+ ImGui::TableSetupColumn("CHG", ImGuiTableColumnFlags_WidthStretch, 1.0f);+ ImGui::TableSetupColumn("%CHG", ImGuiTableColumnFlags_WidthStretch, 1.0f);+ if (!cat.show_name) {+ ImGui::TableSetupColumn("HIGH", ImGuiTableColumnFlags_WidthStretch, 1.0f);+ ImGui::TableSetupColumn("LOW", ImGuiTableColumnFlags_WidthStretch, 1.0f);+ }+ ImGui::TableSetupScrollFreeze(0, 1);++ // Style header row+ ImGui::PushStyleColor(ImGuiCol_TableHeaderBg, BG_DARKEST);+ ImGui::TableHeadersRow();+ ImGui::PopStyleColor();++ if (loading && quotes.empty()) {+ // Loading skeleton+ for (int i = 0; i < (int)cat.symbols.size() && i < 12; i++) {+ ImGui::TableNextRow();+ ImGui::TableSetColumnIndex(0);+ ImGui::TextColored(TEXT_DIM, "...");+ }+ } else if (quotes.empty()) {+ ImGui::TableNextRow();+ ImGui::TableSetColumnIndex(0);+ ImGui::TextColored(TEXT_DIM, "No data");+ } else {+ char buf[32];+ for (auto& q : quotes) {+ ImGui::TableNextRow();++ // Symbol+ ImGui::TableSetColumnIndex(0);+ ImGui::TextColored(TEXT_PRIMARY, "%s", q.symbol.c_str());++ int col_idx = 1;++ // Name (regional only)+ if (cat.show_name) {+ ImGui::TableSetColumnIndex(col_idx++);+ auto it = cat.names.find(q.symbol);+ const char* name = (it != cat.names.end()) ? it->second.c_str() : q.symbol.c_str();+ ImGui::TextColored(TEXT_SECONDARY, "%s", name);+ }++ // Price+ ImGui::TableSetColumnIndex(col_idx++);+ std::snprintf(buf, sizeof(buf), "%.2f", q.price);+ ImGui::TextColored(TEXT_PRIMARY, "%s", buf);++ // Change+ ImGui::TableSetColumnIndex(col_idx++);+ ImVec4 chg_col = q.change >= 0 ? MARKET_GREEN : MARKET_RED;+ fmt_change(buf, sizeof(buf), q.change);+ ImGui::TextColored(chg_col, "%s", buf);++ // %Change+ ImGui::TableSetColumnIndex(col_idx++);+ fmt_pct(buf, sizeof(buf), q.change_percent);+ ImGui::TextColored(chg_col, "%s", buf);++ // High/Low (global only)+ if (!cat.show_name) {+ ImGui::TableSetColumnIndex(col_idx++);+ if (q.high > 0) {+ std::snprintf(buf, sizeof(buf), "%.2f", q.high);+ ImGui::TextColored(TEXT_DIM, "%s", buf);+ } else {+ ImGui::TextColored(TEXT_DIM, "-");+ }++ ImGui::TableSetColumnIndex(col_idx++);+ if (q.low > 0) {+ std::snprintf(buf, sizeof(buf), "%.2f", q.low);+ ImGui::TextColored(TEXT_DIM, "%s", buf);+ } else {+ ImGui::TextColored(TEXT_DIM, "-");+ }+ }+ }+ }++ ImGui::EndTable();+ }+}++} // namespace fincept::marketsdiff --git a/fincept-cpp/src/markets/markets_screen.h b/fincept-cpp/src/markets/markets_screen.hnew file mode 100644index 000000000..100ee5471--- /dev/null+++ b/fincept-cpp/src/markets/markets_screen.h@@ -0,0 +1,38 @@+#pragma once+// Markets tab — main screen with global + regional market panels++#include "markets_data.h"+#include "markets_types.h"+#include <vector>+#include <string>+#include <ctime>++namespace fincept::markets {++class MarketsScreen {+public:+ void render();++private:+ void init();+ void render_header();+ void render_controls();+ void render_panels();+ void render_panel(const MarketCategory& cat);+ void refresh_all();++ bool initialized_ = false;++ MarketsData data_;+ std::vector<MarketCategory> global_markets_;+ std::vector<MarketCategory> regional_markets_;++ bool auto_update_ = true;+ float update_timer_ = 0;+ float update_interval_ = 600.0f; // 10 min default+ int interval_index_ = 0; // combo index++ time_t last_refresh_ = 0;+};++} // namespace fincept::marketsdiff --git a/fincept-cpp/src/markets/markets_types.h b/fincept-cpp/src/markets/markets_types.hnew file mode 100644index 000000000..bc49effcb--- /dev/null+++ b/fincept-cpp/src/markets/markets_types.h@@ -0,0 +1,124 @@+#pragma once+// Markets tab — data types++#include <string>+#include <vector>+#include <map>++namespace fincept::markets {++struct MarketQuote {+ std::string symbol;+ std::string name; // optional display name+ double price = 0;+ double change = 0;+ double change_percent = 0;+ double high = 0;+ double low = 0;+ double open = 0;+ double previous_close = 0;+ double volume = 0;+};++struct MarketCategory {+ std::string title;+ std::vector<std::string> symbols;+ std::map<std::string, std::string> names; // symbol -> display name (for regional)+ bool show_name = false; // show name column+};++// Default ticker categories+inline std::vector<MarketCategory> default_global_markets() {+ return {+ {"Stock Indices", {+ "^GSPC", "^IXIC", "^DJI", "^RUT", "^VIX",+ "^FTSE", "^GDAXI", "^N225", "^FCHI", "^HSI",+ "^AXJO", "^BSESN", "^NSEI", "^STOXX50E"+ }, {}, false},+ {"Forex", {+ "EURUSD=X", "GBPUSD=X", "USDJPY=X", "USDCHF=X",+ "USDCAD=X", "AUDUSD=X", "NZDUSD=X", "EURGBP=X",+ "EURJPY=X", "GBPJPY=X", "USDCNY=X", "USDINR=X"+ }, {}, false},+ {"Commodities", {+ "GC=F", "SI=F", "PL=F", "HG=F",+ "CL=F", "BZ=F", "NG=F",+ "ZC=F", "ZW=F", "ZS=F",+ "KC=F", "CT=F", "SB=F", "CC=F"+ }, {}, false},+ {"Bonds & Fixed Income", {+ "^TNX", "^TYX", "^IRX", "^FVX",+ "TLT", "IEF", "SHY", "BND", "AGG", "LQD", "HYG", "JNK"+ }, {}, false},+ {"ETFs", {+ "SPY", "QQQ", "DIA", "EEM", "GLD",+ "XLK", "XLE", "XLF", "XLV", "VNQ", "IWM", "VTI"+ }, {}, false},+ {"Cryptocurrencies", {+ "BTC-USD", "ETH-USD", "BNB-USD", "SOL-USD",+ "XRP-USD", "ADA-USD", "DOGE-USD", "LINK-USD",+ "DOT-USD", "AVAX-USD", "UNI-USD", "ATOM-USD"+ }, {}, false}+ };+}++inline std::vector<MarketCategory> default_regional_markets() {+ return {+ {"India", {+ "RELIANCE.NS", "TCS.NS", "HDFCBANK.NS", "INFY.NS",+ "HINDUNILVR.NS", "ICICIBANK.NS", "SBIN.NS", "BHARTIARTL.NS",+ "ITC.NS", "KOTAKBANK.NS", "LT.NS", "WIPRO.NS"+ }, {+ {"RELIANCE.NS", "Reliance Industries"},+ {"TCS.NS", "Tata Consultancy"},+ {"HDFCBANK.NS", "HDFC Bank"},+ {"INFY.NS", "Infosys"},+ {"HINDUNILVR.NS", "Hindustan Unilever"},+ {"ICICIBANK.NS", "ICICI Bank"},+ {"SBIN.NS", "State Bank of India"},+ {"BHARTIARTL.NS", "Bharti Airtel"},+ {"ITC.NS", "ITC Limited"},+ {"KOTAKBANK.NS", "Kotak Mahindra Bank"},+ {"LT.NS", "Larsen & Toubro"},+ {"WIPRO.NS", "Wipro Limited"}+ }, true},+ {"China", {+ "BABA", "PDD", "JD", "BIDU",+ "NIO", "LI", "XPEV", "BILI",+ "NTES", "ZTO", "VNET", "TAL"+ }, {+ {"BABA", "Alibaba Group"},+ {"PDD", "PDD Holdings"},+ {"JD", "JD.com"},+ {"BIDU", "Baidu"},+ {"NIO", "NIO Inc"},+ {"LI", "Li Auto"},+ {"XPEV", "XPeng"},+ {"BILI", "Bilibili"},+ {"NTES", "NetEase"},+ {"ZTO", "ZTO Express"},+ {"VNET", "VNET Group"},+ {"TAL", "TAL Education"}+ }, true},+ {"United States", {+ "AAPL", "MSFT", "GOOGL", "AMZN",+ "NVDA", "META", "TSLA", "JPM",+ "V", "WMT", "UNH", "MA"+ }, {+ {"AAPL", "Apple Inc"},+ {"MSFT", "Microsoft Corp"},+ {"GOOGL", "Alphabet Inc"},+ {"AMZN", "Amazon.com"},+ {"NVDA", "NVIDIA Corp"},+ {"META", "Meta Platforms"},+ {"TSLA", "Tesla Inc"},+ {"JPM", "JPMorgan Chase"},+ {"V", "Visa Inc"},+ {"WMT", "Walmart Inc"},+ {"UNH", "UnitedHealth Group"},+ {"MA", "Mastercard Inc"}+ }, true}+ };+}++} // namespace fincept::marketsdiff --git a/fincept-cpp/src/news/news_screen.cpp b/fincept-cpp/src/news/news_screen.cppnew file mode 100644index 000000000..e34ea6936--- /dev/null+++ b/fincept-cpp/src/news/news_screen.cpp@@ -0,0 +1,1055 @@+#include "news_screen.h"+#include "http/http_client.h"+#include "theme/bloomberg_theme.h"+#include <imgui.h>+#include <algorithm>+#include <ctime>+#include <cstdio>+#include <thread>+#include <regex>+#include <sstream>+#include <cstring>+#include <map>+#ifdef _WIN32+#include <windows.h>+#include <shellapi.h>+#endif++namespace fincept::news {++// ============================================================================+// Default RSS Feeds (subset of main terminal's 150+ feeds)+// ============================================================================+std::vector<RSSFeed> NewsScreen::get_default_feeds() {+ return {+ // Tier 1 — Wire Services & Regulators+ {"reuters-biz", "Reuters Business", "https://feeds.reuters.com/reuters/businessNews", "MARKETS", "GLOBAL", "REUTERS", 1},+ {"reuters-mkts", "Reuters Markets", "https://feeds.reuters.com/reuters/financialsNews", "MARKETS", "GLOBAL", "REUTERS", 1},+ {"reuters-world", "Reuters World", "https://feeds.reuters.com/Reuters/worldNews", "GEOPOLITICS", "GLOBAL", "REUTERS", 1},+ {"sec-press", "SEC Press Releases", "https://www.sec.gov/news/pressreleases.rss", "REGULATORY", "US", "SEC", 1},+ {"fed-press", "Federal Reserve", "https://www.federalreserve.gov/feeds/press_all.xml", "REGULATORY", "US", "FED RESERVE", 1},++ // Tier 2 — Major Financial Media+ {"bloomberg-mkts", "Bloomberg Markets", "https://feeds.bloomberg.com/markets/news.rss", "MARKETS", "GLOBAL", "BLOOMBERG", 2},+ {"wsj-markets", "WSJ Markets", "https://feeds.a.dj.com/rss/RSSMarketsMain.xml", "MARKETS", "US", "WSJ", 2},+ {"wsj-world", "WSJ World", "https://feeds.a.dj.com/rss/RSSWorldNews.xml", "GEOPOLITICS", "GLOBAL", "WSJ", 2},+ {"cnbc-finance", "CNBC Finance", "https://search.cnbc.com/rs/search/combinedcms/view.xml?partnerId=wrss01&id=100003114", "MARKETS", "US", "CNBC", 2},+ {"marketwatch", "MarketWatch", "https://feeds.marketwatch.com/marketwatch/topstories/", "MARKETS", "US", "MARKETWATCH", 2},+ {"bbc-business", "BBC Business", "http://feeds.bbci.co.uk/news/business/rss.xml", "MARKETS", "GLOBAL", "BBC", 2},+ {"bbc-world", "BBC World", "http://feeds.bbci.co.uk/news/world/rss.xml", "GEOPOLITICS", "GLOBAL", "BBC", 2},++ // Tier 2 — Tech+ {"techcrunch", "TechCrunch", "https://techcrunch.com/feed/", "TECH", "GLOBAL", "TECHCRUNCH", 2},++ // Tier 2 — Crypto+ {"coindesk", "CoinDesk", "https://www.coindesk.com/arc/outboundfeeds/rss/", "CRYPTO", "GLOBAL", "COINDESK", 2},+ {"cointelegraph", "CoinTelegraph", "https://cointelegraph.com/rss", "CRYPTO", "GLOBAL", "COINTELEGRAPH", 2},++ // Tier 2 — Energy+ {"oilprice", "OilPrice", "https://oilprice.com/rss/main", "ENERGY", "GLOBAL", "OILPRICE", 2},++ // Tier 2 — Economics+ {"economist", "The Economist", "https://www.economist.com/sections/economics/rss.xml", "ECONOMIC", "GLOBAL", "ECONOMIST", 2},++ // Tier 2 — Geopolitics+ {"foreignpolicy", "Foreign Policy", "https://foreignpolicy.com/feed/", "GEOPOLITICS", "GLOBAL", "FOREIGN POLICY", 2},+ {"aljazeera", "Al Jazeera", "https://www.aljazeera.com/xml/rss/all.xml", "GEOPOLITICS", "GLOBAL", "AL JAZEERA", 2},+ };+}++// ============================================================================+// Simple XML tag extractor (no dependency needed)+// ============================================================================+static std::string extract_tag(const std::string& xml, const std::string& tag, size_t start = 0) {+ std::string open = "<" + tag + ">";+ std::string open2 = "<" + tag + " "; // tag with attributes+ std::string close = "</" + tag + ">";++ size_t pos = xml.find(open, start);+ size_t content_start = 0;+ if (pos != std::string::npos) {+ content_start = pos + open.size();+ } else {+ pos = xml.find(open2, start);+ if (pos == std::string::npos) return "";+ // Find end of opening tag+ size_t end_bracket = xml.find('>', pos);+ if (end_bracket == std::string::npos) return "";+ content_start = end_bracket + 1;+ }++ size_t end_pos = xml.find(close, content_start);+ if (end_pos == std::string::npos) return "";++ std::string content = xml.substr(content_start, end_pos - content_start);++ // Handle CDATA+ if (content.find("<![CDATA[") == 0) {+ size_t cdata_end = content.find("]]>");+ if (cdata_end != std::string::npos) {+ content = content.substr(9, cdata_end - 9);+ }+ }++ return content;+}++// Find all <item> or <entry> blocks+static std::vector<std::string> extract_items(const std::string& xml) {+ std::vector<std::string> items;++ // Try <item> (RSS 2.0)+ std::string open = "<item>";+ std::string open2 = "<item ";+ std::string close = "</item>";+ size_t pos = 0;++ while (true) {+ size_t start = xml.find(open, pos);+ size_t start2 = xml.find(open2, pos);++ // Pick whichever comes first+ size_t item_start = std::string::npos;+ if (start != std::string::npos && start2 != std::string::npos)+ item_start = std::min(start, start2);+ else if (start != std::string::npos)+ item_start = start;+ else if (start2 != std::string::npos)+ item_start = start2;+ else+ break;++ size_t end = xml.find(close, item_start);+ if (end == std::string::npos) break;++ items.push_back(xml.substr(item_start, end + close.size() - item_start));+ pos = end + close.size();+ }++ // If no <item>, try <entry> (Atom)+ if (items.empty()) {+ open = "<entry>";+ open2 = "<entry ";+ close = "</entry>";+ pos = 0;+ while (true) {+ size_t start = xml.find(open, pos);+ size_t start2 = xml.find(open2, pos);+ size_t item_start = std::string::npos;+ if (start != std::string::npos && start2 != std::string::npos)+ item_start = std::min(start, start2);+ else if (start != std::string::npos)+ item_start = start;+ else if (start2 != std::string::npos)+ item_start = start2;+ else+ break;++ size_t end = xml.find(close, item_start);+ if (end == std::string::npos) break;+ items.push_back(xml.substr(item_start, end + close.size() - item_start));+ pos = end + close.size();+ }+ }++ return items;+}++// ============================================================================+// HTML stripping+// ============================================================================+std::string NewsScreen::strip_html(const std::string& html) {+ std::string result;+ result.reserve(html.size());+ bool in_tag = false;+ for (char c : html) {+ if (c == '<') { in_tag = true; continue; }+ if (c == '>') { in_tag = false; continue; }+ if (!in_tag) result += c;+ }+ // Trim+ size_t s = result.find_first_not_of(" \t\n\r");+ size_t e = result.find_last_not_of(" \t\n\r");+ if (s == std::string::npos) return "";+ return result.substr(s, e - s + 1);+}++// ============================================================================+// Relative time+// ============================================================================+std::string NewsScreen::relative_time(int64_t ts) {+ if (ts == 0) return "";+ int64_t now = (int64_t)std::time(nullptr);+ int64_t diff = now - ts;+ if (diff < 0) diff = 0;+ if (diff < 60) return std::to_string(diff) + "s";+ if (diff < 3600) return std::to_string(diff / 60) + "m";+ if (diff < 86400) return std::to_string(diff / 3600) + "h";+ return std::to_string(diff / 86400) + "d";+}++// Windows doesn't have strptime — minimal implementation+#ifdef _WIN32+static char* strptime(const char* s, const char* fmt, struct tm* t) {+ std::memset(t, 0, sizeof(struct tm));+ std::istringstream input(s);++ const char* p = fmt;+ while (*p) {+ if (*p == '%') {+ p++;+ switch (*p) {+ case 'a': { // abbreviated weekday — skip 3 chars + comma + space+ char buf[16];+ input.read(buf, 3);+ if (input.peek() == ',') input.get();+ if (input.peek() == ' ') input.get();+ break;+ }+ case 'd': input >> t->tm_mday; break;+ case 'b': case 'B': {+ char mon[16] = {};+ input.read(mon, 3);+ const char* months[] = {"Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"};+ for (int i = 0; i < 12; i++) {+ if (_strnicmp(mon, months[i], 3) == 0) { t->tm_mon = i; break; }+ }+ break;+ }+ case 'Y': input >> t->tm_year; t->tm_year -= 1900; break;+ case 'H': input >> t->tm_hour; break;+ case 'M': input >> t->tm_min; break;+ case 'S': input >> t->tm_sec; break;+ case 'm': input >> t->tm_mon; t->tm_mon--; break;+ default: break;+ }+ p++;+ } else {+ if (input.peek() == *p) input.get();+ p++;+ }+ }++ if (input.fail()) return nullptr;+ return const_cast<char*>(s + (size_t)input.tellg());+}+#endif++// ============================================================================+// Parse date string to unix timestamp (handles common RSS date formats)+// ============================================================================+static int64_t parse_rss_date(const std::string& date_str) {+ if (date_str.empty()) return 0;++ struct tm t = {};++ // Try RFC 2822: "Thu, 13 Mar 2025 14:30:00 GMT"+ if (strptime(date_str.c_str(), "%a, %d %b %Y %H:%M:%S", &t) ||+ strptime(date_str.c_str(), "%d %b %Y %H:%M:%S", &t)) {+ #ifdef _WIN32+ return _mkgmtime(&t);+ #else+ return timegm(&t);+ #endif+ }++ // Try ISO 8601: "2025-03-13T14:30:00Z"+ if (strptime(date_str.c_str(), "%Y-%m-%dT%H:%M:%S", &t) ||+ strptime(date_str.c_str(), "%Y-%m-%d %H:%M:%S", &t)) {+ #ifdef _WIN32+ return _mkgmtime(&t);+ #else+ return timegm(&t);+ #endif+ }++ return 0;+}++// ============================================================================+// Parse RSS XML into articles+// ============================================================================+std::vector<NewsArticle> NewsScreen::parse_rss_xml(const std::string& xml, const RSSFeed& feed) {+ std::vector<NewsArticle> articles;+ auto items = extract_items(xml);++ int idx = 0;+ for (const auto& item_xml : items) {+ idx++;+ NewsArticle a;+ a.id = feed.id + "-" + std::to_string(idx);+ a.source = feed.source;+ a.category = feed.category;+ a.region = feed.region;+ a.tier = feed.tier;++ // Extract fields+ a.headline = strip_html(extract_tag(item_xml, "title"));+ if (a.headline.empty()) continue;+ if (a.headline.size() > 200) a.headline = a.headline.substr(0, 200);++ std::string desc = extract_tag(item_xml, "description");+ if (desc.empty()) desc = extract_tag(item_xml, "summary");+ if (desc.empty()) desc = extract_tag(item_xml, "content:encoded");+ a.summary = strip_html(desc);+ if (a.summary.size() > 300) a.summary = a.summary.substr(0, 300);++ a.link = extract_tag(item_xml, "link");++ // Parse date+ std::string date = extract_tag(item_xml, "pubDate");+ if (date.empty()) date = extract_tag(item_xml, "published");+ if (date.empty()) date = extract_tag(item_xml, "updated");+ if (date.empty()) date = extract_tag(item_xml, "dc:date");++ a.sort_ts = parse_rss_date(date);+ if (a.sort_ts > 0) {+ time_t tt = (time_t)a.sort_ts;+ struct tm* lt = gmtime(&tt);+ char buf[32];+ std::strftime(buf, sizeof(buf), "%b %d, %H:%M", lt);+ a.time_str = buf;+ } else {+ a.sort_ts = (int64_t)std::time(nullptr);+ time_t tt = (time_t)a.sort_ts;+ struct tm* lt = localtime(&tt);+ char buf[32];+ std::strftime(buf, sizeof(buf), "%b %d, %H:%M", lt);+ a.time_str = buf;+ }++ // Enrich with sentiment/priority+ enrich_article(a);++ articles.push_back(std::move(a));+ }++ return articles;+}++// ============================================================================+// Sentiment & Priority Enrichment (mirrors Rust enrich_article)+// ============================================================================+void NewsScreen::enrich_article(NewsArticle& a) {+ // Build lowercase combined text+ std::string text = a.headline + " " + a.summary;+ std::transform(text.begin(), text.end(), text.begin(), ::tolower);++ // Priority+ if (text.find("breaking") != std::string::npos || text.find("alert") != std::string::npos)+ a.priority = Priority::FLASH;+ else if (text.find("urgent") != std::string::npos || text.find("emergency") != std::string::npos)+ a.priority = Priority::URGENT;+ else if (text.find("announce") != std::string::npos || text.find("report") != std::string::npos)+ a.priority = Priority::BREAKING;++ // Weighted sentiment+ struct WordWeight { const char* word; int weight; };++ static const WordWeight positive[] = {+ {"surge", 3}, {"soar", 3}, {"breakthrough", 3}, {"boom", 3}, {"record high", 3},+ {"rally", 2}, {"gain", 2}, {"rise", 2}, {"jump", 2}, {"climb", 2}, {"boost", 2},+ {"beat", 2}, {"upgrade", 2}, {"profit", 2}, {"growth", 2}, {"recover", 2},+ {"ceasefire", 2}, {"peace", 2}, {"treaty", 2}, {"reform", 2}, {"milestone", 2},+ {"strong", 1}, {"robust", 1}, {"positive", 1}, {"success", 1}, {"win", 1},+ {"deal", 1}, {"confidence", 1}, {"launch", 1}, {"bullish", 1}, {"outperform", 1},+ };++ static const WordWeight negative[] = {+ {"crash", 3}, {"plunge", 3}, {"collapse", 3}, {"devastat", 3}, {"invasion", 3},+ {"bankruptcy", 3}, {"meltdown", 3}, {"pandemic", 3},+ {"fall", 2}, {"drop", 2}, {"decline", 2}, {"tumble", 2}, {"slump", 2},+ {"crisis", 2}, {"conflict", 2}, {"attack", 2}, {"sanction", 2}, {"tariff", 2},+ {"layoff", 2}, {"downgrade", 2}, {"fraud", 2}, {"scandal", 2}, {"recession", 2},+ {"weak", 1}, {"loss", 1}, {"risk", 1}, {"threat", 1}, {"warning", 1},+ {"debt", 1}, {"inflation", 1}, {"bearish", 1}, {"volatile", 1},+ };++ int score = 0;+ for (const auto& w : positive)+ if (text.find(w.word) != std::string::npos) score += w.weight;+ for (const auto& w : negative)+ if (text.find(w.word) != std::string::npos) score -= w.weight;++ if (score >= 2) a.sentiment = Sentiment::BULLISH;+ else if (score <= -2) a.sentiment = Sentiment::BEARISH;+ else a.sentiment = Sentiment::NEUTRAL;++ // Extract tickers ($AAPL, $TSLA etc)+ for (size_t i = 0; i < a.headline.size(); i++) {+ if (a.headline[i] == '$' && i + 1 < a.headline.size() && std::isalpha(a.headline[i + 1])) {+ std::string ticker;+ for (size_t j = i + 1; j < a.headline.size() && std::isalpha(a.headline[j]); j++)+ ticker += (char)std::toupper(a.headline[j]);+ if (ticker.size() >= 1 && ticker.size() <= 5)+ a.tickers.push_back(ticker);+ }+ }+}++// ============================================================================+// Fetch news from all feeds (background thread)+// ============================================================================+void NewsScreen::fetch_news() {+ if (loading_) return;+ loading_ = true;+ error_.clear();++ std::thread([this]() {+ auto feeds = get_default_feeds();+ auto& http = http::HttpClient::instance();+ std::vector<NewsArticle> all_articles;++ int success_count = 0;+ int fail_count = 0;++ for (const auto& feed : feeds) {+ if (!feed.enabled) continue;++ http::Headers hdrs;+ hdrs["User-Agent"] = "FinceptTerminal/3.3.1";+ hdrs["Accept"] = "application/rss+xml, application/xml, text/xml, */*";++ auto resp = http.get(feed.url, hdrs);+ if (resp.success && !resp.body.empty()) {+ auto parsed = parse_rss_xml(resp.body, feed);+ all_articles.insert(all_articles.end(), parsed.begin(), parsed.end());+ success_count++;+ } else {+ fail_count++;+ }+ }++ // Sort by timestamp descending (newest first)+ std::sort(all_articles.begin(), all_articles.end(),+ [](const NewsArticle& a, const NewsArticle& b) { return a.sort_ts > b.sort_ts; });++ {+ std::lock_guard<std::mutex> lock(data_mutex_);+ articles_ = std::move(all_articles);+ if (success_count == 0) {+ error_ = "Failed to fetch news from all feeds";+ } else if (fail_count > 0) {+ char buf[64];+ std::snprintf(buf, sizeof(buf), "Fetched %d feeds (%d failed)", success_count, fail_count);+ error_ = buf;+ }+ }++ loading_ = false;+ last_fetch_time_ = (double)std::time(nullptr);+ std::printf("[News] Fetched %d articles from %d feeds\n", (int)articles_.size(), success_count);+ }).detach();+}++// ============================================================================+// Get filtered articles based on UI state+// ============================================================================+std::vector<NewsArticle> NewsScreen::get_filtered_articles() {+ std::lock_guard<std::mutex> lock(data_mutex_);+ std::vector<NewsArticle> filtered;++ int64_t now = (int64_t)std::time(nullptr);+ int64_t time_cutoff = 0;+ switch (time_filter_) {+ case 1: time_cutoff = now - 3600; break; // 1h+ case 2: time_cutoff = now - 4 * 3600; break; // 4h+ case 3: time_cutoff = now - 86400; break; // 24h+ case 4: time_cutoff = now - 7 * 86400; break; // 7d+ }++ std::string search_lower;+ if (search_buf_[0]) {+ search_lower = search_buf_;+ std::transform(search_lower.begin(), search_lower.end(), search_lower.begin(), ::tolower);+ }++ for (const auto& a : articles_) {+ // Time filter+ if (time_cutoff > 0 && a.sort_ts < time_cutoff) continue;++ // Category filter+ if (category_filter_ > 0) {+ if (a.category != CATEGORIES[category_filter_]) continue;+ }++ // Search filter+ if (!search_lower.empty()) {+ std::string h = a.headline;+ std::transform(h.begin(), h.end(), h.begin(), ::tolower);+ std::string s = a.source;+ std::transform(s.begin(), s.end(), s.begin(), ::tolower);+ if (h.find(search_lower) == std::string::npos &&+ s.find(search_lower) == std::string::npos)+ continue;+ }++ filtered.push_back(a);+ }++ return filtered;+}++// ============================================================================+// Init+// ============================================================================+void NewsScreen::init() {+ if (initialized_) return;+ initialized_ = true;+ fetch_news();+}++// ============================================================================+// Toolbar — two rows: top = refresh+search+count, bottom = time+category filters+// ============================================================================+void NewsScreen::render_toolbar() {+ using namespace theme::colors;++ ImGui::PushStyleColor(ImGuiCol_ChildBg, BG_DARK);+ ImGui::BeginChild("##news_toolbar", ImVec2(0, (ImGui::GetFrameHeight() + 4) * 2), ImGuiChildFlags_Borders);++ float avail_w = ImGui::GetContentRegionAvail().x;++ // Row 1: Refresh | Search | Article count+ if (loading_) {+ ImGui::TextColored(ACCENT, "LOADING...");+ } else {+ if (theme::AccentButton("REFRESH")) {+ fetch_news();+ }+ }+ ImGui::SameLine(0, 8);+ ImGui::TextColored(TEXT_DIM, "SEARCH:");+ ImGui::SameLine(0, 4);+ float search_w = std::min(200.0f, avail_w * 0.25f);+ ImGui::PushItemWidth(search_w);+ ImGui::PushStyleColor(ImGuiCol_FrameBg, BG_WIDGET);+ ImGui::InputText("##news_search", search_buf_, sizeof(search_buf_));+ ImGui::PopStyleColor();+ ImGui::PopItemWidth();++ // Article count (right-aligned)+ {+ std::lock_guard<std::mutex> lock(data_mutex_);+ char count_buf[64];+ std::snprintf(count_buf, sizeof(count_buf), "%d ARTICLES", (int)articles_.size());+ float tw = ImGui::CalcTextSize(count_buf).x + 8;+ float right_pos = avail_w - tw;+ if (right_pos > ImGui::GetCursorPosX() + 20) {+ ImGui::SameLine(right_pos);+ ImGui::TextColored(TEXT_DIM, "%s", count_buf);+ }+ }++ // Row 2: Time filters | Category filter+ ImGui::TextColored(TEXT_DIM, "TIME:");+ ImGui::SameLine(0, 4);+ const char* time_labels[] = {"ALL", "1H", "4H", "24H", "7D"};+ for (int i = 0; i < 5; i++) {+ bool active = (time_filter_ == i);+ if (active) {+ ImGui::PushStyleColor(ImGuiCol_Button, ACCENT);+ ImGui::PushStyleColor(ImGuiCol_Text, BG_DARKEST);+ } else {+ ImGui::PushStyleColor(ImGuiCol_Button, BG_WIDGET);+ ImGui::PushStyleColor(ImGuiCol_Text, TEXT_DIM);+ }+ char label[16];+ std::snprintf(label, sizeof(label), "%s##tf%d", time_labels[i], i);+ if (ImGui::SmallButton(label)) time_filter_ = i;+ ImGui::PopStyleColor(2);+ ImGui::SameLine(0, 2);+ }++ ImGui::SameLine(0, 12);+ ImGui::TextColored(TEXT_DIM, "CAT:");+ ImGui::SameLine(0, 4);+ float combo_w = std::min(110.0f, avail_w * 0.12f);+ ImGui::PushItemWidth(combo_w);+ ImGui::PushStyleColor(ImGuiCol_FrameBg, BG_WIDGET);+ if (ImGui::BeginCombo("##cat_filter", CATEGORIES[category_filter_], ImGuiComboFlags_NoArrowButton)) {+ for (int i = 0; i < NUM_CATEGORIES; i++) {+ bool sel = (category_filter_ == i);+ if (ImGui::Selectable(CATEGORIES[i], sel))+ category_filter_ = i;+ }+ ImGui::EndCombo();+ }+ ImGui::PopStyleColor();+ ImGui::PopItemWidth();++ ImGui::EndChild();+ ImGui::PopStyleColor();+}++// ============================================================================+// Wire Row — single dense article line (Bloomberg wire style)+// ============================================================================+void NewsScreen::render_wire_row(int index, const NewsArticle& article, float width) {+ using namespace theme::colors;++ bool selected = (index == selected_article_);+ bool is_hot = (article.priority == Priority::FLASH || article.priority == Priority::URGENT);++ ImVec4 pri_color;+ switch (article.priority) {+ case Priority::FLASH: pri_color = ERROR_RED; break;+ case Priority::URGENT: pri_color = ACCENT; break;+ case Priority::BREAKING: pri_color = WARNING; break;+ default: pri_color = TEXT_DISABLED; break;+ }++ ImVec4 sent_color;+ switch (article.sentiment) {+ case Sentiment::BULLISH: sent_color = MARKET_GREEN; break;+ case Sentiment::BEARISH: sent_color = MARKET_RED; break;+ default: sent_color = WARNING; break;+ }++ // Row background+ ImVec2 cursor = ImGui::GetCursorScreenPos();+ float row_h = ImGui::GetTextLineHeightWithSpacing() + 4;+ ImVec4 bg = selected ? ImVec4(INFO.x, INFO.y, INFO.z, 0.08f) :+ ImVec4(0, 0, 0, 0);++ ImGui::PushID(index);++ // Invisible button for the whole row+ if (ImGui::InvisibleButton("##row", ImVec2(width - 16, row_h))) {+ selected_article_ = index;+ }+ bool hovered = ImGui::IsItemHovered();+ if (hovered) bg = ImVec4(1, 1, 1, 0.03f);++ ImDrawList* dl = ImGui::GetWindowDrawList();++ // Background fill+ dl->AddRectFilled(cursor, ImVec2(cursor.x + width - 16, cursor.y + row_h),+ ImGui::ColorConvertFloat4ToU32(bg));++ // Left border (selection or priority indicator)+ if (selected) {+ dl->AddRectFilled(cursor, ImVec2(cursor.x + 2, cursor.y + row_h),+ ImGui::ColorConvertFloat4ToU32(INFO));+ } else if (is_hot) {+ dl->AddRectFilled(cursor, ImVec2(cursor.x + 2, cursor.y + row_h),+ ImGui::ColorConvertFloat4ToU32(pri_color));+ }++ // Bottom border+ dl->AddLine(ImVec2(cursor.x, cursor.y + row_h),+ ImVec2(cursor.x + width - 16, cursor.y + row_h),+ ImGui::ColorConvertFloat4ToU32(BORDER_DIM));++ float row_w = width - 16;+ float x = cursor.x + 6;+ float y = cursor.y + 2;++ // Column widths as percentages of row width+ float time_w = row_w * 0.05f; // 5%+ float dot_w = 14.0f; // fixed dot+ float source_w = row_w * 0.10f; // 10%+ float sent_w = 16.0f; // fixed sentiment icon+ float tail_w = sent_w + 8; // right margin+ float head_w = row_w - time_w - dot_w - source_w - tail_w - 12; // rest = headline++ // Time+ std::string rel = relative_time(article.sort_ts);+ ImGui::PushClipRect(ImVec2(x, y), ImVec2(x + time_w, y + ImGui::GetTextLineHeight()), true);+ dl->AddText(ImVec2(x, y), ImGui::ColorConvertFloat4ToU32(TEXT_DISABLED), rel.c_str());+ ImGui::PopClipRect();+ x += time_w;++ // Priority dot+ float dot_y = y + ImGui::GetTextLineHeight() * 0.5f;+ dl->AddCircleFilled(ImVec2(x + 5, dot_y), 2.5f,+ ImGui::ColorConvertFloat4ToU32(pri_color));+ if (is_hot) {+ dl->AddCircle(ImVec2(x + 5, dot_y), 4.0f,+ ImGui::ColorConvertFloat4ToU32(ImVec4(pri_color.x, pri_color.y, pri_color.z, 0.3f)));+ }+ x += dot_w;++ // Source (clipped)+ ImGui::PushClipRect(ImVec2(x, y), ImVec2(x + source_w, y + ImGui::GetTextLineHeight()), true);+ dl->AddText(ImVec2(x, y), ImGui::ColorConvertFloat4ToU32(INFO), article.source.c_str());+ ImGui::PopClipRect();+ x += source_w + 4;++ // Headline (clipped to remaining space before sentiment)+ if (head_w > 10) {+ ImVec4 hl_color = selected ? TEXT_PRIMARY :+ is_hot ? TEXT_SECONDARY : TEXT_DIM;+ ImGui::PushClipRect(ImVec2(x, y), ImVec2(x + head_w, y + ImGui::GetTextLineHeight()), true);+ dl->AddText(ImVec2(x, y), ImGui::ColorConvertFloat4ToU32(hl_color),+ article.headline.c_str());+ ImGui::PopClipRect();+ }++ // Sentiment arrow (right-aligned)+ float right_x = cursor.x + row_w - sent_w;+ const char* sent_icon = article.sentiment == Sentiment::BULLISH ? "^" :+ article.sentiment == Sentiment::BEARISH ? "v" : "-";+ dl->AddText(ImVec2(right_x, y), ImGui::ColorConvertFloat4ToU32(sent_color), sent_icon);++ ImGui::PopID();+}++// ============================================================================+// Left Sidebar — sentiment summary, top stories, category counts+// ============================================================================+void NewsScreen::render_left_sidebar(float width, float height) {+ using namespace theme::colors;++ ImGui::PushStyleColor(ImGuiCol_ChildBg, BG_PANEL);+ ImGui::BeginChild("##news_left", ImVec2(width, height), ImGuiChildFlags_Borders);++ auto filtered = get_filtered_articles();++ // Sentiment summary+ ImGui::TextColored(ACCENT, "SENTIMENT");+ ImGui::Separator();+ int bullish = 0, bearish = 0, neutral = 0;+ for (const auto& a : filtered) {+ if (a.sentiment == Sentiment::BULLISH) bullish++;+ else if (a.sentiment == Sentiment::BEARISH) bearish++;+ else neutral++;+ }+ int total = (int)filtered.size();+ if (total > 0) {+ char buf[32];+ std::snprintf(buf, sizeof(buf), "BULLISH %d (%.0f%%)", bullish, 100.0f * bullish / total);+ ImGui::TextColored(MARKET_GREEN, "%s", buf);+ std::snprintf(buf, sizeof(buf), "BEARISH %d (%.0f%%)", bearish, 100.0f * bearish / total);+ ImGui::TextColored(MARKET_RED, "%s", buf);+ std::snprintf(buf, sizeof(buf), "NEUTRAL %d (%.0f%%)", neutral, 100.0f * neutral / total);+ ImGui::TextColored(WARNING, "%s", buf);+ }++ ImGui::Spacing();+ ImGui::Spacing();++ // Top Stories (top 10 by priority + recency)+ ImGui::TextColored(ACCENT, "TOP STORIES");+ ImGui::Separator();++ // Sort by priority weight + recency+ auto top = filtered;+ std::sort(top.begin(), top.end(), [](const NewsArticle& a, const NewsArticle& b) {+ auto pri_weight = [](Priority p) -> int {+ switch (p) { case Priority::FLASH: return 4; case Priority::URGENT: return 3;+ case Priority::BREAKING: return 2; default: return 1; }+ };+ int wa = pri_weight(a.priority) * 1000 + (int)(a.sort_ts / 60);+ int wb = pri_weight(b.priority) * 1000 + (int)(b.sort_ts / 60);+ return wa > wb;+ });++ int count = std::min((int)top.size(), 10);+ for (int i = 0; i < count; i++) {+ ImGui::PushID(i + 1000);+ bool clicked = false;++ // Rank number+ char rank[8]; std::snprintf(rank, sizeof(rank), "%d", i + 1);+ ImGui::TextColored(ACCENT, "%s", rank);+ ImGui::SameLine(0, 6);++ // Headline (wrapped to 2 lines)+ float avail = ImGui::GetContentRegionAvail().x;+ ImGui::PushTextWrapPos(ImGui::GetCursorPosX() + avail);++ ImVec4 hl_col = top[i].priority == Priority::FLASH ? TEXT_PRIMARY :+ top[i].priority == Priority::URGENT ? TEXT_SECONDARY : TEXT_DIM;++ ImGui::TextColored(hl_col, "%s", top[i].headline.c_str());+ if (ImGui::IsItemClicked()) {+ // Find index in filtered articles+ for (int j = 0; j < (int)filtered.size(); j++) {+ if (filtered[j].id == top[i].id) { selected_article_ = j; break; }+ }+ }+ ImGui::PopTextWrapPos();++ // Source + time+ ImGui::TextColored(INFO, "%s", top[i].source.c_str());+ ImGui::SameLine(0, 6);+ ImGui::TextColored(TEXT_DISABLED, "%s", relative_time(top[i].sort_ts).c_str());++ ImGui::Spacing();+ ImGui::PopID();+ }++ ImGui::Spacing();+ ImGui::Spacing();++ // Category counts+ ImGui::TextColored(ACCENT, "CATEGORIES");+ ImGui::Separator();+ {+ std::lock_guard<std::mutex> lock(data_mutex_);+ std::map<std::string, int> cat_counts;+ for (const auto& a : articles_) cat_counts[a.category]++;+ for (const auto& [cat, cnt] : cat_counts) {+ char buf[64]; std::snprintf(buf, sizeof(buf), "%-12s %d", cat.c_str(), cnt);+ ImGui::TextColored(TEXT_DIM, "%s", buf);+ }+ }++ ImGui::Spacing();+ ImGui::Spacing();++ // Source counts+ ImGui::TextColored(ACCENT, "SOURCES");+ ImGui::Separator();+ {+ std::lock_guard<std::mutex> lock(data_mutex_);+ std::map<std::string, int> src_counts;+ for (const auto& a : articles_) src_counts[a.source]++;+ for (const auto& [src, cnt] : src_counts) {+ char buf[64]; std::snprintf(buf, sizeof(buf), "%-14s %d", src.c_str(), cnt);+ ImGui::TextColored(TEXT_DIM, "%s", buf);+ }+ }++ ImGui::EndChild();+ ImGui::PopStyleColor();+}++// ============================================================================+// Wire Feed — center panel with scrollable article list+// ============================================================================+void NewsScreen::render_wire_feed(float width, float height) {+ using namespace theme::colors;++ ImGui::PushStyleColor(ImGuiCol_ChildBg, BG_DARKEST);+ ImGui::BeginChild("##wire_feed", ImVec2(width, height), ImGuiChildFlags_Borders);++ auto filtered = get_filtered_articles();++ if (loading_ && filtered.empty()) {+ ImGui::SetCursorPos(ImVec2(width * 0.4f, height * 0.4f));+ ImGui::TextColored(ACCENT, "LOADING NEWS FEEDS...");+ theme::LoadingSpinner("Fetching...");+ } else if (filtered.empty()) {+ ImGui::SetCursorPos(ImVec2(width * 0.3f, height * 0.4f));+ ImGui::TextColored(TEXT_DIM, "No articles match your filters");+ } else {+ // Wire header+ float hw = ImGui::GetContentRegionAvail().x;+ ImGui::TextColored(TEXT_DISABLED, "TIME");+ ImGui::SameLine(hw * 0.07f);+ ImGui::TextColored(TEXT_DISABLED, "SOURCE");+ ImGui::SameLine(hw * 0.20f);+ ImGui::TextColored(TEXT_DISABLED, "HEADLINE");+ ImGui::Separator();++ // Scrollable wire rows+ ImGui::BeginChild("##wire_scroll", ImVec2(0, 0));+ for (int i = 0; i < (int)filtered.size(); i++) {+ render_wire_row(i, filtered[i], width);+ }+ ImGui::EndChild();+ }++ ImGui::EndChild();+ ImGui::PopStyleColor();+}++// ============================================================================+// Article Reader — right panel, shows selected article detail+// ============================================================================+void NewsScreen::render_article_reader(float width, float height) {+ using namespace theme::colors;++ ImGui::PushStyleColor(ImGuiCol_ChildBg, BG_PANEL);+ ImGui::BeginChild("##article_reader", ImVec2(width, height), ImGuiChildFlags_Borders);++ auto filtered = get_filtered_articles();++ if (selected_article_ < 0 || selected_article_ >= (int)filtered.size()) {+ ImGui::SetCursorPos(ImVec2(width * 0.15f, height * 0.4f));+ ImGui::TextColored(TEXT_DISABLED, "Select an article to read");+ } else {+ const auto& a = filtered[selected_article_];++ // Priority badge+ const char* pri_label = "ROUTINE";+ ImVec4 pri_color = TEXT_DISABLED;+ switch (a.priority) {+ case Priority::FLASH: pri_label = "FLASH"; pri_color = ERROR_RED; break;+ case Priority::URGENT: pri_label = "URGENT"; pri_color = ACCENT; break;+ case Priority::BREAKING: pri_label = "BREAKING"; pri_color = WARNING; break;+ default: break;+ }+ ImGui::TextColored(pri_color, "[%s]", pri_label);+ ImGui::SameLine(0, 8);++ // Sentiment badge+ const char* sent_label = "NEUTRAL";+ ImVec4 sent_color = WARNING;+ switch (a.sentiment) {+ case Sentiment::BULLISH: sent_label = "BULLISH"; sent_color = MARKET_GREEN; break;+ case Sentiment::BEARISH: sent_label = "BEARISH"; sent_color = MARKET_RED; break;+ default: break;+ }+ ImGui::TextColored(sent_color, "[%s]", sent_label);++ ImGui::Spacing();++ // Headline+ ImGui::PushTextWrapPos(ImGui::GetCursorPosX() + width - 20);+ ImGui::TextColored(TEXT_PRIMARY, "%s", a.headline.c_str());+ ImGui::PopTextWrapPos();++ ImGui::Spacing();++ // Metadata — compact single line with wrapping fallback+ {+ char meta[256];+ std::snprintf(meta, sizeof(meta), "%s | %s | %s | %s",+ a.source.c_str(), a.time_str.c_str(), a.category.c_str(), a.region.c_str());+ ImGui::PushTextWrapPos(ImGui::GetCursorPosX() + width - 20);+ ImGui::TextColored(INFO, "%s", meta);+ ImGui::PopTextWrapPos();+ }++ // Tickers+ if (!a.tickers.empty()) {+ ImGui::Spacing();+ for (const auto& t : a.tickers) {+ ImGui::SameLine(0, 4);+ ImGui::TextColored(WARNING, "$%s", t.c_str());+ }+ }++ ImGui::Spacing();+ ImGui::Separator();+ ImGui::Spacing();++ // Summary+ ImGui::PushTextWrapPos(ImGui::GetCursorPosX() + width - 20);+ ImGui::TextColored(TEXT_SECONDARY, "%s", a.summary.empty() ? "No summary available." : a.summary.c_str());+ ImGui::PopTextWrapPos();++ ImGui::Spacing();+ ImGui::Spacing();++ // Open link button+ if (!a.link.empty()) {+ if (theme::AccentButton("OPEN IN BROWSER")) {+#ifdef _WIN32+ ShellExecuteA(nullptr, "open", a.link.c_str(), nullptr, nullptr, SW_SHOWNORMAL);+#elif __APPLE__+ std::string cmd = "open " + a.link;+ system(cmd.c_str());+#else+ std::string cmd = "xdg-open " + a.link;+ system(cmd.c_str());+#endif+ }+ ImGui::SameLine(0, 8);+ ImGui::PushTextWrapPos(ImGui::GetCursorPosX() + width - 120);+ ImGui::TextColored(TEXT_DISABLED, "%s", a.link.c_str());+ ImGui::PopTextWrapPos();+ }+ }++ ImGui::EndChild();+ ImGui::PopStyleColor();+}++// ============================================================================+// Main Render+// ============================================================================+void NewsScreen::render() {+ init();++ using namespace theme::colors;+ ImGuiViewport* vp = ImGui::GetMainViewport();+ float tab_bar_h = ImGui::GetFrameHeight() + 4;+ float footer_h = ImGui::GetFrameHeight();++ float work_y = vp->WorkPos.y + tab_bar_h;+ float work_h = vp->WorkSize.y - tab_bar_h - footer_h;+ float work_w = vp->WorkSize.x;++ ImGui::SetNextWindowPos(ImVec2(vp->WorkPos.x, work_y));+ ImGui::SetNextWindowSize(ImVec2(work_w, work_h));++ ImGui::PushStyleVar(ImGuiStyleVar_WindowPadding, ImVec2(4, 4));+ ImGui::PushStyleVar(ImGuiStyleVar_WindowBorderSize, 0);+ ImGui::PushStyleColor(ImGuiCol_WindowBg, BG_DARKEST);++ ImGui::Begin("##news", nullptr,+ ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_NoResize | ImGuiWindowFlags_NoMove |+ ImGuiWindowFlags_NoCollapse | ImGuiWindowFlags_NoDocking |+ ImGuiWindowFlags_NoBringToFrontOnFocus);++ // Title bar — safe layout+ float content_w = ImGui::GetContentRegionAvail().x;+ ImGui::TextColored(ACCENT, "NEWS TERMINAL");++ // Right-aligned feed/article count+ {+ char info[64];+ std::snprintf(info, sizeof(info), "%d FEEDS | %d ARTICLES",+ (int)get_default_feeds().size(), (int)articles_.size());+ float info_w = ImGui::CalcTextSize(info).x + 8;+ float right_pos = content_w - info_w;+ if (right_pos > ImGui::GetCursorPosX() + 50) {+ ImGui::SameLine(right_pos);+ ImGui::TextColored(TEXT_DISABLED, "%s", info);+ }+ }++ ImGui::Separator();++ // Toolbar+ render_toolbar();++ // Error banner+ if (!error_.empty()) {+ bool is_error = error_.find("Failed") != std::string::npos;+ ImGui::TextColored(is_error ? ERROR_RED : WARNING, "%s", error_.c_str());+ }++ // Three-panel layout — percentage based+ float avail_w = ImGui::GetContentRegionAvail().x;+ float avail_h = ImGui::GetContentRegionAvail().y;+ float gap = 4.0f;+ float left_w = avail_w * 0.18f; // 18% sidebar+ float right_w = avail_w * 0.24f; // 24% reader+ float center_w = avail_w - left_w - right_w - gap * 2; // rest = wire feed++ // Clamp minimums+ if (left_w < 160) left_w = 160;+ if (right_w < 200) right_w = 200;+ center_w = avail_w - left_w - right_w - gap * 2;+ if (center_w < 200) center_w = 200;++ // Left sidebar+ render_left_sidebar(left_w, avail_h);++ ImGui::SameLine(0, gap);++ // Center wire feed+ render_wire_feed(center_w, avail_h);++ ImGui::SameLine(0, gap);++ // Right article reader+ render_article_reader(right_w, avail_h);++ ImGui::End();+ ImGui::PopStyleColor();+ ImGui::PopStyleVar(2);++ // Auto-refresh every 5 minutes+ double now = (double)std::time(nullptr);+ if (!loading_ && last_fetch_time_ > 0 && (now - last_fetch_time_) > 300) {+ fetch_news();+ }+}++} // namespace fincept::newsdiff --git a/fincept-cpp/src/news/news_screen.h b/fincept-cpp/src/news/news_screen.hnew file mode 100644index 000000000..1aeebdd46--- /dev/null+++ b/fincept-cpp/src/news/news_screen.h@@ -0,0 +1,100 @@+#pragma once+// News Terminal — Bloomberg-style multi-panel news dashboard+// Fetches real RSS feeds, parses XML, enriches with sentiment/priority+// Layout: [Left Sidebar] [Center Wire Feed] [Right Reader]++#include <imgui.h>+#include <string>+#include <vector>+#include <mutex>+#include <atomic>++namespace fincept::news {++// Article priority levels+enum class Priority { FLASH, URGENT, BREAKING, ROUTINE };+// Article sentiment+enum class Sentiment { BULLISH, BEARISH, NEUTRAL };++struct NewsArticle {+ std::string id;+ std::string headline;+ std::string summary;+ std::string source;+ std::string category;+ std::string region;+ std::string link;+ std::string time_str; // formatted time "Mar 13, 14:30"+ int64_t sort_ts = 0; // unix timestamp seconds+ Priority priority = Priority::ROUTINE;+ Sentiment sentiment = Sentiment::NEUTRAL;+ std::vector<std::string> tickers;+ int tier = 3; // 1=wire, 2=major, 3=specialty, 4=blog+};++struct RSSFeed {+ std::string id;+ std::string name;+ std::string url;+ std::string category;+ std::string region;+ std::string source;+ int tier = 3;+ bool enabled = true;+};++class NewsScreen {+public:+ void render();++private:+ bool initialized_ = false;++ // Data (mutex-protected)+ std::mutex data_mutex_;+ std::vector<NewsArticle> articles_;+ std::string error_;+ std::atomic<bool> loading_{false};+ double last_fetch_time_ = 0;++ // UI state+ int selected_article_ = -1;+ std::string search_filter_;+ char search_buf_[128] = "";+ int category_filter_ = 0; // 0=ALL+ int time_filter_ = 0; // 0=ALL, 1=1h, 2=4h, 3=24h, 4=7d++ // Categories for filter+ static constexpr const char* CATEGORIES[] = {+ "ALL", "MARKETS", "CRYPTO", "TECH", "ENERGY",+ "REGULATORY", "ECONOMIC", "GEOPOLITICS", "GENERAL"+ };+ static constexpr int NUM_CATEGORIES = 9;++ // Init+ void init();++ // Section renderers+ void render_left_sidebar(float width, float height);+ void render_wire_feed(float width, float height);+ void render_article_reader(float width, float height);+ void render_toolbar();++ // Wire row+ void render_wire_row(int index, const NewsArticle& article, float width);++ // Data+ void fetch_news();+ std::vector<NewsArticle> get_filtered_articles();++ // RSS parsing+ static std::vector<NewsArticle> parse_rss_xml(const std::string& xml, const RSSFeed& feed);+ static void enrich_article(NewsArticle& article);+ static std::string strip_html(const std::string& html);+ static std::string relative_time(int64_t ts);++ // Feed list+ static std::vector<RSSFeed> get_default_feeds();+};++} // namespace fincept::newsdiff --git a/fincept-cpp/src/profile/profile_screen.cpp b/fincept-cpp/src/profile/profile_screen.cppnew file mode 100644index 000000000..fdf7c0150--- /dev/null+++ b/fincept-cpp/src/profile/profile_screen.cpp@@ -0,0 +1,1083 @@+#include "profile_screen.h"+#include "auth/auth_manager.h"+#include "http/http_client.h"+#include "theme/bloomberg_theme.h"+#include <imgui.h>+#include <cstdio>+#include <cstring>+#include <ctime>+#include <algorithm>+#include <thread>+#ifdef _WIN32+#include <windows.h>+#include <shellapi.h>+#endif++namespace fincept::profile {++// Open URL in default browser+static void open_url(const char* url) {+#ifdef _WIN32+ ShellExecuteA(nullptr, "open", url, nullptr, nullptr, SW_SHOWNORMAL);+#elif __APPLE__+ std::string cmd = std::string("open ") + url;+ system(cmd.c_str());+#else+ std::string cmd = std::string("xdg-open ") + url;+ system(cmd.c_str());+#endif+}++static const char* API_BASE = "https://api.fincept.in";++// Helper: build auth headers+static http::Headers auth_headers(const std::string& api_key, const std::string& session_token = "") {+ http::Headers h;+ h["Content-Type"] = "application/json";+ h["X-API-Key"] = api_key;+ if (!session_token.empty()) h["X-Session-Token"] = session_token;+ return h;+}++// ============================================================================+// Init+// ============================================================================+void ProfileScreen::init() {+ if (initialized_) return;+ auto& session = auth::AuthManager::instance().session();+ if (session.is_registered()) {+ std::strncpy(edit_username_, session.user_info.username.c_str(), sizeof(edit_username_) - 1);+ std::strncpy(edit_phone_, session.user_info.phone.c_str(), sizeof(edit_phone_) - 1);+ std::strncpy(edit_country_, session.user_info.country.c_str(), sizeof(edit_country_) - 1);+ std::strncpy(edit_country_code_, session.user_info.country_code.c_str(), sizeof(edit_country_code_) - 1);+ }+ initialized_ = true;+}++// ============================================================================+// Helpers+// ============================================================================+void ProfileScreen::render_data_row(const char* label, const char* value, ImVec4 value_color) {+ using namespace theme::colors;+ if (value_color.w == 0) value_color = TEXT_PRIMARY;++ float avail = ImGui::GetContentRegionAvail().x;+ float label_w = avail * 0.35f; // 35% for label++ ImGui::TextColored(TEXT_DIM, "%s", label);+ ImGui::SameLine(label_w);+ ImGui::PushTextWrapPos(ImGui::GetCursorPosX() + (avail - label_w));+ ImGui::TextColored(value_color, "%s", value);+ ImGui::PopTextWrapPos();+}++void ProfileScreen::render_stat_box(const char* label, const char* value, ImVec4 color) {+ using namespace theme::colors;+ if (color.w == 0) color = TEXT_PRIMARY;++ ImGui::BeginGroup();+ ImGui::PushStyleColor(ImGuiCol_ChildBg, BG_WIDGET);+ ImGui::BeginChild(ImGui::GetID(label), ImVec2(0, 60), ImGuiChildFlags_Borders);+ ImGui::SetCursorPosY(8);+ float w = ImGui::GetContentRegionAvail().x;+ float tw = ImGui::CalcTextSize(value).x;+ ImGui::SetCursorPosX((w - tw) * 0.5f);+ ImGui::TextColored(color, "%s", value);+ float lw = ImGui::CalcTextSize(label).x;+ ImGui::SetCursorPosX((w - lw) * 0.5f);+ ImGui::TextColored(TEXT_DIM, "%s", label);+ ImGui::EndChild();+ ImGui::PopStyleColor();+ ImGui::EndGroup();+}++void ProfileScreen::render_panel_header(const char* title) {+ ImGui::TextColored(theme::colors::ACCENT, "%s", title);+ ImGui::Separator();+ ImGui::Spacing();+}++// ============================================================================+// Section Tabs+// ============================================================================+void ProfileScreen::render_section_tabs() {+ using namespace theme::colors;++ struct Tab { Section s; const char* label; };+ Tab tabs[] = {+ {Section::Overview, "OVERVIEW"}, {Section::Usage, "USAGE"},+ {Section::Security, "SECURITY"}, {Section::Billing, "BILLING"},+ {Section::Support, "SUPPORT"}+ };++ ImGui::PushStyleVar(ImGuiStyleVar_FramePadding, ImVec2(10, 4));+ ImGui::PushStyleVar(ImGuiStyleVar_ItemSpacing, ImVec2(2, 0));++ for (int i = 0; i < 5; i++) {+ bool active = (active_section_ == tabs[i].s);+ if (active) {+ ImGui::PushStyleColor(ImGuiCol_Button, ACCENT);+ ImGui::PushStyleColor(ImGuiCol_ButtonHovered, ACCENT_HOVER);+ ImGui::PushStyleColor(ImGuiCol_Text, BG_DARKEST);+ } else {+ ImGui::PushStyleColor(ImGuiCol_Button, BG_WIDGET);+ ImGui::PushStyleColor(ImGuiCol_ButtonHovered, BG_HOVER);+ ImGui::PushStyleColor(ImGuiCol_Text, TEXT_SECONDARY);+ }++ if (ImGui::Button(tabs[i].label)) {+ if (active_section_ != tabs[i].s) {+ active_section_ = tabs[i].s;+ // Fetch data for new section+ if (tabs[i].s == Section::Usage && !usage_data_.valid)+ fetch_usage_data();+ else if (tabs[i].s == Section::Billing && !subscription_data_.valid)+ fetch_billing_data();+ }+ }+ ImGui::PopStyleColor(3);+ if (i < 4) ImGui::SameLine();+ }++ ImGui::PopStyleVar(2);+ ImGui::Separator();+}++// ============================================================================+// OVERVIEW+// ============================================================================+void ProfileScreen::render_overview() {+ using namespace theme::colors;+ auto& session = auth::AuthManager::instance().session();++ // Two-column layout+ ImVec2 avail = ImGui::GetContentRegionAvail();+ float col_w = (avail.x - ImGui::GetStyle().ItemSpacing.x) * 0.5f;++ // Left: Account Info+ ImGui::BeginChild("##ov_left", ImVec2(col_w, 0));+ render_panel_header("ACCOUNT INFORMATION");++ render_data_row("USERNAME", session.user_info.username.empty() ? "N/A" : session.user_info.username.c_str());+ render_data_row("EMAIL", session.user_info.email.empty() ? "N/A" : session.user_info.email.c_str());+ render_data_row("USER TYPE", session.is_registered() ? "REGISTERED" : "GUEST");++ std::string at = session.user_info.account_type;+ for (auto& c : at) c = (char)std::toupper(c);+ render_data_row("ACCOUNT TYPE", at.c_str(), ACCENT);+ render_data_row("PHONE", session.user_info.phone.empty() ? "---" : session.user_info.phone.c_str(),+ session.user_info.phone.empty() ? TEXT_DISABLED : TEXT_PRIMARY);+ render_data_row("COUNTRY", session.user_info.country.empty() ? "---" : session.user_info.country.c_str(),+ session.user_info.country.empty() ? TEXT_DISABLED : TEXT_PRIMARY);+ render_data_row("COUNTRY CODE", session.user_info.country_code.empty() ? "---" : session.user_info.country_code.c_str());+ render_data_row("EMAIL VERIFIED", session.user_info.is_verified ? "YES" : "NO",+ session.user_info.is_verified ? SUCCESS : ERROR_RED);+ render_data_row("2FA ENABLED", session.user_info.mfa_enabled ? "YES" : "NO",+ session.user_info.mfa_enabled ? SUCCESS : ERROR_RED);+ render_data_row("MEMBER SINCE", session.user_info.created_at.empty() ? "---" : session.user_info.created_at.substr(0, 10).c_str());+ render_data_row("LAST LOGIN", session.user_info.last_login_at.empty() ? "---" : session.user_info.last_login_at.substr(0, 10).c_str());++ ImGui::Spacing();+ if (theme::AccentButton("EDIT PROFILE")) {+ editing_profile_ = true;+ edit_status_.clear();+ }++ ImGui::EndChild();++ ImGui::SameLine();++ // Right: Credits & Quick Actions+ ImGui::BeginChild("##ov_right", ImVec2(col_w, 0));++ render_panel_header("CREDITS & BALANCE");++ // Big credit display+ char cred_buf[32];+ std::snprintf(cred_buf, sizeof(cred_buf), "%.2f", session.user_info.credit_balance);++ ImGui::PushStyleColor(ImGuiCol_ChildBg, BG_WIDGET);+ ImGui::BeginChild("##cred_box", ImVec2(0, 80), ImGuiChildFlags_Borders);+ ImGui::SetCursorPosY(12);+ float tw = ImGui::CalcTextSize(cred_buf).x;+ float bw = ImGui::GetContentRegionAvail().x;+ ImGui::SetCursorPosX((bw - tw) * 0.5f);++ ImGui::PushFont(nullptr); // Use default but we'll scale+ ImGui::TextColored(INFO, "%s", cred_buf);+ ImGui::PopFont();++ const char* cl = "AVAILABLE CREDITS";+ float clw = ImGui::CalcTextSize(cl).x;+ ImGui::SetCursorPosX((bw - clw) * 0.5f);+ ImGui::TextColored(TEXT_DIM, "%s", cl);+ ImGui::EndChild();+ ImGui::PopStyleColor();++ ImGui::Spacing();+ render_data_row("PLAN", at.c_str(), ACCENT);++ if (session.is_guest()) {+ char rbuf[16];+ std::snprintf(rbuf, sizeof(rbuf), "%d", session.requests_today);+ render_data_row("REQUESTS TODAY", rbuf);+ }++ ImGui::Spacing();+ ImGui::Separator();+ ImGui::Spacing();+ render_panel_header("QUICK ACTIONS");++ if (theme::AccentButton("EDIT PROFILE##2")) {+ editing_profile_ = true;+ edit_status_.clear();+ }+ ImGui::SameLine();+ ImGui::PushStyleColor(ImGuiCol_Button, ImVec4(ERROR_RED.x, ERROR_RED.y, ERROR_RED.z, 0.15f));+ ImGui::PushStyleColor(ImGuiCol_ButtonHovered, ERROR_RED);+ ImGui::PushStyleColor(ImGuiCol_Text, ERROR_RED);+ if (ImGui::Button("LOGOUT")) {+ show_logout_confirm_ = true;+ }+ ImGui::PopStyleColor(3);++ ImGui::EndChild();++ // Edit Profile Modal+ if (editing_profile_) {+ ImGui::OpenPopup("Edit Profile");+ ImVec2 center = ImGui::GetMainViewport()->GetCenter();+ ImGui::SetNextWindowPos(center, ImGuiCond_Appearing, ImVec2(0.5f, 0.5f));+ ImGui::SetNextWindowSize(ImVec2(420, 340));+ }++ ImGui::PushStyleColor(ImGuiCol_PopupBg, BG_PANEL);+ ImGui::PushStyleColor(ImGuiCol_Border, ACCENT);+ if (ImGui::BeginPopupModal("Edit Profile", &editing_profile_, ImGuiWindowFlags_NoResize)) {+ ImGui::TextColored(ACCENT, "EDIT PROFILE");+ ImGui::Separator();+ ImGui::Spacing();++ if (!edit_status_.empty()) {+ bool is_err = edit_status_.find("Error") != std::string::npos || edit_status_.find("Failed") != std::string::npos;+ ImGui::TextColored(is_err ? ERROR_RED : SUCCESS, "%s", edit_status_.c_str());+ ImGui::Spacing();+ }++ ImGui::TextColored(TEXT_DIM, "USERNAME");+ ImGui::PushItemWidth(-1);+ ImGui::InputText("##edit_user", edit_username_, sizeof(edit_username_));+ ImGui::PopItemWidth();++ ImGui::TextColored(TEXT_DIM, "PHONE (with country dial code)");+ ImGui::PushItemWidth(-1);+ ImGui::InputText("##edit_phone", edit_phone_, sizeof(edit_phone_));+ ImGui::PopItemWidth();++ ImGui::TextColored(TEXT_DIM, "COUNTRY");+ ImGui::PushItemWidth(-1);+ ImGui::InputText("##edit_country", edit_country_, sizeof(edit_country_));+ ImGui::PopItemWidth();++ ImGui::TextColored(TEXT_DIM, "COUNTRY CODE (e.g. IN, US)");+ ImGui::PushItemWidth(-1);+ ImGui::InputText("##edit_cc", edit_country_code_, sizeof(edit_country_code_));+ ImGui::PopItemWidth();++ ImGui::Spacing();++ float bw2 = ImGui::GetContentRegionAvail().x;+ if (theme::SecondaryButton("CANCEL")) {+ editing_profile_ = false;+ edit_status_.clear();+ ImGui::CloseCurrentPopup();+ }+ ImGui::SameLine();+ if (edit_loading_) {+ ImGui::TextColored(ACCENT, "SAVING...");+ } else if (theme::AccentButton("SAVE CHANGES")) {+ fetch_profile_update();+ }++ ImGui::EndPopup();+ }+ ImGui::PopStyleColor(2);++ // Logout confirm modal+ if (show_logout_confirm_) {+ ImGui::OpenPopup("Confirm Logout");+ ImVec2 center = ImGui::GetMainViewport()->GetCenter();+ ImGui::SetNextWindowPos(center, ImGuiCond_Appearing, ImVec2(0.5f, 0.5f));+ ImGui::SetNextWindowSize(ImVec2(360, 140));+ }++ ImGui::PushStyleColor(ImGuiCol_PopupBg, BG_PANEL);+ ImGui::PushStyleColor(ImGuiCol_Border, ERROR_RED);+ if (ImGui::BeginPopupModal("Confirm Logout", &show_logout_confirm_, ImGuiWindowFlags_NoResize)) {+ ImGui::TextColored(ERROR_RED, "CONFIRM LOGOUT");+ ImGui::Separator();+ ImGui::TextWrapped("Are you sure you want to logout from Fincept Terminal?");+ ImGui::Spacing();++ if (theme::SecondaryButton("CANCEL")) {+ show_logout_confirm_ = false;+ ImGui::CloseCurrentPopup();+ }+ ImGui::SameLine();+ ImGui::PushStyleColor(ImGuiCol_Button, ERROR_RED);+ ImGui::PushStyleColor(ImGuiCol_ButtonHovered, ImVec4(1.0f, 0.3f, 0.3f, 1.0f));+ ImGui::PushStyleColor(ImGuiCol_Text, ImVec4(1, 1, 1, 1));+ if (ImGui::Button("LOGOUT")) {+ show_logout_confirm_ = false;+ auth::AuthManager::instance().logout_async();+ ImGui::CloseCurrentPopup();+ }+ ImGui::PopStyleColor(3);+ ImGui::EndPopup();+ }+ ImGui::PopStyleColor(2);+}++// ============================================================================+// USAGE+// ============================================================================+void ProfileScreen::render_usage() {+ using namespace theme::colors;+ auto& session = auth::AuthManager::instance().session();++ // Account & Credits stats+ render_panel_header("ACCOUNT & CREDITS");++ if (ImGui::BeginTable("##usage_stats", 3, ImGuiTableFlags_SizingStretchSame)) {+ ImGui::TableNextRow();++ ImGui::TableNextColumn();+ char cb[32]; std::snprintf(cb, sizeof(cb), "%.2f", session.user_info.credit_balance);+ render_stat_box("CREDIT BALANCE", cb, INFO);++ ImGui::TableNextColumn();+ std::string at = session.user_info.account_type;+ for (auto& c : at) c = (char)std::toupper(c);+ render_stat_box("ACCOUNT TYPE", at.c_str(), ACCENT);++ ImGui::TableNextColumn();+ char rl[16]; std::snprintf(rl, sizeof(rl), "%d", usage_data_.valid ? usage_data_.account.rate_limit_per_hour : 0);+ render_stat_box("RATE LIMIT/HR", rl);++ ImGui::EndTable();+ }++ ImGui::Spacing();++ if (loading_) {+ theme::LoadingSpinner("Loading usage data...");+ return;+ }++ if (!usage_data_.valid) {+ ImGui::TextColored(TEXT_DIM, "Click USAGE tab to load data");+ if (theme::AccentButton("LOAD USAGE DATA")) fetch_usage_data();+ return;+ }++ // Summary+ render_panel_header("USAGE SUMMARY");++ if (ImGui::BeginTable("##sum_stats", 4, ImGuiTableFlags_SizingStretchSame)) {+ ImGui::TableNextRow();++ ImGui::TableNextColumn();+ char tr[16]; std::snprintf(tr, sizeof(tr), "%d", usage_data_.summary.total_requests);+ render_stat_box("TOTAL REQUESTS", tr);++ ImGui::TableNextColumn();+ char cu[16]; std::snprintf(cu, sizeof(cu), "%.1f", usage_data_.summary.total_credits_used);+ render_stat_box("CREDITS USED", cu, WARNING);++ ImGui::TableNextColumn();+ char ac[16]; std::snprintf(ac, sizeof(ac), "%.2f", usage_data_.summary.avg_credits_per_request);+ render_stat_box("AVG CREDITS/REQ", ac);++ ImGui::TableNextColumn();+ char ar[16]; std::snprintf(ar, sizeof(ar), "%.0f", usage_data_.summary.avg_response_time_ms);+ render_stat_box("AVG RESPONSE MS", ar);++ ImGui::EndTable();+ }++ ImGui::Spacing();++ // Daily usage table+ if (!usage_data_.daily_usage.empty()) {+ render_panel_header("DAILY USAGE");++ // Bar chart+ ImVec2 chart_avail = ImGui::GetContentRegionAvail();+ float chart_h = 60;+ ImVec2 cp = ImGui::GetCursorScreenPos();+ ImDrawList* dl = ImGui::GetWindowDrawList();++ int max_reqs = 1;+ for (auto& d : usage_data_.daily_usage) max_reqs = std::max(max_reqs, d.request_count);++ int n = (int)usage_data_.daily_usage.size();+ float bar_w = chart_avail.x / (float)n;++ for (int i = 0; i < n; i++) {+ float h = (usage_data_.daily_usage[i].request_count / (float)max_reqs) * chart_h;+ float x = cp.x + i * bar_w;+ float y = cp.y + chart_h - h;+ dl->AddRectFilled(ImVec2(x + 1, y), ImVec2(x + bar_w - 1, cp.y + chart_h),+ usage_data_.daily_usage[i].credits_used > 0 ? IM_COL32(61, 143, 240, 180) : IM_COL32(100, 100, 100, 120));+ }+ ImGui::Dummy(ImVec2(chart_avail.x, chart_h + 4));++ // Table+ if (ImGui::BeginTable("##daily", 3,+ ImGuiTableFlags_Borders | ImGuiTableFlags_RowBg | ImGuiTableFlags_ScrollY | ImGuiTableFlags_SizingStretchProp,+ ImVec2(0, 150))) {+ ImGui::TableSetupColumn("DATE"); ImGui::TableSetupColumn("REQUESTS"); ImGui::TableSetupColumn("CREDITS");+ ImGui::TableSetupScrollFreeze(0, 1);+ ImGui::TableHeadersRow();++ for (int i = (int)usage_data_.daily_usage.size() - 1; i >= 0 && i >= (int)usage_data_.daily_usage.size() - 10; i--) {+ auto& d = usage_data_.daily_usage[i];+ ImGui::TableNextRow();+ ImGui::TableNextColumn(); ImGui::TextColored(TEXT_PRIMARY, "%s", d.date.c_str());+ ImGui::TableNextColumn(); ImGui::TextColored(INFO, "%d", d.request_count);+ ImGui::TableNextColumn(); ImGui::TextColored(d.credits_used > 0 ? WARNING : TEXT_DISABLED, "%.1f", d.credits_used);+ }+ ImGui::EndTable();+ }+ }++ // Endpoint breakdown+ if (!usage_data_.endpoint_breakdown.empty()) {+ ImGui::Spacing();+ render_panel_header("TOP ENDPOINTS");++ if (ImGui::BeginTable("##ep", 4,+ ImGuiTableFlags_Borders | ImGuiTableFlags_RowBg | ImGuiTableFlags_ScrollY | ImGuiTableFlags_SizingStretchProp,+ ImVec2(0, 180))) {+ ImGui::TableSetupColumn("ENDPOINT", 0, 3.0f);+ ImGui::TableSetupColumn("REQUESTS", 0, 1.0f);+ ImGui::TableSetupColumn("CREDITS", 0, 1.0f);+ ImGui::TableSetupColumn("AVG MS", 0, 1.0f);+ ImGui::TableSetupScrollFreeze(0, 1);+ ImGui::TableHeadersRow();++ for (size_t i = 0; i < usage_data_.endpoint_breakdown.size() && i < 15; i++) {+ auto& ep = usage_data_.endpoint_breakdown[i];+ ImGui::TableNextRow();+ ImGui::TableNextColumn(); ImGui::TextColored(TEXT_PRIMARY, "%s", ep.endpoint.c_str());+ ImGui::TableNextColumn(); ImGui::TextColored(INFO, "%d", ep.request_count);+ ImGui::TableNextColumn(); ImGui::TextColored(ep.credits_used > 0 ? WARNING : TEXT_DISABLED, "%.1f", ep.credits_used);+ ImGui::TableNextColumn(); ImGui::TextColored(TEXT_DIM, "%.0f", ep.avg_response_time_ms);+ }+ ImGui::EndTable();+ }+ }++ // Recent requests+ if (!usage_data_.recent_requests.empty()) {+ ImGui::Spacing();+ render_panel_header("RECENT REQUESTS");++ if (ImGui::BeginTable("##rr", 5,+ ImGuiTableFlags_Borders | ImGuiTableFlags_RowBg | ImGuiTableFlags_ScrollY | ImGuiTableFlags_SizingStretchProp,+ ImVec2(0, 180))) {+ ImGui::TableSetupColumn("TIME", 0, 1.5f);+ ImGui::TableSetupColumn("ENDPOINT", 0, 3.0f);+ ImGui::TableSetupColumn("METHOD", 0, 1.0f);+ ImGui::TableSetupColumn("STATUS", 0, 1.0f);+ ImGui::TableSetupColumn("MS", 0, 1.0f);+ ImGui::TableSetupScrollFreeze(0, 1);+ ImGui::TableHeadersRow();++ for (size_t i = 0; i < usage_data_.recent_requests.size() && i < 20; i++) {+ auto& rq = usage_data_.recent_requests[i];+ ImGui::TableNextRow();+ ImGui::TableNextColumn();+ // Show just time portion+ std::string ts = rq.timestamp.length() > 11 ? rq.timestamp.substr(11, 8) : rq.timestamp;+ ImGui::TextColored(TEXT_DIM, "%s", ts.c_str());+ ImGui::TableNextColumn(); ImGui::TextColored(TEXT_PRIMARY, "%s", rq.endpoint.c_str());+ ImGui::TableNextColumn();+ ImGui::TextColored(rq.method == "GET" ? INFO : ACCENT, "%s", rq.method.c_str());+ ImGui::TableNextColumn();+ ImGui::TextColored(rq.status_code < 400 ? SUCCESS : ERROR_RED, "%d", rq.status_code);+ ImGui::TableNextColumn(); ImGui::TextColored(TEXT_DIM, "%.0f", rq.response_time_ms);+ }+ ImGui::EndTable();+ }+ }+}++// ============================================================================+// SECURITY+// ============================================================================+void ProfileScreen::render_security() {+ using namespace theme::colors;+ auto& session = auth::AuthManager::instance().session();++ // API Key Management+ render_panel_header("API KEY MANAGEMENT");++ ImGui::PushStyleColor(ImGuiCol_ChildBg, BG_WIDGET);+ ImGui::BeginChild("##apikey_box", ImVec2(0, 70), ImGuiChildFlags_Borders);++ std::string masked = session.api_key;+ if (!show_api_key_ && masked.length() > 20) {+ masked = masked.substr(0, 20) + std::string(masked.length() - 20, '*');+ }+ ImGui::TextColored(TEXT_SECONDARY, "%s", masked.c_str());+ ImGui::TextColored(TEXT_DISABLED, "Keep your API key secure. Never share it publicly.");++ ImGui::EndChild();+ ImGui::PopStyleColor();++ ImGui::Spacing();+ if (theme::SecondaryButton(show_api_key_ ? "HIDE KEY" : "SHOW KEY")) {+ show_api_key_ = !show_api_key_;+ }+ ImGui::SameLine();+ if (regen_loading_) {+ ImGui::TextColored(ACCENT, "REGENERATING...");+ } else if (theme::AccentButton("REGENERATE KEY")) {+ show_regen_confirm_ = true;+ }++ if (!regen_status_.empty()) {+ ImGui::Spacing();+ bool is_err = regen_status_.find("Error") != std::string::npos || regen_status_.find("Failed") != std::string::npos;+ ImGui::TextColored(is_err ? ERROR_RED : SUCCESS, "%s", regen_status_.c_str());+ }++ ImGui::Spacing();+ ImGui::Spacing();++ // Security Status+ render_panel_header("SECURITY STATUS");++ if (!mfa_status_.empty()) {+ bool is_err = mfa_status_.find("Error") != std::string::npos || mfa_status_.find("Failed") != std::string::npos;+ ImGui::TextColored(is_err ? ERROR_RED : SUCCESS, "%s", mfa_status_.c_str());+ ImGui::Spacing();+ }++ // Email verification+ if (ImGui::BeginTable("##sec_rows", 2, ImGuiTableFlags_SizingStretchProp)) {+ ImGui::TableNextRow();+ ImGui::TableNextColumn(); ImGui::TextColored(TEXT_PRIMARY, "EMAIL VERIFICATION");+ ImGui::TableNextColumn();+ ImGui::TextColored(session.user_info.is_verified ? SUCCESS : ERROR_RED,+ session.user_info.is_verified ? "ENABLED" : "DISABLED");++ ImGui::TableNextRow();+ ImGui::TableNextColumn(); ImGui::TextColored(TEXT_PRIMARY, "MULTI-FACTOR AUTH (EMAIL)");+ ImGui::TableNextColumn();+ ImGui::TextColored(session.user_info.mfa_enabled ? SUCCESS : ERROR_RED,+ session.user_info.mfa_enabled ? "ENABLED" : "DISABLED");+ ImGui::SameLine();+ if (mfa_loading_) {+ ImGui::TextColored(ACCENT, " PROCESSING...");+ } else {+ if (session.user_info.mfa_enabled) {+ ImGui::PushStyleColor(ImGuiCol_Button, ImVec4(ERROR_RED.x, ERROR_RED.y, ERROR_RED.z, 0.15f));+ ImGui::PushStyleColor(ImGuiCol_ButtonHovered, ERROR_RED);+ ImGui::PushStyleColor(ImGuiCol_Text, ERROR_RED);+ if (ImGui::SmallButton("DISABLE")) toggle_mfa(false);+ ImGui::PopStyleColor(3);+ } else {+ ImGui::PushStyleColor(ImGuiCol_Button, ImVec4(SUCCESS.x, SUCCESS.y, SUCCESS.z, 0.15f));+ ImGui::PushStyleColor(ImGuiCol_ButtonHovered, SUCCESS);+ ImGui::PushStyleColor(ImGuiCol_Text, SUCCESS);+ if (ImGui::SmallButton("ENABLE")) toggle_mfa(true);+ ImGui::PopStyleColor(3);+ }+ }++ ImGui::EndTable();+ }++ // Regenerate confirm modal+ if (show_regen_confirm_) {+ ImGui::OpenPopup("Regenerate Key");+ ImVec2 center = ImGui::GetMainViewport()->GetCenter();+ ImGui::SetNextWindowPos(center, ImGuiCond_Appearing, ImVec2(0.5f, 0.5f));+ ImGui::SetNextWindowSize(ImVec2(400, 150));+ }++ ImGui::PushStyleColor(ImGuiCol_PopupBg, BG_PANEL);+ ImGui::PushStyleColor(ImGuiCol_Border, ACCENT);+ if (ImGui::BeginPopupModal("Regenerate Key", &show_regen_confirm_, ImGuiWindowFlags_NoResize)) {+ ImGui::TextColored(ACCENT, "REGENERATE API KEY");+ ImGui::Separator();+ ImGui::TextWrapped("Your current API key will be invalidated. Are you sure?");+ ImGui::Spacing();++ if (theme::SecondaryButton("CANCEL")) {+ show_regen_confirm_ = false;+ ImGui::CloseCurrentPopup();+ }+ ImGui::SameLine();+ if (theme::AccentButton("CONFIRM")) {+ show_regen_confirm_ = false;+ regenerate_api_key();+ ImGui::CloseCurrentPopup();+ }+ ImGui::EndPopup();+ }+ ImGui::PopStyleColor(2);+}++// ============================================================================+// BILLING+// ============================================================================+void ProfileScreen::render_billing() {+ using namespace theme::colors;++ if (loading_) {+ theme::LoadingSpinner("Loading billing data...");+ return;+ }++ // Account & Plan+ render_panel_header("ACCOUNT & PLAN");++ if (subscription_data_.valid) {+ if (ImGui::BeginTable("##bill_stats", 3, ImGuiTableFlags_SizingStretchSame)) {+ ImGui::TableNextRow();++ ImGui::TableNextColumn();+ std::string plan = subscription_data_.account_type;+ for (auto& c : plan) c = (char)std::toupper(c);+ render_stat_box("PLAN", plan.c_str(), ACCENT);++ ImGui::TableNextColumn();+ char cb[16]; std::snprintf(cb, sizeof(cb), "%.2f", subscription_data_.credit_balance);+ render_stat_box("CREDITS", cb, INFO);++ ImGui::TableNextColumn();+ std::string st = subscription_data_.support_type;+ for (auto& c : st) c = (char)std::toupper(c);+ render_stat_box("SUPPORT", st.c_str());++ ImGui::EndTable();+ }++ ImGui::Spacing();+ render_data_row("MEMBER SINCE", subscription_data_.created_at.substr(0, 10).c_str());+ if (!subscription_data_.credits_expire_at.empty())+ render_data_row("CREDITS EXPIRE", subscription_data_.credits_expire_at.substr(0, 10).c_str(), WARNING);+ if (!subscription_data_.last_credit_purchase_at.empty())+ render_data_row("LAST PURCHASE", subscription_data_.last_credit_purchase_at.substr(0, 10).c_str());+ } else {+ ImGui::TextColored(TEXT_DIM, "No account data available");+ if (theme::AccentButton("LOAD BILLING DATA")) fetch_billing_data();+ }++ ImGui::Spacing();++ // Payment History+ render_panel_header("PAYMENT HISTORY");++ std::lock_guard<std::mutex> lock(data_mutex_);+ if (payment_history_.empty()) {+ ImGui::TextColored(TEXT_DIM, "No payment history");+ } else {+ if (ImGui::BeginTable("##payments", 5,+ ImGuiTableFlags_Borders | ImGuiTableFlags_RowBg | ImGuiTableFlags_ScrollY | ImGuiTableFlags_SizingStretchProp,+ ImVec2(0, 250))) {+ ImGui::TableSetupColumn("DATE", 0, 1.5f);+ ImGui::TableSetupColumn("PLAN", 0, 1.5f);+ ImGui::TableSetupColumn("GATEWAY", 0, 1.2f);+ ImGui::TableSetupColumn("AMOUNT", 0, 1.0f);+ ImGui::TableSetupColumn("STATUS", 0, 1.0f);+ ImGui::TableSetupScrollFreeze(0, 1);+ ImGui::TableHeadersRow();++ for (auto& p : payment_history_) {+ ImGui::TableNextRow();+ ImGui::TableNextColumn();+ ImGui::TextColored(TEXT_PRIMARY, "%s", p.created_at.substr(0, 10).c_str());+ ImGui::TableNextColumn();+ ImGui::TextColored(TEXT_PRIMARY, "%s", p.plan_name.empty() ? "PURCHASE" : p.plan_name.c_str());+ ImGui::TableNextColumn();+ ImGui::TextColored(TEXT_DIM, "%s", p.payment_gateway.empty() ? "N/A" : p.payment_gateway.c_str());+ ImGui::TableNextColumn();+ char amt[16]; std::snprintf(amt, sizeof(amt), "$%.2f", p.amount_usd);+ ImGui::TextColored(INFO, "%s", amt);+ ImGui::TableNextColumn();+ ImVec4 sc = (p.status == "success" || p.status == "completed") ? SUCCESS :+ (p.status == "pending" ? WARNING : ERROR_RED);+ std::string su = p.status;+ for (auto& c : su) c = (char)std::toupper(c);+ ImGui::TextColored(sc, "%s", su.c_str());+ }+ ImGui::EndTable();+ }+ }+}++// ============================================================================+// SUPPORT+// ============================================================================+void ProfileScreen::render_support() {+ using namespace theme::colors;++ render_panel_header("CONTACT & SUPPORT");+ ImGui::TextColored(TEXT_SECONDARY, "For support, reach us at:");+ ImGui::Spacing();++ // Clickable links+ ImGui::TextColored(TEXT_DIM, "EMAIL:");+ ImGui::SameLine(0, 8);+ ImGui::PushStyleColor(ImGuiCol_Button, ImVec4(0, 0, 0, 0));+ ImGui::PushStyleColor(ImGuiCol_ButtonHovered, BG_HOVER);+ ImGui::PushStyleColor(ImGuiCol_Text, INFO);+ if (ImGui::SmallButton("[email protected]")) open_url("mailto:[email protected]");+ ImGui::PopStyleColor(3);++ ImGui::TextColored(TEXT_DIM, "DISCORD:");+ ImGui::SameLine(0, 8);+ ImGui::PushStyleColor(ImGuiCol_Button, ImVec4(0, 0, 0, 0));+ ImGui::PushStyleColor(ImGuiCol_ButtonHovered, BG_HOVER);+ ImGui::PushStyleColor(ImGuiCol_Text, INFO);+ if (ImGui::SmallButton("discord.gg/ae87a8ygbN")) open_url("https://discord.gg/ae87a8ygbN");+ ImGui::PopStyleColor(3);++ ImGui::TextColored(TEXT_DIM, "GITHUB:");+ ImGui::SameLine(0, 8);+ ImGui::PushStyleColor(ImGuiCol_Button, ImVec4(0, 0, 0, 0));+ ImGui::PushStyleColor(ImGuiCol_ButtonHovered, BG_HOVER);+ ImGui::PushStyleColor(ImGuiCol_Text, INFO);+ if (ImGui::SmallButton("github.com/Fincept-Corporation/FinceptTerminal")) open_url("https://github.com/Fincept-Corporation/FinceptTerminal");+ ImGui::PopStyleColor(3);++ ImGui::Spacing();+ ImGui::Separator();+ ImGui::Spacing();++ render_panel_header("ABOUT");+ render_data_row("VERSION", "3.3.1", ACCENT);+ render_data_row("PLATFORM", "C++ / ImGui Desktop");+ render_data_row("LICENSE", "AGPL-3.0-or-later");+ render_data_row("DEVELOPER", "Fincept Corporation");+}++// ============================================================================+// API Calls (background threads)+// ============================================================================+void ProfileScreen::fetch_usage_data() {+ if (loading_) return;+ loading_ = true;+ error_.clear();++ std::thread([this]() {+ auto& session = auth::AuthManager::instance().session();+ auto& http = http::HttpClient::instance();+ auto hdrs = auth_headers(session.api_key, session.session_token);++ auto resp = http.get(std::string(API_BASE) + "/user/usage?days=30", hdrs);++ std::lock_guard<std::mutex> lock(data_mutex_);+ if (resp.success) {+ try {+ auto j = resp.json_body();+ auto data = j.contains("data") ? j["data"] : j;++ // Account+ if (data.contains("account")) {+ auto& a = data["account"];+ if (a.contains("credit_balance")) usage_data_.account.credit_balance = a["credit_balance"].get<double>();+ if (a.contains("account_type")) usage_data_.account.account_type = a["account_type"].get<std::string>();+ if (a.contains("rate_limit_per_hour")) usage_data_.account.rate_limit_per_hour = a["rate_limit_per_hour"].get<int>();+ }+ if (data.contains("period_days")) usage_data_.period_days = data["period_days"].get<int>();++ // Summary+ if (data.contains("summary")) {+ auto& s = data["summary"];+ if (s.contains("total_requests")) usage_data_.summary.total_requests = s["total_requests"].get<int>();+ if (s.contains("total_credits_used")) usage_data_.summary.total_credits_used = s["total_credits_used"].get<double>();+ if (s.contains("avg_credits_per_request")) usage_data_.summary.avg_credits_per_request = s["avg_credits_per_request"].get<double>();+ if (s.contains("avg_response_time_ms")) usage_data_.summary.avg_response_time_ms = s["avg_response_time_ms"].get<double>();+ }++ // Daily usage+ usage_data_.daily_usage.clear();+ if (data.contains("daily_usage") && data["daily_usage"].is_array()) {+ for (auto& d : data["daily_usage"]) {+ DailyUsage du;+ if (d.contains("date")) du.date = d["date"].get<std::string>();+ if (d.contains("request_count")) du.request_count = d["request_count"].get<int>();+ if (d.contains("credits_used")) du.credits_used = d["credits_used"].get<double>();+ usage_data_.daily_usage.push_back(du);+ }+ }++ // Endpoint breakdown+ usage_data_.endpoint_breakdown.clear();+ if (data.contains("endpoint_breakdown") && data["endpoint_breakdown"].is_array()) {+ for (auto& e : data["endpoint_breakdown"]) {+ EndpointBreakdown eb;+ if (e.contains("endpoint")) eb.endpoint = e["endpoint"].get<std::string>();+ if (e.contains("request_count")) eb.request_count = e["request_count"].get<int>();+ if (e.contains("credits_used")) eb.credits_used = e["credits_used"].get<double>();+ if (e.contains("avg_response_time_ms")) eb.avg_response_time_ms = e["avg_response_time_ms"].get<double>();+ usage_data_.endpoint_breakdown.push_back(eb);+ }+ }++ // Recent requests+ usage_data_.recent_requests.clear();+ if (data.contains("recent_requests") && data["recent_requests"].is_array()) {+ for (auto& r : data["recent_requests"]) {+ RecentRequest rq;+ if (r.contains("timestamp")) rq.timestamp = r["timestamp"].get<std::string>();+ if (r.contains("endpoint")) rq.endpoint = r["endpoint"].get<std::string>();+ if (r.contains("method")) rq.method = r["method"].get<std::string>();+ if (r.contains("status_code")) rq.status_code = r["status_code"].get<int>();+ if (r.contains("credits_used")) rq.credits_used = r["credits_used"].get<double>();+ if (r.contains("response_time_ms")) rq.response_time_ms = r["response_time_ms"].get<double>();+ usage_data_.recent_requests.push_back(rq);+ }+ }++ usage_data_.valid = true;+ } catch (std::exception& e) {+ error_ = std::string("Parse error: ") + e.what();+ }+ } else {+ error_ = resp.error.empty() ? "Failed to fetch usage data" : resp.error;+ }+ loading_ = false;+ }).detach();+}++void ProfileScreen::fetch_billing_data() {+ if (loading_) return;+ loading_ = true;+ error_.clear();++ std::thread([this]() {+ auto& session = auth::AuthManager::instance().session();+ auto& http = http::HttpClient::instance();+ auto hdrs = auth_headers(session.api_key, session.session_token);++ // Fetch subscription + payment history in sequence+ auto sub_resp = http.get(std::string(API_BASE) + "/cashfree/subscription", hdrs);+ auto pay_resp = http.get(std::string(API_BASE) + "/cashfree/payments?page=1&page_size=20", hdrs);++ std::lock_guard<std::mutex> lock(data_mutex_);++ if (sub_resp.success) {+ try {+ auto j = sub_resp.json_body();+ auto d = j.contains("data") ? j["data"] : j;+ if (d.contains("user_id")) subscription_data_.user_id = d["user_id"].get<int>();+ if (d.contains("account_type")) subscription_data_.account_type = d["account_type"].get<std::string>();+ if (d.contains("credit_balance")) subscription_data_.credit_balance = d["credit_balance"].get<double>();+ if (d.contains("credits_expire_at") && !d["credits_expire_at"].is_null())+ subscription_data_.credits_expire_at = d["credits_expire_at"].get<std::string>();+ if (d.contains("support_type")) subscription_data_.support_type = d["support_type"].get<std::string>();+ if (d.contains("last_credit_purchase_at") && !d["last_credit_purchase_at"].is_null())+ subscription_data_.last_credit_purchase_at = d["last_credit_purchase_at"].get<std::string>();+ if (d.contains("created_at")) subscription_data_.created_at = d["created_at"].get<std::string>();+ subscription_data_.valid = true;+ } catch (...) {}+ }++ if (pay_resp.success) {+ try {+ auto j = pay_resp.json_body();+ auto data = j.contains("data") ? j["data"] : j;+ auto payments = data.contains("payments") ? data["payments"] : json::array();++ payment_history_.clear();+ for (auto& p : payments) {+ PaymentHistoryItem item;+ if (p.contains("payment_uuid")) item.payment_uuid = p["payment_uuid"].get<std::string>();+ if (p.contains("payment_gateway")) item.payment_gateway = p["payment_gateway"].get<std::string>();+ if (p.contains("amount_usd")) item.amount_usd = p["amount_usd"].get<double>();+ if (p.contains("status")) item.status = p["status"].get<std::string>();+ if (p.contains("plan_name")) item.plan_name = p["plan_name"].get<std::string>();+ if (p.contains("created_at")) item.created_at = p["created_at"].get<std::string>();+ payment_history_.push_back(item);+ }+ } catch (...) {}+ }++ loading_ = false;+ }).detach();+}++void ProfileScreen::fetch_profile_update() {+ edit_loading_ = true;+ edit_status_.clear();++ std::thread([this]() {+ auto& session = auth::AuthManager::instance().session();+ auto& http = http::HttpClient::instance();+ auto hdrs = auth_headers(session.api_key, session.session_token);++ json body;+ if (edit_username_[0]) body["username"] = edit_username_;+ if (edit_phone_[0]) body["phone"] = edit_phone_;+ if (edit_country_[0]) body["country"] = edit_country_;+ if (edit_country_code_[0]) body["country_code"] = edit_country_code_;++ auto resp = http.put_json(std::string(API_BASE) + "/user/profile", body, hdrs);++ if (resp.success) {+ edit_status_ = "Profile updated successfully!";+ auth::AuthManager::instance().refresh_user_data();+ } else {+ edit_status_ = "Error: " + (resp.error.empty() ? "Failed to update profile" : resp.error);+ }+ edit_loading_ = false;+ }).detach();+}++void ProfileScreen::toggle_mfa(bool enable) {+ mfa_loading_ = true;+ mfa_status_.clear();++ std::thread([this, enable]() {+ auto& session = auth::AuthManager::instance().session();+ auto& http = http::HttpClient::instance();+ auto hdrs = auth_headers(session.api_key, session.session_token);++ std::string url = std::string(API_BASE) + (enable ? "/user/mfa/enable" : "/user/mfa/disable");+ auto resp = http.post_json(url, json::object(), hdrs);++ if (resp.success) {+ mfa_status_ = enable ? "MFA enabled! OTP codes will be sent via email." : "MFA disabled successfully!";+ auth::AuthManager::instance().refresh_user_data();+ } else {+ mfa_status_ = "Error: " + (resp.error.empty() ? "Failed" : resp.error);+ }+ mfa_loading_ = false;+ }).detach();+}++void ProfileScreen::regenerate_api_key() {+ regen_loading_ = true;+ regen_status_.clear();++ std::thread([this]() {+ auto& session = auth::AuthManager::instance().session();+ auto& http = http::HttpClient::instance();+ auto hdrs = auth_headers(session.api_key, session.session_token);++ auto resp = http.post_json(std::string(API_BASE) + "/user/regenerate-api-key", json::object(), hdrs);++ if (resp.success) {+ regen_status_ = "API key regenerated. Please re-login.";+ auth::AuthManager::instance().refresh_user_data();+ } else {+ regen_status_ = "Error: " + (resp.error.empty() ? "Failed" : resp.error);+ }+ regen_loading_ = false;+ }).detach();+}++// ============================================================================+// MAIN RENDER+// ============================================================================+void ProfileScreen::render() {+ init();++ using namespace theme::colors;+ auto& session = auth::AuthManager::instance().session();++ ImGuiViewport* vp = ImGui::GetMainViewport();+ float tab_bar_h = ImGui::GetFrameHeight() + 4;+ float footer_h = ImGui::GetFrameHeight();++ float work_y = vp->WorkPos.y + tab_bar_h;+ float work_h = vp->WorkSize.y - tab_bar_h - footer_h;+ float work_w = vp->WorkSize.x;++ ImGui::SetNextWindowPos(ImVec2(vp->WorkPos.x, work_y));+ ImGui::SetNextWindowSize(ImVec2(work_w, work_h));++ ImGui::PushStyleVar(ImGuiStyleVar_WindowPadding, ImVec2(12, 8));+ ImGui::PushStyleVar(ImGuiStyleVar_WindowBorderSize, 0);+ ImGui::PushStyleColor(ImGuiCol_WindowBg, BG_DARKEST);++ ImGui::Begin("##profile", nullptr,+ ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_NoResize | ImGuiWindowFlags_NoMove |+ ImGuiWindowFlags_NoCollapse | ImGuiWindowFlags_NoDocking |+ ImGuiWindowFlags_NoBringToFrontOnFocus);++ // Header — left: title + subtitle, right: badges (all on one row, safely spaced)+ std::string subtitle = session.is_registered()+ ? (session.user_info.username.empty() ? session.user_info.email : session.user_info.username)+ : "Guest Session";++ // Build right-side text first to measure+ char cb[32]; std::snprintf(cb, sizeof(cb), "%.2f", session.user_info.credit_balance);+ std::string at = session.user_info.account_type;+ for (auto& c : at) c = (char)std::toupper(c);+ char badge_credits[64]; std::snprintf(badge_credits, sizeof(badge_credits), "CREDITS: %s", cb);+ char badge_plan[64]; std::snprintf(badge_plan, sizeof(badge_plan), "PLAN: %s", at.c_str());+ float badge_w = ImGui::CalcTextSize(badge_credits).x + 16 + ImGui::CalcTextSize(badge_plan).x + 16;++ float win_w = ImGui::GetContentRegionAvail().x;+ float title_w = ImGui::CalcTextSize("PROFILE & ACCOUNT").x;+ float max_subtitle_w = win_w - title_w - badge_w - 40; // 40px safety margin++ ImGui::TextColored(ACCENT, "PROFILE & ACCOUNT");+ ImGui::SameLine(0, 8);++ // Truncate subtitle if it would collide+ if (max_subtitle_w > 60) {+ ImGui::PushClipRect(ImGui::GetCursorScreenPos(),+ ImVec2(ImGui::GetCursorScreenPos().x + max_subtitle_w, ImGui::GetCursorScreenPos().y + ImGui::GetTextLineHeight()),+ true);+ ImGui::TextColored(TEXT_DIM, "%s", subtitle.c_str());+ ImGui::PopClipRect();+ }++ // Right-aligned badges+ ImGui::SameLine(win_w - badge_w + ImGui::GetStyle().WindowPadding.x);+ ImGui::TextColored(INFO, "%s", badge_credits);+ ImGui::SameLine(0, 16);+ ImGui::TextColored(ACCENT, "%s", badge_plan);++ ImGui::Separator();++ // Error banner+ if (!error_.empty()) {+ ImGui::PushStyleColor(ImGuiCol_ChildBg, ImVec4(ERROR_RED.x, ERROR_RED.y, ERROR_RED.z, 0.1f));+ ImGui::BeginChild("##err_banner", ImVec2(0, 24), ImGuiChildFlags_Borders);+ ImGui::TextColored(ERROR_RED, "%s", error_.c_str());+ ImGui::EndChild();+ ImGui::PopStyleColor();+ }++ // Section tabs+ render_section_tabs();+ ImGui::Spacing();++ // Content (scrollable)+ ImGui::BeginChild("##profile_content", ImVec2(0, 0));++ switch (active_section_) {+ case Section::Overview: render_overview(); break;+ case Section::Usage: render_usage(); break;+ case Section::Security: render_security(); break;+ case Section::Billing: render_billing(); break;+ case Section::Support: render_support(); break;+ }++ ImGui::EndChild();++ ImGui::End();+ ImGui::PopStyleColor();+ ImGui::PopStyleVar(2);+}++} // namespace fincept::profilediff --git a/fincept-cpp/src/profile/profile_screen.h b/fincept-cpp/src/profile/profile_screen.hnew file mode 100644index 000000000..5e2809dfb--- /dev/null+++ b/fincept-cpp/src/profile/profile_screen.h@@ -0,0 +1,160 @@+#pragma once+// Profile & Account Management — mirrors ProfileTab.tsx+// Sections: Overview, Usage, Security, Billing, Support+// Real API calls to api.fincept.in++#include <imgui.h>+#include <string>+#include <vector>+#include <mutex>+#include <atomic>+#include <thread>+#include <nlohmann/json.hpp>++namespace fincept::profile {++using json = nlohmann::json;++enum class Section { Overview, Usage, Security, Billing, Support };++// API data types matching profileTypes.ts+struct UsageSummary {+ int total_requests = 0;+ double total_credits_used = 0;+ double avg_credits_per_request = 0;+ double avg_response_time_ms = 0;+ std::string first_request_at;+ std::string last_request_at;+};++struct DailyUsage {+ std::string date;+ int request_count = 0;+ double credits_used = 0;+};++struct EndpointBreakdown {+ std::string endpoint;+ int request_count = 0;+ double credits_used = 0;+ double avg_response_time_ms = 0;+};++struct RecentRequest {+ std::string timestamp;+ std::string endpoint;+ std::string method;+ int status_code = 0;+ double credits_used = 0;+ double response_time_ms = 0;+};++struct UsageAccount {+ double credit_balance = 0;+ std::string account_type;+ std::string credits_expire_at;+ int rate_limit_per_hour = 0;+ std::string support_type;+};++struct UsageData {+ UsageAccount account;+ int period_days = 30;+ UsageSummary summary;+ std::vector<DailyUsage> daily_usage;+ std::vector<EndpointBreakdown> endpoint_breakdown;+ std::vector<RecentRequest> recent_requests;+ bool valid = false;+};++struct PaymentHistoryItem {+ std::string payment_uuid;+ std::string payment_gateway;+ double amount_usd = 0;+ std::string currency;+ std::string status;+ std::string plan_name;+ double credits_purchased = 0;+ std::string payment_method;+ std::string created_at;+ std::string completed_at;+};++struct SubscriptionData {+ int user_id = 0;+ std::string account_type;+ double credit_balance = 0;+ std::string credits_expire_at;+ std::string support_type;+ std::string last_credit_purchase_at;+ std::string created_at;+ bool valid = false;+};++class ProfileScreen {+public:+ void render();++private:+ bool initialized_ = false;+ Section active_section_ = Section::Overview;++ // Data (protected by mutex for async fetches)+ std::mutex data_mutex_;+ UsageData usage_data_;+ SubscriptionData subscription_data_;+ std::vector<PaymentHistoryItem> payment_history_;+ std::string error_;+ std::atomic<bool> loading_{false};++ // Security+ bool show_api_key_ = false;+ bool show_logout_confirm_ = false;+ bool show_regen_confirm_ = false;++ // Edit profile+ bool editing_profile_ = false;+ char edit_username_[128] = "";+ char edit_phone_[64] = "";+ char edit_country_[64] = "";+ char edit_country_code_[16] = "";+ std::string edit_status_;+ bool edit_loading_ = false;++ // MFA+ bool mfa_loading_ = false;+ std::string mfa_status_;++ // API key regen+ bool regen_loading_ = false;+ std::string regen_status_;++ // Fetch tracking+ double last_fetch_time_ = 0;+ Section last_fetched_section_ = Section::Overview;++ // Init+ void init();++ // Section renderers+ void render_section_tabs();+ void render_overview();+ void render_usage();+ void render_security();+ void render_billing();+ void render_support();++ // API calls (run in background thread)+ void fetch_usage_data();+ void fetch_billing_data();+ void fetch_profile_update();+ void toggle_mfa(bool enable);+ void regenerate_api_key();++ // Helpers+ void render_data_row(const char* label, const char* value, ImVec4 value_color = ImVec4(0, 0, 0, 0));+ void render_stat_box(const char* label, const char* value, ImVec4 color = ImVec4(0, 0, 0, 0));+ void render_panel_header(const char* title);+};++} // namespace fincept::profilediff --git a/fincept-cpp/src/research/analysis_panel.cpp b/fincept-cpp/src/research/analysis_panel.cppnew file mode 100644index 000000000..f23a7fc05--- /dev/null+++ b/fincept-cpp/src/research/analysis_panel.cpp@@ -0,0 +1,163 @@+#include "analysis_panel.h"+#include "../theme/bloomberg_theme.h"+#include <imgui.h>+#include <cstdio>+#include <cmath>++namespace fincept::research {++using namespace theme::colors;++static bool is_missing(double v) { return std::isnan(v); }++static void fmt_large(char* buf, size_t sz, double v) {+ if (is_missing(v)) { std::snprintf(buf, sz, "N/A"); return; }+ double av = std::abs(v);+ const char* sign = v < 0 ? "-" : "";+ if (av >= 1e12) std::snprintf(buf, sz, "%s$%.2fT", sign, av / 1e12);+ else if (av >= 1e9) std::snprintf(buf, sz, "%s$%.2fB", sign, av / 1e9);+ else if (av >= 1e6) std::snprintf(buf, sz, "%s$%.2fM", sign, av / 1e6);+ else if (av >= 1e3) std::snprintf(buf, sz, "%s$%.2fK", sign, av / 1e3);+ else std::snprintf(buf, sz, "%s$%.2f", sign, av);+}++static void fmt_percent(char* buf, size_t sz, double v) {+ if (is_missing(v)) { std::snprintf(buf, sz, "N/A"); return; }+ std::snprintf(buf, sz, "%.2f%%", v * 100.0);+}++static void fmt_number(char* buf, size_t sz, double v) {+ if (is_missing(v)) { std::snprintf(buf, sz, "N/A"); return; }+ std::snprintf(buf, sz, "%.2f", v);+}++// Metric card: label on top (dim), value below (large, colored)+static void metric_card(const char* label, const char* value, ImVec4 color) {+ ImGui::TextColored(TEXT_DIM, "%s", label);+ ImGui::PushStyleColor(ImGuiCol_Text, color);+ ImGui::SetWindowFontScale(1.2f);+ ImGui::TextUnformatted(value);+ ImGui::SetWindowFontScale(1.0f);+ ImGui::PopStyleColor();+ ImGui::Spacing();+}++// Section with colored left bar+static void section_start(const char* title, ImVec4 color) {+ ImDrawList* dl = ImGui::GetWindowDrawList();+ ImVec2 pos = ImGui::GetCursorScreenPos();+ dl->AddRectFilled(pos, ImVec2(pos.x + 4, pos.y + 16), ImGui::GetColorU32(color));+ ImGui::SetCursorPosX(ImGui::GetCursorPosX() + 12);+ ImGui::PushStyleColor(ImGuiCol_Text, color);+ ImGui::TextUnformatted(title);+ ImGui::PopStyleColor();+ ImGui::PushStyleColor(ImGuiCol_Separator, color);+ ImGui::Separator();+ ImGui::PopStyleColor();+ ImGui::Spacing();+}++void AnalysisPanel::render(ResearchData& data) {+ std::lock_guard<std::mutex> lock(data.mutex());+ auto& si = data.stock_info();+ char buf[64];++ ImVec2 avail = ImGui::GetContentRegionAvail();+ float half_w = (avail.x - 8) * 0.5f;+ float half_h = (avail.y - 8) * 0.5f;++ // ── Top Left: Financial Health ──+ ImGui::BeginChild("##fh", ImVec2(half_w, half_h), true);+ section_start("FINANCIAL HEALTH", ACCENT);++ // 2x2 grid+ float col_w = (ImGui::GetContentRegionAvail().x - 8) * 0.5f;++ ImGui::BeginChild("##fh_tl", ImVec2(col_w, 0), false);+ fmt_large(buf, sizeof(buf), si.total_cash);+ metric_card("TOTAL CASH", buf, MARKET_GREEN);+ fmt_large(buf, sizeof(buf), si.free_cashflow);+ metric_card("FREE CASHFLOW", buf, INFO);+ ImGui::EndChild();+ ImGui::SameLine(0, 8);+ ImGui::BeginChild("##fh_tr", ImVec2(col_w, 0), false);+ fmt_large(buf, sizeof(buf), si.total_debt);+ metric_card("TOTAL DEBT", buf, MARKET_RED);+ fmt_large(buf, sizeof(buf), si.operating_cashflow);+ metric_card("OPERATING CF", buf, ImVec4(0.24f, 0.56f, 0.94f, 1.0f));+ ImGui::EndChild();++ ImGui::EndChild();++ ImGui::SameLine(0, 8);++ // ── Top Right: Enterprise Value ──+ ImGui::BeginChild("##ev", ImVec2(half_w, half_h), true);+ section_start("ENTERPRISE VALUE", INFO);++ ImGui::BeginChild("##ev_tl", ImVec2(col_w, 0), false);+ fmt_large(buf, sizeof(buf), si.enterprise_value);+ metric_card("ENTERPRISE VALUE", buf, WARNING);+ fmt_number(buf, sizeof(buf), si.enterprise_to_ebitda);+ metric_card("EV/EBITDA", buf, INFO);+ ImGui::EndChild();+ ImGui::SameLine(0, 8);+ ImGui::BeginChild("##ev_tr", ImVec2(col_w, 0), false);+ fmt_number(buf, sizeof(buf), si.enterprise_to_revenue);+ metric_card("EV/REVENUE", buf, INFO);+ if (!is_missing(si.book_value)) std::snprintf(buf, sizeof(buf), "$%.2f", si.book_value);+ else std::snprintf(buf, sizeof(buf), "N/A");+ metric_card("BOOK VALUE", buf, TEXT_PRIMARY);+ ImGui::EndChild();++ ImGui::EndChild();++ // ── Bottom Left: Revenue & Profits ──+ ImGui::BeginChild("##rp", ImVec2(half_w, 0), true);+ section_start("REVENUE & PROFITS", MARKET_GREEN);++ ImGui::BeginChild("##rp_tl", ImVec2(col_w, 0), false);+ fmt_large(buf, sizeof(buf), si.total_revenue);+ metric_card("TOTAL REVENUE", buf, MARKET_GREEN);+ fmt_large(buf, sizeof(buf), si.gross_profits);+ metric_card("GROSS PROFITS", buf, MARKET_GREEN);+ ImGui::EndChild();+ ImGui::SameLine(0, 8);+ ImGui::BeginChild("##rp_tr", ImVec2(col_w, 0), false);+ if (!is_missing(si.revenue_per_share)) std::snprintf(buf, sizeof(buf), "$%.2f", si.revenue_per_share);+ else std::snprintf(buf, sizeof(buf), "N/A");+ metric_card("REVENUE/SHARE", buf, INFO);+ fmt_percent(buf, sizeof(buf), si.ebitda_margins);+ metric_card("EBITDA MARGINS", buf, WARNING);+ ImGui::EndChild();++ ImGui::EndChild();++ ImGui::SameLine(0, 8);++ // ── Bottom Right: Key Ratios ──+ ImGui::BeginChild("##kr", ImVec2(half_w, 0), true);+ section_start("KEY RATIOS", ImVec4(0.7f, 0.3f, 0.9f, 1.0f));++ ImGui::BeginChild("##kr_tl", ImVec2(col_w, 0), false);+ fmt_number(buf, sizeof(buf), si.pe_ratio);+ metric_card("P/E RATIO", buf, TEXT_PRIMARY);+ fmt_percent(buf, sizeof(buf), si.return_on_equity);+ metric_card("ROE", buf, MARKET_GREEN);+ fmt_number(buf, sizeof(buf), si.beta);+ metric_card("BETA", buf, INFO);+ ImGui::EndChild();+ ImGui::SameLine(0, 8);+ ImGui::BeginChild("##kr_tr", ImVec2(col_w, 0), false);+ fmt_number(buf, sizeof(buf), si.peg_ratio);+ metric_card("PEG RATIO", buf, TEXT_PRIMARY);+ fmt_percent(buf, sizeof(buf), si.return_on_assets);+ metric_card("ROA", buf, MARKET_GREEN);+ fmt_number(buf, sizeof(buf), si.short_ratio);+ metric_card("SHORT RATIO", buf, MARKET_RED);+ ImGui::EndChild();++ ImGui::EndChild();+}++} // namespace fincept::researchdiff --git a/fincept-cpp/src/research/analysis_panel.h b/fincept-cpp/src/research/analysis_panel.hnew file mode 100644index 000000000..c1ef7a00f--- /dev/null+++ b/fincept-cpp/src/research/analysis_panel.h@@ -0,0 +1,15 @@+#pragma once+// Analysis panel — Financial Health, Enterprise Value, Revenue & Profits, Key Ratios+// Mirrors AnalysisTab.tsx: 2x2 grid of financial metric cards++#include "research_types.h"+#include "research_data.h"++namespace fincept::research {++class AnalysisPanel {+public:+ void render(ResearchData& data);+};++} // namespace fincept::researchdiff --git a/fincept-cpp/src/research/financials_panel.cpp b/fincept-cpp/src/research/financials_panel.cppnew file mode 100644index 000000000..67376a592--- /dev/null+++ b/fincept-cpp/src/research/financials_panel.cpp@@ -0,0 +1,153 @@+#include "financials_panel.h"+#include "../theme/bloomberg_theme.h"+#include <imgui.h>+#include <cstdio>+#include <algorithm>+#include <vector>+#include <set>++namespace fincept::research {++using namespace theme::colors;++static void fmt_large(char* buf, size_t sz, double v) {+ if (v == 0) { std::snprintf(buf, sz, "-"); return; }+ double av = std::abs(v);+ const char* sign = v < 0 ? "-" : "";+ if (av >= 1e12) std::snprintf(buf, sz, "%s$%.2fT", sign, av / 1e12);+ else if (av >= 1e9) std::snprintf(buf, sz, "%s$%.2fB", sign, av / 1e9);+ else if (av >= 1e6) std::snprintf(buf, sz, "%s$%.2fM", sign, av / 1e6);+ else if (av >= 1e3) std::snprintf(buf, sz, "%s$%.2fK", sign, av / 1e3);+ else std::snprintf(buf, sz, "%s$%.0f", sign, av);+}++// Make metric names more readable+static std::string format_metric_name(const std::string& key) {+ std::string result;+ for (size_t i = 0; i < key.size(); i++) {+ char c = key[i];+ if (i > 0 && std::isupper(c) && std::islower(key[i-1])) {+ result += ' ';+ }+ result += (char)std::toupper(c);+ }+ return result;+}++void FinancialsPanel::render(ResearchData& data) {+ std::lock_guard<std::mutex> lock(data.mutex());+ auto& fin = data.financials();++ // Statement selector tabs+ ImGui::PushStyleVar(ImGuiStyleVar_FramePadding, ImVec2(12, 4));+ const char* labels[] = {"INCOME STATEMENT", "BALANCE SHEET", "CASH FLOW"};+ for (int i = 0; i < 3; i++) {+ bool active = (active_statement_ == i);+ if (active) {+ ImGui::PushStyleColor(ImGuiCol_Button, ACCENT);+ ImGui::PushStyleColor(ImGuiCol_Text, BG_DARKEST);+ }+ if (ImGui::Button(labels[i])) active_statement_ = i;+ if (active) ImGui::PopStyleColor(2);+ if (i < 2) ImGui::SameLine(0, 4);+ }+ ImGui::PopStyleVar();++ ImGui::Spacing();+ ImGui::Separator();+ ImGui::Spacing();++ // Render the selected statement+ switch (active_statement_) {+ case 0: render_statement_table(fin.income_statement, "INCOME STATEMENT"); break;+ case 1: render_statement_table(fin.balance_sheet, "BALANCE SHEET"); break;+ case 2: render_statement_table(fin.cash_flow, "CASH FLOW STATEMENT"); break;+ }+}++void FinancialsPanel::render_statement_table(const FinancialStatement& stmt, const char* title) {+ if (stmt.data.empty()) {+ ImGui::TextColored(TEXT_DIM, "No %s data available.", title);+ return;+ }++ // Get sorted periods (most recent first)+ std::vector<std::string> periods;+ for (auto& [date, _] : stmt.data) periods.push_back(date);+ std::sort(periods.begin(), periods.end(), std::greater<>());++ // Get all unique metric keys+ std::set<std::string> metric_set;+ for (auto& [_, metrics] : stmt.data) {+ for (auto& [key, __] : metrics) {+ metric_set.insert(key);+ }+ }+ std::vector<std::string> metric_keys(metric_set.begin(), metric_set.end());+ std::sort(metric_keys.begin(), metric_keys.end());++ int num_cols = 1 + (int)periods.size(); // metric name + periods+ if (num_cols > 6) num_cols = 6; // cap at 5 periods+ int num_periods = num_cols - 1;++ ImGuiTableFlags flags = ImGuiTableFlags_Borders | ImGuiTableFlags_RowBg |+ ImGuiTableFlags_ScrollY | ImGuiTableFlags_Resizable |+ ImGuiTableFlags_SizingStretchProp;++ float table_h = ImGui::GetContentRegionAvail().y;++ if (ImGui::BeginTable(title, num_cols, flags, ImVec2(0, table_h))) {+ // Header+ ImGui::TableSetupColumn("METRIC", ImGuiTableColumnFlags_WidthStretch, 2.0f);+ for (int i = 0; i < num_periods; i++) {+ // Extract year from date+ std::string year = periods[i].substr(0, 4);+ ImGui::TableSetupColumn(year.c_str(), ImGuiTableColumnFlags_WidthStretch, 1.0f);+ }+ ImGui::TableSetupScrollFreeze(1, 1);++ // Custom header rendering+ ImGui::TableNextRow(ImGuiTableRowFlags_Headers);+ ImGui::TableSetColumnIndex(0);+ ImGui::PushStyleColor(ImGuiCol_Text, ACCENT);+ ImGui::TextUnformatted("METRIC");+ ImGui::PopStyleColor();++ for (int i = 0; i < num_periods; i++) {+ ImGui::TableSetColumnIndex(i + 1);+ std::string year = periods[i].substr(0, 4);+ ImGui::PushStyleColor(ImGuiCol_Text, INFO);+ ImGui::TextUnformatted(year.c_str());+ ImGui::PopStyleColor();+ }++ // Data rows+ for (auto& key : metric_keys) {+ ImGui::TableNextRow();+ ImGui::TableSetColumnIndex(0);++ std::string display_name = format_metric_name(key);+ ImGui::TextColored(TEXT_SECONDARY, "%s", display_name.c_str());++ for (int i = 0; i < num_periods; i++) {+ ImGui::TableSetColumnIndex(i + 1);+ auto it = stmt.data.find(periods[i]);+ if (it != stmt.data.end()) {+ auto mit = it->second.find(key);+ if (mit != it->second.end()) {+ char buf[64];+ fmt_large(buf, sizeof(buf), mit->second);+ ImVec4 color = mit->second < 0 ? MARKET_RED : TEXT_PRIMARY;+ ImGui::TextColored(color, "%s", buf);+ } else {+ ImGui::TextColored(TEXT_DISABLED, "-");+ }+ }+ }+ }++ ImGui::EndTable();+ }+}++} // namespace fincept::researchdiff --git a/fincept-cpp/src/research/financials_panel.h b/fincept-cpp/src/research/financials_panel.hnew file mode 100644index 000000000..48b59475d--- /dev/null+++ b/fincept-cpp/src/research/financials_panel.h@@ -0,0 +1,20 @@+#pragma once+// Financials panel — Income Statement, Balance Sheet, Cash Flow+// Mirrors FinancialsTab.tsx: table-based display of financial statements++#include "research_types.h"+#include "research_data.h"++namespace fincept::research {++class FinancialsPanel {+public:+ void render(ResearchData& data);++private:+ int active_statement_ = 0; // 0=income, 1=balance, 2=cashflow++ void render_statement_table(const FinancialStatement& stmt, const char* title);+};++} // namespace fincept::researchdiff --git a/fincept-cpp/src/research/news_panel.cpp b/fincept-cpp/src/research/news_panel.cppnew file mode 100644index 000000000..8b1c9897e--- /dev/null+++ b/fincept-cpp/src/research/news_panel.cpp@@ -0,0 +1,124 @@+#include "news_panel.h"+#include "../theme/bloomberg_theme.h"+#include <imgui.h>++#ifdef _WIN32+#include <windows.h>+#include <shellapi.h>+#endif++namespace fincept::research {++using namespace theme::colors;++static void open_url(const std::string& url) {+#ifdef _WIN32+ ShellExecuteA(nullptr, "open", url.c_str(), nullptr, nullptr, SW_SHOWNORMAL);+#endif+}++void ResearchNewsPanel::render(ResearchData& data, const std::string& symbol) {+ std::lock_guard<std::mutex> lock(data.mutex());+ auto& articles = data.news();++ // Header bar+ ImGui::PushStyleColor(ImGuiCol_ChildBg, BG_WIDGET);+ ImGui::BeginChild("##news_hdr", ImVec2(0, 30), true);+ ImGui::TextColored(ACCENT, "LATEST NEWS");+ ImGui::SameLine(0, 16);+ ImGui::TextColored(TEXT_DIM, "%d articles found", (int)articles.size());+ ImGui::SameLine(0, 16);+ ImGui::TextColored(INFO, "%s", symbol.c_str());++ ImGui::SameLine(ImGui::GetContentRegionAvail().x - 60);+ if (theme::SecondaryButton("REFRESH")) {+ data.fetch_news(symbol);+ }+ ImGui::EndChild();+ ImGui::PopStyleColor();++ ImGui::Spacing();++ if (data.is_news_loading()) {+ ImVec2 avail = ImGui::GetContentRegionAvail();+ ImGui::SetCursorPos(ImVec2(avail.x * 0.35f, ImGui::GetCursorPosY() + avail.y * 0.3f));+ theme::LoadingSpinner("Fetching latest news...");+ return;+ }++ if (articles.empty()) {+ ImVec2 avail = ImGui::GetContentRegionAvail();+ ImGui::SetCursorPos(ImVec2(avail.x * 0.3f, ImGui::GetCursorPosY() + avail.y * 0.3f));+ ImGui::TextColored(WARNING, "NO NEWS FOUND");+ ImGui::SetCursorPosX(avail.x * 0.3f);+ ImGui::TextColored(TEXT_DIM, "No recent news articles found for %s", symbol.c_str());+ return;+ }++ // Article list+ ImGui::BeginChild("##news_list", ImVec2(0, 0), false);++ for (int i = 0; i < (int)articles.size(); i++) {+ auto& article = articles[i];+ bool is_selected = (i == selected_);++ ImGui::PushID(i);++ // Article card+ ImGui::PushStyleColor(ImGuiCol_ChildBg, is_selected ? BG_HOVER : BG_PANEL);+ ImGui::BeginChild("##art", ImVec2(0, 0),+ ImGuiChildFlags_AutoResizeY | ImGuiChildFlags_Borders);++ // Title (clickable)+ ImGui::PushStyleColor(ImGuiCol_Text, TEXT_PRIMARY);+ ImGui::PushTextWrapPos(ImGui::GetContentRegionAvail().x);+ ImGui::TextWrapped("%s", article.title.c_str());+ ImGui::PopTextWrapPos();+ ImGui::PopStyleColor();++ if (ImGui::IsItemClicked()) {+ selected_ = (selected_ == i) ? -1 : i;+ }++ // Metadata line+ ImGui::TextColored(INFO, "%s", article.publisher.c_str());+ ImGui::SameLine(0, 16);+ ImGui::TextColored(TEXT_DIM, "%s", article.published_date.c_str());++ // Description (if selected)+ if (is_selected && !article.description.empty()) {+ ImGui::Spacing();+ ImGui::PushTextWrapPos(ImGui::GetContentRegionAvail().x);+ ImGui::TextColored(TEXT_SECONDARY, "%s", article.description.c_str());+ ImGui::PopTextWrapPos();+ }++ // Open link button+ if (!article.url.empty()) {+ if (is_selected) {+ ImGui::Spacing();+ if (theme::AccentButton("OPEN IN BROWSER")) {+ open_url(article.url);+ }+ } else {+ ImGui::SameLine(ImGui::GetContentRegionAvail().x - 110);+ ImGui::PushStyleColor(ImGuiCol_Button, ImVec4(0, 0, 0, 0));+ ImGui::PushStyleColor(ImGuiCol_Text, ACCENT);+ if (ImGui::SmallButton("READ ARTICLE >>")) {+ open_url(article.url);+ }+ ImGui::PopStyleColor(2);+ }+ }++ ImGui::EndChild();+ ImGui::PopStyleColor();++ ImGui::PopID();+ ImGui::Spacing();+ }++ ImGui::EndChild();+}++} // namespace fincept::researchdiff --git a/fincept-cpp/src/research/news_panel.h b/fincept-cpp/src/research/news_panel.hnew file mode 100644index 000000000..fbbfc9b9b--- /dev/null+++ b/fincept-cpp/src/research/news_panel.h@@ -0,0 +1,18 @@+#pragma once+// News panel — Symbol-specific news articles+// Mirrors NewsTab.tsx: article list with headline, publisher, date, description++#include "research_types.h"+#include "research_data.h"++namespace fincept::research {++class ResearchNewsPanel {+public:+ void render(ResearchData& data, const std::string& symbol);++private:+ int selected_ = -1;+};++} // namespace fincept::researchdiff --git a/fincept-cpp/src/research/overview_panel.cpp b/fincept-cpp/src/research/overview_panel.cppnew file mode 100644index 000000000..fb8840d16--- /dev/null+++ b/fincept-cpp/src/research/overview_panel.cpp@@ -0,0 +1,408 @@+#include "overview_panel.h"+#include "../theme/bloomberg_theme.h"+#include <imgui.h>+#include <cstdio>+#include <cmath>+#include <algorithm>++namespace fincept::research {++using namespace theme::colors;++// ─── Formatting helpers ─────────────────────────────────────────────────────+// NaN sentinel: we treat exactly 0 as valid (many fields can be 0)+// Only show N/A for NaN+static bool is_missing(double v) { return std::isnan(v); }++static void fmt_number(char* buf, size_t sz, double v, int decimals = 2) {+ if (is_missing(v)) { std::snprintf(buf, sz, "N/A"); return; }+ std::snprintf(buf, sz, "%.*f", decimals, v);+}++static void fmt_large(char* buf, size_t sz, double v) {+ if (is_missing(v)) { std::snprintf(buf, sz, "N/A"); return; }+ double av = std::abs(v);+ const char* sign = v < 0 ? "-" : "";+ if (av >= 1e12) std::snprintf(buf, sz, "%s$%.2fT", sign, av / 1e12);+ else if (av >= 1e9) std::snprintf(buf, sz, "%s$%.2fB", sign, av / 1e9);+ else if (av >= 1e6) std::snprintf(buf, sz, "%s$%.2fM", sign, av / 1e6);+ else if (av >= 1e3) std::snprintf(buf, sz, "%s$%.2fK", sign, av / 1e3);+ else std::snprintf(buf, sz, "%s$%.2f", sign, av);+}++// Format ratio as percentage (multiply by 100): e.g. 0.27 -> "27.00%"+static void fmt_percent(char* buf, size_t sz, double v) {+ if (is_missing(v)) { std::snprintf(buf, sz, "N/A"); return; }+ std::snprintf(buf, sz, "%.2f%%", v * 100.0);+}++// Format value that's already a percentage: e.g. 0.41 -> "0.41%"+static void fmt_pct_raw(char* buf, size_t sz, double v) {+ if (is_missing(v)) { std::snprintf(buf, sz, "N/A"); return; }+ std::snprintf(buf, sz, "%.2f%%", v);+}++static void data_row(const char* label, const char* value, ImVec4 color) {+ float w = ImGui::GetContentRegionAvail().x;+ ImGui::TextColored(TEXT_DIM, "%s", label);+ ImGui::SameLine(w - ImGui::CalcTextSize(value).x);+ ImGui::TextColored(color, "%s", value);+}++// ─── Section with colored header ────────────────────────────────────────────+static void section_header(const char* label, ImVec4 color) {+ ImGui::PushStyleColor(ImGuiCol_Text, color);+ ImGui::TextUnformatted(label);+ ImGui::PopStyleColor();+ ImGui::PushStyleColor(ImGuiCol_Separator, BORDER_DIM);+ ImGui::Separator();+ ImGui::PopStyleColor();+ ImGui::Spacing();+}++// ─────────────────────────────────────────────────────────────────────────────+void OverviewPanel::render(ResearchData& data, ChartPeriod& period) {+ std::lock_guard<std::mutex> lock(data.mutex());+ auto& si = data.stock_info();+ auto& q = data.quote_data();+ auto& hist = data.historical();++ ImVec2 avail = ImGui::GetContentRegionAvail();+ float col1_w = avail.x * 0.20f;+ float col4_w = avail.x * 0.20f;+ float chart_w = avail.x - col1_w - col4_w - 16; // 16px for spacing+ float top_h = avail.y * 0.65f;++ // ── Top row: 3 columns ──+ ImGui::BeginChild("##ov_col1", ImVec2(col1_w, top_h), true);+ render_trading_valuation(q, si, col1_w);+ ImGui::EndChild();++ ImGui::SameLine(0, 4);++ ImGui::BeginChild("##ov_chart", ImVec2(chart_w, top_h), true);+ render_chart(hist, period, chart_w, top_h - 40);+ ImGui::EndChild();++ ImGui::SameLine(0, 4);++ ImGui::BeginChild("##ov_col4", ImVec2(col4_w, top_h), true);+ render_analyst_performance(si, col4_w);+ ImGui::EndChild();++ // ── Bottom: Company overview ──+ ImGui::Spacing();+ ImGui::BeginChild("##ov_bottom", ImVec2(avail.x, 0), true);+ render_company_overview(si);+ ImGui::EndChild();+}++// ─────────────────────────────────────────────────────────────────────────────+void OverviewPanel::render_trading_valuation(const QuoteData& q, const StockInfo& si, float width) {+ char buf[64];++ section_header("TODAY'S TRADING", ACCENT);++ fmt_number(buf, sizeof(buf), q.open);+ data_row("OPEN", buf, INFO);++ fmt_number(buf, sizeof(buf), q.high);+ data_row("HIGH", buf, MARKET_GREEN);++ fmt_number(buf, sizeof(buf), q.low);+ data_row("LOW", buf, MARKET_RED);++ fmt_number(buf, sizeof(buf), q.previous_close);+ data_row("PREV CLOSE", buf, TEXT_PRIMARY);++ fmt_number(buf, sizeof(buf), q.volume, 0);+ data_row("VOLUME", buf, WARNING);++ ImGui::Spacing(); ImGui::Spacing();+ section_header("VALUATION", INFO);++ fmt_large(buf, sizeof(buf), si.market_cap);+ data_row("MARKET CAP", buf, INFO);++ fmt_number(buf, sizeof(buf), si.pe_ratio);+ data_row("P/E RATIO", buf, WARNING);++ fmt_number(buf, sizeof(buf), si.forward_pe);+ data_row("FWD P/E", buf, WARNING);++ fmt_number(buf, sizeof(buf), si.peg_ratio);+ data_row("PEG RATIO", buf, WARNING);++ fmt_number(buf, sizeof(buf), si.price_to_book);+ data_row("P/B RATIO", buf, INFO);++ fmt_pct_raw(buf, sizeof(buf), si.dividend_yield);+ data_row("DIV YIELD", buf, MARKET_GREEN);++ fmt_number(buf, sizeof(buf), si.beta);+ data_row("BETA", buf, TEXT_PRIMARY);++ ImGui::Spacing(); ImGui::Spacing();+ section_header("SHARE STATS", ImVec4(0.7f, 0.3f, 0.9f, 1.0f));++ fmt_large(buf, sizeof(buf), si.shares_outstanding);+ data_row("SHARES OUT", buf, INFO);++ fmt_large(buf, sizeof(buf), si.float_shares);+ data_row("FLOAT", buf, INFO);++ fmt_percent(buf, sizeof(buf), si.held_percent_insiders);+ data_row("INSIDERS", buf, WARNING);++ fmt_percent(buf, sizeof(buf), si.held_percent_institutions);+ data_row("INSTITUTIONS", buf, WARNING);++ fmt_percent(buf, sizeof(buf), si.short_percent_of_float);+ data_row("SHORT %", buf, MARKET_RED);+}++// ─────────────────────────────────────────────────────────────────────────────+void OverviewPanel::render_chart(const std::vector<HistoricalDataPoint>& hist,+ ChartPeriod& period, float width, float height) {+ // Period selector+ ImGui::TextColored(TEXT_DIM, "PERIOD");+ ImGui::SameLine(0, 8);++ static const ChartPeriod periods[] = {+ ChartPeriod::M1, ChartPeriod::M3, ChartPeriod::M6, ChartPeriod::Y1, ChartPeriod::Y5+ };+ for (auto p : periods) {+ bool active = (p == period);+ if (active) {+ ImGui::PushStyleColor(ImGuiCol_Button, ACCENT);+ ImGui::PushStyleColor(ImGuiCol_Text, BG_DARKEST);+ }+ if (ImGui::SmallButton(chart_period_label(p))) {+ period = p;+ }+ if (active) ImGui::PopStyleColor(2);+ ImGui::SameLine(0, 4);+ }+ ImGui::NewLine();+ ImGui::Spacing();++ if (hist.empty()) {+ ImVec2 center(ImGui::GetCursorPosX() + width * 0.5f, ImGui::GetCursorPosY() + height * 0.3f);+ ImGui::SetCursorPos(ImVec2(center.x - 60, center.y));+ ImGui::TextColored(TEXT_DIM, "No chart data available");+ return;+ }++ // Find price range+ double min_price = 1e18, max_price = -1e18;+ double max_vol = 0;+ for (auto& dp : hist) {+ if (dp.low > 0) min_price = std::min(min_price, dp.low);+ max_price = std::max(max_price, dp.high);+ max_vol = std::max(max_vol, dp.volume);+ }+ double price_range = max_price - min_price;+ if (price_range < 0.01) price_range = 1;++ float chart_h = height * 0.75f;+ float vol_h = height * 0.20f;+ ImVec2 chart_origin = ImGui::GetCursorScreenPos();+ float chart_w = width - 16;++ ImDrawList* dl = ImGui::GetWindowDrawList();++ // Background+ dl->AddRectFilled(chart_origin,+ ImVec2(chart_origin.x + chart_w, chart_origin.y + chart_h),+ IM_COL32(10, 10, 10, 255));++ // Grid lines (5 horizontal)+ for (int i = 0; i <= 4; i++) {+ float y = chart_origin.y + chart_h * i / 4.0f;+ dl->AddLine(ImVec2(chart_origin.x, y),+ ImVec2(chart_origin.x + chart_w, y),+ IM_COL32(40, 40, 40, 255));+ // Price label+ char lbl[32];+ double p = max_price - price_range * i / 4.0;+ std::snprintf(lbl, sizeof(lbl), "$%.2f", p);+ dl->AddText(ImVec2(chart_origin.x + 2, y + 1), IM_COL32(100, 100, 100, 255), lbl);+ }++ // Candlestick rendering+ float bar_w = std::max(1.0f, chart_w / (float)hist.size() - 1);+ float half_bar = bar_w * 0.4f;++ for (size_t i = 0; i < hist.size(); i++) {+ float x = chart_origin.x + (float)i / hist.size() * chart_w;++ float y_open = chart_origin.y + (float)((max_price - hist[i].open) / price_range) * chart_h;+ float y_close = chart_origin.y + (float)((max_price - hist[i].close) / price_range) * chart_h;+ float y_high = chart_origin.y + (float)((max_price - hist[i].high) / price_range) * chart_h;+ float y_low = chart_origin.y + (float)((max_price - hist[i].low) / price_range) * chart_h;++ bool bullish = hist[i].close >= hist[i].open;+ ImU32 col = bullish ? IM_COL32(0, 200, 90, 255) : IM_COL32(240, 50, 50, 255);++ // Wick+ dl->AddLine(ImVec2(x + half_bar, y_high), ImVec2(x + half_bar, y_low), col);+ // Body+ float body_top = std::min(y_open, y_close);+ float body_bot = std::max(y_open, y_close);+ if (body_bot - body_top < 1) body_bot = body_top + 1;+ dl->AddRectFilled(ImVec2(x, body_top), ImVec2(x + bar_w, body_bot), col);+ }++ // Volume bars below chart+ ImVec2 vol_origin(chart_origin.x, chart_origin.y + chart_h + 4);+ dl->AddRectFilled(vol_origin,+ ImVec2(vol_origin.x + chart_w, vol_origin.y + vol_h),+ IM_COL32(10, 10, 10, 255));++ if (max_vol > 0) {+ for (size_t i = 0; i < hist.size(); i++) {+ float x = vol_origin.x + (float)i / hist.size() * chart_w;+ float h = (float)(hist[i].volume / max_vol) * vol_h;+ bool bullish = hist[i].close >= hist[i].open;+ ImU32 col = bullish ? IM_COL32(0, 200, 90, 80) : IM_COL32(240, 50, 50, 80);+ dl->AddRectFilled(+ ImVec2(x, vol_origin.y + vol_h - h),+ ImVec2(x + bar_w, vol_origin.y + vol_h),+ col);+ }+ }++ // Advance cursor past chart+ ImGui::Dummy(ImVec2(chart_w, chart_h + vol_h + 8));+}++// ─────────────────────────────────────────────────────────────────────────────+void OverviewPanel::render_analyst_performance(const StockInfo& si, float width) {+ char buf[64];++ section_header("ANALYST TARGETS", ImVec4(1.0f, 0.0f, 1.0f, 1.0f));++ if (!is_missing(si.target_high_price)) std::snprintf(buf, sizeof(buf), "$%.2f", si.target_high_price);+ else std::snprintf(buf, sizeof(buf), "N/A");+ data_row("HIGH", buf, MARKET_GREEN);++ if (!is_missing(si.target_mean_price)) std::snprintf(buf, sizeof(buf), "$%.2f", si.target_mean_price);+ else std::snprintf(buf, sizeof(buf), "N/A");+ data_row("MEAN", buf, WARNING);++ if (!is_missing(si.target_low_price)) std::snprintf(buf, sizeof(buf), "$%.2f", si.target_low_price);+ else std::snprintf(buf, sizeof(buf), "N/A");+ data_row("LOW", buf, MARKET_RED);++ std::snprintf(buf, sizeof(buf), "%d", si.number_of_analysts);+ data_row("ANALYSTS", buf, INFO);++ // Recommendation badge+ if (!si.recommendation_key.empty()) {+ ImGui::Spacing();+ ImVec4 rec_col = WARNING;+ if (si.recommendation_key == "buy" || si.recommendation_key == "strong_buy")+ rec_col = MARKET_GREEN;+ else if (si.recommendation_key == "sell" || si.recommendation_key == "strong_sell")+ rec_col = MARKET_RED;++ std::string rec_text = si.recommendation_key;+ for (auto& c : rec_text) c = (char)std::toupper(c);+ for (auto& c : rec_text) if (c == '_') c = ' ';+ ImGui::TextColored(rec_col, ">> %s", rec_text.c_str());+ }++ ImGui::Spacing(); ImGui::Spacing();+ section_header("52 WEEK RANGE", WARNING);++ if (!is_missing(si.fifty_two_week_high)) std::snprintf(buf, sizeof(buf), "$%.2f", si.fifty_two_week_high);+ else std::snprintf(buf, sizeof(buf), "N/A");+ data_row("HIGH", buf, MARKET_GREEN);++ if (!is_missing(si.fifty_two_week_low)) std::snprintf(buf, sizeof(buf), "$%.2f", si.fifty_two_week_low);+ else std::snprintf(buf, sizeof(buf), "N/A");+ data_row("LOW", buf, MARKET_RED);++ fmt_number(buf, sizeof(buf), si.average_volume, 0);+ data_row("AVG VOL", buf, INFO);++ ImGui::Spacing(); ImGui::Spacing();+ section_header("PROFITABILITY", MARKET_GREEN);++ fmt_percent(buf, sizeof(buf), si.gross_margins);+ data_row("GROSS MARGIN", buf, MARKET_GREEN);++ fmt_percent(buf, sizeof(buf), si.operating_margins);+ data_row("OPER. MARGIN", buf, MARKET_GREEN);++ fmt_percent(buf, sizeof(buf), si.profit_margins);+ data_row("PROFIT MARGIN", buf, MARKET_GREEN);++ fmt_percent(buf, sizeof(buf), si.return_on_assets);+ data_row("ROA", buf, INFO);++ fmt_percent(buf, sizeof(buf), si.return_on_equity);+ data_row("ROE", buf, INFO);++ ImGui::Spacing(); ImGui::Spacing();+ section_header("GROWTH RATES", ImVec4(0.24f, 0.56f, 0.94f, 1.0f));++ fmt_percent(buf, sizeof(buf), si.revenue_growth);+ data_row("REVENUE", buf, MARKET_GREEN);++ fmt_percent(buf, sizeof(buf), si.earnings_growth);+ data_row("EARNINGS", buf, MARKET_GREEN);+}++// ─────────────────────────────────────────────────────────────────────────────+void OverviewPanel::render_company_overview(const StockInfo& si) {+ if (si.description.empty()) {+ ImGui::TextColored(TEXT_DIM, "No company description available.");+ return;+ }++ float avail_w = ImGui::GetContentRegionAvail().x;+ float desc_w = avail_w * 0.65f;+ float info_w = avail_w - desc_w - 8;++ // Left: description+ ImGui::BeginChild("##desc", ImVec2(desc_w, 0), false);+ section_header("COMPANY OVERVIEW", INFO);+ ImGui::PushTextWrapPos(desc_w - 8);+ ImGui::TextColored(TEXT_SECONDARY, "%s", si.description.c_str());+ ImGui::PopTextWrapPos();+ ImGui::EndChild();++ ImGui::SameLine(0, 8);++ // Right: key info+ ImGui::BeginChild("##info_right", ImVec2(info_w, 0), false);+ char buf[64];++ section_header("COMPANY INFO", TEXT_PRIMARY);+ fmt_number(buf, sizeof(buf), (double)si.employees, 0);+ data_row("EMPLOYEES", buf, INFO);++ if (!si.website.empty()) {+ std::string site = si.website.substr(0, 30);+ data_row("WEBSITE", site.c_str(), ImVec4(0.24f, 0.56f, 0.94f, 1.0f));+ }+ if (!si.currency.empty())+ data_row("CURRENCY", si.currency.c_str(), INFO);++ ImGui::Spacing(); ImGui::Spacing();+ section_header("FINANCIAL HEALTH", ACCENT);++ fmt_large(buf, sizeof(buf), si.total_cash);+ data_row("CASH", buf, MARKET_GREEN);++ fmt_large(buf, sizeof(buf), si.total_debt);+ data_row("DEBT", buf, MARKET_RED);++ fmt_large(buf, sizeof(buf), si.free_cashflow);+ data_row("FREE CF", buf, INFO);++ ImGui::EndChild();+}++} // namespace fincept::researchdiff --git a/fincept-cpp/src/research/overview_panel.h b/fincept-cpp/src/research/overview_panel.hnew file mode 100644index 000000000..d4f9a0933--- /dev/null+++ b/fincept-cpp/src/research/overview_panel.h@@ -0,0 +1,21 @@+#pragma once+// Overview panel — Trading, Valuation, Chart, Analyst Targets, Profitability, Growth+// Mirrors OverviewTab.tsx: 4-column data grid + bottom company overview++#include "research_types.h"+#include "research_data.h"++namespace fincept::research {++class OverviewPanel {+public:+ void render(ResearchData& data, ChartPeriod& period);++private:+ void render_trading_valuation(const QuoteData& q, const StockInfo& si, float width);+ void render_chart(const std::vector<HistoricalDataPoint>& hist, ChartPeriod& period, float width, float height);+ void render_analyst_performance(const StockInfo& si, float width);+ void render_company_overview(const StockInfo& si);+};++} // namespace fincept::researchdiff --git a/fincept-cpp/src/research/research_data.cpp b/fincept-cpp/src/research/research_data.cppnew file mode 100644index 000000000..4671014a0--- /dev/null+++ b/fincept-cpp/src/research/research_data.cpp@@ -0,0 +1,712 @@+#include "research_data.h"+#include <nlohmann/json.hpp>+#include <thread>+#include <cmath>+#include <algorithm>+#include <numeric>+#include <array>+#include <cstdio>+#include <string>+#include <sstream>+#include <limits>++#ifdef _WIN32+#include <windows.h>+#else+#include <cstdlib>+#endif++using json = nlohmann::json;++namespace fincept::research {++// ─────────────────────────────────────────────────────────────────────────────+// Path to the yfinance Python script (relative to exe, or absolute)+// ─────────────────────────────────────────────────────────────────────────────+static const char* PYTHON_EXE = "C:/ProgramData/miniconda3/python.exe";+static const char* YFINANCE_SCRIPT =+ "C:/windowsdisk/finceptTerminal/fincept-terminal-desktop/"+ "src-tauri/resources/scripts/yfinance_data.py";++// ─────────────────────────────────────────────────────────────────────────────+// Run a command and capture stdout+// ─────────────────────────────────────────────────────────────────────────────+static std::string run_python(const std::string& args) {+ std::string cmd = std::string("\"") + PYTHON_EXE + "\" \""+ + YFINANCE_SCRIPT + "\" " + args;++#ifdef _WIN32+ // Use CreateProcess with pipe to capture output+ SECURITY_ATTRIBUTES sa{};+ sa.nLength = sizeof(sa);+ sa.bInheritHandle = TRUE;++ HANDLE hRead = nullptr, hWrite = nullptr;+ CreatePipe(&hRead, &hWrite, &sa, 0);+ 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{};+ std::string cmd_line = cmd;++ BOOL ok = CreateProcessA(+ nullptr, cmd_line.data(), nullptr, nullptr, TRUE,+ CREATE_NO_WINDOW, nullptr, nullptr, &si, &pi+ );+ CloseHandle(hWrite);++ if (!ok) {+ CloseHandle(hRead);+ return "";+ }++ // Read all output+ std::string output;+ char buffer[4096];+ DWORD bytesRead;+ while (ReadFile(hRead, buffer, sizeof(buffer) - 1, &bytesRead, nullptr) && bytesRead > 0) {+ buffer[bytesRead] = '\0';+ output += buffer;+ }+ CloseHandle(hRead);++ WaitForSingleObject(pi.hProcess, 30000); // 30s timeout+ CloseHandle(pi.hProcess);+ CloseHandle(pi.hThread);++ // Extract last line that looks like JSON (yfinance prints warnings to stdout too)+ std::string json_line;+ std::istringstream stream(output);+ std::string line;+ while (std::getline(stream, line)) {+ // Trim whitespace+ size_t start = line.find_first_not_of(" \t\r\n");+ if (start == std::string::npos) continue;+ char first = line[start];+ if (first == '{' || first == '[') {+ json_line = line;+ }+ }+ return json_line;+#else+ // Unix: popen+ FILE* pipe = popen(cmd.c_str(), "r");+ if (!pipe) return "";+ std::string output;+ char buffer[4096];+ while (fgets(buffer, sizeof(buffer), pipe)) output += buffer;+ pclose(pipe);++ std::string json_line;+ std::istringstream stream(output);+ std::string line;+ while (std::getline(stream, line)) {+ size_t start = line.find_first_not_of(" \t\r\n");+ if (start == std::string::npos) continue;+ char first = line[start];+ if (first == '{' || first == '[') json_line = line;+ }+ return json_line;+#endif+}++// Helper: safely get double from flat json (yfinance returns flat keys)+static const double NAN_VAL = std::numeric_limits<double>::quiet_NaN();++static double jd(const json& j, const char* key, double def = 0.0) {+ if (j.contains(key) && !j[key].is_null()) {+ if (j[key].is_number()) return j[key].get<double>();+ }+ return def;+}++// Same but returns NaN for missing fields (for display-only data)+static double jd_nan(const json& j, const char* key) {+ if (j.contains(key) && !j[key].is_null()) {+ if (j[key].is_number()) return j[key].get<double>();+ }+ return NAN_VAL;+}++static std::string js(const json& j, const char* key, const std::string& def = "") {+ if (j.contains(key) && j[key].is_string()) return j[key].get<std::string>();+ return def;+}++static int ji(const json& j, const char* key, int def = 0) {+ if (j.contains(key) && !j[key].is_null()) {+ if (j[key].is_number()) return j[key].get<int>();+ }+ return def;+}++// ─────────────────────────────────────────────────────────────────────────────+void ResearchData::fetch(const std::string& symbol, ChartPeriod period) {+ if (loading_.load()) return;+ loading_ = true;+ error_.clear();+ current_symbol_ = symbol;++ std::string sym = symbol;+ std::string per = chart_period_yf(period);++ std::thread([this, sym, per]() {+ // 1. Fetch quote+ {+ std::string out = run_python("quote " + sym);+ if (!out.empty()) {+ std::lock_guard<std::mutex> lock(mutex_);+ parse_quote(out);+ }+ }++ // 2. Fetch stock info+ {+ std::string out = run_python("info " + sym);+ if (!out.empty()) {+ std::lock_guard<std::mutex> lock(mutex_);+ parse_stock_info(out);+ }+ }++ // 3. Fetch historical data+ {+ std::string out = run_python("historical_period " + sym + " " + per + " 1d");+ if (!out.empty()) {+ std::lock_guard<std::mutex> lock(mutex_);+ parse_historical(out);+ }+ }++ // 4. Fetch financials+ {+ std::string out = run_python("financials " + sym);+ if (!out.empty()) {+ std::lock_guard<std::mutex> lock(mutex_);+ parse_financials(out);+ }+ }++ // 5. Compute technicals from historical data+ {+ std::lock_guard<std::mutex> lock(mutex_);+ compute_technicals();+ }++ has_data_ = true;+ loading_ = false;+ }).detach();+}++// ─────────────────────────────────────────────────────────────────────────────+void ResearchData::fetch_news(const std::string& symbol) {+ if (news_loading_.load()) return;+ news_loading_ = true;++ std::string sym = symbol;+ std::thread([this, sym]() {+ std::string out = run_python("news " + sym + " 20");+ if (!out.empty()) {+ std::lock_guard<std::mutex> lock(mutex_);+ parse_news(out);+ }+ news_loading_ = false;+ }).detach();+}++// ─────────────────────────────────────────────────────────────────────────────+// Parse quote from yfinance: flat JSON with price, change, volume, etc.+// ─────────────────────────────────────────────────────────────────────────────+void ResearchData::parse_quote(const std::string& json_str) {+ try {+ auto j = json::parse(json_str);+ if (j.contains("error")) return;++ quote_data_.symbol = js(j, "symbol");+ quote_data_.price = jd(j, "price");+ quote_data_.change = jd(j, "change");+ quote_data_.change_percent = jd(j, "change_percent");+ quote_data_.volume = jd(j, "volume");+ quote_data_.high = jd(j, "high");+ quote_data_.low = jd(j, "low");+ quote_data_.open = jd(j, "open");+ quote_data_.previous_close = jd(j, "previous_close");+ } catch (...) {}+}++// ─────────────────────────────────────────────────────────────────────────────+// Parse historical from yfinance: array of {timestamp, open, high, low, close, volume}+// ─────────────────────────────────────────────────────────────────────────────+void ResearchData::parse_historical(const std::string& json_str) {+ historical_.clear();+ try {+ auto j = json::parse(json_str);+ if (!j.is_array()) return;++ for (auto& item : j) {+ HistoricalDataPoint dp;+ dp.timestamp = jd(item, "timestamp");+ dp.open = jd(item, "open");+ dp.high = jd(item, "high");+ dp.low = jd(item, "low");+ dp.close = jd(item, "close");+ dp.volume = jd(item, "volume");+ if (dp.close > 0)+ historical_.push_back(dp);+ }+ } catch (...) {}+}++// ─────────────────────────────────────────────────────────────────────────────+// Parse stock info from yfinance: flat JSON with all info fields+// ─────────────────────────────────────────────────────────────────────────────+void ResearchData::parse_stock_info(const std::string& json_str) {+ try {+ auto j = json::parse(json_str);+ if (j.contains("error")) return;++ auto& si = stock_info_;+ si.symbol = current_symbol_;+ si.company_name = js(j, "company_name", current_symbol_);+ si.sector = js(j, "sector");+ si.industry = js(j, "industry");+ si.description = js(j, "description");+ si.website = js(j, "website");+ si.country = js(j, "country");+ si.currency = js(j, "currency");+ si.exchange = js(j, "exchange");+ si.employees = ji(j, "employees");++ // Prices & targets (use jd_nan so 0 vs missing is distinguishable)+ si.current_price = jd_nan(j, "current_price");+ si.target_high_price = jd_nan(j, "target_high_price");+ si.target_low_price = jd_nan(j, "target_low_price");+ si.target_mean_price = jd_nan(j, "target_mean_price");+ si.recommendation_mean = jd_nan(j, "recommendation_mean");+ si.recommendation_key = js(j, "recommendation_key");+ si.number_of_analysts = ji(j, "number_of_analyst_opinions");++ // Financial data+ si.total_cash = jd_nan(j, "total_cash");+ si.total_debt = jd_nan(j, "total_debt");+ si.total_revenue = jd_nan(j, "total_revenue");+ si.revenue_per_share = jd_nan(j, "revenue_per_share");+ si.return_on_assets = jd_nan(j, "return_on_assets");+ si.return_on_equity = jd_nan(j, "return_on_equity");+ si.gross_profits = jd_nan(j, "gross_profits");+ si.free_cashflow = jd_nan(j, "free_cashflow");+ si.operating_cashflow = jd_nan(j, "operating_cashflow");+ si.earnings_growth = jd_nan(j, "earnings_growth");+ si.revenue_growth = jd_nan(j, "revenue_growth");+ si.gross_margins = jd_nan(j, "gross_margins");+ si.operating_margins = jd_nan(j, "operating_margins");+ si.ebitda_margins = jd_nan(j, "ebitda_margins");+ si.profit_margins = jd_nan(j, "profit_margins");++ // Key statistics+ si.beta = jd_nan(j, "beta");+ si.book_value = jd_nan(j, "book_value");+ si.price_to_book = jd_nan(j, "price_to_book");+ si.enterprise_value = jd_nan(j, "enterprise_value");+ si.enterprise_to_revenue = jd_nan(j, "enterprise_to_revenue");+ si.enterprise_to_ebitda = jd_nan(j, "enterprise_to_ebitda");+ si.shares_outstanding = jd_nan(j, "shares_outstanding");+ si.float_shares = jd_nan(j, "float_shares");+ si.held_percent_insiders = jd_nan(j, "held_percent_insiders");+ si.held_percent_institutions = jd_nan(j, "held_percent_institutions");+ si.short_ratio = jd_nan(j, "short_ratio");+ si.short_percent_of_float = jd_nan(j, "short_percent_of_float");+ si.peg_ratio = jd_nan(j, "peg_ratio");+ si.forward_pe = jd_nan(j, "forward_pe");++ // Summary+ si.pe_ratio = jd_nan(j, "pe_ratio");+ si.dividend_yield = jd_nan(j, "dividend_yield");+ si.fifty_two_week_high = jd_nan(j, "fifty_two_week_high");+ si.fifty_two_week_low = jd_nan(j, "fifty_two_week_low");+ si.average_volume = jd_nan(j, "average_volume");+ si.market_cap = jd_nan(j, "market_cap");++ if ((std::isnan(si.current_price) || si.current_price == 0) && quote_data_.price > 0)+ si.current_price = quote_data_.price;+ } catch (...) {}+}++// ─────────────────────────────────────────────────────────────────────────────+// Parse financials from yfinance+// Format: { "income_statement": { "2025-09-30 00:00:00": { "Total Revenue": 1234, ... } }, ... }+// ─────────────────────────────────────────────────────────────────────────────+void ResearchData::parse_financials(const std::string& json_str) {+ financials_ = FinancialsData{};+ try {+ auto j = json::parse(json_str);+ if (j.contains("error")) return;++ auto parse_statement = [](const json& stmt_json, FinancialStatement& out) {+ if (!stmt_json.is_object()) return;+ for (auto& [period_key, metrics_json] : stmt_json.items()) {+ if (!metrics_json.is_object()) continue;+ // Clean up period key: "2025-09-30 00:00:00" -> "2025-09-30"+ std::string period = period_key;+ auto space_pos = period.find(' ');+ if (space_pos != std::string::npos)+ period = period.substr(0, space_pos);++ std::map<std::string, double> metrics;+ for (auto& [metric_key, val] : metrics_json.items()) {+ if (val.is_number()) {+ metrics[metric_key] = val.get<double>();+ }+ }+ if (!metrics.empty())+ out.data[period] = metrics;+ }+ };++ if (j.contains("income_statement"))+ parse_statement(j["income_statement"], financials_.income_statement);+ if (j.contains("balance_sheet"))+ parse_statement(j["balance_sheet"], financials_.balance_sheet);+ if (j.contains("cash_flow"))+ parse_statement(j["cash_flow"], financials_.cash_flow);+ } catch (...) {}+}++// ─────────────────────────────────────────────────────────────────────────────+// Parse news from yfinance+// Format: { "articles": [ { "title": ..., "url": ..., "publisher": ..., ... } ] }+// ─────────────────────────────────────────────────────────────────────────────+void ResearchData::parse_news(const std::string& json_str) {+ news_.clear();+ try {+ auto j = json::parse(json_str);+ if (!j.contains("articles")) return;+ for (auto& item : j["articles"]) {+ ResearchNewsArticle a;+ a.title = js(item, "title");+ a.url = js(item, "url");+ a.publisher = js(item, "publisher");+ a.description = js(item, "description");+ a.published_date = js(item, "published_date");+ if (!a.title.empty())+ news_.push_back(a);+ }+ } catch (...) {}+}++// ─────────────────────────────────────────────────────────────────────────────+// Compute technical indicators from historical data+// ─────────────────────────────────────────────────────────────────────────────+static Signal get_signal(const std::string& name, double value, double prev) {+ if (name.find("RSI") != std::string::npos) {+ if (value <= 30) return Signal::BUY;+ if (value >= 70) return Signal::SELL;+ return Signal::NEUTRAL;+ }+ if (name.find("Stoch") != std::string::npos) {+ if (value <= 20) return Signal::BUY;+ if (value >= 80) return Signal::SELL;+ return Signal::NEUTRAL;+ }+ if (name == "MACD") {+ if (prev < 0 && value > 0) return Signal::BUY;+ if (prev > 0 && value < 0) return Signal::SELL;+ return Signal::NEUTRAL;+ }+ if (name.find("CCI") != std::string::npos) {+ if (value <= -100) return Signal::BUY;+ if (value >= 100) return Signal::SELL;+ return Signal::NEUTRAL;+ }+ if (name.find("Williams") != std::string::npos) {+ if (value <= -80) return Signal::BUY;+ if (value >= -20) return Signal::SELL;+ return Signal::NEUTRAL;+ }+ if (name.find("ROC") != std::string::npos) {+ if (value > 5) return Signal::BUY;+ if (value < -5) return Signal::SELL;+ return Signal::NEUTRAL;+ }+ if (name.find("BB %B") != std::string::npos) {+ if (value < 0.2) return Signal::BUY;+ if (value > 0.8) return Signal::SELL;+ return Signal::NEUTRAL;+ }+ if (name == "ADX") {+ if (value > 25) return Signal::BUY;+ return Signal::NEUTRAL;+ }+ if (name.find("SMA") != std::string::npos || name.find("EMA") != std::string::npos) {+ if (value > 0) return Signal::BUY;+ if (value < 0) return Signal::SELL;+ return Signal::NEUTRAL;+ }+ return Signal::NEUTRAL;+}++void ResearchData::compute_technicals() {+ technicals_ = TechnicalsData{};+ if (historical_.size() < 30) return;++ size_t n = historical_.size();+ std::vector<double> closes(n);+ std::vector<double> highs(n);+ std::vector<double> lows(n);+ std::vector<double> volumes(n);+ for (size_t i = 0; i < n; i++) {+ closes[i] = historical_[i].close;+ highs[i] = historical_[i].high;+ lows[i] = historical_[i].low;+ volumes[i] = historical_[i].volume;+ }++ auto prev_idx = [&](size_t idx) -> size_t { return idx > 0 ? idx - 1 : 0; };++ auto add_indicator = [&](const std::string& name, double val, double prev,+ double mn, double mx, double avg, const std::string& cat) {+ IndicatorValue iv;+ iv.name = name;+ iv.value = val;+ iv.prev_value = prev;+ iv.min_val = mn;+ iv.max_val = mx;+ iv.avg_val = avg;+ iv.category = cat;+ iv.signal = get_signal(name, val, prev);+ technicals_.indicators.push_back(iv);+ };++ // ── SMA ──+ auto calc_sma = [&](size_t period) -> std::vector<double> {+ std::vector<double> sma(n, 0);+ if (period == 0 || period > n) return sma;+ for (size_t i = period - 1; i < n; i++) {+ double sum = 0;+ for (size_t j = 0; j < period; j++) sum += closes[i - j];+ sma[i] = sum / (double)period;+ }+ return sma;+ };++ double last_price = closes.back();++ if (n >= 20) {+ auto sma20 = calc_sma(20);+ if (sma20.back() > 0)+ add_indicator("SMA 20", last_price - sma20.back(), last_price - sma20[prev_idx(n-1)],+ sma20.back(), sma20.back(), sma20.back(), "trend");+ }+ if (n >= 50) {+ auto sma50 = calc_sma(50);+ if (sma50.back() > 0)+ add_indicator("SMA 50", last_price - sma50.back(), last_price - sma50[prev_idx(n-1)],+ sma50.back(), sma50.back(), sma50.back(), "trend");+ }+ if (n >= 200) {+ auto sma200 = calc_sma(200);+ if (sma200.back() > 0)+ add_indicator("SMA 200", last_price - sma200.back(), last_price - sma200[prev_idx(n-1)],+ sma200.back(), sma200.back(), sma200.back(), "trend");+ }++ // ── EMA ──+ auto calc_ema = [&](int period) -> std::vector<double> {+ std::vector<double> ema(n, 0);+ double mult = 2.0 / (period + 1);+ ema[0] = closes[0];+ for (size_t i = 1; i < n; i++)+ ema[i] = closes[i] * mult + ema[i-1] * (1 - mult);+ return ema;+ };++ auto ema12 = calc_ema(12);+ auto ema26 = calc_ema(26);++ add_indicator("EMA 12", last_price - ema12.back(), last_price - ema12[prev_idx(n-1)],+ ema12.back(), ema12.back(), ema12.back(), "trend");+ add_indicator("EMA 26", last_price - ema26.back(), last_price - ema26[prev_idx(n-1)],+ ema26.back(), ema26.back(), ema26.back(), "trend");++ // ── MACD ──+ {+ std::vector<double> macd_line(n);+ for (size_t i = 0; i < n; i++) macd_line[i] = ema12[i] - ema26[i];++ std::vector<double> signal_line(n, 0);+ double mult = 2.0 / 10.0;+ signal_line[0] = macd_line[0];+ for (size_t i = 1; i < n; i++)+ signal_line[i] = macd_line[i] * mult + signal_line[i-1] * (1 - mult);++ double histogram = macd_line.back() - signal_line.back();+ double prev_hist = macd_line[prev_idx(n-1)] - signal_line[prev_idx(n-1)];++ add_indicator("MACD", histogram, prev_hist,+ -std::abs(histogram), std::abs(histogram), 0, "momentum");+ }++ // ── RSI(14) ──+ if (n > 16) {+ int period = 14;+ std::vector<double> rsi_vals(n, 50);+ double avg_gain = 0, avg_loss = 0;+ for (int i = 1; i <= period; i++) {+ double d = closes[i] - closes[i-1];+ if (d > 0) avg_gain += d; else avg_loss += std::abs(d);+ }+ avg_gain /= period;+ avg_loss /= period;++ for (size_t i = (size_t)period; i < n; i++) {+ double d = closes[i] - closes[i-1];+ avg_gain = (avg_gain * (period - 1) + (d > 0 ? d : 0)) / period;+ avg_loss = (avg_loss * (period - 1) + (d < 0 ? std::abs(d) : 0)) / period;+ double rs = avg_loss > 0 ? avg_gain / avg_loss : 100;+ rsi_vals[i] = 100.0 - (100.0 / (1.0 + rs));+ }++ size_t start = (size_t)period;+ double mn = rsi_vals[start], mx = rsi_vals[start], sum = 0;+ for (size_t i = start; i < n; i++) {+ mn = std::min(mn, rsi_vals[i]);+ mx = std::max(mx, rsi_vals[i]);+ sum += rsi_vals[i];+ }+ double avg = sum / (double)(n - start);+ add_indicator("RSI (14)", rsi_vals.back(), rsi_vals[prev_idx(n-1)], mn, mx, avg, "momentum");+ }++ // ── Stochastic %K(14,3) ──+ if (n > 17) {+ size_t k_period = 14;+ std::vector<double> stoch_k(n, 50);+ for (size_t i = k_period - 1; i < n; i++) {+ size_t start = i - k_period + 1;+ double hi = *std::max_element(highs.begin() + (ptrdiff_t)start, highs.begin() + (ptrdiff_t)(i + 1));+ double lo = *std::min_element(lows.begin() + (ptrdiff_t)start, lows.begin() + (ptrdiff_t)(i + 1));+ stoch_k[i] = (hi != lo) ? ((closes[i] - lo) / (hi - lo)) * 100.0 : 50.0;+ }+ std::vector<double> stoch_d(n, 50);+ for (size_t i = k_period + 2; i < n; i++) {+ stoch_d[i] = (stoch_k[i] + stoch_k[i-1] + stoch_k[i-2]) / 3.0;+ }++ add_indicator("Stoch %K", stoch_k.back(), stoch_k[prev_idx(n-1)], 0, 100, 50, "momentum");+ add_indicator("Stoch %D", stoch_d.back(), stoch_d[prev_idx(n-1)], 0, 100, 50, "momentum");+ }++ // ── CCI(20) ──+ if (n > 21) {+ size_t period = 20;+ std::vector<double> cci_vals(n, 0);+ for (size_t i = period - 1; i < n; i++) {+ double tp = (highs[i] + lows[i] + closes[i]) / 3.0;+ double tp_sma = 0;+ for (size_t j = 0; j < period; j++)+ tp_sma += (highs[i-j] + lows[i-j] + closes[i-j]) / 3.0;+ tp_sma /= (double)period;++ double mean_dev = 0;+ for (size_t j = 0; j < period; j++) {+ double tp_j = (highs[i-j] + lows[i-j] + closes[i-j]) / 3.0;+ mean_dev += std::abs(tp_j - tp_sma);+ }+ mean_dev /= (double)period;+ cci_vals[i] = mean_dev > 0 ? (tp - tp_sma) / (0.015 * mean_dev) : 0;+ }+ add_indicator("CCI (20)", cci_vals.back(), cci_vals[prev_idx(n-1)], -200, 200, 0, "momentum");+ }++ // ── Williams %R(14) ──+ if (n > 15) {+ size_t period = 14;+ std::vector<double> wr(n, -50);+ for (size_t i = period - 1; i < n; i++) {+ size_t start = i - period + 1;+ double hi = *std::max_element(highs.begin() + (ptrdiff_t)start, highs.begin() + (ptrdiff_t)(i + 1));+ double lo = *std::min_element(lows.begin() + (ptrdiff_t)start, lows.begin() + (ptrdiff_t)(i + 1));+ wr[i] = (hi != lo) ? ((hi - closes[i]) / (hi - lo)) * -100.0 : -50.0;+ }+ add_indicator("Williams %R", wr.back(), wr[prev_idx(n-1)], -100, 0, -50, "momentum");+ }++ // ── Bollinger Bands %B ──+ if (n > 21) {+ size_t period = 20;+ double sma = 0;+ for (size_t i = n - period; i < n; i++) sma += closes[i];+ sma /= (double)period;++ double variance = 0;+ for (size_t i = n - period; i < n; i++)+ variance += (closes[i] - sma) * (closes[i] - sma);+ double stddev = std::sqrt(variance / (double)period);++ double upper = sma + 2 * stddev;+ double lower = sma - 2 * stddev;+ double pct_b = (upper != lower) ? (closes.back() - lower) / (upper - lower) : 0.5;++ add_indicator("BB %B", pct_b, 0.5, 0, 1, 0.5, "volatility");+ add_indicator("BB Width", sma > 0 ? (upper - lower) / sma : 0, 0, 0, 0.5, 0.1, "volatility");+ }++ // ── ROC(12) ──+ if (n > 14) {+ size_t period = 12;+ size_t ref = n - 1 - period;+ size_t prev_ref = n - 2 - period;+ if (ref < n && prev_ref < n && closes[ref] != 0 && closes[prev_ref] != 0) {+ double roc = ((closes[n-1] - closes[ref]) / closes[ref]) * 100.0;+ double prev_roc = ((closes[n-2] - closes[prev_ref]) / closes[prev_ref]) * 100.0;+ add_indicator("ROC (12)", roc, prev_roc, -20, 20, 0, "momentum");+ }+ }++ // ── ADX(14) — simplified ──+ if (n > 29) {+ size_t period = 14;+ double sum = 0;+ for (size_t i = n - period; i < n; i++) {+ double up = highs[i] - highs[i-1];+ double dn = lows[i-1] - lows[i];+ sum += (up > dn && up > 0) ? up : (dn > up && dn > 0) ? dn : 0;+ }+ double avg_dm = sum / (double)period;+ double avg_tr = 0;+ for (size_t i = n - period; i < n; i++)+ avg_tr += std::max({highs[i] - lows[i],+ std::abs(highs[i] - closes[i-1]),+ std::abs(lows[i] - closes[i-1])});+ avg_tr /= (double)period;+ double adx = avg_tr > 0 ? (avg_dm / avg_tr) * 100.0 : 0;+ add_indicator("ADX", std::min(adx, 100.0), 0, 0, 100, 25, "trend");+ }++ // Count signals+ for (auto& ind : technicals_.indicators) {+ if (ind.signal == Signal::BUY) technicals_.buy_count++;+ else if (ind.signal == Signal::SELL) technicals_.sell_count++;+ else technicals_.neutral_count++;+ }++ int total = technicals_.buy_count + technicals_.sell_count + technicals_.neutral_count;+ if (total > 0) {+ double buy_pct = (double)technicals_.buy_count / total * 100.0;+ double sell_pct = (double)technicals_.sell_count / total * 100.0;+ if (buy_pct >= 70) technicals_.recommendation = "STRONG BUY";+ else if (buy_pct >= 50) technicals_.recommendation = "BUY";+ else if (sell_pct >= 70) technicals_.recommendation = "STRONG SELL";+ else if (sell_pct >= 50) technicals_.recommendation = "SELL";+ else technicals_.recommendation = "NEUTRAL";+ } else {+ technicals_.recommendation = "NEUTRAL";+ }+}++} // namespace fincept::researchdiff --git a/fincept-cpp/src/research/research_data.h b/fincept-cpp/src/research/research_data.hnew file mode 100644index 000000000..02dd328c0--- /dev/null+++ b/fincept-cpp/src/research/research_data.h@@ -0,0 +1,63 @@+#pragma once+// Equity Research — Data fetching layer+// Fetches stock info, quote, historical, financials, technicals, news via public APIs+// All fetching is async (background thread) with mutex-protected results++#include "research_types.h"+#include <mutex>+#include <atomic>+#include <string>+#include <vector>++namespace fincept::research {++class ResearchData {+public:+ // Fetch all data for a symbol (runs in background thread)+ void fetch(const std::string& symbol, ChartPeriod period);++ // Fetch news for current symbol+ void fetch_news(const std::string& symbol);++ // Access data (call under lock or copy)+ std::mutex& mutex() { return mutex_; }++ bool is_loading() const { return loading_.load(); }+ bool is_news_loading() const { return news_loading_.load(); }+ bool has_data() const { return has_data_; }+ const std::string& error() const { return error_; }++ const StockInfo& stock_info() const { return stock_info_; }+ const QuoteData& quote_data() const { return quote_data_; }+ const std::vector<HistoricalDataPoint>& historical() const { return historical_; }+ const FinancialsData& financials() const { return financials_; }+ const TechnicalsData& technicals() const { return technicals_; }+ const std::vector<ResearchNewsArticle>& news() const { return news_; }++ const std::string& current_symbol() const { return current_symbol_; }++private:+ std::mutex mutex_;+ std::atomic<bool> loading_{false};+ std::atomic<bool> news_loading_{false};+ bool has_data_ = false;+ std::string error_;+ std::string current_symbol_;++ StockInfo stock_info_;+ QuoteData quote_data_;+ std::vector<HistoricalDataPoint> historical_;+ FinancialsData financials_;+ TechnicalsData technicals_;+ std::vector<ResearchNewsArticle> news_;++ // Parse helpers+ void parse_stock_info(const std::string& json_str);+ void parse_quote(const std::string& json_str);+ void parse_historical(const std::string& json_str);+ void parse_financials(const std::string& json_str);+ void compute_technicals();+ void parse_news(const std::string& json_str);+};++} // namespace fincept::researchdiff --git a/fincept-cpp/src/research/research_screen.cpp b/fincept-cpp/src/research/research_screen.cppnew file mode 100644index 000000000..d7e691aac--- /dev/null+++ b/fincept-cpp/src/research/research_screen.cpp@@ -0,0 +1,297 @@+#include "research_screen.h"+#include "../theme/bloomberg_theme.h"+#include <imgui.h>+#include <cstdio>+#include <cstring>+#include <ctime>+#include <cmath>+#include <cctype>++namespace fincept::research {++using namespace theme::colors;++// ─── Formatting helpers (local) ─────────────────────────────────────────────+static void fmt_number(char* buf, size_t sz, double v, int decimals = 2) {+ if (v == 0) { std::snprintf(buf, sz, "N/A"); return; }+ std::snprintf(buf, sz, "%.*f", decimals, v);+}++// ─────────────────────────────────────────────────────────────────────────────+void ResearchScreen::init() {+ std::strncpy(search_buf_, "AAPL", sizeof(search_buf_));+ current_symbol_ = "AAPL";+ data_.fetch(current_symbol_, chart_period_);+ initialized_ = true;+}++void ResearchScreen::do_search() {+ // Normalize to uppercase+ for (char* p = search_buf_; *p; p++) *p = (char)std::toupper(*p);+ std::string sym(search_buf_);++ // Trim whitespace+ while (!sym.empty() && sym.back() == ' ') sym.pop_back();+ while (!sym.empty() && sym.front() == ' ') sym.erase(sym.begin());++ if (sym.empty()) return;+ if (sym == current_symbol_ && data_.has_data()) return;++ current_symbol_ = sym;+ data_.fetch(current_symbol_, chart_period_);++ if (active_tab_ == 4) { // News tab+ data_.fetch_news(current_symbol_);+ }+}++// ─────────────────────────────────────────────────────────────────────────────+void ResearchScreen::render() {+ if (!initialized_) init();++ ImGuiViewport* vp = ImGui::GetMainViewport();+ float tab_h = ImGui::GetFrameHeight() + 4;+ float footer_h = ImGui::GetFrameHeight();++ ImGui::SetNextWindowPos(ImVec2(vp->WorkPos.x, vp->WorkPos.y + tab_h));+ ImGui::SetNextWindowSize(ImVec2(vp->WorkSize.x, vp->WorkSize.y - tab_h - footer_h));++ ImGui::PushStyleColor(ImGuiCol_WindowBg, BG_DARK);+ ImGui::PushStyleVar(ImGuiStyleVar_WindowPadding, ImVec2(0, 0));++ ImGui::Begin("##research_screen", nullptr,+ ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_NoResize | ImGuiWindowFlags_NoMove |+ ImGuiWindowFlags_NoScrollbar | ImGuiWindowFlags_NoDocking |+ ImGuiWindowFlags_NoFocusOnAppearing | ImGuiWindowFlags_NoBringToFrontOnFocus);++ render_header();+ render_ticker_bar();+ render_sub_tabs();+ render_content();++ ImGui::End();+ ImGui::PopStyleVar();+ ImGui::PopStyleColor();+}++// ─────────────────────────────────────────────────────────────────────────────+// Header: [RESEARCH icon] | [Symbol Search] [GO] [REFRESH] | [Sub-tabs] | [Status]+// ─────────────────────────────────────────────────────────────────────────────+void ResearchScreen::render_header() {+ ImGui::PushStyleColor(ImGuiCol_ChildBg, BG_PANEL);+ ImGui::BeginChild("##res_header", ImVec2(0, 32), true);++ // Title+ ImGui::TextColored(ACCENT, "RESEARCH");+ ImGui::SameLine(0, 12);++ // Separator+ ImGui::TextColored(BORDER_BRIGHT, "|");+ ImGui::SameLine(0, 12);++ // Symbol search+ ImGui::PushItemWidth(120);+ ImGui::PushStyleColor(ImGuiCol_FrameBg, BG_INPUT);+ ImGui::PushStyleColor(ImGuiCol_Text, TEXT_PRIMARY);+ if (ImGui::InputText("##sym_search", search_buf_, sizeof(search_buf_),+ ImGuiInputTextFlags_EnterReturnsTrue | ImGuiInputTextFlags_CharsUppercase)) {+ do_search();+ }+ ImGui::PopStyleColor(2);+ ImGui::PopItemWidth();++ ImGui::SameLine(0, 4);+ if (theme::AccentButton("GO")) {+ do_search();+ }++ ImGui::SameLine(0, 4);+ if (theme::SecondaryButton("REFRESH")) {+ data_.fetch(current_symbol_, chart_period_);+ }++ ImGui::SameLine(0, 12);+ ImGui::TextColored(BORDER_BRIGHT, "|");+ ImGui::SameLine(0, 12);++ // Status+ ImGui::SameLine(ImGui::GetContentRegionAvail().x - 200);++ // Current time+ time_t now = time(nullptr);+ struct tm* t = localtime(&now);+ char tb[16];+ std::strftime(tb, sizeof(tb), "%H:%M:%S", t);+ ImGui::TextColored(TEXT_DIM, "%s", tb);++ ImGui::SameLine(0, 12);+ ImGui::TextColored(BORDER_BRIGHT, "|");+ ImGui::SameLine(0, 12);++ ImGui::TextColored(INFO, "%s", current_symbol_.c_str());++ ImGui::SameLine(0, 8);+ if (data_.is_loading()) {+ ImGui::TextColored(WARNING, "[LOADING]");+ } else {+ ImGui::TextColored(SUCCESS, "[LIVE]");+ }++ ImGui::EndChild();+ ImGui::PopStyleColor();+}++// ─────────────────────────────────────────────────────────────────────────────+// Ticker bar: SYMBOL | Company Name | Sector | Price | Change+// ─────────────────────────────────────────────────────────────────────────────+void ResearchScreen::render_ticker_bar() {+ std::lock_guard<std::mutex> lock(data_.mutex());+ auto& si = data_.stock_info();+ auto& q = data_.quote_data();++ double price = q.price > 0 ? q.price : si.current_price;+ double change = q.change;+ double change_pct = q.change_percent;++ ImGui::PushStyleColor(ImGuiCol_ChildBg, BG_PANEL);+ ImGui::BeginChild("##ticker_bar", ImVec2(0, 44), true);++ // Left: Symbol + Company+ ImGui::SetWindowFontScale(1.3f);+ ImGui::TextColored(ACCENT, "%s", current_symbol_.c_str());+ ImGui::SetWindowFontScale(1.0f);++ ImGui::SameLine(0, 12);+ ImGui::TextColored(TEXT_PRIMARY, "%s",+ si.company_name.empty() ? "Loading..." : si.company_name.c_str());++ if (!si.sector.empty()) {+ ImGui::SameLine(0, 12);+ ImGui::PushStyleColor(ImGuiCol_Text, INFO);+ ImGui::TextUnformatted(si.sector.c_str());+ ImGui::PopStyleColor();+ }++ if (!si.recommendation_key.empty()) {+ ImGui::SameLine(0, 12);+ ImVec4 rec_col = WARNING;+ if (si.recommendation_key == "buy" || si.recommendation_key == "strong_buy")+ rec_col = MARKET_GREEN;+ else if (si.recommendation_key == "sell" || si.recommendation_key == "strong_sell")+ rec_col = MARKET_RED;+ std::string rec = si.recommendation_key;+ for (auto& c : rec) c = (char)std::toupper(c);+ for (auto& c : rec) if (c == '_') c = ' ';+ ImGui::PushStyleColor(ImGuiCol_Text, rec_col);+ ImGui::TextUnformatted(rec.c_str());+ ImGui::PopStyleColor();+ }++ // Second line: exchange, industry, country+ if (!si.industry.empty()) {+ ImGui::TextColored(TEXT_DIM, "%s%s%s%s%s",+ si.exchange.empty() ? "" : si.exchange.c_str(),+ si.exchange.empty() ? "" : " | ",+ si.industry.c_str(),+ si.country.empty() ? "" : " | ",+ si.country.c_str());+ }++ // Right: Price+ if (price > 0) {+ float right_x = ImGui::GetContentRegionAvail().x;+ ImGui::SameLine(right_x - 160);++ char price_buf[32];+ std::snprintf(price_buf, sizeof(price_buf), "$%.2f", price);+ ImGui::SetWindowFontScale(1.4f);+ ImGui::TextColored(TEXT_PRIMARY, "%s", price_buf);+ ImGui::SetWindowFontScale(1.0f);++ ImGui::SameLine(0, 8);+ ImVec4 chg_col = change >= 0 ? MARKET_GREEN : MARKET_RED;+ char chg_buf[32];+ std::snprintf(chg_buf, sizeof(chg_buf), "%s$%.2f (%.2f%%)",+ change >= 0 ? "+" : "", change, change_pct);+ ImGui::TextColored(chg_col, "%s", chg_buf);+ }++ ImGui::EndChild();+ ImGui::PopStyleColor();+}++// ─────────────────────────────────────────────────────────────────────────────+// Sub-tabs: OVERVIEW | FINANCIALS | ANALYSIS | TECHNICALS | NEWS+// ─────────────────────────────────────────────────────────────────────────────+void ResearchScreen::render_sub_tabs() {+ ImGui::PushStyleColor(ImGuiCol_ChildBg, BG_DARKEST);+ ImGui::BeginChild("##res_tabs", ImVec2(0, 28), true);++ static const char* tab_labels[] = {+ "OVERVIEW", "FINANCIALS", "ANALYSIS", "TECHNICALS", "NEWS"+ };+ int num_tabs = 5;++ ImGui::PushStyleVar(ImGuiStyleVar_FramePadding, ImVec2(10, 3));+ ImGui::PushStyleVar(ImGuiStyleVar_ItemSpacing, ImVec2(2, 0));++ for (int i = 0; i < num_tabs; i++) {+ bool active = (i == active_tab_);++ if (active) {+ ImGui::PushStyleColor(ImGuiCol_Button, ACCENT);+ ImGui::PushStyleColor(ImGuiCol_ButtonHovered, ACCENT_HOVER);+ ImGui::PushStyleColor(ImGuiCol_Text, BG_DARKEST);+ } else {+ ImGui::PushStyleColor(ImGuiCol_Button, ImVec4(0, 0, 0, 0));+ ImGui::PushStyleColor(ImGuiCol_ButtonHovered, BG_HOVER);+ ImGui::PushStyleColor(ImGuiCol_Text, TEXT_DIM);+ }++ if (ImGui::Button(tab_labels[i])) {+ active_tab_ = i;+ // Fetch news when switching to news tab+ if (i == 4 && data_.news().empty()) {+ data_.fetch_news(current_symbol_);+ }+ }++ ImGui::PopStyleColor(3);+ if (i < num_tabs - 1) ImGui::SameLine(0, 2);+ }++ ImGui::PopStyleVar(2);+ ImGui::EndChild();+ ImGui::PopStyleColor();+}++// ─────────────────────────────────────────────────────────────────────────────+// Main content area — routes to active sub-panel+// ─────────────────────────────────────────────────────────────────────────────+void ResearchScreen::render_content() {+ ImGui::PushStyleVar(ImGuiStyleVar_WindowPadding, ImVec2(6, 6));+ ImGui::BeginChild("##res_content", ImVec2(0, 0), false,+ ImGuiWindowFlags_NoScrollbar);++ if (data_.is_loading() && !data_.has_data()) {+ // Full loading state+ ImVec2 avail = ImGui::GetContentRegionAvail();+ ImGui::SetCursorPos(ImVec2(avail.x * 0.35f, avail.y * 0.4f));+ theme::LoadingSpinner("Fetching stock data...");+ ImGui::SetCursorPosX(avail.x * 0.35f);+ ImGui::TextColored(TEXT_DIM, "Loading data for %s", current_symbol_.c_str());+ } else {+ switch (active_tab_) {+ case 0: overview_.render(data_, chart_period_); break;+ case 1: financials_.render(data_); break;+ case 2: analysis_.render(data_); break;+ case 3: technicals_.render(data_); break;+ case 4: news_.render(data_, current_symbol_); break;+ }+ }++ ImGui::EndChild();+ ImGui::PopStyleVar();+}++} // namespace fincept::researchdiff --git a/fincept-cpp/src/research/research_screen.h b/fincept-cpp/src/research/research_screen.hnew file mode 100644index 000000000..fa295771d--- /dev/null+++ b/fincept-cpp/src/research/research_screen.h@@ -0,0 +1,53 @@+#pragma once+// Equity Research Screen — Bloomberg-style multi-tab research terminal+// Mirrors EquityResearchTab.tsx: Symbol search, ticker bar, sub-tabs+// Sub-tabs: Overview, Financials, Analysis, Technicals, News++#include "research_types.h"+#include "research_data.h"+#include "overview_panel.h"+#include "financials_panel.h"+#include "analysis_panel.h"+#include "technicals_panel.h"+#include "news_panel.h"++namespace fincept::research {++class ResearchScreen {+public:+ void render();++private:+ bool initialized_ = false;++ // Data layer+ ResearchData data_;++ // UI state+ char search_buf_[32] = "AAPL";+ std::string current_symbol_ = "AAPL";+ ChartPeriod chart_period_ = ChartPeriod::M6;+ int active_tab_ = 0; // 0=Overview, 1=Financials, 2=Analysis, 3=Technicals, 4=News++ // Sub-panels+ OverviewPanel overview_;+ FinancialsPanel financials_;+ AnalysisPanel analysis_;+ TechnicalsPanel technicals_;+ ResearchNewsPanel news_;++ // Init+ void init();++ // Section renderers+ void render_header();+ void render_ticker_bar();+ void render_sub_tabs();+ void render_content();+ void render_footer();++ // Actions+ void do_search();+};++} // namespace fincept::researchdiff --git a/fincept-cpp/src/research/research_types.h b/fincept-cpp/src/research/research_types.hnew file mode 100644index 000000000..359208477--- /dev/null+++ b/fincept-cpp/src/research/research_types.h@@ -0,0 +1,164 @@+#pragma once+// Equity Research — Data types mirroring the React terminal's types/index.ts+// StockInfo, QuoteData, HistoricalData, FinancialsData, TechnicalsData++#include <string>+#include <vector>+#include <map>+#include <cmath>+#include <limits>++namespace fincept::research {++// NaN sentinel for "no data" — distinct from a valid 0 value+constexpr double NODATA = std::numeric_limits<double>::quiet_NaN();++struct StockInfo {+ std::string symbol;+ std::string company_name;+ std::string sector;+ std::string industry;+ std::string description;+ std::string website;+ std::string country;+ std::string currency;+ std::string exchange;+ std::string recommendation_key; // "buy", "hold", "sell", "strong_buy", "strong_sell"++ double market_cap = NODATA;+ double pe_ratio = NODATA;+ double forward_pe = NODATA;+ double dividend_yield = NODATA;+ double beta = NODATA;+ double fifty_two_week_high= NODATA;+ double fifty_two_week_low = NODATA;+ double average_volume = NODATA;+ double current_price = NODATA;+ double target_high_price = NODATA;+ double target_low_price = NODATA;+ double target_mean_price = NODATA;+ double recommendation_mean= NODATA;+ int number_of_analysts = 0;+ int employees = 0;++ // Financial health+ double total_cash = NODATA;+ double total_debt = NODATA;+ double total_revenue = NODATA;+ double revenue_per_share = NODATA;+ double return_on_assets = NODATA;+ double return_on_equity = NODATA;+ double gross_profits = NODATA;+ double free_cashflow = NODATA;+ double operating_cashflow = NODATA;+ double earnings_growth = NODATA;+ double revenue_growth = NODATA;+ double gross_margins = NODATA;+ double operating_margins = NODATA;+ double ebitda_margins = NODATA;+ double profit_margins = NODATA;+ double book_value = NODATA;+ double price_to_book = NODATA;+ double enterprise_value = NODATA;+ double enterprise_to_revenue = NODATA;+ double enterprise_to_ebitda = NODATA;+ double shares_outstanding = NODATA;+ double float_shares = NODATA;+ double held_percent_insiders = NODATA;+ double held_percent_institutions = NODATA;+ double short_ratio = NODATA;+ double short_percent_of_float = NODATA;+ double peg_ratio = NODATA;+};++struct QuoteData {+ std::string symbol;+ double price = 0;+ double change = 0;+ double change_percent = 0;+ double volume = 0;+ double high = 0;+ double low = 0;+ double open = 0;+ double previous_close = 0;+};++struct HistoricalDataPoint {+ double timestamp = 0; // unix seconds+ double open = 0;+ double high = 0;+ double low = 0;+ double close = 0;+ double volume = 0;+};++// Period-based historical data+struct FinancialStatement {+ // period label -> (metric name -> value)+ // e.g. "2024-12-31" -> { "TotalRevenue": 123456, ... }+ std::map<std::string, std::map<std::string, double>> data;+};++struct FinancialsData {+ FinancialStatement income_statement;+ FinancialStatement balance_sheet;+ FinancialStatement cash_flow;+};++// Technical indicator signal+enum class Signal { BUY, SELL, NEUTRAL };++struct IndicatorValue {+ std::string name;+ double value = 0;+ double prev_value = 0;+ double min_val = 0;+ double max_val = 0;+ double avg_val = 0;+ Signal signal = Signal::NEUTRAL;+ std::string category; // "trend", "momentum", "volatility", "volume"+};++struct TechnicalsData {+ std::vector<IndicatorValue> indicators;+ int buy_count = 0;+ int sell_count = 0;+ int neutral_count= 0;+ std::string recommendation; // "STRONG BUY", "BUY", "NEUTRAL", "SELL", "STRONG SELL"+};++// News article (symbol-specific)+struct ResearchNewsArticle {+ std::string title;+ std::string description;+ std::string url;+ std::string publisher;+ std::string published_date;+};++// Chart period+enum class ChartPeriod { M1, M3, M6, Y1, Y5 };++inline const char* chart_period_label(ChartPeriod p) {+ switch (p) {+ case ChartPeriod::M1: return "1M";+ case ChartPeriod::M3: return "3M";+ case ChartPeriod::M6: return "6M";+ case ChartPeriod::Y1: return "1Y";+ case ChartPeriod::Y5: return "5Y";+ }+ return "6M";+}++inline const char* chart_period_yf(ChartPeriod p) {+ switch (p) {+ case ChartPeriod::M1: return "1mo";+ case ChartPeriod::M3: return "3mo";+ case ChartPeriod::M6: return "6mo";+ case ChartPeriod::Y1: return "1y";+ case ChartPeriod::Y5: return "5y";+ }+ return "6mo";+}++} // namespace fincept::researchdiff --git a/fincept-cpp/src/research/technicals_panel.cpp b/fincept-cpp/src/research/technicals_panel.cppnew file mode 100644index 000000000..3485c5df6--- /dev/null+++ b/fincept-cpp/src/research/technicals_panel.cpp@@ -0,0 +1,286 @@+#include "technicals_panel.h"+#include "../theme/bloomberg_theme.h"+#include <imgui.h>+#include <cstdio>+#include <cmath>++namespace fincept::research {++using namespace theme::colors;++static ImVec4 signal_color(Signal s) {+ switch (s) {+ case Signal::BUY: return MARKET_GREEN;+ case Signal::SELL: return MARKET_RED;+ case Signal::NEUTRAL: return TEXT_DIM;+ }+ return TEXT_DIM;+}++static const char* signal_text(Signal s) {+ switch (s) {+ case Signal::BUY: return "BUY";+ case Signal::SELL: return "SELL";+ case Signal::NEUTRAL: return "HOLD";+ }+ return "HOLD";+}++static const char* signal_arrow(Signal s) {+ switch (s) {+ case Signal::BUY: return "^";+ case Signal::SELL: return "v";+ case Signal::NEUTRAL: return "-";+ }+ return "-";+}++void TechnicalsPanel::render(ResearchData& data) {+ std::lock_guard<std::mutex> lock(data.mutex());+ auto& tech = data.technicals();++ if (tech.indicators.empty()) {+ ImVec2 avail = ImGui::GetContentRegionAvail();+ ImGui::SetCursorPos(ImVec2(avail.x * 0.35f, avail.y * 0.4f));+ if (data.is_loading()) {+ theme::LoadingSpinner("Computing technical indicators...");+ } else {+ ImGui::TextColored(MARKET_RED, "NO TECHNICAL DATA AVAILABLE");+ ImGui::SetCursorPosX(avail.x * 0.35f);+ ImGui::TextColored(TEXT_DIM, "Waiting for historical data");+ }+ return;+ }++ ImVec2 avail = ImGui::GetContentRegionAvail();++ // ─── Top: Summary Dashboard ───+ float summary_h = 120;+ float left_w = 220;+ float right_w = avail.x - left_w - 8;++ // Overall Signal Panel+ ImGui::BeginChild("##tech_signal", ImVec2(left_w, summary_h), true);+ {+ // Header+ ImGui::PushStyleColor(ImGuiCol_Text, ACCENT);+ ImGui::TextUnformatted("TECHNICAL RATING");+ ImGui::PopStyleColor();+ ImGui::Separator();+ ImGui::Spacing();++ // Recommendation+ ImVec4 rec_col = WARNING;+ if (tech.recommendation.find("BUY") != std::string::npos) rec_col = MARKET_GREEN;+ else if (tech.recommendation.find("SELL") != std::string::npos) rec_col = MARKET_RED;++ ImGui::SetWindowFontScale(1.3f);+ float text_w = ImGui::CalcTextSize(tech.recommendation.c_str()).x;+ ImGui::SetCursorPosX((left_w - text_w) * 0.5f);+ ImGui::TextColored(rec_col, "%s", tech.recommendation.c_str());+ ImGui::SetWindowFontScale(1.0f);++ ImGui::Spacing();++ // Signal gauge bar+ int total = tech.buy_count + tech.sell_count + tech.neutral_count;+ if (total > 0) {+ float bar_w = ImGui::GetContentRegionAvail().x;+ ImVec2 pos = ImGui::GetCursorScreenPos();+ ImDrawList* dl = ImGui::GetWindowDrawList();++ float sell_w = bar_w * (float)tech.sell_count / total;+ float neut_w = bar_w * (float)tech.neutral_count / total;+ float buy_w = bar_w * (float)tech.buy_count / total;++ dl->AddRectFilled(pos, ImVec2(pos.x + sell_w, pos.y + 6), ImGui::GetColorU32(MARKET_RED));+ dl->AddRectFilled(ImVec2(pos.x + sell_w, pos.y),+ ImVec2(pos.x + sell_w + neut_w, pos.y + 6), IM_COL32(100, 100, 100, 255));+ dl->AddRectFilled(ImVec2(pos.x + sell_w + neut_w, pos.y),+ ImVec2(pos.x + bar_w, pos.y + 6), ImGui::GetColorU32(MARKET_GREEN));+ ImGui::Dummy(ImVec2(bar_w, 10));+ }++ // Counts+ float third_w = (ImGui::GetContentRegionAvail().x - 8) / 3.0f;+ ImGui::BeginChild("##buy_c", ImVec2(third_w, 0), false);+ ImGui::TextColored(MARKET_GREEN, "%d", tech.buy_count);+ ImGui::TextColored(TEXT_DIM, "BUY");+ ImGui::EndChild();+ ImGui::SameLine(0, 4);+ ImGui::BeginChild("##hold_c", ImVec2(third_w, 0), false);+ ImGui::TextColored(TEXT_PRIMARY, "%d", tech.neutral_count);+ ImGui::TextColored(TEXT_DIM, "HOLD");+ ImGui::EndChild();+ ImGui::SameLine(0, 4);+ ImGui::BeginChild("##sell_c", ImVec2(third_w, 0), false);+ ImGui::TextColored(MARKET_RED, "%d", tech.sell_count);+ ImGui::TextColored(TEXT_DIM, "SELL");+ ImGui::EndChild();+ }+ ImGui::EndChild();++ ImGui::SameLine(0, 8);++ // Key Indicators Quick View+ ImGui::BeginChild("##tech_key", ImVec2(right_w, summary_h), true);+ {+ ImGui::PushStyleColor(ImGuiCol_Text, INFO);+ ImGui::TextUnformatted("KEY INDICATORS");+ ImGui::PopStyleColor();+ ImGui::Separator();+ ImGui::Spacing();++ // Grid of key indicators+ float card_w = 120;+ int cols = std::max(1, (int)(right_w / (card_w + 8)));+ int col = 0;++ for (auto& ind : tech.indicators) {+ if (col > 0) ImGui::SameLine(0, 4);++ ImGui::BeginChild(("##ki_" + ind.name).c_str(), ImVec2(card_w, 50), true);+ ImVec4 sc = signal_color(ind.signal);++ // Left border color+ ImDrawList* dl = ImGui::GetWindowDrawList();+ ImVec2 p = ImGui::GetWindowPos();+ dl->AddRectFilled(p, ImVec2(p.x + 2, p.y + 50), ImGui::GetColorU32(sc));++ ImGui::TextColored(TEXT_DIM, "%s", ind.name.c_str());+ char buf[32];+ std::snprintf(buf, sizeof(buf), "%.2f", ind.value);+ ImGui::TextColored(TEXT_PRIMARY, "%s", buf);+ ImGui::SameLine();+ ImGui::TextColored(sc, "%s %s", signal_arrow(ind.signal), signal_text(ind.signal));+ ImGui::EndChild();++ col++;+ if (col >= cols) col = 0;+ }+ }+ ImGui::EndChild();++ ImGui::Spacing();++ // ─── Category Sections ───+ auto render_category = [&](const char* title, const char* cat, ImVec4 color, bool& expanded) {+ // Count signals in this category+ int buy = 0, sell = 0, neutral = 0;+ for (auto& ind : tech.indicators) {+ if (ind.category == cat) {+ if (ind.signal == Signal::BUY) buy++;+ else if (ind.signal == Signal::SELL) sell++;+ else neutral++;+ }+ }+ int cat_total = buy + sell + neutral;+ if (cat_total == 0) return;++ // Header+ ImGui::PushStyleColor(ImGuiCol_Header, BG_WIDGET);+ ImGui::PushStyleColor(ImGuiCol_HeaderHovered, BG_HOVER);++ // Build header label with counts+ char hdr[128];+ std::snprintf(hdr, sizeof(hdr), "%s %s [%d INDICATORS]", expanded ? "v" : ">", title, cat_total);++ if (ImGui::Selectable(hdr, false, 0, ImVec2(0, 24))) {+ expanded = !expanded;+ }++ // Signal counts on the same line (draw after selectable)+ {+ ImGui::SameLine(ImGui::GetContentRegionAvail().x - 200);+ if (buy > 0) {+ ImGui::TextColored(MARKET_GREEN, "%d BUY", buy);+ ImGui::SameLine(0, 8);+ }+ if (sell > 0) {+ ImGui::TextColored(MARKET_RED, "%d SELL", sell);+ ImGui::SameLine(0, 8);+ }+ if (neutral > 0) {+ ImGui::TextColored(TEXT_DIM, "%d HOLD", neutral);+ }+ }++ ImGui::PopStyleColor(2);++ // Left color border+ ImDrawList* dl = ImGui::GetWindowDrawList();+ ImVec2 last_pos = ImGui::GetItemRectMin();+ dl->AddRectFilled(last_pos, ImVec2(last_pos.x + 2, last_pos.y + 24), ImGui::GetColorU32(color));++ if (expanded) {+ ImGui::Indent(8);++ // Table for indicators in this category+ ImGuiTableFlags flags = ImGuiTableFlags_Borders | ImGuiTableFlags_RowBg |+ ImGuiTableFlags_SizingStretchProp;+ if (ImGui::BeginTable(cat, 6, flags)) {+ ImGui::TableSetupColumn("INDICATOR", ImGuiTableColumnFlags_WidthStretch, 2.0f);+ ImGui::TableSetupColumn("VALUE", ImGuiTableColumnFlags_WidthStretch, 1.0f);+ ImGui::TableSetupColumn("PREV", ImGuiTableColumnFlags_WidthStretch, 1.0f);+ ImGui::TableSetupColumn("MIN", ImGuiTableColumnFlags_WidthStretch, 1.0f);+ ImGui::TableSetupColumn("MAX", ImGuiTableColumnFlags_WidthStretch, 1.0f);+ ImGui::TableSetupColumn("SIGNAL", ImGuiTableColumnFlags_WidthStretch, 1.0f);+ ImGui::TableHeadersRow();++ for (auto& ind : tech.indicators) {+ if (ind.category != cat) continue;+ ImGui::TableNextRow();++ ImGui::TableSetColumnIndex(0);+ ImGui::TextColored(TEXT_SECONDARY, "%s", ind.name.c_str());++ char buf[32];++ ImGui::TableSetColumnIndex(1);+ std::snprintf(buf, sizeof(buf), "%.2f", ind.value);+ ImGui::TextColored(TEXT_PRIMARY, "%s", buf);++ ImGui::TableSetColumnIndex(2);+ std::snprintf(buf, sizeof(buf), "%.2f", ind.prev_value);+ ImGui::TextColored(TEXT_DIM, "%s", buf);++ ImGui::TableSetColumnIndex(3);+ std::snprintf(buf, sizeof(buf), "%.2f", ind.min_val);+ ImGui::TextColored(TEXT_DIM, "%s", buf);++ ImGui::TableSetColumnIndex(4);+ std::snprintf(buf, sizeof(buf), "%.2f", ind.max_val);+ ImGui::TextColored(TEXT_DIM, "%s", buf);++ ImGui::TableSetColumnIndex(5);+ ImVec4 sc = signal_color(ind.signal);+ ImGui::TextColored(sc, "%s %s", signal_arrow(ind.signal), signal_text(ind.signal));+ }++ ImGui::EndTable();+ }++ ImGui::Unindent(8);+ ImGui::Spacing();+ }+ };++ render_category("TREND INDICATORS", "trend", INFO, show_trend_);+ render_category("MOMENTUM INDICATORS", "momentum", MARKET_GREEN, show_momentum_);+ render_category("VOLATILITY INDICATORS", "volatility", WARNING, show_volatility_);++ // Trading notes+ ImGui::Spacing();+ ImGui::BeginChild("##trade_notes", ImVec2(0, 0), ImGuiChildFlags_AutoResizeY | ImGuiChildFlags_Borders);+ ImGui::PushStyleColor(ImGuiCol_Text, WARNING);+ ImGui::TextUnformatted("TRADING NOTES");+ ImGui::PopStyleColor();+ ImGui::Separator();+ ImGui::TextColored(TEXT_DIM, "* Technical indicators should be used with fundamental analysis and risk management.");+ ImGui::TextColored(TEXT_DIM, "* Signal strength increases when multiple indicators align (confluence).");+ ImGui::TextColored(TEXT_DIM, "* Overbought/oversold conditions can persist in strong trends.");+ ImGui::TextColored(TEXT_DIM, "* Past performance does not guarantee future results. Always use stop-losses.");+ ImGui::EndChild();+}++} // namespace fincept::researchdiff --git a/fincept-cpp/src/research/technicals_panel.h b/fincept-cpp/src/research/technicals_panel.hnew file mode 100644index 000000000..b09bb3b96--- /dev/null+++ b/fincept-cpp/src/research/technicals_panel.h@@ -0,0 +1,20 @@+#pragma once+// Technicals panel — Technical indicators with signal summary+// Mirrors TechnicalsTab.tsx: Overall rating, key indicators, category sections++#include "research_types.h"+#include "research_data.h"++namespace fincept::research {++class TechnicalsPanel {+public:+ void render(ResearchData& data);++private:+ bool show_trend_ = true;+ bool show_momentum_ = true;+ bool show_volatility_= false;+};++} // namespace fincept::researchdiff --git a/fincept-cpp/src/storage/crypto.cpp b/fincept-cpp/src/storage/crypto.cppnew file mode 100644index 000000000..06ab0b785--- /dev/null+++ b/fincept-cpp/src/storage/crypto.cpp@@ -0,0 +1,141 @@+#include "crypto.h"+#include <openssl/evp.h>+#include <openssl/rand.h>+#include <openssl/bio.h>+#include <openssl/buffer.h>+#include <cstring>++namespace fincept::storage {++static constexpr int AES_KEY_SIZE = 32; // 256 bits+static constexpr int GCM_NONCE_SIZE = 12;+static constexpr int GCM_TAG_SIZE = 16;++std::vector<unsigned char> Crypto::random_bytes(size_t count) {+ std::vector<unsigned char> buf(count);+ RAND_bytes(buf.data(), (int)count);+ return buf;+}++std::string Crypto::base64_encode(const std::vector<unsigned char>& data) {+ BIO* bio = BIO_new(BIO_s_mem());+ BIO* b64 = BIO_new(BIO_f_base64());+ BIO_set_flags(b64, BIO_FLAGS_BASE64_NO_NL);+ bio = BIO_push(b64, bio);++ BIO_write(bio, data.data(), (int)data.size());+ BIO_flush(bio);++ BUF_MEM* buf_mem = nullptr;+ BIO_get_mem_ptr(bio, &buf_mem);++ std::string result(buf_mem->data, buf_mem->length);+ BIO_free_all(bio);+ return result;+}++std::vector<unsigned char> Crypto::base64_decode(const std::string& encoded) {+ BIO* bio = BIO_new_mem_buf(encoded.data(), (int)encoded.size());+ BIO* b64 = BIO_new(BIO_f_base64());+ BIO_set_flags(b64, BIO_FLAGS_BASE64_NO_NL);+ bio = BIO_push(b64, bio);++ std::vector<unsigned char> result(encoded.size());+ int len = BIO_read(bio, result.data(), (int)result.size());+ result.resize(len > 0 ? len : 0);++ BIO_free_all(bio);+ return result;+}++std::string Crypto::derive_key(const std::string& passphrase, const std::string& salt) {+ std::vector<unsigned char> key(AES_KEY_SIZE);+ PKCS5_PBKDF2_HMAC(+ passphrase.c_str(), (int)passphrase.size(),+ reinterpret_cast<const unsigned char*>(salt.c_str()), (int)salt.size(),+ 100000, EVP_sha256(),+ AES_KEY_SIZE, key.data()+ );+ return std::string(reinterpret_cast<char*>(key.data()), AES_KEY_SIZE);+}++std::optional<std::string> Crypto::encrypt(const std::string& plaintext, const std::string& key) {+ if (key.size() < AES_KEY_SIZE) return std::nullopt;++ auto nonce = random_bytes(GCM_NONCE_SIZE);+ std::vector<unsigned char> ciphertext(plaintext.size());+ std::vector<unsigned char> tag(GCM_TAG_SIZE);++ EVP_CIPHER_CTX* ctx = EVP_CIPHER_CTX_new();+ if (!ctx) return std::nullopt;++ int len = 0;+ bool ok = true;++ ok = ok && EVP_EncryptInit_ex(ctx, EVP_aes_256_gcm(), nullptr, nullptr, nullptr);+ ok = ok && EVP_CIPHER_CTX_ctrl(ctx, EVP_CTRL_GCM_SET_IVLEN, GCM_NONCE_SIZE, nullptr);+ ok = ok && EVP_EncryptInit_ex(ctx, nullptr, nullptr,+ reinterpret_cast<const unsigned char*>(key.data()), nonce.data());+ ok = ok && EVP_EncryptUpdate(ctx, ciphertext.data(), &len,+ reinterpret_cast<const unsigned char*>(plaintext.data()), (int)plaintext.size());+ int ciphertext_len = len;+ ok = ok && EVP_EncryptFinal_ex(ctx, ciphertext.data() + len, &len);+ ciphertext_len += len;+ ok = ok && EVP_CIPHER_CTX_ctrl(ctx, EVP_CTRL_GCM_GET_TAG, GCM_TAG_SIZE, tag.data());++ EVP_CIPHER_CTX_free(ctx);+ if (!ok) return std::nullopt;++ ciphertext.resize(ciphertext_len);++ // Pack: nonce || ciphertext || tag+ std::vector<unsigned char> packed;+ packed.reserve(GCM_NONCE_SIZE + ciphertext_len + GCM_TAG_SIZE);+ packed.insert(packed.end(), nonce.begin(), nonce.end());+ packed.insert(packed.end(), ciphertext.begin(), ciphertext.end());+ packed.insert(packed.end(), tag.begin(), tag.end());++ return base64_encode(packed);+}++std::optional<std::string> Crypto::decrypt(const std::string& ciphertext_b64, const std::string& key) {+ if (key.size() < AES_KEY_SIZE) return std::nullopt;++ auto packed = base64_decode(ciphertext_b64);+ if (packed.size() < GCM_NONCE_SIZE + GCM_TAG_SIZE) return std::nullopt;++ // Unpack: nonce || ciphertext || tag+ auto nonce_begin = packed.begin();+ auto ct_begin = nonce_begin + GCM_NONCE_SIZE;+ auto tag_begin = packed.end() - GCM_TAG_SIZE;+ int ct_len = (int)(tag_begin - ct_begin);++ if (ct_len < 0) return std::nullopt;++ std::vector<unsigned char> plaintext(ct_len);++ EVP_CIPHER_CTX* ctx = EVP_CIPHER_CTX_new();+ if (!ctx) return std::nullopt;++ int len = 0;+ bool ok = true;++ ok = ok && EVP_DecryptInit_ex(ctx, EVP_aes_256_gcm(), nullptr, nullptr, nullptr);+ ok = ok && EVP_CIPHER_CTX_ctrl(ctx, EVP_CTRL_GCM_SET_IVLEN, GCM_NONCE_SIZE, nullptr);+ ok = ok && EVP_DecryptInit_ex(ctx, nullptr, nullptr,+ reinterpret_cast<const unsigned char*>(key.data()), &(*nonce_begin));+ ok = ok && EVP_DecryptUpdate(ctx, plaintext.data(), &len, &(*ct_begin), ct_len);+ int plaintext_len = len;+ ok = ok && EVP_CIPHER_CTX_ctrl(ctx, EVP_CTRL_GCM_SET_TAG, GCM_TAG_SIZE, (void*)&(*tag_begin));++ int ret = EVP_DecryptFinal_ex(ctx, plaintext.data() + len, &len);+ plaintext_len += len;++ EVP_CIPHER_CTX_free(ctx);++ if (!ok || ret <= 0) return std::nullopt;++ return std::string(reinterpret_cast<char*>(plaintext.data()), plaintext_len);+}++} // namespace fincept::storagediff --git a/fincept-cpp/src/storage/crypto.h b/fincept-cpp/src/storage/crypto.hnew file mode 100644index 000000000..6ded14006--- /dev/null+++ b/fincept-cpp/src/storage/crypto.h@@ -0,0 +1,31 @@+#pragma once+// AES-256-GCM encryption for credential storage+// Matches the Tauri/Rust backend's encryption approach++#include <string>+#include <vector>+#include <optional>++namespace fincept::storage {++class Crypto {+public:+ // Encrypt plaintext with AES-256-GCM+ // Returns base64-encoded ciphertext (nonce + ciphertext + tag)+ static std::optional<std::string> encrypt(const std::string& plaintext, const std::string& key);++ // Decrypt base64-encoded ciphertext with AES-256-GCM+ static std::optional<std::string> decrypt(const std::string& ciphertext_b64, const std::string& key);++ // Derive a 256-bit key from a passphrase using PBKDF2+ static std::string derive_key(const std::string& passphrase, const std::string& salt = "fincept_terminal_v3");++ // Generate cryptographically secure random bytes+ static std::vector<unsigned char> random_bytes(size_t count);++ // Base64 encode/decode+ static std::string base64_encode(const std::vector<unsigned char>& data);+ static std::vector<unsigned char> base64_decode(const std::string& encoded);+};++} // namespace fincept::storagediff --git a/fincept-cpp/src/storage/sqlite_store.cpp b/fincept-cpp/src/storage/sqlite_store.cppnew file mode 100644index 000000000..257f7a088--- /dev/null+++ b/fincept-cpp/src/storage/sqlite_store.cpp@@ -0,0 +1,161 @@+#include "sqlite_store.h"+#include <sqlite3.h>+#include <filesystem>+#include <iostream>++#ifdef _WIN32+#include <shlobj.h>+#pragma comment(lib, "shell32.lib")+#endif++namespace fincept::storage {++SqliteStore& SqliteStore::instance() {+ static SqliteStore store;+ return store;+}++SqliteStore::~SqliteStore() {+ close();+}++std::string SqliteStore::get_default_db_path() {+ std::string base_dir;++#ifdef _WIN32+ char path[MAX_PATH];+ if (SUCCEEDED(SHGetFolderPathA(nullptr, CSIDL_LOCAL_APPDATA, nullptr, 0, path))) {+ base_dir = std::string(path) + "\\FinceptTerminal";+ } else {+ base_dir = ".";+ }+#elif defined(__APPLE__)+ const char* home = getenv("HOME");+ base_dir = std::string(home ? home : ".") + "/Library/Application Support/FinceptTerminal";+#else+ const char* home = getenv("HOME");+ base_dir = std::string(home ? home : ".") + "/.local/share/fincept-terminal";+#endif++ std::filesystem::create_directories(base_dir);+ return base_dir + "/fincept_settings.db";+}++bool SqliteStore::initialize(const std::string& db_path) {+ std::lock_guard<std::mutex> lock(mutex_);+ if (initialized_) return true;++ std::string path = db_path.empty() ? get_default_db_path() : db_path;++ int rc = sqlite3_open(path.c_str(), &db_);+ if (rc != SQLITE_OK) {+ std::cerr << "[SqliteStore] Failed to open database: " << sqlite3_errmsg(db_) << std::endl;+ return false;+ }++ // Enable WAL mode for better concurrent access+ sqlite3_exec(db_, "PRAGMA journal_mode=WAL;", nullptr, nullptr, nullptr);+ sqlite3_exec(db_, "PRAGMA synchronous=NORMAL;", nullptr, nullptr, nullptr);++ if (!create_tables()) {+ return false;+ }++ initialized_ = true;+ std::cout << "[SqliteStore] Initialized at: " << path << std::endl;+ return true;+}++bool SqliteStore::create_tables() {+ const char* sql = R"(+ CREATE TABLE IF NOT EXISTS settings (+ key TEXT PRIMARY KEY,+ value TEXT NOT NULL,+ category TEXT DEFAULT 'general',+ updated_at DATETIME DEFAULT CURRENT_TIMESTAMP+ );+ )";++ char* err_msg = nullptr;+ int rc = sqlite3_exec(db_, sql, nullptr, nullptr, &err_msg);+ if (rc != SQLITE_OK) {+ std::cerr << "[SqliteStore] Failed to create tables: " << err_msg << std::endl;+ sqlite3_free(err_msg);+ return false;+ }+ return true;+}++void SqliteStore::close() {+ std::lock_guard<std::mutex> lock(mutex_);+ if (db_) {+ sqlite3_close(db_);+ db_ = nullptr;+ initialized_ = false;+ }+}++bool SqliteStore::save_setting(const std::string& key, const std::string& value, const std::string& category) {+ std::lock_guard<std::mutex> lock(mutex_);+ if (!db_) return false;++ const char* sql = R"(+ INSERT OR REPLACE INTO settings (key, value, category, updated_at)+ VALUES (?, ?, ?, CURRENT_TIMESTAMP);+ )";++ sqlite3_stmt* stmt = nullptr;+ int rc = sqlite3_prepare_v2(db_, sql, -1, &stmt, nullptr);+ if (rc != SQLITE_OK) return false;++ sqlite3_bind_text(stmt, 1, key.c_str(), -1, SQLITE_TRANSIENT);+ sqlite3_bind_text(stmt, 2, value.c_str(), -1, SQLITE_TRANSIENT);+ sqlite3_bind_text(stmt, 3, category.c_str(), -1, SQLITE_TRANSIENT);++ rc = sqlite3_step(stmt);+ sqlite3_finalize(stmt);+ return rc == SQLITE_DONE;+}++std::optional<std::string> SqliteStore::get_setting(const std::string& key) {+ std::lock_guard<std::mutex> lock(mutex_);+ if (!db_) return std::nullopt;++ const char* sql = "SELECT value FROM settings WHERE key = ?;";++ sqlite3_stmt* stmt = nullptr;+ int rc = sqlite3_prepare_v2(db_, sql, -1, &stmt, nullptr);+ if (rc != SQLITE_OK) return std::nullopt;++ sqlite3_bind_text(stmt, 1, key.c_str(), -1, SQLITE_TRANSIENT);++ std::optional<std::string> result;+ if (sqlite3_step(stmt) == SQLITE_ROW) {+ const char* val = reinterpret_cast<const char*>(sqlite3_column_text(stmt, 0));+ if (val && val[0] != '\0') {+ result = std::string(val);+ }+ }++ sqlite3_finalize(stmt);+ return result;+}++bool SqliteStore::delete_setting(const std::string& key) {+ std::lock_guard<std::mutex> lock(mutex_);+ if (!db_) return false;++ const char* sql = "DELETE FROM settings WHERE key = ?;";++ sqlite3_stmt* stmt = nullptr;+ int rc = sqlite3_prepare_v2(db_, sql, -1, &stmt, nullptr);+ if (rc != SQLITE_OK) return false;++ sqlite3_bind_text(stmt, 1, key.c_str(), -1, SQLITE_TRANSIENT);++ rc = sqlite3_step(stmt);+ sqlite3_finalize(stmt);+ return rc == SQLITE_DONE;+}++} // namespace fincept::storagediff --git a/fincept-cpp/src/storage/sqlite_store.h b/fincept-cpp/src/storage/sqlite_store.hnew file mode 100644index 000000000..a2d04ee79--- /dev/null+++ b/fincept-cpp/src/storage/sqlite_store.h@@ -0,0 +1,40 @@+#pragma once+// SQLite-based key-value store for session and settings persistence+// Thread-safe, auto-creates tables, matches Tauri app's storage model++#include <string>+#include <optional>+#include <mutex>++struct sqlite3;++namespace fincept::storage {++class SqliteStore {+public:+ static SqliteStore& instance();++ bool initialize(const std::string& db_path = "");+ void close();++ // Key-value operations (mirrors Tauri sqliteService)+ bool save_setting(const std::string& key, const std::string& value, const std::string& category = "general");+ std::optional<std::string> get_setting(const std::string& key);+ bool delete_setting(const std::string& key);++ SqliteStore(const SqliteStore&) = delete;+ SqliteStore& operator=(const SqliteStore&) = delete;++private:+ SqliteStore() = default;+ ~SqliteStore();++ sqlite3* db_ = nullptr;+ std::mutex mutex_;+ bool initialized_ = false;++ bool create_tables();+ std::string get_default_db_path();+};++} // namespace fincept::storagediff --git a/fincept-cpp/src/theme/bloomberg_theme.h b/fincept-cpp/src/theme/bloomberg_theme.hnew file mode 100644index 000000000..c3cea8c6b--- /dev/null+++ b/fincept-cpp/src/theme/bloomberg_theme.h@@ -0,0 +1,250 @@+#pragma once+// Bloomberg Terminal-inspired dark theme for Dear ImGui+// Dense, data-focused, monospace, orange accent on near-black background++#include <imgui.h>+#include <string>++namespace fincept::theme {++// Bloomberg color palette+namespace colors {+ // Backgrounds+ constexpr ImVec4 BG_DARKEST = {0.039f, 0.039f, 0.039f, 1.0f}; // #0A0A0A+ constexpr ImVec4 BG_DARK = {0.059f, 0.059f, 0.059f, 1.0f}; // #0F0F0F+ constexpr ImVec4 BG_PANEL = {0.078f, 0.078f, 0.078f, 1.0f}; // #141414+ constexpr ImVec4 BG_WIDGET = {0.098f, 0.098f, 0.098f, 1.0f}; // #191919+ constexpr ImVec4 BG_INPUT = {0.118f, 0.118f, 0.118f, 1.0f}; // #1E1E1E+ constexpr ImVec4 BG_HOVER = {0.157f, 0.157f, 0.157f, 1.0f}; // #282828++ // Borders+ constexpr ImVec4 BORDER_DIM = {0.157f, 0.157f, 0.157f, 1.0f}; // #282828+ constexpr ImVec4 BORDER = {0.196f, 0.196f, 0.196f, 1.0f}; // #323232+ constexpr ImVec4 BORDER_BRIGHT = {0.275f, 0.275f, 0.275f, 1.0f}; // #464646++ // Text+ constexpr ImVec4 TEXT_PRIMARY = {0.894f, 0.894f, 0.906f, 1.0f}; // #E4E4E7+ constexpr ImVec4 TEXT_SECONDARY = {0.631f, 0.631f, 0.655f, 1.0f}; // #A1A1A7+ constexpr ImVec4 TEXT_DIM = {0.443f, 0.443f, 0.478f, 1.0f}; // #71717A+ constexpr ImVec4 TEXT_DISABLED = {0.318f, 0.318f, 0.349f, 1.0f}; // #515159++ // Bloomberg orange accents+ constexpr ImVec4 ACCENT = {1.0f, 0.4f, 0.0f, 1.0f}; // #FF6600+ constexpr ImVec4 ACCENT_HOVER = {1.0f, 0.467f, 0.067f, 1.0f}; // #FF7711+ constexpr ImVec4 ACCENT_DIM = {0.8f, 0.32f, 0.0f, 0.7f}; // #CC5200+ constexpr ImVec4 ACCENT_BG = {1.0f, 0.4f, 0.0f, 0.12f}; // #FF6600 at 12%++ // Semantic+ constexpr ImVec4 SUCCESS = {0.2f, 0.78f, 0.35f, 1.0f}; // #33C759+ constexpr ImVec4 ERROR_RED = {0.94f, 0.27f, 0.27f, 1.0f}; // #F04545+ constexpr ImVec4 WARNING = {1.0f, 0.73f, 0.0f, 1.0f}; // #FFBB00+ constexpr ImVec4 INFO = {0.24f, 0.56f, 0.94f, 1.0f}; // #3D8FF0++ // Market colors+ constexpr ImVec4 MARKET_GREEN = {0.0f, 0.8f, 0.36f, 1.0f}; // #00CC5C+ constexpr ImVec4 MARKET_RED = {0.94f, 0.2f, 0.2f, 1.0f}; // #F03333+ constexpr ImVec4 MARKET_YELLOW = {1.0f, 0.84f, 0.0f, 1.0f}; // #FFD700++ // Tab colors+ constexpr ImVec4 TAB_BG = {0.059f, 0.059f, 0.059f, 1.0f}; // #0F0F0F+ constexpr ImVec4 TAB_ACTIVE = {0.118f, 0.118f, 0.118f, 1.0f}; // #1E1E1E+ constexpr ImVec4 TAB_HOVERED = {0.098f, 0.098f, 0.098f, 1.0f}; // #191919++ // Scrollbar+ constexpr ImVec4 SCROLLBAR_BG = {0.039f, 0.039f, 0.039f, 0.5f};+ constexpr ImVec4 SCROLLBAR_GRAB = {0.196f, 0.196f, 0.196f, 0.8f};+}++inline void ApplyBloombergTheme() {+ ImGuiStyle& style = ImGui::GetStyle();++ // No rounding — Bloomberg is sharp and angular+ style.WindowRounding = 0.0f;+ style.ChildRounding = 0.0f;+ style.FrameRounding = 1.0f; // Minimal rounding on inputs only+ style.PopupRounding = 0.0f;+ style.ScrollbarRounding = 0.0f;+ style.GrabRounding = 0.0f;+ style.TabRounding = 0.0f;++ // Dense, compact spacing+ style.WindowPadding = ImVec2(8.0f, 8.0f);+ style.FramePadding = ImVec2(6.0f, 4.0f);+ style.CellPadding = ImVec2(4.0f, 2.0f);+ style.ItemSpacing = ImVec2(6.0f, 4.0f);+ style.ItemInnerSpacing = ImVec2(4.0f, 4.0f);+ style.IndentSpacing = 16.0f;+ style.ScrollbarSize = 10.0f;+ style.GrabMinSize = 8.0f;++ // Borders+ style.WindowBorderSize = 1.0f;+ style.ChildBorderSize = 1.0f;+ style.FrameBorderSize = 1.0f;+ style.PopupBorderSize = 1.0f;+ style.TabBorderSize = 1.0f;++ // Separators+ style.SeparatorTextBorderSize = 1.0f;++ // Docking+ style.DockingSeparatorSize = 2.0f;++ // Colors+ ImVec4* c = style.Colors;++ // Window+ c[ImGuiCol_WindowBg] = colors::BG_DARK;+ c[ImGuiCol_ChildBg] = colors::BG_PANEL;+ c[ImGuiCol_PopupBg] = colors::BG_PANEL;++ // Borders+ c[ImGuiCol_Border] = colors::BORDER_DIM;+ c[ImGuiCol_BorderShadow] = {0.0f, 0.0f, 0.0f, 0.0f};++ // Text+ c[ImGuiCol_Text] = colors::TEXT_PRIMARY;+ c[ImGuiCol_TextDisabled] = colors::TEXT_DISABLED;+ c[ImGuiCol_TextSelectedBg] = colors::ACCENT_DIM;++ // Frame (input fields, checkboxes)+ c[ImGuiCol_FrameBg] = colors::BG_INPUT;+ c[ImGuiCol_FrameBgHovered] = colors::BG_HOVER;+ c[ImGuiCol_FrameBgActive] = colors::BG_HOVER;++ // Title bar+ c[ImGuiCol_TitleBg] = colors::BG_DARKEST;+ c[ImGuiCol_TitleBgActive] = colors::BG_DARK;+ c[ImGuiCol_TitleBgCollapsed] = colors::BG_DARKEST;++ // Menu+ c[ImGuiCol_MenuBarBg] = colors::BG_DARKEST;++ // Scrollbar+ c[ImGuiCol_ScrollbarBg] = colors::SCROLLBAR_BG;+ c[ImGuiCol_ScrollbarGrab] = colors::SCROLLBAR_GRAB;+ c[ImGuiCol_ScrollbarGrabHovered] = colors::BORDER_BRIGHT;+ c[ImGuiCol_ScrollbarGrabActive] = colors::TEXT_DIM;++ // Buttons+ c[ImGuiCol_Button] = colors::BG_WIDGET;+ c[ImGuiCol_ButtonHovered] = colors::BG_HOVER;+ c[ImGuiCol_ButtonActive] = colors::ACCENT_DIM;++ // Headers (collapsing headers, selectables)+ c[ImGuiCol_Header] = colors::BG_WIDGET;+ c[ImGuiCol_HeaderHovered] = colors::BG_HOVER;+ c[ImGuiCol_HeaderActive] = colors::ACCENT_DIM;++ // Separator+ c[ImGuiCol_Separator] = colors::BORDER_DIM;+ c[ImGuiCol_SeparatorHovered] = colors::ACCENT;+ c[ImGuiCol_SeparatorActive] = colors::ACCENT;++ // Resize grip+ c[ImGuiCol_ResizeGrip] = colors::BORDER_DIM;+ c[ImGuiCol_ResizeGripHovered] = colors::ACCENT;+ c[ImGuiCol_ResizeGripActive] = colors::ACCENT;++ // Tabs+ c[ImGuiCol_Tab] = colors::TAB_BG;+ c[ImGuiCol_TabHovered] = colors::TAB_HOVERED;+ c[ImGuiCol_TabSelected] = colors::TAB_ACTIVE;+ c[ImGuiCol_TabSelectedOverline] = colors::ACCENT;+ c[ImGuiCol_TabDimmed] = colors::BG_DARKEST;+ c[ImGuiCol_TabDimmedSelected] = colors::BG_DARK;++ // Docking+ c[ImGuiCol_DockingPreview] = colors::ACCENT_DIM;+ c[ImGuiCol_DockingEmptyBg] = colors::BG_DARKEST;++ // Checkmark+ c[ImGuiCol_CheckMark] = colors::ACCENT;++ // Slider+ c[ImGuiCol_SliderGrab] = colors::ACCENT_DIM;+ c[ImGuiCol_SliderGrabActive] = colors::ACCENT;++ // Nav+ c[ImGuiCol_NavHighlight] = colors::ACCENT;+ c[ImGuiCol_NavWindowingHighlight]= {1.0f, 1.0f, 1.0f, 0.7f};+ c[ImGuiCol_NavWindowingDimBg] = {0.0f, 0.0f, 0.0f, 0.5f};++ // Modal dim+ c[ImGuiCol_ModalWindowDimBg] = {0.0f, 0.0f, 0.0f, 0.65f};++ // Table+ c[ImGuiCol_TableHeaderBg] = colors::BG_WIDGET;+ c[ImGuiCol_TableBorderStrong] = colors::BORDER;+ c[ImGuiCol_TableBorderLight] = colors::BORDER_DIM;+ c[ImGuiCol_TableRowBg] = {0.0f, 0.0f, 0.0f, 0.0f};+ c[ImGuiCol_TableRowBgAlt] = {1.0f, 1.0f, 1.0f, 0.02f};++ // Plot+ c[ImGuiCol_PlotLines] = colors::ACCENT;+ c[ImGuiCol_PlotLinesHovered] = colors::ACCENT_HOVER;+ c[ImGuiCol_PlotHistogram] = colors::ACCENT;+ c[ImGuiCol_PlotHistogramHovered] = colors::ACCENT_HOVER;++ // Drag/drop+ c[ImGuiCol_DragDropTarget] = colors::ACCENT;+}++// Helper to draw Bloomberg-style section header with orange left border+inline void SectionHeader(const char* label) {+ ImGui::PushStyleColor(ImGuiCol_Text, colors::ACCENT);+ ImGui::SeparatorText(label);+ ImGui::PopStyleColor();+}++// Helper for Bloomberg-style status indicator (green/red dot + text)+inline void StatusIndicator(const char* label, bool online) {+ ImVec4 color = online ? colors::SUCCESS : colors::ERROR_RED;+ ImGui::PushStyleColor(ImGuiCol_Text, color);+ ImGui::Bullet();+ ImGui::PopStyleColor();+ ImGui::SameLine();+ ImGui::TextColored(colors::TEXT_SECONDARY, "%s", label);+}++// Helper for accent-colored button (Bloomberg orange)+inline bool AccentButton(const char* label, const ImVec2& size = ImVec2(0, 0)) {+ ImGui::PushStyleColor(ImGuiCol_Button, colors::ACCENT_DIM);+ ImGui::PushStyleColor(ImGuiCol_ButtonHovered, colors::ACCENT);+ ImGui::PushStyleColor(ImGuiCol_ButtonActive, colors::ACCENT_HOVER);+ ImGui::PushStyleColor(ImGuiCol_Text, ImVec4(1.0f, 1.0f, 1.0f, 1.0f));+ bool clicked = ImGui::Button(label, size);+ ImGui::PopStyleColor(4);+ return clicked;+}++// Helper for disabled/secondary button+inline bool SecondaryButton(const char* label, const ImVec2& size = ImVec2(0, 0)) {+ ImGui::PushStyleColor(ImGuiCol_Button, colors::BG_WIDGET);+ ImGui::PushStyleColor(ImGuiCol_ButtonHovered, colors::BG_HOVER);+ ImGui::PushStyleColor(ImGuiCol_ButtonActive, colors::BORDER);+ ImGui::PushStyleColor(ImGuiCol_Text, colors::TEXT_SECONDARY);+ bool clicked = ImGui::Button(label, size);+ ImGui::PopStyleColor(4);+ return clicked;+}++// Bloomberg-style error message box+inline void ErrorMessage(const char* msg) {+ if (!msg || msg[0] == '\0') return;+ ImGui::PushStyleColor(ImGuiCol_Text, colors::ERROR_RED);+ ImGui::PushStyleColor(ImGuiCol_ChildBg, ImVec4(0.94f, 0.27f, 0.27f, 0.08f));+ ImGui::BeginChild("##error_msg", ImVec2(0, 0), ImGuiChildFlags_AutoResizeY | ImGuiChildFlags_Borders);+ ImGui::TextWrapped("%s", msg);+ ImGui::EndChild();+ ImGui::PopStyleColor(2);+}++// Loading spinner (simple rotating text indicator)+inline void LoadingSpinner(const char* label = "Loading...") {+ static const char* frames[] = {"|", "/", "-", "\\"};+ int frame = (int)(ImGui::GetTime() / 0.15f) % 4;+ ImGui::TextColored(colors::ACCENT, "%s %s", frames[frame], label);+}++} // namespace fincept::themediff --git a/fincept-cpp/src/utils/device_id.cpp b/fincept-cpp/src/utils/device_id.cppnew file mode 100644index 000000000..497629193--- /dev/null+++ b/fincept-cpp/src/utils/device_id.cpp@@ -0,0 +1,75 @@+#include "device_id.h"+#include <sstream>+#include <iomanip>+#include <chrono>+#include <random>+#include <cstdlib>+#include <functional>++#ifdef _WIN32+#include <windows.h>+#endif++namespace fincept::utils {++std::string generate_device_id() {+ // Gather system info similar to TypeScript's navigator properties+ std::ostringstream info;++#ifdef _WIN32+ // Platform+ info << "Win32;";++ // Screen resolution+ int w = GetSystemMetrics(SM_CXSCREEN);+ int h = GetSystemMetrics(SM_CYSCREEN);+ info << w << "x" << h << ";";++ // Computer name+ char computer_name[256] = {};+ DWORD size = sizeof(computer_name);+ GetComputerNameA(computer_name, &size);+ info << computer_name << ";";++ // Processor count+ SYSTEM_INFO si;+ GetSystemInfo(&si);+ info << si.dwNumberOfProcessors << ";";+#else+ info << "Desktop;";+ const char* user = std::getenv("USER");+ if (user) info << user << ";";+ const char* home = std::getenv("HOME");+ if (home) info << home << ";";+#endif++ // Hash the info string+ std::string info_str = info.str();+ std::hash<std::string> hasher;+ size_t hash = hasher(info_str);++ // Timestamp component (base36)+ auto now = std::chrono::system_clock::now().time_since_epoch();+ auto ms = std::chrono::duration_cast<std::chrono::milliseconds>(now).count();++ // Random component+ std::random_device rd;+ std::mt19937 gen(rd());+ std::uniform_int_distribution<uint64_t> dist;+ uint64_t random_val = dist(gen);++ // Format: fincept_desktop_{hash}_{timestamp}_{random}+ std::ostringstream device_id;+ device_id << "fincept_desktop_"+ << std::hex << hash << "_"+ << std::hex << ms << "_"+ << std::hex << random_val;++ std::string result = device_id.str();++ // Ensure 10-255 characters+ if (result.size() > 255) result.resize(255);+ return result;+}++} // namespace fincept::utilsdiff --git a/fincept-cpp/src/utils/device_id.h b/fincept-cpp/src/utils/device_id.hnew file mode 100644index 000000000..1d9f87a3b--- /dev/null+++ b/fincept-cpp/src/utils/device_id.h@@ -0,0 +1,11 @@+#pragma once+// Device ID generation matching the TypeScript implementation++#include <string>++namespace fincept::utils {++// Generate a unique device ID (10-255 chars) based on system info+std::string generate_device_id();++} // namespace fincept::utilsdiff --git a/fincept-cpp/src/utils/validators.h b/fincept-cpp/src/utils/validators.hnew file mode 100644index 000000000..47ff8687f--- /dev/null+++ b/fincept-cpp/src/utils/validators.h@@ -0,0 +1,76 @@+#pragma once+// Input validation utilities matching the TypeScript validators++#include <string>+#include <regex>+#include <algorithm>++namespace fincept::utils {++struct ValidationResult {+ bool valid = false;+ std::string error;+};++inline ValidationResult validate_email(const std::string& email) {+ if (email.empty()) return {false, "Email is required"};++ // Standard email regex+ static const std::regex email_re(R"([^\s@]+@[^\s@]+\.[^\s@]+)");+ if (!std::regex_match(email, email_re)) {+ return {false, "Invalid email format"};+ }+ return {true, ""};+}++struct PasswordStrength {+ bool min_length = false;+ bool has_upper = false;+ bool has_lower = false;+ bool has_number = false;+ bool has_special = false;++ bool is_valid() const {+ return min_length && has_upper && has_lower && has_number && has_special;+ }++ int score() const {+ return (int)min_length + (int)has_upper + (int)has_lower + (int)has_number + (int)has_special;+ }+};++inline PasswordStrength validate_password(const std::string& pw) {+ PasswordStrength s;+ s.min_length = pw.size() >= 8;+ s.has_upper = std::any_of(pw.begin(), pw.end(), ::isupper);+ s.has_lower = std::any_of(pw.begin(), pw.end(), ::islower);+ s.has_number = std::any_of(pw.begin(), pw.end(), ::isdigit);+ s.has_special = std::any_of(pw.begin(), pw.end(), [](char c) {+ return std::string("!@#$%^&*(),.?\":{}|<>").find(c) != std::string::npos;+ });+ return s;+}++// Sanitize input string (strip leading/trailing whitespace, remove control chars)+inline std::string sanitize_input(const std::string& input) {+ std::string result;+ result.reserve(input.size());+ for (char c : input) {+ if (c >= 32 || c == '\t') { // Allow printable chars and tab+ result += c;+ }+ }+ // Trim+ size_t start = result.find_first_not_of(" \t\r\n");+ size_t end = result.find_last_not_of(" \t\r\n");+ if (start == std::string::npos) return "";+ return result.substr(start, end - start + 1);+}++// Lowercase a string+inline std::string to_lower(std::string s) {+ std::transform(s.begin(), s.end(), s.begin(), ::tolower);+ return s;+}++} // namespace fincept::utilsdiff --git a/fincept-cpp/vcpkg.json b/fincept-cpp/vcpkg.jsonnew file mode 100644index 000000000..fff57d1ed--- /dev/null+++ b/fincept-cpp/vcpkg.json@@ -0,0 +1,16 @@+{+ "name": "fincept-terminal",+ "version": "3.3.1",+ "description": "Fincept Terminal - Production-grade financial intelligence terminal",+ "dependencies": [+ "glfw3",+ "curl",+ "nlohmann-json",+ "sqlite3",+ "openssl",+ {+ "name": "imgui",+ "features": ["glfw-binding", "opengl3-binding", "docking-experimental"]+ }+ ]+}diff --git a/fincept-terminal-desktop/fincept_imgui.ini b/fincept-terminal-desktop/fincept_imgui.ininew file mode 100644index 000000000..e328675a2--- /dev/null+++ b/fincept-terminal-desktop/fincept_imgui.ini@@ -0,0 +1,45 @@+[Window][##footer]+Pos=0,0+Size=40,40+Collapsed=0++[Window][##dash]+Pos=0,64+Size=40,40+Collapsed=0++[Window][##tabbar]+Pos=0,30+Size=40,40+Collapsed=0++[Window][Debug##Default]+Pos=60,60+Size=400,400+Collapsed=0++[Window][##research_screen]+Pos=0,64+Size=1920,897+Collapsed=0++[Window][##markets_screen]+Pos=0,64+Size=1920,897+Collapsed=0++[Window][##profile]+Pos=0,64+Size=1920,897+Collapsed=0++[Table][0x9CA2F2F4,8]++[Table][0x348D77D2,6]++[Table][0x317DA68C,6]++[Table][0xE946D5C0,6]++[Docking][Data]+diff --git a/fincept-terminal-desktop/src-tauri/resources/scripts/yfinance_data.py b/fincept-terminal-desktop/src-tauri/resources/scripts/yfinance_data.pyindex b8155f234..d02f754c4 100644--- a/fincept-terminal-desktop/src-tauri/resources/scripts/yfinance_data.py+++ b/fincept-terminal-desktop/src-tauri/resources/scripts/yfinance_data.py@@ -472,6 +472,76 @@ def search_symbols(query, limit=20):except Exception as e:return {"error": str(e), "query": query, "results": []}+def get_news(symbol, count=20):+ """Fetch news articles for a symbol using yfinance"""+ try:+ import re+ ticker = yf.Ticker(symbol)+ raw_news = ticker.news+ if not raw_news:+ return {"articles": [], "symbol": symbol}++ articles = []+ for item in raw_news[:count]:+ content = item.get("content", {})+ title = content.get("title", "")+ if not title:+ continue+ # Clean HTML from summary+ summary = content.get("summary", "")+ summary = re.sub(r'<[^>]+>', '', summary)+ pub_date = content.get("pubDate", "")+ provider = content.get("provider", {})+ publisher = provider.get("displayName", "")+ # Get URL+ url = ""+ click_url = content.get("clickThroughUrl", {})+ if click_url:+ url = click_url.get("url", "")+ if not url:+ canonical = content.get("canonicalUrl", {})+ if canonical:+ url = canonical.get("url", "")++ articles.append({+ "title": title,+ "description": summary,+ "url": url,+ "publisher": publisher,+ "published_date": pub_date+ })++ return {"articles": articles, "symbol": symbol}+ except Exception as e:+ return {"error": str(e), "symbol": symbol, "articles": []}++def get_historical_period(symbol, period='6mo', interval='1d'):+ """Fetch historical data using a period string (e.g., '1mo', '6mo', '1y', '5y')"""+ try:+ import io, contextlib+ ticker = yf.Ticker(symbol)+ _buf = io.StringIO()+ with contextlib.redirect_stdout(_buf):+ hist = ticker.history(period=period, interval=interval)++ if hist.empty:+ return []++ historical_data = []+ for index, row in hist.iterrows():+ historical_data.append({+ "timestamp": int(index.timestamp()),+ "open": round(float(row['Open']), 2),+ "high": round(float(row['High']), 2),+ "low": round(float(row['Low']), 2),+ "close": round(float(row['Close']), 2),+ "volume": int(row['Volume'])+ })++ return historical_data+ except Exception as e:+ return {"error": str(e), "symbol": symbol}+def resolve_symbol(symbol):"""Resolve a bare stock symbol to its correct yfinance-compatible form.@@ -611,6 +681,23 @@ def main(args=None):limit = int(args[2]) if len(args) > 2 else 50result = search_symbols(query, limit)+ elif command == "news":+ if len(args) < 2:+ result = {"error": "Usage: python yfinance_data.py news <symbol> [count]"}+ else:+ symbol = args[1]+ count = int(args[2]) if len(args) > 2 else 20+ result = get_news(symbol, count)++ elif command == "historical_period":+ if len(args) < 2:+ result = {"error": "Usage: python yfinance_data.py historical_period <symbol> [period] [interval]"}+ else:+ symbol = args[1]+ period = args[2] if len(args) > 2 else '6mo'+ interval = args[3] if len(args) > 3 else '1d'+ result = get_historical_period(symbol, period, interval)+elif command == "resolve_symbol":if len(args) < 2:result = {"error": "Usage: python yfinance_data.py resolve_symbol <symbol>"}diff --git a/fincept-terminal-desktop/src/App.tsx b/fincept-terminal-desktop/src/App.tsxindex 8741c9c30..72fb687e6 100644--- a/fincept-terminal-desktop/src/App.tsx+++ b/fincept-terminal-desktop/src/App.tsx@@ -185,15 +185,16 @@ const App: React.FC = () => {useEffect(() => {if (!isLoading) {if (session?.authenticated) {- const isFreePlan = session.user_info?.account_type === 'free';- const hasPaidPlan = session.user_info?.account_type &&- ['basic', 'standard', 'pro', 'enterprise'].includes(session.user_info.account_type);+ const accountType = session.user_info?.account_type?.toLowerCase() || 'free';+ const isFreePlan = accountType === 'free';+ const hasPaidPlan = ['basic', 'standard', 'pro', 'enterprise'].includes(accountType);++ console.log('[App] Navigation check — account_type:', session.user_info?.account_type, 'hasPaidPlan:', hasPaidPlan, 'isFreePlan:', isFreePlan, 'currentScreen:', currentScreen);// If user has a paid plan (basic, standard, pro, enterprise), go to dashboardif (session.user_type === 'registered' && hasPaidPlan) {if (currentScreen !== 'paymentProcessing' &¤tScreen !== 'paymentSuccess' &&- currentScreen !== 'pricing' &¤tScreen !== 'dashboard') {setCurrentScreen('dashboard');}diff --git a/fincept-terminal-desktop/src/components/auth/RegisterScreen.tsx b/fincept-terminal-desktop/src/components/auth/RegisterScreen.tsxindex 9c295c65c..3e18cc6e2 100644--- a/fincept-terminal-desktop/src/components/auth/RegisterScreen.tsx+++ b/fincept-terminal-desktop/src/components/auth/RegisterScreen.tsx@@ -154,8 +154,10 @@ const RegisterScreen: React.FC<RegisterScreenProps> = ({ onNavigate }) => {if (session?.authenticated && session?.user_type === 'registered' && state.isVerificationComplete) {console.log('Registration complete, navigating based on account type:', session.user_info?.account_type);- if (session.subscription?.has_subscription) {- console.log('User has subscription, redirecting to dashboard');+ const accountType = (session.user_info?.account_type || 'free').toLowerCase();+ const hasPaidPlan = ['basic', 'standard', 'pro', 'enterprise'].includes(accountType);+ if (hasPaidPlan) {+ console.log('User has paid plan, redirecting to dashboard');onNavigate('dashboard' as Screen);} else {console.log('User is free tier, showing pricing screen');diff --git a/fincept-terminal-desktop/src/components/auth/SessionGuard.tsx b/fincept-terminal-desktop/src/components/auth/SessionGuard.tsxnew file mode 100644index 000000000..a140f0590--- /dev/null+++ b/fincept-terminal-desktop/src/components/auth/SessionGuard.tsx@@ -0,0 +1,85 @@+// File: src/components/auth/SessionGuard.tsx+// Polls /user/validate-session every 30s. On 401 → instant logout.+// Pauses when tab is hidden.++import { useEffect, useRef, useCallback } from 'react';+import { useAuth } from '@/contexts/AuthContext';+import { AuthApiService } from '@/services/auth/authApi';++const PULSE_INTERVAL_MS = 30_000; // 30 seconds++export const SessionGuard: React.FC = () => {+ const { session, logout } = useAuth();+ const intervalRef = useRef<ReturnType<typeof setInterval> | null>(null);+ const isCheckingRef = useRef(false);+ const logoutRef = useRef(logout);+ logoutRef.current = logout;++ const clearPoll = useCallback(() => {+ if (intervalRef.current) {+ clearInterval(intervalRef.current);+ intervalRef.current = null;+ }+ }, []);++ const checkPulse = useCallback(async () => {+ if (!session?.api_key || !session.session_token || session.user_type !== 'registered') return;+ if (isCheckingRef.current) return;++ isCheckingRef.current = true;+ try {+ const result = await AuthApiService.validateSessionServer(session.api_key);++ // 401 = session expired / logged in from another device+ if (!result.success && (result.status_code === 401 || result.status_code === 403)) {+ console.warn('[SessionGuard] Session expired (status', result.status_code, ') — logging out');+ clearPoll();+ await logoutRef.current();+ return;+ }++ // Also check the response body for valid: false+ const data = (result.data as any)?.data || result.data;+ if (result.success && data && data.valid === false) {+ console.warn('[SessionGuard] Session invalid (valid=false) — logging out');+ clearPoll();+ await logoutRef.current();+ }+ } catch {+ // Network errors are non-fatal — don't logout on connectivity issues+ } finally {+ isCheckingRef.current = false;+ }+ }, [session?.api_key, session?.session_token, session?.user_type, clearPoll]);++ // Start/stop polling based on session state+ useEffect(() => {+ if (session?.user_type === 'registered' && session.session_token) {+ checkPulse();+ clearPoll();+ intervalRef.current = setInterval(checkPulse, PULSE_INTERVAL_MS);+ } else {+ clearPoll();+ }++ return clearPoll;+ }, [session?.user_type, session?.session_token, checkPulse, clearPoll]);++ // Pause when tab is hidden, resume when visible+ useEffect(() => {+ const handleVisibility = () => {+ if (document.hidden) {+ clearPoll();+ } else if (session?.user_type === 'registered' && session.session_token) {+ checkPulse();+ clearPoll();+ intervalRef.current = setInterval(checkPulse, PULSE_INTERVAL_MS);+ }+ };++ document.addEventListener('visibilitychange', handleVisibility);+ return () => document.removeEventListener('visibilitychange', handleVisibility);+ }, [session?.user_type, session?.session_token, checkPulse, clearPoll]);++ return null;+};diff --git a/fincept-terminal-desktop/src/components/dashboard/DashboardScreen.tsx b/fincept-terminal-desktop/src/components/dashboard/DashboardScreen.tsxindex da77494c5..6f6531637 100644--- a/fincept-terminal-desktop/src/components/dashboard/DashboardScreen.tsx+++ b/fincept-terminal-desktop/src/components/dashboard/DashboardScreen.tsx@@ -192,10 +192,8 @@ function FinxeptTerminalContent() {const username = session.user_info?.username || session.user_info?.email || 'User';const accountType = session.user_info?.account_type || 'free';const creditBalance = session.user_info?.credit_balance ?? 0;- const hasSubscription = (session.subscription as any)?.data?.has_subscription || session.subscription?.has_subscription;- const planName = hasSubscription- ? ((session.subscription as any)?.data?.subscription?.plan?.name || session.subscription?.subscription?.plan?.name || accountType)- : (accountType === 'free' ? 'Free Plan' : accountType.charAt(0).toUpperCase() + accountType.slice(1));+ const hasPaidPlan = ['basic', 'standard', 'pro', 'enterprise'].includes(accountType.toLowerCase());+ const planName = accountType === 'free' ? 'Free Plan' : accountType.charAt(0).toUpperCase() + accountType.slice(1) + ' Plan';return (<span style={{ color: '#fbbf24', fontSize: '10px', display: 'flex', alignItems: 'center', gap: '4px' }}>@@ -218,11 +216,11 @@ function FinxeptTerminalContent() {<spanonClick={() => navigation.navigateToPricing()}style={{ cursor: 'pointer', textDecoration: 'underline' }}- title={hasSubscription ? 'Change Plan' : 'View Plans'}+ title={hasPaidPlan ? 'Change Plan' : 'View Plans'}>📦 {planName}</span>- {hasSubscription && (+ {hasPaidPlan && (<><span style={{ color: '#787878' }}>|</span><span>[OK] Active</span>diff --git a/fincept-terminal-desktop/src/components/tabs/profile/ProfileTab.tsx b/fincept-terminal-desktop/src/components/tabs/profile/ProfileTab.tsxindex d567cdba8..243aa7ac7 100644--- a/fincept-terminal-desktop/src/components/tabs/profile/ProfileTab.tsx+++ b/fincept-terminal-desktop/src/components/tabs/profile/ProfileTab.tsx@@ -71,13 +71,17 @@ const ProfileTab: React.FC = () => {if (state.activeSection === 'usage') {const result = session.user_type === 'guest'? { success: true, data: { requests_today: session.requests_today || 0, credit_balance: session.credit_balance || 0, expires_at: session.expires_at }, error: undefined, status_code: 200 }- : await withTimeout(UserApiService.getUserUsage(session.api_key), API_TIMEOUT_MS, 'Usage fetch timeout');+ : await withTimeout(UserApiService.getUserUsage(session.api_key, { days: 30 }), API_TIMEOUT_MS, 'Usage fetch timeout');if (!mountedRef.current || currentFetchId !== fetchIdRef.current) return;+ console.log('[Profile] Usage API result:', { success: result.success, status: result.status_code, hasData: !!result.data, error: result.error });+if (result.success && result.data) {const raw = result.data as any;- dispatch({ type: 'SET_USAGE_DATA', data: raw?.data || raw });+ const usagePayload = raw?.data || raw;+ console.log('[Profile] Usage data keys:', Object.keys(usagePayload || {}));+ dispatch({ type: 'SET_USAGE_DATA', data: usagePayload });} else {dispatch({ type: 'SET_ERROR', error: result.error || 'Failed to load usage data' });}@@ -524,18 +528,25 @@ const OverviewSection: React.FC<{ session: any; onLogout: () => void; isLoggingOconst UsageSection: React.FC<{ usageData: UsageData | null; loading: boolean; session: any }> = ({ usageData, loading, session }) => {const credits = session?.user_type === 'guest'? (session?.credit_balance || 0)- : (session?.user_info?.credit_balance || 0);+ : (usageData?.account?.credit_balance ?? session?.user_info?.credit_balance ?? 0);const requestsToday = session?.requests_today || 0;+ const accountType = usageData?.account?.account_type || session?.user_info?.account_type || 'free';+ const rateLimit = usageData?.account?.rate_limit_per_hour || 0;return (<div style={{ display: 'flex', flexDirection: 'column', gap: '16px' }}>- <Panel title="CREDIT BALANCE" icon={<Zap size={14} />}>- <div style={{ padding: '20px 0', textAlign: 'center' }}>- <div style={{ fontSize: '48px', color: F.CYAN, fontWeight: 700, marginBottom: '8px', fontFamily: FONT }}>- {credits.toLocaleString()}- </div>- <div style={{ fontSize: '9px', color: F.GRAY, letterSpacing: '0.5px', fontWeight: 700 }}>AVAILABLE CREDITS</div>+ {/* Account & Credit Balance */}+ <Panel title="ACCOUNT & CREDITS" icon={<Zap size={14} />}>+ <div style={{ display: 'grid', gridTemplateColumns: 'repeat(3, 1fr)', gap: '16px', padding: '12px 0' }}>+ <StatBox label="CREDIT BALANCE" value={credits} color={F.CYAN} />+ <StatBox label="ACCOUNT TYPE" value={accountType.toUpperCase()} />+ <StatBox label="RATE LIMIT / HR" value={rateLimit} /></div>+ {usageData?.account?.credits_expire_at && (+ <div style={{ fontSize: '9px', color: F.MUTED, textAlign: 'center', marginTop: '4px' }}>+ Credits expire: {new Date(usageData.account.credits_expire_at).toLocaleDateString()}+ </div>+ )}</Panel>{session?.user_type === 'guest' && (@@ -553,52 +564,138 @@ const UsageSection: React.FC<{ usageData: UsageData | null; loading: boolean; se<LoadingState message="Loading usage data..." />) : usageData ? (<>- <Panel title="USAGE STATISTICS" icon={<BarChart size={14} />}>- <div style={{ display: 'grid', gridTemplateColumns: 'repeat(3, 1fr)', gap: '16px', padding: '12px 0' }}>- <StatBox label="TOTAL REQUESTS" value={usageData.total_requests || 0} />- <StatBox label="CREDITS USED" value={usageData.total_credits_used || 0} color={F.YELLOW} />- <StatBox label="BALANCE" value={usageData.current_balance || 0} />+ {/* Summary Statistics */}+ <Panel title={`USAGE SUMMARY — LAST ${usageData.period_days || 7} DAYS`} icon={<BarChart size={14} />}>+ <div style={{ display: 'grid', gridTemplateColumns: 'repeat(4, 1fr)', gap: '16px', padding: '12px 0' }}>+ <StatBox label="TOTAL REQUESTS" value={usageData.summary?.total_requests || 0} />+ <StatBox label="CREDITS USED" value={usageData.summary?.total_credits_used || 0} color={F.YELLOW} />+ <StatBox label="AVG CREDITS/REQ" value={usageData.summary?.avg_credits_per_request?.toFixed(2) || '0'} />+ <StatBox label="AVG RESPONSE (ms)" value={usageData.summary?.avg_response_time_ms?.toFixed(0) || '0'} /></div>- {usageData.period && (- <div style={{ fontSize: '9px', color: F.MUTED, textAlign: 'center', marginTop: '8px' }}>- Period: {usageData.period.replace(/_/g, ' ').toUpperCase()}+ {usageData.summary?.first_request_at && usageData.summary?.last_request_at && (+ <div style={{ fontSize: '9px', color: F.MUTED, textAlign: 'center', marginTop: '4px' }}>+ {new Date(usageData.summary.first_request_at).toLocaleDateString()} — {new Date(usageData.summary.last_request_at).toLocaleDateString()}</div>)}</Panel>+ {/* Daily Usage Chart */}+ {usageData.daily_usage && usageData.daily_usage.length > 0 && (+ <Panel title="DAILY USAGE" icon={<Activity size={14} />}>+ <div style={{ padding: '8px 0' }}>+ {/* Simple bar chart */}+ <div style={{ display: 'flex', alignItems: 'flex-end', gap: '2px', height: '80px', padding: '0 4px' }}>+ {(() => {+ const maxReqs = Math.max(...usageData.daily_usage!.map(d => d.request_count), 1);+ return usageData.daily_usage!.map((day) => (+ <div key={day.date} style={{ flex: 1, display: 'flex', flexDirection: 'column', alignItems: 'center', gap: '2px' }}>+ <div+ title={`${day.date}: ${day.request_count} requests, ${day.credits_used} credits`}+ style={{+ width: '100%',+ height: `${Math.max((day.request_count / maxReqs) * 70, 2)}px`,+ backgroundColor: day.credits_used > 0 ? F.CYAN : F.MUTED,+ borderRadius: '1px 1px 0 0',+ opacity: 0.8,+ }}+ />+ </div>+ ));+ })()}+ </div>+ <div style={{ display: 'flex', justifyContent: 'space-between', padding: '4px 4px 0', fontSize: '8px', color: F.MUTED }}>+ <span>{usageData.daily_usage[0]?.date?.slice(5)}</span>+ <span>{usageData.daily_usage[usageData.daily_usage.length - 1]?.date?.slice(5)}</span>+ </div>+ </div>+ {/* Daily totals table */}+ <table style={{ width: '100%', fontSize: '10px', fontFamily: FONT, borderCollapse: 'collapse', marginTop: '8px' }}>+ <thead>+ <tr style={{ borderBottom: `1px solid ${F.BORDER}` }}>+ {['DATE', 'REQUESTS', 'CREDITS'].map(h => (+ <th key={h} style={{+ padding: '6px 8px',+ textAlign: h === 'DATE' ? 'left' : 'right',+ color: F.GRAY, fontSize: '9px', fontWeight: 700, letterSpacing: '0.5px',+ }}>{h}</th>+ ))}+ </tr>+ </thead>+ <tbody>+ {usageData.daily_usage.slice().reverse().slice(0, 10).map((day) => (+ <tr key={day.date} style={{ borderBottom: `1px solid ${F.BORDER}` }}>+ <td style={{ padding: '6px 8px', color: F.WHITE, fontSize: '9px' }}>{day.date}</td>+ <td style={{ padding: '6px 8px', textAlign: 'right', color: F.CYAN, fontWeight: 700 }}>{day.request_count.toLocaleString()}</td>+ <td style={{ padding: '6px 8px', textAlign: 'right', color: day.credits_used > 0 ? F.YELLOW : F.MUTED, fontWeight: 700 }}>{day.credits_used.toLocaleString()}</td>+ </tr>+ ))}+ </tbody>+ </table>+ </Panel>+ )}+{/* Top Endpoints Breakdown */}- {usageData.endpoint_usage && Object.keys(usageData.endpoint_usage).length > 0 && (- <Panel title="ENDPOINT USAGE" icon={<Activity size={14} />}>+ {usageData.endpoint_breakdown && usageData.endpoint_breakdown.length > 0 && (+ <Panel title="TOP ENDPOINTS" icon={<Activity size={14} />}><table style={{ width: '100%', fontSize: '10px', fontFamily: FONT, borderCollapse: 'collapse' }}><thead><tr style={{ borderBottom: `1px solid ${F.BORDER}` }}>- {['ENDPOINT', 'REQUESTS', 'CREDITS'].map(h => (+ {['ENDPOINT', 'REQUESTS', 'CREDITS', 'AVG MS'].map(h => (<th key={h} style={{padding: '6px 8px',textAlign: h === 'ENDPOINT' ? 'left' : 'right',- color: F.GRAY,- fontSize: '9px',- fontWeight: 700,- letterSpacing: '0.5px',+ color: F.GRAY, fontSize: '9px', fontWeight: 700, letterSpacing: '0.5px',}}>{h}</th>))}</tr></thead><tbody>- {Object.entries(usageData.endpoint_usage)- .sort(([, a], [, b]) => b.count - a.count)+ {usageData.endpoint_breakdown.slice(0, 15)- .map(([endpoint, stats]) => (- <tr key={endpoint} style={{ borderBottom: `1px solid ${F.BORDER}` }}>- <td style={{ padding: '6px 8px', color: F.WHITE, fontSize: '9px' }}>{endpoint}</td>- <td style={{ padding: '6px 8px', textAlign: 'right', color: F.CYAN, fontWeight: 700 }}>{stats.count}</td>- <td style={{ padding: '6px 8px', textAlign: 'right', color: stats.credits > 0 ? F.YELLOW : F.MUTED, fontWeight: 700 }}>{stats.credits}</td>+ .map((ep) => (+ <tr key={ep.endpoint} style={{ borderBottom: `1px solid ${F.BORDER}` }}>+ <td style={{ padding: '6px 8px', color: F.WHITE, fontSize: '9px', maxWidth: '200px', overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>{ep.endpoint}</td>+ <td style={{ padding: '6px 8px', textAlign: 'right', color: F.CYAN, fontWeight: 700 }}>{ep.request_count.toLocaleString()}</td>+ <td style={{ padding: '6px 8px', textAlign: 'right', color: ep.credits_used > 0 ? F.YELLOW : F.MUTED, fontWeight: 700 }}>{ep.credits_used.toLocaleString()}</td>+ <td style={{ padding: '6px 8px', textAlign: 'right', color: F.MUTED, fontWeight: 700 }}>{ep.avg_response_time_ms.toFixed(0)}</td></tr>))}</tbody></table></Panel>)}++ {/* Recent Requests */}+ {usageData.recent_requests && usageData.recent_requests.length > 0 && (+ <Panel title="RECENT REQUESTS" icon={<FileText size={14} />}>+ <table style={{ width: '100%', fontSize: '10px', fontFamily: FONT, borderCollapse: 'collapse' }}>+ <thead>+ <tr style={{ borderBottom: `1px solid ${F.BORDER}` }}>+ {['TIME', 'ENDPOINT', 'METHOD', 'STATUS', 'MS'].map(h => (+ <th key={h} style={{+ padding: '6px 8px',+ textAlign: h === 'ENDPOINT' ? 'left' : 'center',+ color: F.GRAY, fontSize: '9px', fontWeight: 700, letterSpacing: '0.5px',+ }}>{h}</th>+ ))}+ </tr>+ </thead>+ <tbody>+ {usageData.recent_requests.slice(0, 20).map((req, i) => (+ <tr key={i} style={{ borderBottom: `1px solid ${F.BORDER}` }}>+ <td style={{ padding: '6px 8px', color: F.MUTED, fontSize: '9px', whiteSpace: 'nowrap' }}>+ {new Date(req.timestamp).toLocaleTimeString([], { hour: '2-digit', minute: '2-digit', second: '2-digit' })}+ </td>+ <td style={{ padding: '6px 8px', color: F.WHITE, fontSize: '9px', maxWidth: '180px', overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>{req.endpoint}</td>+ <td style={{ padding: '6px 8px', textAlign: 'center', color: req.method === 'GET' ? F.CYAN : F.ORANGE, fontWeight: 700, fontSize: '9px' }}>{req.method}</td>+ <td style={{ padding: '6px 8px', textAlign: 'center', color: req.status_code < 400 ? F.GREEN : F.RED, fontWeight: 700, fontSize: '9px' }}>{req.status_code}</td>+ <td style={{ padding: '6px 8px', textAlign: 'center', color: F.MUTED, fontSize: '9px' }}>{req.response_time_ms}</td>+ </tr>+ ))}+ </tbody>+ </table>+ </Panel>+ )}</>) : null}</div>diff --git a/fincept-terminal-desktop/src/components/tabs/profile/profileTypes.ts b/fincept-terminal-desktop/src/components/tabs/profile/profileTypes.tsindex 58d266124..59b4bd6d2 100644--- a/fincept-terminal-desktop/src/components/tabs/profile/profileTypes.ts+++ b/fincept-terminal-desktop/src/components/tabs/profile/profileTypes.ts@@ -30,13 +30,49 @@ export interface PaymentHistoryItem {completed_at: string | null;}-// GET /user/usage → { success, data: { period, total_requests, total_credits_used, current_balance, endpoint_usage } }+// GET /user/usage → { success, data: { account, period_days, summary, daily_usage, endpoint_breakdown, recent_requests, ... } }export interface UsageData {- period?: string;- total_requests?: number;- total_credits_used?: number;- current_balance?: number;- endpoint_usage?: Record<string, { count: number; credits: number }>;+ account?: {+ credit_balance: number;+ account_type: string;+ credits_expire_at: string | null;+ rate_limit_per_hour: number;+ support_type: string;+ };+ period_days?: number;+ summary?: {+ total_requests: number;+ total_credits_used: number;+ avg_credits_per_request: number;+ avg_response_time_ms: number;+ first_request_at: string;+ last_request_at: string;+ };+ daily_usage?: Array<{+ date: string;+ request_count: number;+ credits_used: number;+ }>;+ endpoint_breakdown?: Array<{+ endpoint: string;+ request_count: number;+ credits_used: number;+ avg_response_time_ms: number;+ }>;+ recent_requests?: Array<{+ timestamp: string;+ endpoint: string;+ method: string;+ status_code: number;+ credits_used: number;+ response_time_ms: number;+ }>;+ pagination?: {+ page: number;+ page_size: number;+ total_records: number;+ total_pages: number;+ };}export type Section = 'overview' | 'usage' | 'security' | 'billing' | 'support';diff --git a/fincept-terminal-desktop/src/contexts/AuthContext.tsx b/fincept-terminal-desktop/src/contexts/AuthContext.tsxindex 8fbb45571..8ea01cbb3 100644--- a/fincept-terminal-desktop/src/contexts/AuthContext.tsx+++ b/fincept-terminal-desktop/src/contexts/AuthContext.tsx@@ -2,7 +2,7 @@// Authentication context for managing user state and backend API integration with payment supportimport React, { createContext, useContext, useState, useEffect, ReactNode } from 'react';-import { AuthApiService } from '@/services/auth/authApi';+import { AuthApiService, setSessionToken } from '@/services/auth/authApi';import { PaymentApiService } from '@/services/payment/paymentApi';import { UserApiService } from '@/services/auth/userApi';import { saveSetting, getSetting } from '@/services/core/sqliteService';@@ -29,7 +29,15 @@ export interface UserProfileResponse {account_type: string;credit_balance: number;is_verified: boolean;+ is_admin?: boolean;mfa_enabled: boolean;+ phone?: string | null;+ country_code?: string | null;+ country?: string | null;+ notify_email?: boolean;+ notify_telegram?: boolean;+ notify_in_app?: boolean;+ telegram_connected?: boolean;created_at: string;last_login_at: string;};@@ -92,25 +100,13 @@ export interface PaymentSession {}export interface UserSubscription {- has_subscription: boolean;- subscription?: {- subscription_uuid: string;- plan: {- name: string;- plan_id: string;- price: number;- };- status: string;- current_period_start: string;- current_period_end: string;- days_remaining: number;- cancel_at_period_end: boolean;- usage: {- api_calls_used: number;- api_calls_limit: number | string;- usage_percentage: number;- };- };+ user_id: number;+ account_type: string;+ credit_balance: number;+ credits_expire_at: string | null;+ support_type: string;+ last_credit_purchase_at: string | null;+ created_at: string;}// Types based on your Python API client@@ -118,6 +114,7 @@ export interface SessionData {authenticated: boolean;user_type: 'guest' | 'registered' | null;api_key: string | null;+ session_token?: string | null;device_id: string;user_info?: {username?: string;@@ -267,29 +264,36 @@ export const AuthProvider: React.FC<AuthProviderProps> = ({ children }) => {const [isLoadingPlans, setIsLoadingPlans] = useState(false);// Fetch user profile after login- // Find this function in AuthContext.tsx and update it:-const fetchUserProfile = async (apiKey: string): Promise<UserProfileResponse['data'] | null> => {- try {- const result = await AuthApiService.getUserProfile(apiKey);+ // API returns: { success, message, data: { id, username, email, account_type, ... } }+ // makeApiRequest wraps it: { success, data: { success, message, data: { ... } } }+ const fetchUserProfile = async (apiKey: string): Promise<UserProfileResponse['data'] | null> => {+ try {+ const result = await AuthApiService.getUserProfile(apiKey);- if (result.success && result.data) {- const profileData = (result.data as any).data || result.data;- return profileData;+ if (result.success && result.data) {+ // Unwrap double-wrapped response+ const profileData = (result.data as any).data || result.data;+ console.log('[AuthContext] Profile data:', JSON.stringify(profileData));+ return profileData;+ }+ console.warn('[AuthContext] Profile fetch failed:', result.error);+ return null;+ } catch (error) {+ console.error('Failed to fetch user profile:', error);+ return null;}- return null;- } catch (error) {- console.error('Failed to fetch user profile:', error);- return null;- }-};+ };// Fetch user subscription data+ // API returns: { success, message, data: { user_id, account_type, credit_balance, ... } }const fetchUserSubscription = async (apiKey: string): Promise<UserSubscription | null> => {try {const result = await PaymentApiService.getUserSubscription(apiKey);if (result.success && result.data) {+ console.log('[AuthContext] Subscription data:', JSON.stringify(result.data));return result.data;}+ console.warn('[AuthContext] Subscription fetch failed:', result.error);return null;} catch (error) {console.error('Failed to fetch user subscription:', error);@@ -317,9 +321,9 @@ const fetchUserProfile = async (apiKey: string): Promise<UserProfileResponse['dacredit_balance: userProfile.credit_balance,is_verified: userProfile.is_verified,mfa_enabled: userProfile.mfa_enabled,- phone: (userProfile as any).phone ?? null,- country: (userProfile as any).country ?? null,- country_code: (userProfile as any).country_code ?? null,+ phone: userProfile.phone ?? null,+ country: userProfile.country ?? null,+ country_code: userProfile.country_code ?? null,},subscription: userSubscription || undefined};@@ -338,39 +342,54 @@ const fetchUserProfile = async (apiKey: string): Promise<UserProfileResponse['dareturn null;}- const result = await AuthApiService.getAuthStatus(sessionData.api_key, sessionData.device_id);+ // Restore session token for API calls+ if (sessionData.session_token) {+ setSessionToken(sessionData.session_token);+ }+ // First try validate-session (requires session_token)+ if (sessionData.session_token) {+ const valResult = await AuthApiService.validateSessionServer(sessionData.api_key);+ const valData = (valResult.data as any)?.data || valResult.data;+ if (!valResult.success || !valData?.valid) {+ console.warn('[AuthContext] Session token invalid, session expired');+ setSessionToken(null);+ return null;+ }+ }++ // Fetch fresh profile and subscription data+ const result = await AuthApiService.getAuthStatus(sessionData.api_key, sessionData.device_id);const authData = (result.data as any)?.data || result.data;if (result.success && authData?.authenticated) {- const apiData = authData;-let userProfile = null;let userSubscription = null;- if (apiData.user_type === 'registered') {+ if (authData.user_type === 'registered') {userProfile = await fetchUserProfile(sessionData.api_key);userSubscription = await fetchUserSubscription(sessionData.api_key);}- const validatedSession = {+ const validatedSession: SessionData = {authenticated: true,- user_type: apiData.user_type,+ user_type: authData.user_type,api_key: sessionData.api_key,+ session_token: sessionData.session_token,device_id: sessionData.device_id,- user_info: apiData.user_type === 'registered' && userProfile ? {+ user_info: authData.user_type === 'registered' && userProfile ? {username: userProfile.username,email: userProfile.email,account_type: userProfile.account_type,credit_balance: userProfile.credit_balance,is_verified: userProfile.is_verified,mfa_enabled: userProfile.mfa_enabled,- phone: (userProfile as any).phone ?? null,- country: (userProfile as any).country ?? null,- country_code: (userProfile as any).country_code ?? null,- } : apiData.user,- expires_at: apiData.user_type === 'guest' ? apiData.guest?.expires_at : undefined,- requests_today: apiData.user_type === 'guest' ? apiData.guest?.requests_today : undefined,+ phone: userProfile.phone ?? null,+ country: userProfile.country ?? null,+ country_code: userProfile.country_code ?? null,+ } : authData.user,+ expires_at: authData.user_type === 'guest' ? authData.guest?.expires_at : undefined,+ requests_today: authData.user_type === 'guest' ? authData.guest?.requests_today : undefined,subscription: userSubscription || undefined};@@ -554,7 +573,7 @@ const fetchUserProfile = async (apiKey: string): Promise<UserProfileResponse['daconst apiData = (result.data as any)?.data || result.data;// Check if there's an active session on another device- if (!result.success && apiData && apiData.active_session) {+ if (apiData && apiData.active_session) {return {success: false,active_session: true,@@ -573,6 +592,10 @@ const fetchUserProfile = async (apiKey: string): Promise<UserProfileResponse['daif (result.success && apiData && apiData.api_key) {const apiKey = apiData.api_key;+ const sessionToken = apiData.session_token || null;++ // Set session token globally for all subsequent API calls+ setSessionToken(sessionToken);const [userProfile, userSubscription] = await Promise.all([fetchUserProfile(apiKey),@@ -583,6 +606,7 @@ const fetchUserProfile = async (apiKey: string): Promise<UserProfileResponse['daauthenticated: true,user_type: 'registered',api_key: apiKey,+ session_token: sessionToken,device_id: generateDeviceId(),user_info: userProfile ? {username: userProfile.username,@@ -591,9 +615,9 @@ const fetchUserProfile = async (apiKey: string): Promise<UserProfileResponse['dacredit_balance: userProfile.credit_balance,is_verified: userProfile.is_verified,mfa_enabled: userProfile.mfa_enabled,- phone: (userProfile as any).phone ?? null,- country: (userProfile as any).country ?? null,- country_code: (userProfile as any).country_code ?? null,+ phone: userProfile.phone ?? null,+ country: userProfile.country ?? null,+ country_code: userProfile.country_code ?? null,} : {email: email,account_type: 'free',@@ -602,6 +626,8 @@ const fetchUserProfile = async (apiKey: string): Promise<UserProfileResponse['dasubscription: userSubscription || undefined};+ console.log('[AuthContext] Login success — account_type:', newSession.user_info?.account_type, 'session_token:', !!sessionToken);+setSession(newSession);await saveSession(newSession);// Save to legacy location for backward compatibility@@ -673,6 +699,8 @@ const fetchUserProfile = async (apiKey: string): Promise<UserProfileResponse['daif (result.success && apiData && apiData.api_key) {const apiKey = apiData.api_key;+ const sessionToken = apiData.session_token || null;+ setSessionToken(sessionToken);const userProfile = await fetchUserProfile(apiKey);@@ -680,6 +708,7 @@ const fetchUserProfile = async (apiKey: string): Promise<UserProfileResponse['daauthenticated: true,user_type: 'registered',api_key: apiKey,+ session_token: sessionToken,device_id: generateDeviceId(),user_info: userProfile ? {username: userProfile.username,@@ -688,9 +717,9 @@ const fetchUserProfile = async (apiKey: string): Promise<UserProfileResponse['dacredit_balance: userProfile.credit_balance,is_verified: userProfile.is_verified,mfa_enabled: userProfile.mfa_enabled,- phone: (userProfile as any).phone ?? null,- country: (userProfile as any).country ?? null,- country_code: (userProfile as any).country_code ?? null,+ phone: userProfile.phone ?? null,+ country: userProfile.country ?? null,+ country_code: userProfile.country_code ?? null,} : {email: email,account_type: 'free',@@ -729,6 +758,8 @@ const fetchUserProfile = async (apiKey: string): Promise<UserProfileResponse['daif (result.success && apiData && apiData.api_key) {const apiKey = apiData.api_key;+ const sessionToken = apiData.session_token || null;+ setSessionToken(sessionToken);const [userProfile, userSubscription] = await Promise.all([fetchUserProfile(apiKey),@@ -739,6 +770,7 @@ const fetchUserProfile = async (apiKey: string): Promise<UserProfileResponse['daauthenticated: true,user_type: 'registered',api_key: apiKey,+ session_token: sessionToken,device_id: generateDeviceId(),user_info: userProfile ? {username: userProfile.username,@@ -747,9 +779,9 @@ const fetchUserProfile = async (apiKey: string): Promise<UserProfileResponse['dacredit_balance: userProfile.credit_balance,is_verified: userProfile.is_verified,mfa_enabled: userProfile.mfa_enabled,- phone: (userProfile as any).phone ?? null,- country: (userProfile as any).country ?? null,- country_code: (userProfile as any).country_code ?? null,+ phone: userProfile.phone ?? null,+ country: userProfile.country ?? null,+ country_code: userProfile.country_code ?? null,} : {email: email,account_type: 'free',@@ -899,6 +931,9 @@ const fetchUserProfile = async (apiKey: string): Promise<UserProfileResponse['da}}+ // Clear session token globally+ setSessionToken(null);+// Clear session data first (async operations)await clearSession();diff --git a/fincept-terminal-desktop/src/main.tsx b/fincept-terminal-desktop/src/main.tsxindex 3376555eb..7031d92d6 100644--- a/fincept-terminal-desktop/src/main.tsx+++ b/fincept-terminal-desktop/src/main.tsx@@ -24,6 +24,7 @@ import { AuthProvider } from './contexts/AuthContext'import { LanguageProvider } from './contexts/LanguageContext'import { BrokerProvider } from './contexts/BrokerContext'import { TimezoneProvider } from './contexts/TimezoneContext'+import { SessionGuard } from './components/auth/SessionGuard'import './i18n/config' // Initialize i18nimport './App.css' // Make sure this line existsimport './tauri-cors-config' // Initialize Tauri CORS plugin@@ -98,6 +99,7 @@ ReactDOM.createRoot(document.getElementById('root')!).render(<React.StrictMode><ErrorBoundary><AuthProvider>+ <SessionGuard /><LanguageProvider><BrokerProvider><TimezoneProvider>diff --git a/fincept-terminal-desktop/src/services/auth/authApi.tsx b/fincept-terminal-desktop/src/services/auth/authApi.tsxindex 4ed56488a..1cc69ff5a 100644--- a/fincept-terminal-desktop/src/services/auth/authApi.tsx+++ b/fincept-terminal-desktop/src/services/auth/authApi.tsx@@ -13,6 +13,29 @@ const API_CONFIG = {const getApiEndpoint = (path: string) => `${API_CONFIG.BASE_URL}${path}`;+// Session token management — the API requires X-Session-Token for authenticated endpoints+let _sessionToken: string | null = null;++export const setSessionToken = (token: string | null) => {+ _sessionToken = token;+};++export const getSessionToken = (): string | null => _sessionToken;++/**+ * Returns auth headers (X-API-Key + X-Session-Token) for use in any service.+ * Pass apiKey explicitly; session token is auto-injected from global state.+ */+export const getAuthHeaders = (apiKey: string): Record<string, string> => {+ const headers: Record<string, string> = {+ 'X-API-Key': apiKey,+ };+ if (_sessionToken) {+ headers['X-Session-Token'] = _sessionToken;+ }+ return headers;+};+// API Response Typesinterface ApiResponse<T = any> {success: boolean;@@ -64,16 +87,11 @@ interface DeviceRegisterRequest {// Response Typesinterface LoginResponse {api_key: string;+ session_token: string;+ message?: string;username?: string;email?: string;credit_balance?: number;- user?: {- id: number;- username: string;- email: string;- account_type: string;- credit_balance: number;- };}interface UserProfileResponse {@@ -85,6 +103,13 @@ interface UserProfileResponse {is_verified: boolean;is_admin: boolean;mfa_enabled: boolean;+ phone?: string;+ country_code?: string;+ country?: string;+ notify_email?: boolean;+ notify_telegram?: boolean;+ notify_in_app?: boolean;+ telegram_connected?: boolean;created_at: string;last_login_at: string;}@@ -125,11 +150,16 @@ const makeApiRequest = async <T = any>(headers?: Record<string, string>): Promise<ApiResponse<T>> => {try {- const defaultHeaders = {+ const defaultHeaders: Record<string, string> = {'Content-Type': 'application/json',...headers};+ // Auto-inject session token for authenticated requests+ if (_sessionToken && !defaultHeaders['X-Session-Token']) {+ defaultHeaders['X-Session-Token'] = _sessionToken;+ }+const url = getApiEndpoint(endpoint);const controller = new AbortController();@@ -371,6 +401,7 @@ export class AuthApiService {});}+// Get login historystatic async getLoginHistory(apiKey: string, limit: number = 20, offset: number = 0): Promise<ApiResponse<any>> {return makeApiRequest('GET', `/user/login-history?limit=${limit}&offset=${offset}`, undefined, {@@ -619,9 +650,10 @@ export class AuthUtils {return session?.user_info?.account_type === 'free';}- // Check if user has active subscription+ // Check if user has active subscription (non-free account_type)static hasActiveSubscription(session: any): boolean {- return session?.subscription?.has_subscription === true;+ const accountType = (session?.subscription?.account_type || session?.user_info?.account_type || 'free').toLowerCase();+ return ['basic', 'standard', 'pro', 'enterprise'].includes(accountType);}// Get user display namediff --git a/fincept-terminal-desktop/src/services/auth/userApi.tsx b/fincept-terminal-desktop/src/services/auth/userApi.tsxindex bd95d89a4..d49126fc3 100644--- a/fincept-terminal-desktop/src/services/auth/userApi.tsx+++ b/fincept-terminal-desktop/src/services/auth/userApi.tsx@@ -2,10 +2,11 @@// User and Profile API Serviceimport { fetch as tauriFetch } from '@tauri-apps/plugin-http';+import { getSessionToken } from '@/services/auth/authApi';-// API Configuration - always use full URL for Tauri fetch+// API Configurationconst API_CONFIG = {- BASE_URL: 'https://api.fincept.in',+ BASE_URL: import.meta.env.DEV ? '/api' : 'https://api.fincept.in',};const getApiEndpoint = (path: string) => `${API_CONFIG.BASE_URL}${path}`;@@ -33,12 +34,18 @@ async function makeApiRequest<T = any>(const controller = new AbortController();const timeoutId = setTimeout(() => controller.abort(), REQUEST_TIMEOUT_MS);+ const headers: Record<string, string> = {+ 'Content-Type': 'application/json',+ 'X-API-Key': apiKey,+ };+ const sessionToken = getSessionToken();+ if (sessionToken) {+ headers['X-Session-Token'] = sessionToken;+ }+const options: RequestInit = {method,- headers: {- 'Content-Type': 'application/json',- 'X-API-Key': apiKey,- },+ headers,signal: controller.signal,};@@ -46,18 +53,23 @@ async function makeApiRequest<T = any>(options.body = JSON.stringify(body);}+ const url = getApiEndpoint(endpoint);+ console.log(`[UserAPI] ${method} ${url}`);+let response: Response;try {- response = await safeFetch(getApiEndpoint(endpoint), options);+ response = await safeFetch(url, options);} finally {clearTimeout(timeoutId);}const data = await response.json();+ console.log(`[UserAPI] ${method} ${endpoint} → ${response.status}`, data?.success);+return {success: response.ok,data: data,- error: response.ok ? undefined : data.detail || data.error || 'Request failed',+ error: response.ok ? undefined : data.detail || data.message || data.error || 'Request failed',status_code: response.status,};} catch (error) {diff --git a/fincept-terminal-desktop/src/services/chat/llmApi.ts b/fincept-terminal-desktop/src/services/chat/llmApi.tsindex 6b34977e6..22824b2a7 100644--- a/fincept-terminal-desktop/src/services/chat/llmApi.ts+++ b/fincept-terminal-desktop/src/services/chat/llmApi.ts@@ -4,6 +4,7 @@import { fetch } from '@tauri-apps/plugin-http';import { invoke } from '@tauri-apps/api/core';import { llmLogger } from '../core/loggerService';+import { getSessionToken } from '@/services/auth/authApi';// ── Fincept rate limiter + auth helper (TypeScript side) ─────────────────────// The Python subprocess has its own file-based rate limiter, but the Chat tab@@ -33,6 +34,8 @@ async function _finceptHeaders(apiKey?: string): Promise<Record<string, string>>}const headers: Record<string, string> = { 'Content-Type': 'application/json' };if (key) headers['X-API-Key'] = key;+ const sessionToken = getSessionToken();+ if (sessionToken) headers['X-Session-Token'] = sessionToken;return headers;}diff --git a/fincept-terminal-desktop/src/services/data-sources/chatModeApi.ts b/fincept-terminal-desktop/src/services/data-sources/chatModeApi.tsindex f3d4d0141..cd0697394 100644--- a/fincept-terminal-desktop/src/services/data-sources/chatModeApi.ts+++ b/fincept-terminal-desktop/src/services/data-sources/chatModeApi.ts@@ -2,6 +2,7 @@// API service for Chat Mode - integrates with Fincept APIimport { getSetting } from '../core/sqliteService';+import { getSessionToken } from '@/services/auth/authApi';export interface ChatModeMessage {id: string;@@ -67,7 +68,8 @@ class ChatModeApiService {method: 'POST',headers: {'Content-Type': 'application/json',- ...(this.apiKey && { 'X-API-Key': this.apiKey })+ ...(this.apiKey && { 'X-API-Key': this.apiKey }),+ ...(getSessionToken() ? { 'X-Session-Token': getSessionToken()! } : {})},body: JSON.stringify({ content: message })});@@ -110,7 +112,8 @@ class ChatModeApiService {method: 'POST',headers: {'Content-Type': 'application/json',- ...(this.apiKey && { 'X-API-Key': this.apiKey })+ ...(this.apiKey && { 'X-API-Key': this.apiKey }),+ ...(getSessionToken() ? { 'X-Session-Token': getSessionToken()! } : {})},body: JSON.stringify({ title: title || 'New Conversation' })});@@ -149,7 +152,8 @@ class ChatModeApiService {method: 'GET',headers: {'Content-Type': 'application/json',- ...(this.apiKey && { 'X-API-Key': this.apiKey })+ ...(this.apiKey && { 'X-API-Key': this.apiKey }),+ ...(getSessionToken() ? { 'X-Session-Token': getSessionToken()! } : {})}});@@ -187,7 +191,8 @@ class ChatModeApiService {method: 'POST',headers: {'Content-Type': 'application/json',- ...(this.apiKey && { 'X-API-Key': this.apiKey })+ ...(this.apiKey && { 'X-API-Key': this.apiKey }),+ ...(getSessionToken() ? { 'X-Session-Token': getSessionToken()! } : {})},body: JSON.stringify({ content: message })});@@ -229,7 +234,8 @@ class ChatModeApiService {method: 'GET',headers: {'Content-Type': 'application/json',- ...(this.apiKey && { 'X-API-Key': this.apiKey })+ ...(this.apiKey && { 'X-API-Key': this.apiKey }),+ ...(getSessionToken() ? { 'X-Session-Token': getSessionToken()! } : {})}});@@ -267,7 +273,8 @@ class ChatModeApiService {method: 'DELETE',headers: {'Content-Type': 'application/json',- ...(this.apiKey && { 'X-API-Key': this.apiKey })+ ...(this.apiKey && { 'X-API-Key': this.apiKey }),+ ...(getSessionToken() ? { 'X-Session-Token': getSessionToken()! } : {})}});@@ -302,7 +309,8 @@ class ChatModeApiService {method: 'PUT',headers: {'Content-Type': 'application/json',- ...(this.apiKey && { 'X-API-Key': this.apiKey })+ ...(this.apiKey && { 'X-API-Key': this.apiKey }),+ ...(getSessionToken() ? { 'X-Session-Token': getSessionToken()! } : {})},body: JSON.stringify({ title })});@@ -338,7 +346,8 @@ class ChatModeApiService {method: 'DELETE',headers: {'Content-Type': 'application/json',- ...(this.apiKey && { 'X-API-Key': this.apiKey })+ ...(this.apiKey && { 'X-API-Key': this.apiKey }),+ ...(getSessionToken() ? { 'X-Session-Token': getSessionToken()! } : {})},body: JSON.stringify({ session_uuids: sessionUuids })});@@ -374,7 +383,8 @@ class ChatModeApiService {method: 'PUT',headers: {'Content-Type': 'application/json',- ...(this.apiKey && { 'X-API-Key': this.apiKey })+ ...(this.apiKey && { 'X-API-Key': this.apiKey }),+ ...(getSessionToken() ? { 'X-Session-Token': getSessionToken()! } : {})}});@@ -409,7 +419,8 @@ class ChatModeApiService {method: 'GET',headers: {'Content-Type': 'application/json',- ...(this.apiKey && { 'X-API-Key': this.apiKey })+ ...(this.apiKey && { 'X-API-Key': this.apiKey }),+ ...(getSessionToken() ? { 'X-Session-Token': getSessionToken()! } : {})}});@@ -444,7 +455,8 @@ class ChatModeApiService {method: 'GET',headers: {'Content-Type': 'application/json',- ...(this.apiKey && { 'X-API-Key': this.apiKey })+ ...(this.apiKey && { 'X-API-Key': this.apiKey }),+ ...(getSessionToken() ? { 'X-Session-Token': getSessionToken()! } : {})}});@@ -479,7 +491,8 @@ class ChatModeApiService {method: 'POST',headers: {'Content-Type': 'application/json',- ...(this.apiKey && { 'X-API-Key': this.apiKey })+ ...(this.apiKey && { 'X-API-Key': this.apiKey }),+ ...(getSessionToken() ? { 'X-Session-Token': getSessionToken()! } : {})},body: JSON.stringify({ session_uuids: sessionUuids || [] })});@@ -515,7 +528,8 @@ class ChatModeApiService {method: 'GET',headers: {'Content-Type': 'application/json',- ...(this.apiKey && { 'X-API-Key': this.apiKey })+ ...(this.apiKey && { 'X-API-Key': this.apiKey }),+ ...(getSessionToken() ? { 'X-Session-Token': getSessionToken()! } : {})}});@@ -550,7 +564,8 @@ class ChatModeApiService {method: 'POST',headers: {'Content-Type': 'application/json',- ...(this.apiKey && { 'X-API-Key': this.apiKey })+ ...(this.apiKey && { 'X-API-Key': this.apiKey }),+ ...(getSessionToken() ? { 'X-Session-Token': getSessionToken()! } : {})},body: JSON.stringify({ prompt })});@@ -586,7 +601,8 @@ class ChatModeApiService {method: 'POST',headers: {'Content-Type': 'application/json',- ...(this.apiKey && { 'X-API-Key': this.apiKey })+ ...(this.apiKey && { 'X-API-Key': this.apiKey }),+ ...(getSessionToken() ? { 'X-Session-Token': getSessionToken()! } : {})}});diff --git a/fincept-terminal-desktop/src/services/forum/forumApi.tsx b/fincept-terminal-desktop/src/services/forum/forumApi.tsxindex 8428a4b88..d02d82af4 100644--- a/fincept-terminal-desktop/src/services/forum/forumApi.tsx+++ b/fincept-terminal-desktop/src/services/forum/forumApi.tsx@@ -2,6 +2,7 @@// Forum API service for handling all forum-related API callsimport { fetch } from '@tauri-apps/plugin-http';+import { getSessionToken } from '@/services/auth/authApi';// API Configuration - matches your existing auth setupconst API_CONFIG = {@@ -121,6 +122,10 @@ const makeForumRequest = async <T = any>(if (apiKey) {headers['X-API-Key'] = apiKey;}+ const sessionToken = getSessionToken();+ if (sessionToken) {+ headers['X-Session-Token'] = sessionToken;+ }if (deviceId) {headers['X-Device-ID'] = deviceId;}diff --git a/fincept-terminal-desktop/src/services/forum/supportApi.tsx b/fincept-terminal-desktop/src/services/forum/supportApi.tsxindex f8be6f09a..6c440352c 100644--- a/fincept-terminal-desktop/src/services/forum/supportApi.tsx+++ b/fincept-terminal-desktop/src/services/forum/supportApi.tsx@@ -2,6 +2,7 @@// Support Ticket API Serviceimport { fetch } from '@tauri-apps/plugin-http';+import { getSessionToken } from '@/services/auth/authApi';// API Configurationconst API_CONFIG = {@@ -30,6 +31,7 @@ async function makeApiRequest<T = any>(headers: {'Content-Type': 'application/json',...(apiKey && { 'X-API-Key': apiKey }),+ ...(getSessionToken() ? { 'X-Session-Token': getSessionToken()! } : {}),},};diff --git a/fincept-terminal-desktop/src/services/maritime/marineApi.ts b/fincept-terminal-desktop/src/services/maritime/marineApi.tsindex b1b65e8e6..ea2757b34 100644--- a/fincept-terminal-desktop/src/services/maritime/marineApi.ts+++ b/fincept-terminal-desktop/src/services/maritime/marineApi.ts@@ -2,6 +2,7 @@// Marine Vessel Tracking API service for handling all marine-related API callsimport { fetch } from '@tauri-apps/plugin-http';+import { getSessionToken } from '@/services/auth/authApi';// API Configurationconst API_CONFIG = {@@ -148,6 +149,10 @@ async function makeApiRequest<T>(if (apiKey) {headers['X-API-Key'] = apiKey;}+ const sessionToken = getSessionToken();+ if (sessionToken) {+ headers['X-Session-Token'] = sessionToken;+ }const response = await fetch(endpoint, {...options,diff --git a/fincept-terminal-desktop/src/services/marketplace/excelMarketplaceService.ts b/fincept-terminal-desktop/src/services/marketplace/excelMarketplaceService.tsindex d9081d7fd..04f8f2542 100644--- a/fincept-terminal-desktop/src/services/marketplace/excelMarketplaceService.ts+++ b/fincept-terminal-desktop/src/services/marketplace/excelMarketplaceService.ts@@ -2,6 +2,7 @@// Excel Marketplace API service for handling Excel file marketplace endpointsimport { fetch } from '@tauri-apps/plugin-http';+import { getSessionToken } from '@/services/auth/authApi';// API Configurationconst API_CONFIG = {@@ -101,6 +102,10 @@ const makeApiRequest = async <T = any>('Content-Type': 'application/json',...headers};+ const sessionToken = getSessionToken();+ if (sessionToken && !defaultHeaders['X-Session-Token']) {+ defaultHeaders['X-Session-Token'] = sessionToken;+ }const url = getApiEndpoint(endpoint);@@ -298,7 +303,8 @@ export class ExcelMarketplaceService {const response = await fetch(url, {method: 'GET',headers: {- 'X-API-Key': apiKey+ 'X-API-Key': apiKey,+ ...(getSessionToken() ? { 'X-Session-Token': getSessionToken()! } : {}),},mode: 'cors',});diff --git a/fincept-terminal-desktop/src/services/markets/marketApi.ts b/fincept-terminal-desktop/src/services/markets/marketApi.tsindex 8fd6e201c..c4c9b0271 100644--- a/fincept-terminal-desktop/src/services/markets/marketApi.ts+++ b/fincept-terminal-desktop/src/services/markets/marketApi.ts@@ -3,6 +3,7 @@// Complements marketDataService.ts (which uses Tauri invoke/Rust bridge)import { fetch as tauriFetch } from '@tauri-apps/plugin-http';+import { getSessionToken } from '@/services/auth/authApi';const API_CONFIG = {BASE_URL: import.meta.env.DEV ? '/api' : 'https://api.fincept.in',@@ -27,6 +28,8 @@ async function makeApiRequest<T = any>('Content-Type': 'application/json',};if (apiKey) headers['X-API-Key'] = apiKey;+ const sessionToken = getSessionToken();+ if (sessionToken) headers['X-Session-Token'] = sessionToken;const response = await safeFetch(getApiEndpoint(endpoint), { method: 'GET', headers });const data = await response.json();diff --git a/fincept-terminal-desktop/src/services/mcp/internal/EconomicsMCPBridge.ts b/fincept-terminal-desktop/src/services/mcp/internal/EconomicsMCPBridge.tsindex 1287f5b8b..fd686a91a 100644--- a/fincept-terminal-desktop/src/services/mcp/internal/EconomicsMCPBridge.ts+++ b/fincept-terminal-desktop/src/services/mcp/internal/EconomicsMCPBridge.ts@@ -2,6 +2,7 @@// Provides AI access to: CEIC economic series, economic calendar, WGB sovereign dataimport { terminalMCPProvider } from './TerminalMCPProvider';+import { getSessionToken } from '@/services/auth/authApi';const BASE_URL = 'https://api.fincept.in';@@ -20,7 +21,7 @@ const CONTEXT_KEYS = [async function finceptFetch(path: string, apiKey: string): Promise<any> {const res = await fetch(`${BASE_URL}${path}`, {- headers: { 'X-API-Key': apiKey, 'Accept': 'application/json' },+ headers: { 'X-API-Key': apiKey, 'Accept': 'application/json', ...(getSessionToken() ? { 'X-Session-Token': getSessionToken()! } : {}) },});if (!res.ok) {const body = await res.text().catch(() => '');diff --git a/fincept-terminal-desktop/src/services/mcp/internal/QuantLibMCPBridge.ts b/fincept-terminal-desktop/src/services/mcp/internal/QuantLibMCPBridge.tsindex 9917a0992..d931b60fe 100644--- a/fincept-terminal-desktop/src/services/mcp/internal/QuantLibMCPBridge.ts+++ b/fincept-terminal-desktop/src/services/mcp/internal/QuantLibMCPBridge.ts@@ -1,6 +1,7 @@// QuantLib MCP Bridge - Manages API key and provides shared utilities for QuantLib toolsimport { terminalMCPProvider } from './TerminalMCPProvider';+import { getSessionToken } from '@/services/auth/authApi';const QUANTLIB_BASE_URL = 'https://api.fincept.in';@@ -17,6 +18,8 @@ export async function quantlibApiCall<T = any>(const headers: Record<string, string> = { 'Content-Type': 'application/json' };if (apiKey) headers['X-API-Key'] = apiKey;+ const sessionToken = getSessionToken();+ if (sessionToken) headers['X-Session-Token'] = sessionToken;const opts: RequestInit = { method, headers };diff --git a/fincept-terminal-desktop/src/services/news/newsAnalysisService.ts b/fincept-terminal-desktop/src/services/news/newsAnalysisService.tsindex aae2b89b9..b94e29fd6 100644--- a/fincept-terminal-desktop/src/services/news/newsAnalysisService.ts+++ b/fincept-terminal-desktop/src/services/news/newsAnalysisService.ts@@ -3,6 +3,8 @@* AI-powered news article analysis via Fincept Backend API*/+import { getSessionToken } from '@/services/auth/authApi';+const API_BASE_URL = 'https://api.fincept.in';export interface NewsAnalysisRequest {@@ -104,6 +106,7 @@ export async function analyzeNewsArticle(headers: {'Content-Type': 'application/json','X-API-Key': apiKey,+ ...(getSessionToken() ? { 'X-Session-Token': getSessionToken()! } : {}),},body: JSON.stringify({ url }),});diff --git a/fincept-terminal-desktop/src/services/news/newsEventsService.ts b/fincept-terminal-desktop/src/services/news/newsEventsService.tsindex 709df7ed2..09ee46040 100644--- a/fincept-terminal-desktop/src/services/news/newsEventsService.ts+++ b/fincept-terminal-desktop/src/services/news/newsEventsService.ts@@ -1,3 +1,5 @@+import { getSessionToken } from '@/services/auth/authApi';+const API_BASE = 'https://api.fincept.in';export interface NewsEvent {@@ -61,6 +63,7 @@ export class NewsEventsService {method: 'GET',headers: {'X-API-Key': apiKey,+ ...(getSessionToken() ? { 'X-Session-Token': getSessionToken()! } : {}),'accept': 'application/json'}});@@ -90,6 +93,7 @@ export class NewsEventsService {method: 'GET',headers: {'X-API-Key': apiKey,+ ...(getSessionToken() ? { 'X-Session-Token': getSessionToken()! } : {}),'accept': 'application/json'}});@@ -119,6 +123,7 @@ export class NewsEventsService {method: 'GET',headers: {'X-API-Key': apiKey,+ ...(getSessionToken() ? { 'X-Session-Token': getSessionToken()! } : {}),'accept': 'application/json'}});@@ -162,6 +167,7 @@ export class NewsEventsService {method: 'GET',headers: {'X-API-Key': apiKey,+ ...(getSessionToken() ? { 'X-Session-Token': getSessionToken()! } : {}),'accept': 'application/json'}});diff --git a/fincept-terminal-desktop/src/services/payment/paymentApi.tsx b/fincept-terminal-desktop/src/services/payment/paymentApi.tsxindex 207575785..b8541bd94 100644--- a/fincept-terminal-desktop/src/services/payment/paymentApi.tsx+++ b/fincept-terminal-desktop/src/services/payment/paymentApi.tsx@@ -2,6 +2,7 @@// Payment API service for handling all payment-related API calls with in-app payment window supportimport { fetch } from '@tauri-apps/plugin-http';+import { getSessionToken } from '@/services/auth/authApi';// API Configurationconst PAYMENT_API_CONFIG = {@@ -69,25 +70,13 @@ interface CheckoutResponse {}interface UserSubscriptionResponse {- has_subscription: boolean;- subscription?: {- subscription_uuid: string;- plan: {- name: string;- plan_id: string;- price: number;- };- status: string;- current_period_start: string;- current_period_end: string;- days_remaining: number;- cancel_at_period_end: boolean;- usage: {- api_calls_used: number;- api_calls_limit: number | string;- usage_percentage: number;- };- };+ user_id: number;+ account_type: string;+ credit_balance: number;+ credits_expire_at: string | null;+ support_type: string;+ last_credit_purchase_at: string | null;+ created_at: string;}interface PaymentSuccessResponse {@@ -126,11 +115,17 @@ const makePaymentApiRequest = async <T = any>(headers?: Record<string, string>): Promise<PaymentApiResponse<T>> => {try {- const defaultHeaders = {+ const defaultHeaders: Record<string, string> = {'Content-Type': 'application/json',...headers};+ // Auto-inject session token for authenticated requests+ const sessionToken = getSessionToken();+ if (sessionToken && !defaultHeaders['X-Session-Token']) {+ defaultHeaders['X-Session-Token'] = sessionToken;+ }+const url = getPaymentApiEndpoint(endpoint);const config: RequestInit = {@@ -299,9 +294,22 @@ export class PaymentApiService {// Get user's current subscription - Updated to use new endpointstatic async getUserSubscription(apiKey: string): Promise<PaymentApiResponse<UserSubscriptionResponse>> {- return makePaymentApiRequest<UserSubscriptionResponse>('GET', '/cashfree/subscription', undefined, {+ const response = await makePaymentApiRequest<any>('GET', '/cashfree/subscription', undefined, {'X-API-Key': apiKey});++ if (response.success && response.data) {+ // Backend returns: { success, message, data: { user_id, account_type, ... } }+ // makePaymentApiRequest puts raw JSON in data, so actual data is at response.data.data+ const subData = response.data.data || response.data;+ return {+ success: true,+ data: subData,+ status_code: response.status_code+ };+ }++ return response as PaymentApiResponse<UserSubscriptionResponse>;}// Get user's usage detailsdiff --git a/fincept-terminal-desktop/src/services/sentinels/sentinelApi.ts b/fincept-terminal-desktop/src/services/sentinels/sentinelApi.tsindex c88cf1705..3e9064531 100644--- a/fincept-terminal-desktop/src/services/sentinels/sentinelApi.ts+++ b/fincept-terminal-desktop/src/services/sentinels/sentinelApi.ts@@ -2,6 +2,7 @@// Endpoints: /sentinels/*import { fetch as tauriFetch } from '@tauri-apps/plugin-http';+import { getSessionToken } from '@/services/auth/authApi';const API_CONFIG = {BASE_URL: import.meta.env.DEV ? '/api' : 'https://api.fincept.in',@@ -24,12 +25,16 @@ async function makeApiRequest<T = any>(body?: any): Promise<ApiResponse<T>> {try {+ const headers: Record<string, string> = {+ 'Content-Type': 'application/json',+ 'X-API-Key': apiKey,+ };+ const sessionToken = getSessionToken();+ if (sessionToken) headers['X-Session-Token'] = sessionToken;+const options: RequestInit = {method,- headers: {- 'Content-Type': 'application/json',- 'X-API-Key': apiKey,- },+ headers,};if (body && (method === 'POST' || method === 'PUT')) {diff --git a/fincept-terminal-desktop/src/services/support/supportApi.ts b/fincept-terminal-desktop/src/services/support/supportApi.tsindex 489b0635c..af1caea5b 100644--- a/fincept-terminal-desktop/src/services/support/supportApi.ts+++ b/fincept-terminal-desktop/src/services/support/supportApi.ts@@ -1,6 +1,7 @@// Support API Service - Feedback, Contact, Newsletter endpointsimport { fetch as tauriFetch } from '@tauri-apps/plugin-http';+import { getSessionToken } from '@/services/auth/authApi';const API_BASE_URL = 'https://api.fincept.in';@@ -82,6 +83,7 @@ export async function submitFeedback(data: FeedbackFormData, apiKey: string): Prheaders: {'Content-Type': 'application/json','X-API-Key': apiKey,+ ...(getSessionToken() ? { 'X-Session-Token': getSessionToken()! } : {}),},body: JSON.stringify({rating: data.rating,diff --git a/fincept-terminal-desktop/src/services/trading/tradeService.ts b/fincept-terminal-desktop/src/services/trading/tradeService.tsindex 2b08748c4..95a22667d 100644--- a/fincept-terminal-desktop/src/services/trading/tradeService.ts+++ b/fincept-terminal-desktop/src/services/trading/tradeService.ts@@ -3,6 +3,7 @@// import { loggerService } from './loggerService';import { getSetting } from '../core/sqliteService';+import { getSessionToken } from '@/services/auth/authApi';const API_BASE = 'https://api.fincept.in';@@ -123,6 +124,7 @@ class TradeService {headers: {'X-API-Key': apiKey,'Content-Type': 'application/json',+ ...(getSessionToken() ? { 'X-Session-Token': getSessionToken()! } : {}),},});