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
crpyto tab updated
tilakpatel22375d68a21787
diff --git a/fincept-cpp/.github/workflows/build.yml b/fincept-cpp/.github/workflows/build.ymlnew file mode 100644index 000000000..122c15cdf--- /dev/null+++ b/fincept-cpp/.github/workflows/build.yml@@ -0,0 +1,86 @@+name: Build++on:+ push:+ branches: [main]+ pull_request:+ branches: [main]++env:+ VCPKG_DEFAULT_TRIPLET: x64-windows+ VCPKG_BINARY_SOURCES: "clear;x-gha,readwrite"++jobs:+ build-windows:+ runs-on: windows-latest+ steps:+ - uses: actions/checkout@v4++ - name: Export GitHub Actions cache variables+ 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 || '');++ - name: Setup vcpkg+ uses: lukka/run-vcpkg@v11+ with:+ vcpkgGitCommitId: '01f602195983451bc83e72f4214af2cbc495aa94'++ - name: Configure CMake+ run: >+ cmake -B build+ -G "Visual Studio 17 2022"+ -DCMAKE_TOOLCHAIN_FILE=${{ github.workspace }}/vcpkg/scripts/buildsystems/vcpkg.cmake+ -DFINCEPT_ENABLE_MPV=OFF+ -DFINCEPT_UNITY_BUILD=ON+ shell: bash++ - name: Build+ run: cmake --build build --config Release --parallel+ shell: bash++ - name: Upload artifact+ uses: actions/upload-artifact@v4+ with:+ name: FinceptTerminal-windows+ path: |+ build/Release/FinceptTerminal.exe+ build/Release/fonts/+ build/Release/resources/+ build/Release/scripts/++ build-linux:+ runs-on: ubuntu-latest+ steps:+ - uses: actions/checkout@v4++ - name: Install system dependencies+ run: |+ sudo apt-get update+ sudo apt-get install -y \+ libglfw3-dev \+ libgl-dev \+ libxrandr-dev \+ libxinerama-dev \+ libxcursor-dev \+ libxi-dev \+ libxkbcommon-dev \+ pkg-config++ - name: Setup vcpkg+ uses: lukka/run-vcpkg@v11+ with:+ vcpkgGitCommitId: '01f602195983451bc83e72f4214af2cbc495aa94'++ - name: Configure CMake+ run: >+ cmake -B build+ -DCMAKE_BUILD_TYPE=Release+ -DCMAKE_TOOLCHAIN_FILE=${{ github.workspace }}/vcpkg/scripts/buildsystems/vcpkg.cmake+ -DFINCEPT_ENABLE_MPV=OFF+ -DFINCEPT_UNITY_BUILD=ON++ - name: Build+ run: cmake --build build --parallel $(nproc)diff --git a/fincept-cpp/.gitignore b/fincept-cpp/.gitignoreindex 8af5b7d8c..6fa3ccd59 100644--- a/fincept-cpp/.gitignore+++ b/fincept-cpp/.gitignore@@ -22,3 +22,10 @@ Thumbs.db# vcpkg installed packages (managed by vcpkg)vcpkg_installed/++# Third-party prebuilt binaries (too large for git — download separately)+third_party/++# Debug artifacts+*.log+stderr_out.txtdiff --git a/fincept-cpp/CMakeLists.txt b/fincept-cpp/CMakeLists.txtindex d8e4cc905..3d6d6e468 100644--- a/fincept-cpp/CMakeLists.txt+++ b/fincept-cpp/CMakeLists.txt@@ -5,6 +5,16 @@ set(CMAKE_CXX_STANDARD 20)set(CMAKE_CXX_STANDARD_REQUIRED ON)set(CMAKE_EXPORT_COMPILE_COMMANDS ON)+# =============================================================================+# Build acceleration: Unity builds (merge .cpp files into batches)+# =============================================================================+option(FINCEPT_UNITY_BUILD "Enable unity (jumbo) builds for faster compilation" ON)+if(FINCEPT_UNITY_BUILD)+ set(CMAKE_UNITY_BUILD ON)+ set(CMAKE_UNITY_BUILD_BATCH_SIZE 12)+endif()++# =============================================================================# Dependencies via vcpkg# =============================================================================@@ -21,6 +31,41 @@ find_path(STB_INCLUDE_DIRS "stb_image.h")# OpenGLfind_package(OpenGL REQUIRED)+# =============================================================================+# Optional: libmpv for inline video playback (YouTube widget)+# Cross-platform: Windows uses third_party/mpv, Linux/macOS use pkg-config+# =============================================================================+option(FINCEPT_ENABLE_MPV "Enable mpv video playback in YouTube widget" ON)+set(FINCEPT_HAS_MPV FALSE)+set(MPV_DIR "${CMAKE_CURRENT_SOURCE_DIR}/third_party/mpv")++if(FINCEPT_ENABLE_MPV)+ if(WIN32 AND EXISTS "${MPV_DIR}/include/mpv/client.h")+ # Windows: use prebuilt library from third_party/mpv+ set(FINCEPT_HAS_MPV TRUE)+ set(MPV_INCLUDE_DIR "${MPV_DIR}/include")+ set(MPV_LIBRARY "${MPV_DIR}/mpv.lib")+ message(STATUS "libmpv found (Windows prebuilt): ${MPV_DIR}")+ elseif(NOT WIN32)+ # Linux/macOS: find via pkg-config+ find_package(PkgConfig QUIET)+ if(PkgConfig_FOUND)+ pkg_check_modules(MPV QUIET mpv)+ if(MPV_FOUND)+ set(FINCEPT_HAS_MPV TRUE)+ set(MPV_INCLUDE_DIR ${MPV_INCLUDE_DIRS})+ set(MPV_LIBRARY ${MPV_LIBRARIES})+ message(STATUS "libmpv found (pkg-config): ${MPV_LIBRARIES}")+ endif()+ endif()+ if(NOT FINCEPT_HAS_MPV)+ message(STATUS "libmpv not found — install libmpv-dev (apt) or mpv (brew). YouTube widget will use link-only mode")+ endif()+ else()+ message(STATUS "libmpv not found at ${MPV_DIR} — YouTube widget will use link-only mode")+ endif()+endif()+# =============================================================================# Sources# =============================================================================@@ -103,6 +148,10 @@ set(SOURCESsrc/screens/node_editor/node_editor_screen.cppsrc/screens/node_editor/workflow_templates.cpp+ # Screens — AI Chat+ src/screens/ai_chat/llm_service.cpp+ src/screens/ai_chat/ai_chat_screen.cpp+# Screens — Agent Studiosrc/screens/agent_studio/agent_service.cppsrc/screens/agent_studio/agent_discovery.cpp@@ -206,15 +255,38 @@ set(SOURCES# Trading — Unified Tradingsrc/trading/unified_trading.cpp+ # Screens — AI Quant Lab+ src/screens/ai_quant_lab/ai_quant_lab_api.cpp+ src/screens/ai_quant_lab/ai_quant_lab_screen.cpp+# Screens — Code Editorsrc/screens/code_editor/notebook_io.cppsrc/screens/code_editor/code_editor_screen.cpp+ # Media — mpv video player+ src/media/mpv_player.cpp+# Python bridgesrc/python/python_runner.cppsrc/python/setup_manager.cppsrc/python/setup_screen.cpp+ # MCP — Model Context Protocol+ src/mcp/mcp_provider.cpp+ src/mcp/mcp_client.cpp+ src/mcp/mcp_manager.cpp+ src/mcp/mcp_service.cpp+ src/mcp/mcp_init.cpp+ src/mcp/tools/navigation_tools.cpp+ src/mcp/tools/market_data_tools.cpp+ src/mcp/tools/settings_tools.cpp+ src/mcp/tools/portfolio_tools.cpp++ # Screens — Data Mapping+ src/screens/data_mapping/data_mapping_engine.cpp+ src/screens/data_mapping/data_mapping_db.cpp+ src/screens/data_mapping/data_mapping_screen.cpp+# Core (continued)src/core/device_id.cpp)@@ -224,6 +296,28 @@ set(SOURCES# =============================================================================add_executable(${PROJECT_NAME} ${SOURCES})+# Files that conflict under unity builds (ODR: duplicate static symbols across files)+set_source_files_properties(+ src/screens/gov_data/providers/us_treasury.cpp+ src/screens/gov_data/providers/us_congress.cpp+ src/screens/gov_data/providers/canada_gov.cpp+ src/screens/gov_data/providers/openafrica.cpp+ src/screens/gov_data/providers/spain_data.cpp+ src/screens/gov_data/providers/pxweb.cpp+ src/screens/gov_data/providers/swiss_gov.cpp+ src/screens/gov_data/providers/french_gov.cpp+ src/screens/gov_data/providers/universal_ckan.cpp+ src/screens/gov_data/providers/data_gov_hk.cpp+ src/screens/research/research_screen.cpp+ src/screens/research/overview_panel.cpp+ src/screens/research/financials_panel.cpp+ src/screens/research/analysis_panel.cpp+ src/screens/research/technicals_panel.cpp+ src/screens/research/news_panel.cpp+ src/media/mpv_player.cpp+ PROPERTIES SKIP_UNITY_BUILD_INCLUSION ON+)+target_include_directories(${PROJECT_NAME} PRIVATE${CMAKE_CURRENT_SOURCE_DIR}/src${CMAKE_CURRENT_SOURCE_DIR}/fonts@@ -231,11 +325,59 @@ target_include_directories(${PROJECT_NAME} PRIVATE${STB_INCLUDE_DIRS})+# mpv include path+if(FINCEPT_HAS_MPV)+ target_include_directories(${PROJECT_NAME} PRIVATE ${MPV_INCLUDE_DIR})+endif()++# =============================================================================+# Precompiled Header (PCH) — compiles heavy headers once+# =============================================================================+option(FINCEPT_USE_PCH "Enable precompiled headers for faster builds" ON)+if(FINCEPT_USE_PCH)+ target_precompile_headers(${PROJECT_NAME} PRIVATE+ # C++ standard library (used everywhere)+ <string>+ <vector>+ <unordered_map>+ <unordered_set>+ <mutex>+ <thread>+ <atomic>+ <functional>+ <chrono>+ <memory>+ <optional>+ <algorithm>+ <cstdio>+ <cmath>+ <sstream>+ <fstream>+ # Heavy third-party headers+ <nlohmann/json.hpp>+ )+endif()++# =============================================================================+# Compiler cache (sccache/ccache) — caches compiled objects across builds+# =============================================================================+find_program(CCACHE_PROGRAM ccache)+find_program(SCCACHE_PROGRAM sccache)+if(SCCACHE_PROGRAM)+ message(STATUS "Using sccache: ${SCCACHE_PROGRAM}")+ set(CMAKE_C_COMPILER_LAUNCHER ${SCCACHE_PROGRAM})+ set(CMAKE_CXX_COMPILER_LAUNCHER ${SCCACHE_PROGRAM})+elseif(CCACHE_PROGRAM)+ message(STATUS "Using ccache: ${CCACHE_PROGRAM}")+ set(CMAKE_C_COMPILER_LAUNCHER ${CCACHE_PROGRAM})+ set(CMAKE_CXX_COMPILER_LAUNCHER ${CCACHE_PROGRAM})+endif()+# =============================================================================# Compiler warnings (enable for code quality, CI enforcement)# =============================================================================if(MSVC)- target_compile_options(${PROJECT_NAME} PRIVATE /W3 /FS)+ target_compile_options(${PROJECT_NAME} PRIVATE /W3 /FS /MP)target_compile_definitions(${PROJECT_NAME} PRIVATE _CRT_SECURE_NO_WARNINGS)else()target_compile_options(${PROJECT_NAME} PRIVATE -Wall -Wextra -Wpedantic)@@ -247,6 +389,11 @@ target_compile_definitions(${PROJECT_NAME} PRIVATEIMGUI_ENABLE_FREETYPE)+# mpv compile definition+if(FINCEPT_HAS_MPV)+ target_compile_definitions(${PROJECT_NAME} PRIVATE FINCEPT_HAS_MPV)+endif()+target_link_libraries(${PROJECT_NAME} PRIVATEglfwOpenGL::GL@@ -260,6 +407,14 @@ target_link_libraries(${PROJECT_NAME} PRIVATEyoga::yogacore)+# mpv link library+if(FINCEPT_HAS_MPV)+ target_link_libraries(${PROJECT_NAME} PRIVATE ${MPV_LIBRARY})+ if(NOT WIN32)+ target_link_directories(${PROJECT_NAME} PRIVATE ${MPV_LIBRARY_DIRS})+ endif()+endif()+# =============================================================================# Platform-specific# =============================================================================@@ -290,6 +445,17 @@ elseif(UNIX))endif()+# =============================================================================+# Copy mpv DLL to build directory (Windows only — Linux/macOS use system lib)+# =============================================================================+if(FINCEPT_HAS_MPV AND WIN32)+ add_custom_command(TARGET ${PROJECT_NAME} POST_BUILD+ COMMAND ${CMAKE_COMMAND} -E copy_if_different+ "${MPV_DIR}/libmpv-2.dll"+ $<TARGET_FILE_DIR:${PROJECT_NAME}>+ )+endif()+# =============================================================================# Copy fonts to build directory# =============================================================================diff --git a/fincept-cpp/CMakePresets.json b/fincept-cpp/CMakePresets.jsonindex 7707af132..4d4967e96 100644--- a/fincept-cpp/CMakePresets.json+++ b/fincept-cpp/CMakePresets.json@@ -4,7 +4,7 @@"configurePresets": [{"name": "default",- "displayName": "Default (vcpkg)",+ "displayName": "Default (Ninja + vcpkg)","generator": "Ninja","binaryDir": "${sourceDir}/build","cacheVariables": {@@ -27,6 +27,15 @@"cacheVariables": {"CMAKE_BUILD_TYPE": "Release"}+ },+ {+ "name": "msvc-release",+ "displayName": "MSVC Release (Visual Studio)",+ "generator": "Visual Studio 17 2022",+ "binaryDir": "${sourceDir}/build-msvc",+ "cacheVariables": {+ "CMAKE_TOOLCHAIN_FILE": "$env{VCPKG_ROOT}/scripts/buildsystems/vcpkg.cmake"+ }}],"buildPresets": [@@ -41,6 +50,11 @@{"name": "release","configurePreset": "release"+ },+ {+ "name": "msvc-release",+ "configurePreset": "msvc-release",+ "configuration": "Release"}]}diff --git a/fincept-cpp/scripts/Analytics/economics/business_cycle.py b/fincept-cpp/scripts/Analytics/economics/business_cycle.pynew file mode 100644index 000000000..d842c9a9d--- /dev/null+++ b/fincept-cpp/scripts/Analytics/economics/business_cycle.py@@ -0,0 +1,133 @@+"""+Business Cycle Indicators — Fetch key economic indicators via yfinance/FRED proxies.+Input: JSON via stdin (can be empty {})+Output: JSON with current economic indicators+"""+import sys+import json+import numpy as np+++def convert_numpy(obj):+ if isinstance(obj, dict):+ return {k: convert_numpy(v) for k, v in obj.items()}+ elif isinstance(obj, (list, tuple)):+ return [convert_numpy(v) for v in obj]+ elif isinstance(obj, (np.integer,)):+ return int(obj)+ elif isinstance(obj, (np.floating,)):+ v = float(obj)+ if np.isnan(v) or np.isinf(v):+ return 0.0+ return v+ elif isinstance(obj, np.ndarray):+ return [convert_numpy(x) for x in obj]+ elif isinstance(obj, float):+ if np.isnan(obj) or np.isinf(obj):+ return 0.0+ return obj+++def get_indicators():+ """Fetch market-based economic indicators using yfinance"""+ import yfinance as yf++ indicators = {}++ # Market proxies for economic indicators+ tickers = {+ "^GSPC": "sp500",+ "^VIX": "vix",+ "^TNX": "treasury_10y_yield",+ "^IRX": "treasury_3m_yield",+ "^TYX": "treasury_30y_yield",+ "GC=F": "gold_price",+ "CL=F": "crude_oil_price",+ "DX-Y.NYB": "us_dollar_index",+ }++ for ticker, name in tickers.items():+ try:+ t = yf.Ticker(ticker)+ info = t.fast_info+ price = float(getattr(info, "last_price", 0) or 0)+ prev = float(getattr(info, "previous_close", 0) or 0)+ if price > 0:+ change_pct = ((price - prev) / prev * 100) if prev > 0 else 0+ indicators[name] = price+ indicators[f"{name}_change_pct"] = round(change_pct, 4)+ except Exception:+ pass++ # Yield curve spread (10Y - 3M) — recession indicator+ y10 = indicators.get("treasury_10y_yield", 0)+ y3m = indicators.get("treasury_3m_yield", 0)+ if y10 > 0 and y3m > 0:+ indicators["yield_curve_spread_10y_3m"] = round(y10 - y3m, 4)+ indicators["yield_curve_inverted"] = "Yes" if y10 < y3m else "No"++ # 30Y - 10Y spread+ y30 = indicators.get("treasury_30y_yield", 0)+ if y30 > 0 and y10 > 0:+ indicators["yield_curve_spread_30y_10y"] = round(y30 - y10, 4)++ # Gold/Oil ratio+ gold = indicators.get("gold_price", 0)+ oil = indicators.get("crude_oil_price", 0)+ if gold > 0 and oil > 0:+ indicators["gold_oil_ratio"] = round(gold / oil, 2)++ # S&P 500 stats+ try:+ sp = yf.download("^GSPC", period="1y", interval="1d", progress=False)+ if sp is not None and not sp.empty:+ close = sp["Close"]+ if hasattr(close, "values"):+ vals = close.values.flatten()+ current = float(vals[-1])+ high_52w = float(np.max(vals))+ low_52w = float(np.min(vals))+ sma_200 = float(np.mean(vals[-200:])) if len(vals) >= 200 else float(np.mean(vals))+ sma_50 = float(np.mean(vals[-50:])) if len(vals) >= 50 else float(np.mean(vals))+ indicators["sp500_52w_high"] = round(high_52w, 2)+ indicators["sp500_52w_low"] = round(low_52w, 2)+ indicators["sp500_sma_200"] = round(sma_200, 2)+ indicators["sp500_sma_50"] = round(sma_50, 2)+ indicators["sp500_above_sma200"] = "Yes" if current > sma_200 else "No"+ indicators["sp500_ytd_return_pct"] = round(+ (current / float(vals[0]) - 1) * 100, 2+ )+ except Exception:+ pass++ # VIX interpretation+ vix = indicators.get("vix", 0)+ if vix > 0:+ if vix < 15:+ indicators["market_sentiment"] = "Low Fear (Complacency)"+ elif vix < 20:+ indicators["market_sentiment"] = "Normal"+ elif vix < 30:+ indicators["market_sentiment"] = "Elevated Fear"+ else:+ indicators["market_sentiment"] = "Extreme Fear"++ if not indicators:+ return {"error": "Could not fetch any indicators"}++ return indicators+++def main():+ # Read stdin (may be empty)+ try:+ sys.stdin.read()+ except Exception:+ pass++ result = get_indicators()+ print(json.dumps(convert_numpy(result)))+++if __name__ == "__main__":+ main()diff --git a/fincept-cpp/scripts/Analytics/economics/equity_risk_premium.py b/fincept-cpp/scripts/Analytics/economics/equity_risk_premium.pynew file mode 100644index 000000000..c7a0ca473--- /dev/null+++ b/fincept-cpp/scripts/Analytics/economics/equity_risk_premium.py@@ -0,0 +1,146 @@+"""+Equity Risk Premium (ERP) — Multiple estimation methods.+Input: JSON via stdin (can be empty {})+Output: JSON with ERP estimates from various models+"""+import sys+import json+import numpy as np+++def convert_numpy(obj):+ if isinstance(obj, dict):+ return {k: convert_numpy(v) for k, v in obj.items()}+ elif isinstance(obj, (list, tuple)):+ return [convert_numpy(v) for v in obj]+ elif isinstance(obj, (np.integer,)):+ return int(obj)+ elif isinstance(obj, (np.floating,)):+ v = float(obj)+ if np.isnan(v) or np.isinf(v):+ return 0.0+ return v+ elif isinstance(obj, np.ndarray):+ return [convert_numpy(x) for x in obj]+ elif isinstance(obj, float):+ if np.isnan(obj) or np.isinf(obj):+ return 0.0+ return obj+++def estimate_erp():+ """Estimate ERP using multiple approaches"""+ import yfinance as yf++ result = {}++ # 1. Historical ERP: S&P 500 excess return over risk-free rate+ try:+ sp = yf.download("^GSPC", period="10y", interval="1mo", progress=False)+ if sp is not None and not sp.empty:+ close = sp["Close"].values.flatten()+ monthly_returns = np.diff(close) / close[:-1]+ ann_return = float((1 + np.mean(monthly_returns)) ** 12 - 1)++ # Get current risk-free rate from 10Y treasury+ try:+ tnx = yf.Ticker("^TNX")+ rf = float(getattr(tnx.fast_info, "last_price", 4.0) or 4.0) / 100+ except Exception:+ rf = 0.04++ historical_erp = ann_return - rf+ result["historical_10y_erp"] = round(historical_erp, 4)+ result["sp500_10y_annualized"] = round(ann_return, 4)+ result["risk_free_rate_10y"] = round(rf, 4)+ except Exception:+ pass++ # 2. Short-term historical (5Y)+ try:+ sp5 = yf.download("^GSPC", period="5y", interval="1mo", progress=False)+ if sp5 is not None and not sp5.empty:+ close5 = sp5["Close"].values.flatten()+ mr5 = np.diff(close5) / close5[:-1]+ ann5 = float((1 + np.mean(mr5)) ** 12 - 1)+ rf = result.get("risk_free_rate_10y", 0.04)+ result["historical_5y_erp"] = round(ann5 - rf, 4)+ result["sp500_5y_annualized"] = round(ann5, 4)+ except Exception:+ pass++ # 3. Implied ERP from earnings yield+ try:+ sp_ticker = yf.Ticker("^GSPC")+ pe = getattr(sp_ticker.info, "trailingPE", None)+ if pe is None:+ pe = sp_ticker.info.get("trailingPE", None) if hasattr(sp_ticker, "info") and isinstance(sp_ticker.info, dict) else None+ if pe and pe > 0:+ earnings_yield = 1.0 / pe+ rf = result.get("risk_free_rate_10y", 0.04)+ result["implied_erp_earnings_yield"] = round(earnings_yield - rf, 4)+ result["sp500_earnings_yield"] = round(earnings_yield, 4)+ result["sp500_pe_ratio"] = round(pe, 2)+ except Exception:+ pass++ # 4. Damodaran-style supply-side (dividend yield + buyback + growth - rf)+ try:+ spy = yf.Ticker("SPY")+ div_yield = 0.013 # approximate S&P 500 dividend yield+ try:+ dy = getattr(spy.info, "dividendYield", None)+ if dy is None and hasattr(spy, "info") and isinstance(spy.info, dict):+ dy = spy.info.get("dividendYield", None)+ if dy and dy > 0:+ div_yield = float(dy)+ except Exception:+ pass++ buyback_yield = 0.02 # approximate+ real_gdp_growth = 0.025+ inflation = 0.03++ supply_side_expected = div_yield + buyback_yield + real_gdp_growth + inflation+ rf = result.get("risk_free_rate_10y", 0.04)+ result["supply_side_erp"] = round(supply_side_expected - rf, 4)+ result["dividend_yield"] = round(div_yield, 4)+ except Exception:+ pass++ # 5. VIX-implied (rough approximation: VIX/100 * sqrt(time) as excess return proxy)+ try:+ vix = yf.Ticker("^VIX")+ vix_level = float(getattr(vix.fast_info, "last_price", 0) or 0)+ if vix_level > 0:+ # Variance risk premium approach: implied vol vs realized vol+ result["vix_current"] = round(vix_level, 2)+ result["vix_implied_erp_approx"] = round(vix_level / 100 * 0.5, 4)+ except Exception:+ pass++ # Summary+ erp_values = [v for k, v in result.items() if k.endswith("_erp") and isinstance(v, (int, float))]+ if erp_values:+ result["consensus_erp_estimate"] = round(float(np.mean(erp_values)), 4)+ result["erp_range_low"] = round(float(min(erp_values)), 4)+ result["erp_range_high"] = round(float(max(erp_values)), 4)++ if not result:+ return {"error": "Could not compute ERP estimates"}++ return result+++def main():+ try:+ sys.stdin.read()+ except Exception:+ pass++ result = estimate_erp()+ print(json.dumps(convert_numpy(result)))+++if __name__ == "__main__":+ main()diff --git a/fincept-cpp/scripts/Analytics/fortitudo_tech_wrapper/fortitudo_service.py b/fincept-cpp/scripts/Analytics/fortitudo_tech_wrapper/fortitudo_service.pyindex 5c856b4cf..c3a43ace3 100644--- a/fincept-cpp/scripts/Analytics/fortitudo_tech_wrapper/fortitudo_service.py+++ b/fincept-cpp/scripts/Analytics/fortitudo_tech_wrapper/fortitudo_service.py@@ -160,7 +160,12 @@ def fetch_returns_for_tickers(tickers_str: str) -> pd.DataFrame:def parse_returns_json(returns_json: str) -> pd.DataFrame:"""Parse JSON returns data into DataFrame"""- data = json.loads(returns_json)+ # Handle plain ticker strings (e.g. "AAPL,MSFT") that aren't JSON-wrapped+ try:+ data = json.loads(returns_json)+ except (json.JSONDecodeError, TypeError):+ # Treat as a plain comma-separated ticker string+ data = returns_json# Handle the case where the frontend sends a JSON-encoded ticker string# e.g. JSON.stringify("AAPL,MSFT,GOOGL") → data is a plain string@@ -698,6 +703,14 @@ def main(args: list) -> str:params = json.loads(args[1])except json.JSONDecodeError as e:return serialize_result({"success": False, "error": f"Invalid JSON params: {e}"})+ else:+ # No explicit params arg — read from stdin (C++ execute_with_stdin pipes data here)+ try:+ stdin_data = sys.stdin.read()+ if stdin_data and stdin_data.strip():+ params = json.loads(stdin_data)+ except (json.JSONDecodeError, OSError):+ pass# Route commandshandlers = {diff --git a/fincept-cpp/scripts/Analytics/portfolioManagement/ffn_analysis.py b/fincept-cpp/scripts/Analytics/portfolioManagement/ffn_analysis.pynew file mode 100644index 000000000..5b676e9c4--- /dev/null+++ b/fincept-cpp/scripts/Analytics/portfolioManagement/ffn_analysis.py@@ -0,0 +1,124 @@+"""+FFN (Financial Functions) Analysis — Deep analytics per symbol.+Input: JSON via stdin: {"symbols": ["AAPL","MSFT"]}+Output: JSON to stdout with per-symbol stats+"""+import sys+import json+import numpy as np+++def convert_numpy(obj):+ if isinstance(obj, dict):+ return {k: convert_numpy(v) for k, v in obj.items()}+ elif isinstance(obj, (list, tuple)):+ return [convert_numpy(v) for v in obj]+ elif isinstance(obj, (np.integer,)):+ return int(obj)+ elif isinstance(obj, (np.floating,)):+ v = float(obj)+ if np.isnan(v) or np.isinf(v):+ return 0.0+ return v+ elif isinstance(obj, np.ndarray):+ return [convert_numpy(x) for x in obj]+ elif isinstance(obj, float):+ if np.isnan(obj) or np.isinf(obj):+ return 0.0+ return obj+++def compute_ffn(symbols, period="1y"):+ import yfinance as yf++ data = yf.download(symbols, period=period, interval="1d", progress=False)+ if data is None or data.empty:+ return {"error": "Could not fetch price data"}++ close = data["Close"]+ if len(symbols) == 1:+ import pandas as pd+ if not isinstance(close, pd.DataFrame):+ close = pd.DataFrame({symbols[0]: close})++ result = {}+ for sym in symbols:+ if sym not in close.columns:+ continue+ prices = close[sym].dropna()+ if len(prices) < 2:+ continue++ returns = prices.pct_change().dropna()+ cumulative = (1 + returns).cumprod()++ # Performance+ total_ret = float(cumulative.iloc[-1] - 1)+ ann_ret = float((1 + total_ret) ** (252 / max(len(returns), 1)) - 1)+ ann_vol = float(returns.std() * np.sqrt(252))++ # Drawdown+ peak = prices.expanding().max()+ dd = (prices - peak) / peak+ max_dd = float(dd.min())++ # Streak analysis+ pos = (returns > 0).astype(int)+ neg = (returns < 0).astype(int)++ def max_streak(series):+ max_s = 0+ cur = 0+ for v in series:+ if v:+ cur += 1+ max_s = max(max_s, cur)+ else:+ cur = 0+ return max_s++ # Monthly returns approximation+ monthly_ret = float(returns.mean() * 21)++ result[sym] = {+ "total_return": total_ret,+ "annualized_return": ann_ret,+ "annualized_volatility": ann_vol,+ "max_drawdown": max_dd,+ "sharpe_ratio": float((ann_ret - 0.04) / ann_vol) if ann_vol > 0 else 0,+ "current_price": float(prices.iloc[-1]),+ "start_price": float(prices.iloc[0]),+ "best_day": float(returns.max()),+ "worst_day": float(returns.min()),+ "avg_daily_return": float(returns.mean()),+ "positive_days": int((returns > 0).sum()),+ "negative_days": int((returns < 0).sum()),+ "max_win_streak": max_streak(pos),+ "max_loss_streak": max_streak(neg),+ "avg_monthly_return": monthly_ret,+ "skewness": float(returns.skew()),+ "kurtosis": float(returns.kurtosis()),+ }++ return result+++def main():+ stdin_data = sys.stdin.read()+ if not stdin_data.strip():+ print(json.dumps({"error": "No input data"}))+ return++ params = json.loads(stdin_data)+ symbols = params.get("symbols", [])++ if not symbols:+ print(json.dumps({"error": "No symbols provided"}))+ return++ result = compute_ffn(symbols)+ print(json.dumps(convert_numpy(result)))+++if __name__ == "__main__":+ main()diff --git a/fincept-cpp/scripts/Analytics/portfolioManagement/portfolio_analytics.py b/fincept-cpp/scripts/Analytics/portfolioManagement/portfolio_analytics.pyindex 21e17844a..299ef3bfb 100644--- a/fincept-cpp/scripts/Analytics/portfolioManagement/portfolio_analytics.py+++ b/fincept-cpp/scripts/Analytics/portfolioManagement/portfolio_analytics.py@@ -678,6 +678,323 @@ class PortfolioAnalytics:# CLI Interface# ============================================================================+def convert_numpy(obj):+ """Convert numpy types to JSON-serializable Python types"""+ if isinstance(obj, np.ndarray):+ return obj.tolist()+ elif isinstance(obj, dict):+ return {k: convert_numpy(v) for k, v in obj.items()}+ elif isinstance(obj, list):+ return [convert_numpy(item) for item in obj]+ elif isinstance(obj, (np.integer, np.floating)):+ v = float(obj)+ if np.isnan(v):+ return None+ return v+ return obj+++def cmd_calculate_portfolio_metrics(params):+ """Calculate portfolio metrics from holdings data (called from C++ via stdin).++ Input: {"holdings": [{"symbol": "AAPL", "quantity": 10, "weight": 0.5, ...}, ...]}+ Fetches historical returns via yfinance, runs comprehensive analysis.+ """+ try:+ import yfinance as yf+ except ImportError:+ return {"error": "yfinance not installed"}++ holdings = params.get("holdings", [])+ if not holdings:+ return {"error": "No holdings provided"}++ symbols = [h["symbol"] for h in holdings]+ weights_list = [h.get("weight", 1.0 / len(holdings)) for h in holdings]+ weights_arr = np.array(weights_list)+ w_sum = weights_arr.sum()+ if w_sum > 0:+ weights_arr = weights_arr / w_sum++ try:+ # Download all symbols + SPY benchmark together+ all_tickers = list(set(symbols + ["SPY"]))+ data = yf.download(all_tickers, period="1y", auto_adjust=True, progress=False)+ if data.empty:+ return {"error": "No price data available from yfinance"}++ # Extract Close prices+ if isinstance(data.columns, pd.MultiIndex):+ close = data["Close"]+ else:+ # Single ticker returns flat columns+ close = data[["Close"]]+ close.columns = all_tickers[:1]++ # Ensure close is a DataFrame+ if isinstance(close, pd.Series):+ close = close.to_frame(name=all_tickers[0])++ # Compute daily returns+ returns_all = close.pct_change().dropna()+ if returns_all.empty:+ return {"error": "Insufficient return data after computing returns"}++ # Split into portfolio symbols and SPY+ available = [s for s in symbols if s in returns_all.columns]+ if not available:+ return {"error": "No return data for portfolio symbols: " + ", ".join(symbols)}++ has_spy = "SPY" in returns_all.columns++ # Align indices+ returns = returns_all[available]+ if has_spy:+ spy_returns = returns_all["SPY"]+ common_idx = returns.index.intersection(spy_returns.index)+ returns = returns.loc[common_idx]+ market = spy_returns.loc[common_idx].values+ else:+ market = None++ # Adjust weights for available symbols+ avail_idx = [symbols.index(s) for s in available]+ w = weights_arr[avail_idx]+ w = w / w.sum()++ n_assets = len(available)++ # For single-asset portfolios, compute simpler metrics+ if n_assets == 1:+ asset_returns = returns.iloc[:, 0].values+ ann_return = float(np.mean(asset_returns) * 252)+ ann_vol = float(np.std(asset_returns, ddof=1) * np.sqrt(252))+ sharpe = (ann_return - 0.03) / ann_vol if ann_vol > 0 else 0++ result = {+ "portfolio_metrics": {+ "weights": {available[0]: 1.0},+ "expected_return": ann_return,+ "standard_deviation": ann_vol,+ "variance": ann_vol ** 2,+ "sharpe_ratio": sharpe,+ },+ "risk_metrics": {+ "value_at_risk_95": float(np.percentile(asset_returns, 5)),+ "value_at_risk_99": float(np.percentile(asset_returns, 1)),+ "maximum_drawdown": float(np.min(+ (np.cumprod(1 + asset_returns) -+ np.maximum.accumulate(np.cumprod(1 + asset_returns))) /+ np.maximum.accumulate(np.cumprod(1 + asset_returns))+ )),+ },+ }+ if market is not None and len(market) == len(asset_returns):+ cov = np.cov(asset_returns, market)+ beta = cov[0, 1] / cov[1, 1] if cov[1, 1] != 0 else 0+ mkt_return = float(np.mean(market) * 252)+ alpha = ann_return - (0.03 + beta * (mkt_return - 0.03))+ result["capm_analysis"] = {+ "alpha": alpha,+ "beta": float(beta),+ "actual_return": ann_return,+ "market_return": mkt_return,+ }+ return convert_numpy(result)++ # Multi-asset: run full comprehensive analysis+ returns_dict = {col: returns[col].values for col in returns.columns}+ analytics = PortfolioAnalytics()+ result = analytics.comprehensive_analysis(returns_dict, w, market)+ return convert_numpy(result)++ except Exception as e:+ import traceback+ return {"error": str(e), "traceback": traceback.format_exc()}+++def cmd_tax_report(params):+ """Generate capital gains tax report from holdings data"""+ holdings = params.get("holdings", [])+ if not holdings:+ return {"error": "No holdings provided"}++ total_cost_basis = 0.0+ total_market_value = 0.0+ total_realized_gain = 0.0+ total_unrealized_gain = 0.0+ short_term_gains = 0.0+ long_term_gains = 0.0+ tax_loss_harvest = []++ for h in holdings:+ symbol = h.get("symbol", "")+ qty = float(h.get("quantity", 0))+ avg_price = float(h.get("avg_price", 0))+ current = float(h.get("current_price", avg_price))++ cost_basis = qty * avg_price+ market_val = qty * current+ gain = market_val - cost_basis+ gain_pct = (gain / cost_basis * 100) if cost_basis > 0 else 0++ total_cost_basis += cost_basis+ total_market_value += market_val+ total_unrealized_gain += gain++ # Assume all short-term for now (no purchase date info)+ if gain > 0:+ short_term_gains += gain+ else:+ tax_loss_harvest.append({"symbol": symbol, "unrealized_loss": round(gain, 2)})++ total_gain_pct = (total_unrealized_gain / total_cost_basis * 100) if total_cost_basis > 0 else 0++ # Estimated tax (simplified: 22% short-term, 15% long-term)+ est_short_term_tax = short_term_gains * 0.22+ est_long_term_tax = long_term_gains * 0.15++ result = {+ "total_cost_basis": round(total_cost_basis, 2),+ "total_market_value": round(total_market_value, 2),+ "total_unrealized_gain": round(total_unrealized_gain, 2),+ "total_gain_pct": round(total_gain_pct, 2),+ "short_term_gains": round(short_term_gains, 2),+ "long_term_gains": round(long_term_gains, 2),+ "estimated_short_term_tax": round(est_short_term_tax, 2),+ "estimated_long_term_tax": round(est_long_term_tax, 2),+ "estimated_total_tax": round(est_short_term_tax + est_long_term_tax, 2),+ "num_positions": len(holdings),+ "positions_with_losses": len(tax_loss_harvest),+ }++ if tax_loss_harvest:+ total_harvestable = sum(t["unrealized_loss"] for t in tax_loss_harvest)+ result["tax_loss_harvest_potential"] = round(total_harvestable, 2)+ result["tax_savings_potential"] = round(abs(total_harvestable) * 0.22, 2)++ return result+++def cmd_pme_analysis(params):+ """Public Market Equivalent analysis — compare portfolio vs benchmark"""+ symbols = params.get("symbols", [])+ if not symbols:+ return {"error": "No symbols provided"}++ try:+ import yfinance as yf++ # Download portfolio symbols and benchmark+ all_syms = symbols + ["SPY"]+ data = yf.download(all_syms, period="1y", interval="1d", progress=False)+ if data is None or data.empty:+ return {"error": "Could not fetch price data"}++ close = data["Close"]++ # Portfolio equal-weighted returns+ port_returns = close[symbols].pct_change().dropna().mean(axis=1)+ bench_returns = close["SPY"].pct_change().dropna()++ # Align+ common = port_returns.index.intersection(bench_returns.index)+ port_returns = port_returns.loc[common]+ bench_returns = bench_returns.loc[common]++ port_cum = float((1 + port_returns).prod() - 1)+ bench_cum = float((1 + bench_returns).prod() - 1)+ n_days = len(common)+ ann_factor = 252++ port_ann = float((1 + port_cum) ** (ann_factor / max(n_days, 1)) - 1)+ bench_ann = float((1 + bench_cum) ** (ann_factor / max(n_days, 1)) - 1)++ # PME ratio+ pme_ratio = float((1 + port_cum) / (1 + bench_cum)) if (1 + bench_cum) != 0 else 1.0++ # Alpha and tracking error+ excess = port_returns - bench_returns+ alpha_ann = float(excess.mean() * ann_factor)+ tracking_error = float(excess.std() * np.sqrt(ann_factor))+ info_ratio = float(alpha_ann / tracking_error) if tracking_error > 0 else 0++ # Up/down capture+ up_mask = bench_returns > 0+ down_mask = bench_returns < 0+ up_capture = float(port_returns[up_mask].mean() / bench_returns[up_mask].mean()) if up_mask.sum() > 0 and bench_returns[up_mask].mean() != 0 else 1.0+ down_capture = float(port_returns[down_mask].mean() / bench_returns[down_mask].mean()) if down_mask.sum() > 0 and bench_returns[down_mask].mean() != 0 else 1.0++ return {+ "pme_ratio": round(pme_ratio, 4),+ "portfolio_total_return": round(port_cum, 4),+ "benchmark_total_return": round(bench_cum, 4),+ "portfolio_ann_return": round(port_ann, 4),+ "benchmark_ann_return": round(bench_ann, 4),+ "annualized_alpha": round(alpha_ann, 4),+ "tracking_error": round(tracking_error, 4),+ "information_ratio": round(info_ratio, 4),+ "up_capture_ratio": round(up_capture, 4),+ "down_capture_ratio": round(down_capture, 4),+ "outperformance": round(port_cum - bench_cum, 4),+ "trading_days": n_days,+ "benchmark": "SPY",+ }++ except Exception as e:+ import traceback+ return {"error": str(e), "traceback": traceback.format_exc()}+++def cmd_allocation_analysis(params):+ """Analyze portfolio allocation vs target/benchmark"""+ holdings = params.get("holdings", [])+ if not holdings:+ return {"error": "No holdings provided"}++ symbols = [h["symbol"] for h in holdings]+ weights = [h.get("weight", 0) for h in holdings]+ values = [h.get("value", 0) for h in holdings]+ total_value = sum(values)++ n = len(symbols)++ # Normalize weights to fractions (0-1) if they look like percentages+ w = np.array(weights, dtype=float)+ if np.sum(w) > 1.5:+ w = w / np.sum(w)+ weights_norm = w.tolist()++ # Concentration metrics+ hhi = float(np.sum(w ** 2)) # Herfindahl-Hirschman Index (0-1)+ effective_n = float(1.0 / hhi) if hhi > 0 else n++ # Top holdings concentration+ sorted_w = sorted(weights_norm, reverse=True)+ top3 = sum(sorted_w[:3]) if len(sorted_w) >= 3 else sum(sorted_w)+ top5 = sum(sorted_w[:5]) if len(sorted_w) >= 5 else sum(sorted_w)++ # Ideal equal weight+ equal_weight = 1.0 / n if n > 0 else 0+ max_deviation = max(abs(wt - equal_weight) for wt in weights_norm) if weights_norm else 0++ result = {+ "num_holdings": n,+ "total_value": round(total_value, 2),+ "hhi_concentration": round(hhi, 4),+ "effective_num_stocks": round(effective_n, 2),+ "top_3_concentration_pct": round(top3 * 100, 2),+ "top_5_concentration_pct": round(top5 * 100, 2),+ "equal_weight_target": round(equal_weight, 4),+ "max_deviation_from_equal": round(max_deviation, 4),+ "is_concentrated": "Yes" if hhi > 0.25 else "No",+ "diversification_score": round((1 - hhi) * 100, 1),+ }++ # Sector classification would require additional data, skip for now+ return result++if __name__ == "__main__":import sysimport json@@ -688,35 +1005,59 @@ if __name__ == "__main__":command = sys.argv[1]+ # Read params from stdin if available (C++ execute_with_stdin pipes data here)+ stdin_params = None+ try:+ if not sys.stdin.isatty():+ stdin_data = sys.stdin.read()+ if stdin_data.strip():+ stdin_params = json.loads(stdin_data)+ except (json.JSONDecodeError, OSError):+ pass+try:- if command == "comprehensive_analysis":+ if command == "calculate_portfolio_metrics":+ if stdin_params is None:+ print(json.dumps({"error": "No input data provided via stdin"}))+ sys.exit(1)+ result = cmd_calculate_portfolio_metrics(stdin_params)+ print(json.dumps(result))++ elif command == "comprehensive_analysis":returns_data = json.loads(sys.argv[2])weights = json.loads(sys.argv[3]) if len(sys.argv) > 3 and sys.argv[3] != "null" else Nonemarket_returns = json.loads(sys.argv[4]) if len(sys.argv) > 4 and sys.argv[4] != "null" else None-- # Convert to numpy arrays+returns_dict = {k: np.array(v) for k, v in returns_data.items()}weights_arr = np.array(weights) if weights else Nonemarket_arr = np.array(market_returns) if market_returns else None-+analytics = PortfolioAnalytics()result = analytics.comprehensive_analysis(returns_dict, weights_arr, market_arr)-- # Convert numpy to JSON-serializable- def convert_numpy(obj):- if isinstance(obj, np.ndarray):- return obj.tolist()- elif isinstance(obj, dict):- return {k: convert_numpy(v) for k, v in obj.items()}- elif isinstance(obj, list):- return [convert_numpy(item) for item in obj]- elif isinstance(obj, (np.integer, np.floating)):- return float(obj)- return obj-result = convert_numpy(result)print(json.dumps(result))+ elif command == "tax_report":+ if stdin_params is None:+ print(json.dumps({"error": "No input data provided via stdin"}))+ sys.exit(1)+ result = cmd_tax_report(stdin_params)+ print(json.dumps(convert_numpy(result)))++ elif command == "pme_analysis":+ if stdin_params is None:+ print(json.dumps({"error": "No input data provided via stdin"}))+ sys.exit(1)+ result = cmd_pme_analysis(stdin_params)+ print(json.dumps(convert_numpy(result)))++ elif command == "allocation_analysis":+ if stdin_params is None:+ print(json.dumps({"error": "No input data provided via stdin"}))+ sys.exit(1)+ result = cmd_allocation_analysis(stdin_params)+ print(json.dumps(convert_numpy(result)))+else:print(json.dumps({"error": f"Unknown command: {command}"}))sys.exit(1)diff --git a/fincept-cpp/scripts/Analytics/portfolioManagement/portfolio_optimization.py b/fincept-cpp/scripts/Analytics/portfolioManagement/portfolio_optimization.pynew file mode 100644index 000000000..ca2cb9ebc--- /dev/null+++ b/fincept-cpp/scripts/Analytics/portfolioManagement/portfolio_optimization.py@@ -0,0 +1,164 @@+"""+Portfolio Optimization — Multiple strategies using scipy optimization.+Input: JSON via stdin: {"symbols": ["AAPL","MSFT"], "strategy": "max_sharpe"}+Output: JSON to stdout with weights and performance metrics+"""+import sys+import json+import numpy as np+++def convert_numpy(obj):+ if isinstance(obj, dict):+ return {k: convert_numpy(v) for k, v in obj.items()}+ elif isinstance(obj, (list, tuple)):+ return [convert_numpy(v) for v in obj]+ elif isinstance(obj, (np.integer,)):+ return int(obj)+ elif isinstance(obj, (np.floating,)):+ return float(obj)+ elif isinstance(obj, np.ndarray):+ return obj.tolist()+ return obj+++def fetch_returns(symbols, period="1y"):+ import yfinance as yf+ data = yf.download(symbols, period=period, interval="1d", progress=False)+ if data is None or data.empty:+ return None+ close = data["Close"]+ if isinstance(close, type(data)):+ close = close[symbols]+ elif len(symbols) == 1:+ import pandas as pd+ close = pd.DataFrame({symbols[0]: close})+ returns = close.pct_change().dropna()+ return returns+++def optimize_portfolio(symbols, strategy, params=None):+ if params is None:+ params = {}+ returns = fetch_returns(symbols)+ if returns is None or returns.empty:+ return {"error": "Could not fetch price data"}++ n = len(symbols)+ mean_returns = returns.mean().values * 252+ cov_matrix = returns.cov().values * 252+ rf = 0.04++ from scipy.optimize import minimize++ def neg_sharpe(w):+ port_ret = np.dot(w, mean_returns)+ port_vol = np.sqrt(np.dot(w, np.dot(cov_matrix, w)))+ return -(port_ret - rf) / port_vol if port_vol > 0 else 0++ def port_volatility(w):+ return np.sqrt(np.dot(w, np.dot(cov_matrix, w)))++ def port_return(w):+ return np.dot(w, mean_returns)++ bounds = tuple((0, 1) for _ in range(n))+ constraints = [{"type": "eq", "fun": lambda w: np.sum(w) - 1}]+ w0 = np.ones(n) / n++ try:+ if strategy == "max_sharpe":+ result = minimize(neg_sharpe, w0, bounds=bounds, constraints=constraints, method="SLSQP")+ elif strategy == "min_volatility":+ result = minimize(port_volatility, w0, bounds=bounds, constraints=constraints, method="SLSQP")+ elif strategy == "efficient_risk":+ target_vol = params.get("target_volatility", 0.15)+ constraints.append({"type": "ineq", "fun": lambda w: target_vol - port_volatility(w)})+ result = minimize(lambda w: -port_return(w), w0, bounds=bounds, constraints=constraints, method="SLSQP")+ elif strategy == "efficient_return":+ target_ret = params.get("target_return", 0.10)+ constraints.append({"type": "eq", "fun": lambda w: port_return(w) - target_ret})+ result = minimize(port_volatility, w0, bounds=bounds, constraints=constraints, method="SLSQP")+ elif strategy == "max_quadratic_utility":+ risk_aversion = params.get("risk_aversion", 1.0)+ def neg_utility(w):+ ret = np.dot(w, mean_returns)+ var = np.dot(w, np.dot(cov_matrix, w))+ return -(ret - 0.5 * risk_aversion * var)+ result = minimize(neg_utility, w0, bounds=bounds, constraints=constraints, method="SLSQP")+ elif strategy == "risk_parity":+ def risk_parity_obj(w):+ vol = np.sqrt(np.dot(w, np.dot(cov_matrix, w)))+ if vol == 0:+ return 0+ marginal = np.dot(cov_matrix, w)+ risk_contrib = w * marginal / vol+ target_rc = vol / n+ return np.sum((risk_contrib - target_rc) ** 2)+ result = minimize(risk_parity_obj, w0, bounds=bounds, constraints=constraints, method="SLSQP")+ elif strategy == "black_litterman":+ # Simple Black-Litterman with market-implied equilibrium+ delta = 2.5+ pi = delta * np.dot(cov_matrix, w0) # market implied returns+ bl_returns = pi # Without views, BL returns = equilibrium+ def neg_sharpe_bl(w):+ ret = np.dot(w, bl_returns)+ vol = np.sqrt(np.dot(w, np.dot(cov_matrix, w)))+ return -(ret - rf) / vol if vol > 0 else 0+ result = minimize(neg_sharpe_bl, w0, bounds=bounds, constraints=constraints, method="SLSQP")+ elif strategy == "hrp":+ # Hierarchical Risk Parity via simple inverse-variance+ inv_var = 1.0 / np.diag(cov_matrix)+ weights = inv_var / inv_var.sum()+ result = type("obj", (object,), {"x": weights, "success": True})()+ elif strategy == "custom_constraints":+ # Equal weight as default custom+ weights = np.ones(n) / n+ result = type("obj", (object,), {"x": weights, "success": True})()+ else:+ return {"error": f"Unknown strategy: {strategy}"}++ if not result.success and strategy not in ("hrp", "custom_constraints"):+ return {"error": f"Optimization did not converge: {getattr(result, 'message', '')}"}++ weights = result.x+ port_ret = float(np.dot(weights, mean_returns))+ port_vol = float(np.sqrt(np.dot(weights, np.dot(cov_matrix, weights))))+ sharpe = float((port_ret - rf) / port_vol) if port_vol > 0 else 0++ weights_dict = {symbols[i]: float(weights[i]) for i in range(n)}++ return {+ "weights": weights_dict,+ "expected_annual_return": port_ret,+ "annual_volatility": port_vol,+ "sharpe_ratio": sharpe,+ "strategy": strategy,+ }++ except Exception as e:+ import traceback+ return {"error": str(e), "traceback": traceback.format_exc()}+++def main():+ stdin_data = sys.stdin.read()+ if not stdin_data.strip():+ print(json.dumps({"error": "No input data"}))+ return++ params = json.loads(stdin_data)+ symbols = params.get("symbols", [])+ strategy = params.get("strategy", "max_sharpe")++ if not symbols:+ print(json.dumps({"error": "No symbols provided"}))+ return++ result = optimize_portfolio(symbols, strategy, params)+ print(json.dumps(convert_numpy(result)))+++if __name__ == "__main__":+ # Support command arg (e.g. "optimize") but ignore it — we always optimize+ main()diff --git a/fincept-cpp/scripts/Analytics/portfolioManagement/quantstats_analysis.py b/fincept-cpp/scripts/Analytics/portfolioManagement/quantstats_analysis.pynew file mode 100644index 000000000..57b6807fc--- /dev/null+++ b/fincept-cpp/scripts/Analytics/portfolioManagement/quantstats_analysis.py@@ -0,0 +1,146 @@+"""+QuantStats Analysis — Comprehensive quantitative statistics for a portfolio.+Input: JSON via stdin: {"symbols": ["AAPL","MSFT"], "weights": [0.5, 0.5]}+Output: JSON to stdout with performance, risk, and ratio metrics+"""+import sys+import json+import numpy as np+++def convert_numpy(obj):+ if isinstance(obj, dict):+ return {k: convert_numpy(v) for k, v in obj.items()}+ elif isinstance(obj, (list, tuple)):+ return [convert_numpy(v) for v in obj]+ elif isinstance(obj, (np.integer,)):+ return int(obj)+ elif isinstance(obj, (np.floating,)):+ v = float(obj)+ if np.isnan(v) or np.isinf(v):+ return 0.0+ return v+ elif isinstance(obj, np.ndarray):+ return [convert_numpy(x) for x in obj]+ elif isinstance(obj, float):+ if np.isnan(obj) or np.isinf(obj):+ return 0.0+ return obj+++def compute_stats(symbols, weights, period="1y"):+ import yfinance as yf++ data = yf.download(symbols, period=period, interval="1d", progress=False)+ if data is None or data.empty:+ return {"error": "Could not fetch price data"}++ close = data["Close"]+ if len(symbols) == 1:+ import pandas as pd+ if not isinstance(close, pd.DataFrame):+ close = pd.DataFrame({symbols[0]: close})++ returns = close.pct_change().dropna()+ w = np.array(weights)+ if len(w) != returns.shape[1]:+ w = np.ones(returns.shape[1]) / returns.shape[1]++ port_returns = (returns * w).sum(axis=1)+ cumulative = (1 + port_returns).cumprod()++ rf_daily = 0.04 / 252+ trading_days = len(port_returns)+ ann_factor = 252++ # Basic stats+ total_return = float(cumulative.iloc[-1] / cumulative.iloc[0] - 1) if len(cumulative) > 0 else 0+ ann_return = float((1 + total_return) ** (ann_factor / max(trading_days, 1)) - 1)+ ann_vol = float(port_returns.std() * np.sqrt(ann_factor))+ sharpe = float((ann_return - 0.04) / ann_vol) if ann_vol > 0 else 0+ sortino_vol = float(port_returns[port_returns < 0].std() * np.sqrt(ann_factor))+ sortino = float((ann_return - 0.04) / sortino_vol) if sortino_vol > 0 else 0++ # Drawdown+ peak = cumulative.expanding().max()+ drawdown = (cumulative - peak) / peak+ max_dd = float(drawdown.min())+ calmar = float(ann_return / abs(max_dd)) if max_dd != 0 else 0++ # VaR and CVaR+ var_95 = float(np.percentile(port_returns, 5))+ cvar_95 = float(port_returns[port_returns <= var_95].mean()) if len(port_returns[port_returns <= var_95]) > 0 else var_95++ # Win rate+ wins = int((port_returns > 0).sum())+ losses = int((port_returns < 0).sum())+ win_rate = float(wins / (wins + losses)) if (wins + losses) > 0 else 0++ # Best/worst+ best_day = float(port_returns.max())+ worst_day = float(port_returns.min())+ avg_win = float(port_returns[port_returns > 0].mean()) if wins > 0 else 0+ avg_loss = float(port_returns[port_returns < 0].mean()) if losses > 0 else 0+ profit_factor = float(abs(avg_win * wins) / abs(avg_loss * losses)) if losses > 0 and avg_loss != 0 else 0++ # Skew & Kurtosis+ skew = float(port_returns.skew())+ kurt = float(port_returns.kurtosis())++ return {+ "performance": {+ "total_return": total_return,+ "annualized_return": ann_return,+ "trading_days": trading_days,+ "best_day": best_day,+ "worst_day": worst_day,+ "avg_daily_return": float(port_returns.mean()),+ },+ "risk": {+ "annualized_volatility": ann_vol,+ "max_drawdown": max_dd,+ "var_95_daily": var_95,+ "cvar_95_daily": cvar_95,+ "downside_deviation": sortino_vol,+ },+ "ratios": {+ "sharpe_ratio": sharpe,+ "sortino_ratio": sortino,+ "calmar_ratio": calmar,+ "profit_factor": profit_factor,+ },+ "distribution": {+ "skewness": skew,+ "kurtosis": kurt,+ "win_rate": win_rate,+ "win_days": wins,+ "loss_days": losses,+ "avg_win": avg_win,+ "avg_loss": avg_loss,+ }+ }+++def main():+ stdin_data = sys.stdin.read()+ if not stdin_data.strip():+ print(json.dumps({"error": "No input data"}))+ return++ params = json.loads(stdin_data)+ symbols = params.get("symbols", [])+ weights = params.get("weights", [])++ if not symbols:+ print(json.dumps({"error": "No symbols provided"}))+ return++ if not weights:+ weights = [1.0 / len(symbols)] * len(symbols)++ result = compute_stats(symbols, weights)+ print(json.dumps(convert_numpy(result)))+++if __name__ == "__main__":+ main()diff --git a/fincept-cpp/scripts/exchange/ws_stream.py b/fincept-cpp/scripts/exchange/ws_stream.pyindex 70363301f..1697357d0 100644--- a/fincept-cpp/scripts/exchange/ws_stream.py+++ b/fincept-cpp/scripts/exchange/ws_stream.py@@ -19,6 +19,7 @@ import jsonimport sysimport signalimport traceback+import platformMAX_CONSECUTIVE_ERRORS = 10 # Stop a watcher after this many consecutive errors@@ -222,6 +223,18 @@ async def main():"options": {"defaultType": "spot"},})+ # Fix: On Windows, aiodns/pycares async DNS resolver can fail.+ # Force aiohttp to use ThreadedResolver (synchronous DNS in a thread pool)+ # which works reliably across all platforms.+ try:+ import aiohttp+ from aiohttp.resolver import ThreadedResolver+ exchange.session = aiohttp.ClientSession(+ connector=aiohttp.TCPConnector(resolver=ThreadedResolver())+ )+ except Exception as resolver_err:+ emit({"type": "error", "message": f"Failed to set ThreadedResolver: {resolver_err}"})+# Try to load markets with retry — some exchanges may be temporarily unreachableMAX_RETRIES = 5markets_loaded = Falsediff --git a/fincept-cpp/scripts/yfinance_data.py b/fincept-cpp/scripts/yfinance_data.pyindex d02f754c4..70a84d63b 100644--- a/fincept-cpp/scripts/yfinance_data.py+++ b/fincept-cpp/scripts/yfinance_data.py@@ -258,23 +258,19 @@ def get_batch_quotes(symbols):results = []for symbol in symbols:try:- if len(symbols) == 1:- # Single symbol: data columns are flat (Open, High, Low, Close, Volume)+ if not isinstance(data.columns, pd.MultiIndex):+ # Flat columns (rare): use directlyhist = dataelse:- # Multiple symbols: newer yfinance uses (Price, Ticker) MultiIndex- # older versions use (Ticker, Price) — handle both orderings- if isinstance(data.columns, pd.MultiIndex):- level0 = data.columns.get_level_values(0).unique().tolist()- level1 = data.columns.get_level_values(1).unique().tolist()- if symbol in level1:- # New yfinance: (Price, Ticker) — use xs on level 1- hist = data.xs(symbol, axis=1, level=1)- elif symbol in level0:- # Old yfinance: (Ticker, Price)- hist = data[symbol]- else:- continue+ # MultiIndex columns — detect (Ticker, Price) vs (Price, Ticker)+ level0 = data.columns.get_level_values(0).unique().tolist()+ level1 = data.columns.get_level_values(1).unique().tolist()+ if symbol in level0:+ # (Ticker, Price) ordering+ hist = data[symbol]+ elif symbol in level1:+ # (Price, Ticker) ordering+ hist = data.xs(symbol, axis=1, level=1)else:continuediff --git a/fincept-cpp/src/app.cpp b/fincept-cpp/src/app.cppindex 365ef09c8..bed38c427 100644--- a/fincept-cpp/src/app.cpp+++ b/fincept-cpp/src/app.cpp@@ -4,6 +4,8 @@#include "storage/cache_service.h"#include "core/config.h"#include "core/logger.h"+#include "core/event_bus.h"+#include "mcp/mcp_init.h"#include "ui/theme.h"#include <imgui.h>#include <ctime>@@ -18,6 +20,15 @@ void App::initialize() {CacheService::instance().initialize();auth::AuthManager::instance().initialize();++ // Initialize MCP system (registers all internal tools, starts external servers)+ mcp::initialize_all_tools();++ // Subscribe to MCP navigation events+ core::EventBus::instance().subscribe("nav.switch_tab", [this](const core::Event& e) {+ active_tab_ = e.get<int>("tab_index");+ });+initialized_ = true;if (setup_screen_.needs_setup()) {@@ -30,6 +41,7 @@ void App::initialize() {void App::shutdown() {LOG_INFO("App", "Shutting down");+ mcp::shutdown_mcp();CacheService::instance().shutdown();db::CacheDatabase::instance().close();db::Database::instance().close();@@ -52,7 +64,7 @@ void App::handle_keyboard_shortcuts() {{ImGuiKey_F5, 6}, // Backtesting{ImGuiKey_F6, 14}, // Surface Analytics{ImGuiKey_F9, 2}, // Crypto Trading- {ImGuiKey_F10, 5}, // AI Chat+ {ImGuiKey_F10, 5}, // AI Chat{ImGuiKey_F7, 15}, // Geopolitics{ImGuiKey_F8, 16}, // Watchlist{ImGuiKey_F12, 13}, // Profile@@ -91,31 +103,61 @@ void App::render_top_bar() {ImGui::EndMenu();}if (ImGui::BeginMenu("Navigate")) {- if (ImGui::MenuItem("Dashboard", "F1")) { active_tab_ = 0; }- if (ImGui::MenuItem("Markets", "F2")) { active_tab_ = 1; }- if (ImGui::MenuItem("News", "F3")) { active_tab_ = 4; }- if (ImGui::MenuItem("Portfolio", "F4")) { active_tab_ = 3; }+ // ── Markets & Data ──+ ImGui::TextColored(ACCENT, "Markets & Data");ImGui::Separator();- if (ImGui::MenuItem("Crypto Trading", "F9")) { active_tab_ = 2; }- if (ImGui::MenuItem("Algo Trading")) { active_tab_ = 7; }- if (ImGui::MenuItem("Backtesting", "F5")) { active_tab_ = 6; }+ if (ImGui::MenuItem("Markets", "F2")) { active_tab_ = 1; }+ if (ImGui::MenuItem("Watchlist", "F8")) { active_tab_ = 16; }+ if (ImGui::MenuItem("Economics")) { active_tab_ = 17; }+ if (ImGui::MenuItem("Govt Data")) { active_tab_ = 26; }+ if (ImGui::MenuItem("DBnomics")) { active_tab_ = 18; }+ if (ImGui::MenuItem("Data Sources")) { active_tab_ = 20; }+ if (ImGui::MenuItem("Data Mapping")) { active_tab_ = 28; }++ ImGui::Spacing();++ // ── Trading & Portfolio ──+ ImGui::TextColored(ACCENT, "Trading & Portfolio");+ ImGui::Separator();+ if (ImGui::MenuItem("Crypto Trading", "F9")) { active_tab_ = 2; }+ if (ImGui::MenuItem("Portfolio", "F4")) { active_tab_ = 3; }+ if (ImGui::MenuItem("Backtesting", "F5")) { active_tab_ = 6; }+ if (ImGui::MenuItem("Algo Trading")) { active_tab_ = 7; }if (ImGui::MenuItem("Surface Analytics", "F6")) { active_tab_ = 14; }++ ImGui::Spacing();++ // ── Research & Intelligence ──+ ImGui::TextColored(ACCENT, "Research & Intelligence");ImGui::Separator();- if (ImGui::MenuItem("Watchlist", "F8")) { active_tab_ = 16; }- if (ImGui::MenuItem("Economics")) { active_tab_ = 17; }- if (ImGui::MenuItem("DBnomics")) { active_tab_ = 18; }- if (ImGui::MenuItem("Code Editor")) { active_tab_ = 9; }- if (ImGui::MenuItem("Notes")) { active_tab_ = 19; }- if (ImGui::MenuItem("M&A Analytics")) { active_tab_ = 21; }- if (ImGui::MenuItem("Govt Data")) { active_tab_ = 26; }+ if (ImGui::MenuItem("AI Chat", "F10")) { active_tab_ = 5; }+ if (ImGui::MenuItem("AI Quant Lab")) { active_tab_ = 10; }+ if (ImGui::MenuItem("M&A Analytics")) { active_tab_ = 21; }+ if (ImGui::MenuItem("Geopolitics", "F7")) { active_tab_ = 15; }++ ImGui::Spacing();++ // ── Tools ──+ ImGui::TextColored(ACCENT, "Tools");ImGui::Separator();- if (ImGui::MenuItem("Forum")) { active_tab_ = 22; }- if (ImGui::MenuItem("Documentation")) { active_tab_ = 23; }- if (ImGui::MenuItem("Support")) { active_tab_ = 24; }- if (ImGui::MenuItem("About")) { active_tab_ = 25; }+ if (ImGui::MenuItem("QuantLib")) { active_tab_ = 11; }+ if (ImGui::MenuItem("Node Editor")) { active_tab_ = 8; }+ if (ImGui::MenuItem("Code Editor")) { active_tab_ = 9; }+ if (ImGui::MenuItem("Agent Studio")) { active_tab_ = 27; }+ if (ImGui::MenuItem("Notes")) { active_tab_ = 19; }+ if (ImGui::MenuItem("Settings")) { active_tab_ = 12; }+ if (ImGui::MenuItem("Profile", "F12")) { active_tab_ = 13; }++ ImGui::Spacing();++ // ── Community & Support ──+ ImGui::TextColored(ACCENT, "Community & Support");ImGui::Separator();- if (ImGui::MenuItem("Settings")) { active_tab_ = 12; }- if (ImGui::MenuItem("Profile", "F12")) { active_tab_ = 13; }+ if (ImGui::MenuItem("Forum")) { active_tab_ = 22; }+ if (ImGui::MenuItem("Documentation")) { active_tab_ = 23; }+ if (ImGui::MenuItem("Support")) { active_tab_ = 24; }+ if (ImGui::MenuItem("About")) { active_tab_ = 25; }+ImGui::EndMenu();}if (ImGui::BeginMenu("View")) {@@ -285,31 +327,32 @@ void App::render_tab_bar() {ImGuiWindowFlags_NoFocusOnAppearing | ImGuiWindowFlags_NoBringToFrontOnFocus);if (current_screen_ == AppScreen::Dashboard) {- struct TabDef { const char* label; const char* shortcut; };- static constexpr TabDef tabs[] = {- {"Dashboard", "F1"}, {"Markets", "F2"}, {"Crypto Trading", "F9"},- {"Portfolio", "F4"}, {"News", "F3"}, {"Agent Studio", "F10"},- {"Backtesting", "F5"}, {"Algo Trading", nullptr}, {"Node Editor", nullptr},- {"Code Editor", nullptr}, {"AI Quant Lab", nullptr}, {"QuantLib", nullptr},- {"Settings", nullptr}, {"Profile", "F12"}, {"Surface", "F6"},- {"Geopolitics", "F7"}, {"Watchlist", "F8"}, {"Economics", nullptr},- {"DBnomics", nullptr},- {"Notes", nullptr},- {"Data Sources", nullptr},- {"M&A Analytics", nullptr},- {"Forum", nullptr},- {"Docs", nullptr},- {"Support", nullptr},- {"About", nullptr},- {"Govt Data", nullptr},+ // Primary tabs only — matches Tauri app's tab bar+ // All other tabs are accessible via Navigate dropdown menu+ struct TabDef { const char* label; const char* shortcut; int tab_idx; };+ static constexpr TabDef primary_tabs[] = {+ {"Dashboard", "F1", 0},+ {"Markets", "F2", 1},+ {"Crypto Trading", "F9", 2},+ {"Portfolio", "F4", 3},+ {"News", "F3", 4},+ {"AI Chat", "F10", 5},+ {"Backtesting", "F5", 6},+ {"Algo Trading", nullptr, 7},+ {"Node Editor", nullptr, 8},+ {"Code Editor", nullptr, 9},+ {"AI Quant Lab", nullptr, 10},+ {"QuantLib", nullptr, 11},+ {"Settings", nullptr, 12},+ {"Profile", "F12", 13},};- constexpr int n_tabs = sizeof(tabs) / sizeof(tabs[0]);+ constexpr int n_tabs = sizeof(primary_tabs) / sizeof(primary_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_);+ bool is_active = (primary_tabs[i].tab_idx == active_tab_);if (is_active) {ImGui::PushStyleColor(ImGuiCol_Button, ACCENT_BG);@@ -325,12 +368,12 @@ void App::render_tab_bar() {ImGui::PushStyleVar(ImGuiStyleVar_FrameBorderSize, 0.0f);}- if (ImGui::Button(tabs[i].label)) {- active_tab_ = i;+ if (ImGui::Button(primary_tabs[i].label)) {+ active_tab_ = primary_tabs[i].tab_idx;}- if (tabs[i].shortcut && ImGui::IsItemHovered()) {- ImGui::SetTooltip("%s (%s)", tabs[i].label, tabs[i].shortcut);+ if (primary_tabs[i].shortcut && ImGui::IsItemHovered()) {+ ImGui::SetTooltip("%s (%s)", primary_tabs[i].label, primary_tabs[i].shortcut);}ImGui::PopStyleVar();@@ -544,11 +587,14 @@ void App::render() {else if (active_tab_ == 9) code_editor_screen_.render();else if (active_tab_ == 8) node_editor_screen_.render();else if (active_tab_ == 12) settings_screen_.render();- else if (active_tab_ == 5) agent_studio_screen_.render();+ else if (active_tab_ == 5) ai_chat_screen_.render();+ else if (active_tab_ == 27) agent_studio_screen_.render();else if (active_tab_ == 2) crypto_trading_screen_.render();+ else if (active_tab_ == 10) ai_quant_lab_screen_.render();else if (active_tab_ == 11) quantlib_screen_.render();else if (active_tab_ == 1) markets_screen_.render();else if (active_tab_ == 7) algo_trading_screen_.render();+ else if (active_tab_ == 28) data_mapping_screen_.render();else dashboard_screen_.render();break;default:diff --git a/fincept-cpp/src/app.h b/fincept-cpp/src/app.hindex 87a8c1b8c..fd6560a70 100644--- a/fincept-cpp/src/app.h+++ b/fincept-cpp/src/app.h@@ -35,6 +35,9 @@#include "screens/gov_data/gov_data_screen.h"#include "screens/backtesting/backtesting_screen.h"#include "screens/algo_trading/algo_trading_screen.h"+#include "screens/ai_chat/ai_chat_screen.h"+#include "screens/ai_quant_lab/ai_quant_lab_screen.h"+#include "screens/data_mapping/data_mapping_screen.h"// Fullscreen toggle (implemented in main.cpp, delegates to Window)void toggle_fullscreen();@@ -91,6 +94,9 @@ private:gov_data::GovDataScreen gov_data_screen_;backtesting::BacktestingScreen backtesting_screen_;algo::AlgoTradingScreen algo_trading_screen_;+ ai_chat::AIChatScreen ai_chat_screen_;+ ai_quant_lab::AIQuantLabScreen ai_quant_lab_screen_;+ data_mapping::DataMappingScreen data_mapping_screen_;// Rendering sectionsvoid render_top_bar();diff --git a/fincept-cpp/src/mcp/mcp_client.cpp b/fincept-cpp/src/mcp/mcp_client.cppnew file mode 100644index 000000000..a189436c4--- /dev/null+++ b/fincept-cpp/src/mcp/mcp_client.cpp@@ -0,0 +1,487 @@+// MCPClient — JSON-RPC 2.0 over stdio implementation+// Spawns external MCP servers and communicates via stdin/stdout pipes.++#include "mcp_client.h"+#include "../core/logger.h"+#include <sstream>+#include <chrono>+#include <cstdlib>++#ifdef _WIN32+#include <io.h>+#else+#include <unistd.h>+#include <signal.h>+#include <sys/wait.h>+#include <fcntl.h>+#endif++namespace fincept::mcp {++static constexpr const char* TAG_CLIENT = "MCPClient";++MCPClient::MCPClient(const MCPServerConfig& config) : config_(config) {}++MCPClient::~MCPClient() {+ stop();+}++// ============================================================================+// Lifecycle+// ============================================================================++Result<void> MCPClient::start() {+ if (running_.load()) return {};++ auto result = spawn_process();+ if (result.failed()) return result;++ running_ = true;++ // Start reader thread+ reader_thread_ = std::thread(&MCPClient::reader_loop, this);++ LOG_INFO(TAG_CLIENT, "Started MCP server: %s (%s)", config_.name.c_str(), config_.id.c_str());+ return {};+}++void MCPClient::stop() {+ if (!running_.load()) return;++ running_ = false;++ // Cancel all pending requests+ {+ std::lock_guard<std::mutex> lock(pending_mutex_);+ for (auto& [id, req] : pending_requests_) {+ try {+ req->promise.set_value(json{{"error", "Server shutting down"}});+ } catch (...) {}+ }+ pending_requests_.clear();+ }++ // Wake up any waiting threads+ queue_cv_.notify_all();++ kill_process();++ if (reader_thread_.joinable()) {+ reader_thread_.join();+ }++ LOG_INFO(TAG_CLIENT, "Stopped MCP server: %s", config_.name.c_str());+}++// ============================================================================+// MCP Protocol+// ============================================================================++Result<json> MCPClient::initialize() {+ json params = {+ {"protocolVersion", "2024-11-05"},+ {"capabilities", {+ {"roots", {{"listChanged", false}}}+ }},+ {"clientInfo", {+ {"name", "fincept-terminal"},+ {"version", "1.0.0"}+ }}+ };++ auto result = send_request("initialize", params, 120000); // 120s timeout for init+ if (result.failed()) return result;++ // Send initialized notification (no response expected)+ json notif = {+ {"jsonrpc", "2.0"},+ {"method", "notifications/initialized"}+ };+ write_message(notif.dump());++ return result;+}++Result<std::vector<ExternalTool>> MCPClient::list_tools() {+ auto result = send_request("tools/list");+ if (result.failed()) return Error(result.error().message);++ std::vector<ExternalTool> tools;+ try {+ auto& tools_arr = result.value()["tools"];+ for (auto& t : tools_arr) {+ ExternalTool tool;+ tool.server_id = config_.id;+ tool.server_name = config_.name;+ tool.name = t.value("name", "");+ tool.description = t.value("description", "");+ tool.input_schema = t.value("inputSchema", json::object());+ tools.push_back(std::move(tool));+ }+ } catch (const std::exception& e) {+ return Error(std::string("Failed to parse tools list: ") + e.what());+ }++ return tools;+}++Result<json> MCPClient::call_tool(const std::string& tool_name, const json& args) {+ json params = {+ {"name", tool_name},+ {"arguments", args}+ };+ return send_request("tools/call", params);+}++Result<void> MCPClient::ping() {+ auto result = send_request("ping", json::object(), 5000);+ if (result.failed()) return Error(result.error().message);+ return {};+}++// ============================================================================+// JSON-RPC Transport+// ============================================================================++Result<json> MCPClient::send_request(const std::string& method, const json& params, int timeout_ms) {+ if (!running_.load()) return Error("Server not running");++ int id = next_id_++;++ json request = {+ {"jsonrpc", "2.0"},+ {"id", id},+ {"method", method},+ {"params", params}+ };++ // Register pending request+ auto pending = std::make_shared<PendingRequest>();+ auto future = pending->promise.get_future();++ {+ std::lock_guard<std::mutex> lock(pending_mutex_);+ pending_requests_[id] = pending;+ }++ // Send the request+ std::string msg = request.dump();+ if (!write_message(msg)) {+ std::lock_guard<std::mutex> lock(pending_mutex_);+ pending_requests_.erase(id);+ return Error("Failed to write to server stdin");+ }++ LOG_DEBUG(TAG_CLIENT, "[%s] -> %s (id=%d)", config_.id.c_str(), method.c_str(), id);++ // Wait for response with timeout+ auto status = future.wait_for(std::chrono::milliseconds(timeout_ms));+ if (status == std::future_status::timeout) {+ std::lock_guard<std::mutex> lock(pending_mutex_);+ pending_requests_.erase(id);+ return Error("Request timed out: " + method);+ }++ json response = future.get();++ // Check for JSON-RPC error+ if (response.contains("error")) {+ auto& err = response["error"];+ std::string msg_str = err.value("message", "Unknown error");+ int code = err.value("code", -1);+ return Error(msg_str, code);+ }++ return response.value("result", json::object());+}++bool MCPClient::write_message(const std::string& msg) {+ // MCP uses newline-delimited JSON+ std::string line = msg + "\n";++#ifdef _WIN32+ if (child_stdin_write_ == INVALID_HANDLE_VALUE) return false;+ DWORD written = 0;+ return WriteFile(child_stdin_write_, line.c_str(), (DWORD)line.size(), &written, NULL) != 0;+#else+ if (child_stdin_fd_ < 0) return false;+ ssize_t written = ::write(child_stdin_fd_, line.c_str(), line.size());+ return written == (ssize_t)line.size();+#endif+}++// ============================================================================+// Reader Thread — reads stdout, dispatches responses+// ============================================================================++void MCPClient::reader_loop() {+ std::string buffer;+ char chunk[4096];++ while (running_.load()) {+#ifdef _WIN32+ DWORD bytes_read = 0;+ BOOL ok = ReadFile(child_stdout_read_, chunk, sizeof(chunk) - 1, &bytes_read, NULL);+ if (!ok || bytes_read == 0) {+ if (running_.load()) {+ LOG_WARN(TAG_CLIENT, "[%s] stdout read failed or EOF", config_.id.c_str());+ }+ break;+ }+ chunk[bytes_read] = '\0';+#else+ ssize_t bytes_read = ::read(child_stdout_fd_, chunk, sizeof(chunk) - 1);+ if (bytes_read <= 0) {+ if (running_.load()) {+ LOG_WARN(TAG_CLIENT, "[%s] stdout read failed or EOF", config_.id.c_str());+ }+ break;+ }+ chunk[bytes_read] = '\0';+#endif++ buffer.append(chunk, bytes_read);++ // Process complete lines (newline-delimited JSON)+ size_t pos;+ while ((pos = buffer.find('\n')) != std::string::npos) {+ std::string line = buffer.substr(0, pos);+ buffer.erase(0, pos + 1);++ if (line.empty() || line[0] != '{') continue;++ try {+ json msg = json::parse(line);++ if (msg.contains("id") && !msg["id"].is_null()) {+ // Response to a request+ int id = msg["id"].get<int>();+ std::lock_guard<std::mutex> lock(pending_mutex_);+ auto it = pending_requests_.find(id);+ if (it != pending_requests_.end()) {+ try {+ it->second->promise.set_value(msg);+ } catch (...) {}+ pending_requests_.erase(it);+ }+ } else {+ // Notification+ std::lock_guard<std::mutex> lock(queue_mutex_);+ notification_queue_.push(msg);+ queue_cv_.notify_one();+ }+ } catch (const json::parse_error& e) {+ LOG_DEBUG(TAG_CLIENT, "[%s] Non-JSON line: %s", config_.id.c_str(), line.substr(0, 100).c_str());+ }+ }+ }++ running_ = false;+}++// ============================================================================+// Process Management+// ============================================================================++std::string MCPClient::resolve_command() const {+ const auto& cmd = config_.command;++#ifdef _WIN32+ // On Windows, resolve npx/bunx/uvx to .cmd variants+ if (cmd == "npx" || cmd == "bunx" || cmd == "uvx" || cmd == "node" || cmd == "python" || cmd == "python3") {+ // Try cmd.exe wrapper — Windows needs this for .cmd scripts+ return cmd;+ }+#endif++ return cmd;+}++Result<void> MCPClient::spawn_process() {+ std::string cmd = resolve_command();+ LOG_INFO(TAG_CLIENT, "Spawning: %s %s", cmd.c_str(),+ config_.args.empty() ? "" : config_.args[0].c_str());++#ifdef _WIN32+ // Create pipes for stdin/stdout+ SECURITY_ATTRIBUTES sa;+ sa.nLength = sizeof(SECURITY_ATTRIBUTES);+ sa.bInheritHandle = TRUE;+ sa.lpSecurityDescriptor = NULL;++ HANDLE stdin_read = INVALID_HANDLE_VALUE, stdin_write = INVALID_HANDLE_VALUE;+ HANDLE stdout_read = INVALID_HANDLE_VALUE, stdout_write = INVALID_HANDLE_VALUE;++ if (!CreatePipe(&stdin_read, &stdin_write, &sa, 0))+ return Error("Failed to create stdin pipe");+ if (!CreatePipe(&stdout_read, &stdout_write, &sa, 0)) {+ CloseHandle(stdin_read); CloseHandle(stdin_write);+ return Error("Failed to create stdout pipe");+ }++ // Ensure our ends are not inherited+ SetHandleInformation(stdin_write, HANDLE_FLAG_INHERIT, 0);+ SetHandleInformation(stdout_read, HANDLE_FLAG_INHERIT, 0);++ // Build command line+ std::string cmdline = cmd;+ for (const auto& arg : config_.args) {+ cmdline += " " + arg;+ }++ // Set up environment block if needed+ std::vector<char> env_block;+ if (!config_.env.empty()) {+ // Get current environment+ LPCH current_env = GetEnvironmentStrings();+ if (current_env) {+ LPCH p = current_env;+ while (*p) {+ std::string var(p);+ env_block.insert(env_block.end(), var.begin(), var.end());+ env_block.push_back('\0');+ p += var.size() + 1;+ }+ FreeEnvironmentStrings(current_env);+ }+ // Add custom env vars+ for (const auto& [key, val] : config_.env) {+ std::string entry = key + "=" + val;+ env_block.insert(env_block.end(), entry.begin(), entry.end());+ env_block.push_back('\0');+ }+ env_block.push_back('\0'); // Double null terminator+ }++ STARTUPINFOA si = {};+ si.cb = sizeof(si);+ si.hStdInput = stdin_read;+ si.hStdOutput = stdout_write;+ si.hStdError = GetStdHandle(STD_ERROR_HANDLE);+ si.dwFlags |= STARTF_USESTDHANDLES;++ PROCESS_INFORMATION pi = {};++ // CREATE_NO_WINDOW to avoid flashing console+ DWORD flags = CREATE_NO_WINDOW;++ BOOL success = CreateProcessA(+ NULL,+ const_cast<char*>(cmdline.c_str()),+ NULL, NULL, TRUE, flags,+ env_block.empty() ? NULL : env_block.data(),+ NULL,+ &si, &pi+ );++ // Close child-side pipe handles+ CloseHandle(stdin_read);+ CloseHandle(stdout_write);++ if (!success) {+ CloseHandle(stdin_write);+ CloseHandle(stdout_read);+ DWORD err = GetLastError();+ return Error("Failed to spawn process: error code " + std::to_string(err));+ }++ child_stdin_write_ = stdin_write;+ child_stdout_read_ = stdout_read;+ process_handle_ = pi.hProcess;+ thread_handle_ = pi.hThread;++ return {};++#else+ // Unix: fork + exec with pipes+ int stdin_pipe[2], stdout_pipe[2];++ if (pipe(stdin_pipe) < 0) return Error("Failed to create stdin pipe");+ if (pipe(stdout_pipe) < 0) {+ close(stdin_pipe[0]); close(stdin_pipe[1]);+ return Error("Failed to create stdout pipe");+ }++ pid_t pid = fork();+ if (pid < 0) {+ close(stdin_pipe[0]); close(stdin_pipe[1]);+ close(stdout_pipe[0]); close(stdout_pipe[1]);+ return Error("Failed to fork");+ }++ if (pid == 0) {+ // Child process+ dup2(stdin_pipe[0], STDIN_FILENO);+ dup2(stdout_pipe[1], STDOUT_FILENO);+ close(stdin_pipe[0]); close(stdin_pipe[1]);+ close(stdout_pipe[0]); close(stdout_pipe[1]);++ // Set environment variables+ for (const auto& [key, val] : config_.env) {+ setenv(key.c_str(), val.c_str(), 1);+ }++ // Build argv+ std::vector<const char*> argv;+ argv.push_back(cmd.c_str());+ for (const auto& arg : config_.args) {+ argv.push_back(arg.c_str());+ }+ argv.push_back(nullptr);++ execvp(cmd.c_str(), const_cast<char* const*>(argv.data()));+ _exit(127);+ }++ // Parent+ close(stdin_pipe[0]);+ close(stdout_pipe[1]);++ child_stdin_fd_ = stdin_pipe[1];+ child_stdout_fd_ = stdout_pipe[0];+ child_pid_ = pid;++ return {};+#endif+}++void MCPClient::kill_process() {+#ifdef _WIN32+ if (child_stdin_write_ != INVALID_HANDLE_VALUE) {+ CloseHandle(child_stdin_write_);+ child_stdin_write_ = INVALID_HANDLE_VALUE;+ }+ if (child_stdout_read_ != INVALID_HANDLE_VALUE) {+ CloseHandle(child_stdout_read_);+ child_stdout_read_ = INVALID_HANDLE_VALUE;+ }+ if (process_handle_ != INVALID_HANDLE_VALUE) {+ TerminateProcess(process_handle_, 0);+ WaitForSingleObject(process_handle_, 5000);+ CloseHandle(process_handle_);+ process_handle_ = INVALID_HANDLE_VALUE;+ }+ if (thread_handle_ != INVALID_HANDLE_VALUE) {+ CloseHandle(thread_handle_);+ thread_handle_ = INVALID_HANDLE_VALUE;+ }+#else+ if (child_stdin_fd_ >= 0) { close(child_stdin_fd_); child_stdin_fd_ = -1; }+ if (child_stdout_fd_ >= 0) { close(child_stdout_fd_); child_stdout_fd_ = -1; }+ if (child_pid_ > 0) {+ kill(child_pid_, SIGTERM);+ int status;+ // Wait up to 5s+ for (int i = 0; i < 50; ++i) {+ if (waitpid(child_pid_, &status, WNOHANG) != 0) break;+ std::this_thread::sleep_for(std::chrono::milliseconds(100));+ }+ // Force kill if still alive+ kill(child_pid_, SIGKILL);+ waitpid(child_pid_, &status, 0);+ child_pid_ = -1;+ }+#endif+}++} // namespace fincept::mcpdiff --git a/fincept-cpp/src/mcp/mcp_client.h b/fincept-cpp/src/mcp/mcp_client.hnew file mode 100644index 000000000..2591a545d--- /dev/null+++ b/fincept-cpp/src/mcp/mcp_client.h@@ -0,0 +1,95 @@+#pragma once+// MCPClient — JSON-RPC 2.0 client over stdio for external MCP servers+// Spawns a child process (npx, uvx, node, etc.) and communicates via stdin/stdout.+// Each MCPClient instance manages one external server connection.++#include "mcp_types.h"+#include "../core/result.h"+#include <thread>+#include <atomic>+#include <condition_variable>+#include <queue>++#ifdef _WIN32+#include <windows.h>+#endif++namespace fincept::mcp {++using core::Result;+using core::Error;++// ============================================================================+// MCPClient — one-per-server stdio transport+// ============================================================================++class MCPClient {+public:+ explicit MCPClient(const MCPServerConfig& config);+ ~MCPClient();++ MCPClient(const MCPClient&) = delete;+ MCPClient& operator=(const MCPClient&) = delete;++ // Lifecycle+ Result<void> start();+ void stop();+ bool is_running() const { return running_.load(); }++ // MCP Protocol+ Result<json> initialize();+ Result<std::vector<ExternalTool>> list_tools();+ Result<json> call_tool(const std::string& tool_name, const json& args);+ Result<void> ping();++ // Server info+ const MCPServerConfig& config() const { return config_; }+ const std::string& server_id() const { return config_.id; }++private:+ MCPServerConfig config_;+ std::atomic<bool> running_{false};+ int next_id_ = 1;++ // JSON-RPC request/response+ Result<json> send_request(const std::string& method, const json& params = json::object(),+ int timeout_ms = 30000);+ bool write_message(const std::string& msg);+ Result<std::string> read_message(int timeout_ms);++ // Reader thread+ std::thread reader_thread_;+ void reader_loop();++ // Pending requests+ struct PendingRequest {+ std::promise<json> promise;+ };+ std::mutex pending_mutex_;+ std::unordered_map<int, std::shared_ptr<PendingRequest>> pending_requests_;++ // Incoming message queue (for notifications)+ std::mutex queue_mutex_;+ std::condition_variable queue_cv_;+ std::queue<json> notification_queue_;++ // Process handles+#ifdef _WIN32+ HANDLE child_stdin_write_ = INVALID_HANDLE_VALUE;+ HANDLE child_stdout_read_ = INVALID_HANDLE_VALUE;+ HANDLE process_handle_ = INVALID_HANDLE_VALUE;+ HANDLE thread_handle_ = INVALID_HANDLE_VALUE;+#else+ int child_stdin_fd_ = -1;+ int child_stdout_fd_ = -1;+ pid_t child_pid_ = -1;+#endif++ Result<void> spawn_process();+ void kill_process();++ // Resolve command (handle npx, uvx, bunx)+ std::string resolve_command() const;+};++} // namespace fincept::mcpdiff --git a/fincept-cpp/src/mcp/mcp_init.cpp b/fincept-cpp/src/mcp/mcp_init.cppnew file mode 100644index 000000000..07df88f80--- /dev/null+++ b/fincept-cpp/src/mcp/mcp_init.cpp@@ -0,0 +1,36 @@+// MCP Initialization — register all tools and start the system++#include "mcp_init.h"+#include "mcp_provider.h"+#include "mcp_service.h"+#include "tools/navigation_tools.h"+#include "tools/market_data_tools.h"+#include "tools/settings_tools.h"+#include "tools/portfolio_tools.h"+#include "../core/logger.h"++namespace fincept::mcp {++static constexpr const char* TAG_INIT = "MCPInit";++void initialize_all_tools() {+ auto& provider = MCPProvider::instance();++ // Register tool modules+ provider.register_tools(tools::get_navigation_tools());+ provider.register_tools(tools::get_market_data_tools());+ provider.register_tools(tools::get_settings_tools());+ provider.register_tools(tools::get_portfolio_tools());++ LOG_INFO(TAG_INIT, "Registered %zu internal MCP tools", provider.tool_count());++ // Initialize the unified service (starts external servers too)+ MCPService::instance().initialize();+}++void shutdown_mcp() {+ MCPService::instance().shutdown();+ LOG_INFO(TAG_INIT, "MCP system shut down");+}++} // namespace fincept::mcpdiff --git a/fincept-cpp/src/mcp/mcp_init.h b/fincept-cpp/src/mcp/mcp_init.hnew file mode 100644index 000000000..a92e3faf8--- /dev/null+++ b/fincept-cpp/src/mcp/mcp_init.h@@ -0,0 +1,13 @@+#pragma once+// MCP Initialization — registers all internal tools with MCPProvider+// Call mcp::initialize_all_tools() during App::initialize()++namespace fincept::mcp {++/// Register all built-in tools and initialize the MCP system+void initialize_all_tools();++/// Shutdown the MCP system+void shutdown_mcp();++} // namespace fincept::mcpdiff --git a/fincept-cpp/src/mcp/mcp_manager.cpp b/fincept-cpp/src/mcp/mcp_manager.cppnew file mode 100644index 000000000..97943f73c--- /dev/null+++ b/fincept-cpp/src/mcp/mcp_manager.cpp@@ -0,0 +1,449 @@+// MCPManager — External MCP server lifecycle management++#include "mcp_manager.h"+#include "../core/logger.h"+#include "../storage/database.h"+#include <algorithm>++namespace fincept::mcp {++static constexpr const char* TAG_MANAGER = "MCPManager";++MCPManager& MCPManager::instance() {+ static MCPManager s;+ return s;+}++// ============================================================================+// Initialization+// ============================================================================++void MCPManager::initialize() {+ create_mcp_schema();+ load_configs_from_db();+ LOG_INFO(TAG_MANAGER, "Loaded %zu MCP server configs", configs_.size());+}++void MCPManager::shutdown() {+ stop_health_check();+ stop_all();+ LOG_INFO(TAG_MANAGER, "MCPManager shut down");+}++// ============================================================================+// Server Configuration+// ============================================================================++Result<void> MCPManager::save_server(const MCPServerConfig& config) {+ std::lock_guard<std::mutex> lock(mutex_);+ configs_[config.id] = config;+ save_config_to_db(config);+ LOG_INFO(TAG_MANAGER, "Saved server config: %s", config.name.c_str());+ return {};+}++Result<void> MCPManager::remove_server(const std::string& server_id) {+ // Stop if running+ stop_server(server_id);++ std::lock_guard<std::mutex> lock(mutex_);+ configs_.erase(server_id);+ tool_cache_.erase(server_id);+ restart_info_.erase(server_id);+ delete_config_from_db(server_id);+ LOG_INFO(TAG_MANAGER, "Removed server: %s", server_id.c_str());+ return {};+}++std::vector<MCPServerConfig> MCPManager::get_servers() const {+ std::lock_guard<std::mutex> lock(mutex_);+ std::vector<MCPServerConfig> result;+ result.reserve(configs_.size());+ for (const auto& [id, cfg] : configs_) {+ auto copy = cfg;+ // Update runtime status+ auto it = clients_.find(id);+ copy.status = (it != clients_.end() && it->second->is_running())+ ? ServerStatus::Running : ServerStatus::Stopped;+ result.push_back(std::move(copy));+ }+ return result;+}++std::optional<MCPServerConfig> MCPManager::get_server(const std::string& server_id) const {+ std::lock_guard<std::mutex> lock(mutex_);+ auto it = configs_.find(server_id);+ if (it == configs_.end()) return std::nullopt;+ return it->second;+}++// ============================================================================+// Server Lifecycle+// ============================================================================++Result<void> MCPManager::start_server(const std::string& server_id) {+ std::lock_guard<std::mutex> lock(mutex_);++ auto cfg_it = configs_.find(server_id);+ if (cfg_it == configs_.end()) return Error("Server not found: " + server_id);++ // Already running?+ auto client_it = clients_.find(server_id);+ if (client_it != clients_.end() && client_it->second->is_running()) {+ return {}; // Already running+ }++ auto client = std::make_unique<MCPClient>(cfg_it->second);+ auto result = client->start();+ if (result.failed()) {+ LOG_ERROR(TAG_MANAGER, "Failed to start server %s: %s", server_id.c_str(), result.error().message.c_str());+ update_server_status_in_db(server_id, ServerStatus::Error);+ return result;+ }++ // Initialize MCP handshake+ auto init_result = client->initialize();+ if (init_result.failed()) {+ LOG_ERROR(TAG_MANAGER, "MCP init failed for %s: %s", server_id.c_str(), init_result.error().message.c_str());+ client->stop();+ update_server_status_in_db(server_id, ServerStatus::Error);+ return Error("MCP initialization failed: " + init_result.error().message);+ }++ // Fetch tools+ auto tools_result = client->list_tools();+ if (tools_result.ok()) {+ tool_cache_[server_id] = tools_result.value();+ LOG_INFO(TAG_MANAGER, "Server %s has %zu tools", server_id.c_str(), tools_result.value().size());+ }++ clients_[server_id] = std::move(client);+ update_server_status_in_db(server_id, ServerStatus::Running);+ restart_info_.erase(server_id); // Reset restart counter on successful start++ return {};+}++Result<void> MCPManager::stop_server(const std::string& server_id) {+ std::lock_guard<std::mutex> lock(mutex_);++ auto it = clients_.find(server_id);+ if (it == clients_.end()) return {};++ it->second->stop();+ clients_.erase(it);+ tool_cache_.erase(server_id);+ update_server_status_in_db(server_id, ServerStatus::Stopped);++ return {};+}++Result<void> MCPManager::restart_server(const std::string& server_id) {+ stop_server(server_id);+ return start_server(server_id);+}++void MCPManager::start_auto_servers() {+ std::vector<std::string> auto_ids;+ {+ std::lock_guard<std::mutex> lock(mutex_);+ for (const auto& [id, cfg] : configs_) {+ if (cfg.auto_start && cfg.enabled) {+ auto_ids.push_back(id);+ }+ }+ }++ for (const auto& id : auto_ids) {+ auto result = start_server(id);+ if (result.failed()) {+ LOG_WARN(TAG_MANAGER, "Auto-start failed for %s: %s", id.c_str(), result.error().message.c_str());+ }+ }+}++void MCPManager::stop_all() {+ std::lock_guard<std::mutex> lock(mutex_);+ for (auto& [id, client] : clients_) {+ client->stop();+ update_server_status_in_db(id, ServerStatus::Stopped);+ }+ clients_.clear();+ tool_cache_.clear();+}++ServerStatus MCPManager::get_server_status(const std::string& server_id) const {+ std::lock_guard<std::mutex> lock(mutex_);+ auto it = clients_.find(server_id);+ if (it == clients_.end()) return ServerStatus::Stopped;+ return it->second->is_running() ? ServerStatus::Running : ServerStatus::Error;+}++// ============================================================================+// Tool Aggregation+// ============================================================================++std::vector<ExternalTool> MCPManager::get_all_external_tools() const {+ std::lock_guard<std::mutex> lock(mutex_);+ std::vector<ExternalTool> result;+ for (const auto& [server_id, tools] : tool_cache_) {+ // Only include tools from running servers+ auto it = clients_.find(server_id);+ if (it != clients_.end() && it->second->is_running()) {+ result.insert(result.end(), tools.begin(), tools.end());+ }+ }+ return result;+}++Result<json> MCPManager::call_external_tool(const std::string& server_id,+ const std::string& tool_name,+ const json& args) {+ std::lock_guard<std::mutex> lock(mutex_);++ auto it = clients_.find(server_id);+ if (it == clients_.end() || !it->second->is_running()) {+ return Error("Server not running: " + server_id);+ }++ return it->second->call_tool(tool_name, args);+}++// ============================================================================+// Health Check+// ============================================================================++void MCPManager::start_health_check(int interval_seconds) {+ if (health_running_.load()) return;++ health_interval_seconds_ = interval_seconds;+ health_running_ = true;+ health_thread_ = std::thread(&MCPManager::health_check_loop, this);+ LOG_INFO(TAG_MANAGER, "Health check started (interval: %ds)", interval_seconds);+}++void MCPManager::stop_health_check() {+ health_running_ = false;+ if (health_thread_.joinable()) {+ health_thread_.join();+ }+}++void MCPManager::health_check_loop() {+ while (health_running_.load()) {+ // Sleep in small increments so we can exit quickly+ for (int i = 0; i < health_interval_seconds_ * 10 && health_running_.load(); ++i) {+ std::this_thread::sleep_for(std::chrono::milliseconds(100));+ }++ if (!health_running_.load()) break;++ std::lock_guard<std::mutex> lock(mutex_);+ std::vector<std::string> dead_servers;++ for (auto& [id, client] : clients_) {+ if (!client->is_running()) {+ dead_servers.push_back(id);+ continue;+ }++ auto ping_result = client->ping();+ if (ping_result.failed()) {+ LOG_WARN(TAG_MANAGER, "Ping failed for %s: %s", id.c_str(), ping_result.error().message.c_str());+ dead_servers.push_back(id);+ }+ }++ // Attempt restart for dead servers+ for (const auto& id : dead_servers) {+ auto& info = restart_info_[id];+ auto now = std::chrono::steady_clock::now();+ auto elapsed = std::chrono::duration_cast<std::chrono::seconds>(+ now - info.last_attempt).count();++ if (info.attempts >= MAX_RESTART_ATTEMPTS && elapsed < RESTART_COOLDOWN_SECONDS) {+ LOG_WARN(TAG_MANAGER, "Server %s exceeded max restart attempts, cooldown active", id.c_str());+ continue;+ }++ if (elapsed >= RESTART_COOLDOWN_SECONDS) {+ info.attempts = 0; // Reset after cooldown+ }++ info.attempts++;+ info.last_attempt = now;++ LOG_INFO(TAG_MANAGER, "Attempting restart of %s (attempt %d/%d)",+ id.c_str(), info.attempts, MAX_RESTART_ATTEMPTS);++ // Clean up the dead client+ clients_.erase(id);+ tool_cache_.erase(id);++ // We need to release the lock to call start_server which also locks+ // So we just mark for restart and do it outside+ // Actually, let's restart inline since we already have the lock+ auto cfg_it = configs_.find(id);+ if (cfg_it == configs_.end()) continue;++ auto client = std::make_unique<MCPClient>(cfg_it->second);+ auto result = client->start();+ if (result.ok()) {+ auto init_result = client->initialize();+ if (init_result.ok()) {+ auto tools_result = client->list_tools();+ if (tools_result.ok()) {+ tool_cache_[id] = tools_result.value();+ }+ clients_[id] = std::move(client);+ update_server_status_in_db(id, ServerStatus::Running);+ LOG_INFO(TAG_MANAGER, "Successfully restarted %s", id.c_str());+ restart_info_.erase(id);+ } else {+ client->stop();+ update_server_status_in_db(id, ServerStatus::Error);+ }+ } else {+ update_server_status_in_db(id, ServerStatus::Error);+ }+ }+ }+}++// ============================================================================+// Database Operations+// ============================================================================++void MCPManager::create_mcp_schema() {+ auto& db = fincept::db::Database::instance();+ std::lock_guard<std::recursive_mutex> lock(db.mutex());++ db.exec(R"(+ CREATE TABLE IF NOT EXISTS mcp_servers (+ id TEXT PRIMARY KEY,+ name TEXT NOT NULL,+ description TEXT DEFAULT '',+ command TEXT NOT NULL,+ args TEXT DEFAULT '[]',+ env TEXT DEFAULT '{}',+ category TEXT DEFAULT '',+ enabled INTEGER DEFAULT 1,+ auto_start INTEGER DEFAULT 0,+ status TEXT DEFAULT 'stopped',+ created_at TEXT DEFAULT (datetime('now')),+ updated_at TEXT DEFAULT (datetime('now'))+ )+ )");+}++void MCPManager::load_configs_from_db() {+ auto& db = fincept::db::Database::instance();+ std::lock_guard<std::recursive_mutex> lock(db.mutex());++ auto stmt = db.prepare("SELECT id, name, description, command, args, env, category, enabled, auto_start, status, created_at, updated_at FROM mcp_servers");++ std::lock_guard<std::mutex> my_lock(mutex_);+ configs_.clear();++ while (stmt.step()) {+ MCPServerConfig cfg;+ cfg.id = stmt.col_text(0);+ cfg.name = stmt.col_text(1);+ cfg.description = stmt.col_text(2);+ cfg.command = stmt.col_text(3);++ // Parse args JSON array+ try {+ auto args_json = json::parse(stmt.col_text(4));+ if (args_json.is_array()) {+ for (const auto& a : args_json) {+ cfg.args.push_back(a.get<std::string>());+ }+ }+ } catch (...) {}++ // Parse env JSON object+ try {+ auto env_json = json::parse(stmt.col_text(5));+ if (env_json.is_object()) {+ for (auto& [key, val] : env_json.items()) {+ cfg.env[key] = val.get<std::string>();+ }+ }+ } catch (...) {}++ cfg.category = stmt.col_text(6);+ cfg.enabled = stmt.col_bool(7);+ cfg.auto_start = stmt.col_bool(8);++ std::string status_str = stmt.col_text(9);+ if (status_str == "running") cfg.status = ServerStatus::Running;+ else if (status_str == "error") cfg.status = ServerStatus::Error;+ else cfg.status = ServerStatus::Stopped;++ cfg.created_at = stmt.col_text(10);+ cfg.updated_at = stmt.col_text(11);++ configs_[cfg.id] = std::move(cfg);+ }+}++void MCPManager::save_config_to_db(const MCPServerConfig& config) {+ auto& db = fincept::db::Database::instance();+ std::lock_guard<std::recursive_mutex> lock(db.mutex());++ json args_json = json::array();+ for (const auto& a : config.args) args_json.push_back(a);++ json env_json = json::object();+ for (const auto& [k, v] : config.env) env_json[k] = v;++ auto stmt = db.prepare(R"(+ INSERT OR REPLACE INTO mcp_servers+ (id, name, description, command, args, env, category, enabled, auto_start, status, updated_at)+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, datetime('now'))+ )");++ stmt.bind_text(1, config.id);+ stmt.bind_text(2, config.name);+ stmt.bind_text(3, config.description);+ stmt.bind_text(4, config.command);+ stmt.bind_text(5, args_json.dump());+ stmt.bind_text(6, env_json.dump());+ stmt.bind_text(7, config.category);+ stmt.bind_int(8, config.enabled ? 1 : 0);+ stmt.bind_int(9, config.auto_start ? 1 : 0);+ stmt.bind_text(10, server_status_str(config.status));+ stmt.execute();+}++void MCPManager::delete_config_from_db(const std::string& server_id) {+ auto& db = fincept::db::Database::instance();+ std::lock_guard<std::recursive_mutex> lock(db.mutex());++ auto stmt = db.prepare("DELETE FROM mcp_servers WHERE id = ?");+ stmt.bind_text(1, server_id);+ stmt.execute();+}++void MCPManager::update_server_status_in_db(const std::string& server_id, ServerStatus status) {+ auto& db = fincept::db::Database::instance();+ std::lock_guard<std::recursive_mutex> lock(db.mutex());++ auto stmt = db.prepare("UPDATE mcp_servers SET status = ?, updated_at = datetime('now') WHERE id = ?");+ stmt.bind_text(1, server_status_str(status));+ stmt.bind_text(2, server_id);+ stmt.execute();+}++void MCPManager::refresh_tool_cache(const std::string& server_id) {+ auto it = clients_.find(server_id);+ if (it == clients_.end() || !it->second->is_running()) return;++ auto result = it->second->list_tools();+ if (result.ok()) {+ tool_cache_[server_id] = result.value();+ }+}++} // namespace fincept::mcpdiff --git a/fincept-cpp/src/mcp/mcp_manager.h b/fincept-cpp/src/mcp/mcp_manager.hnew file mode 100644index 000000000..41ea7f5cd--- /dev/null+++ b/fincept-cpp/src/mcp/mcp_manager.h@@ -0,0 +1,128 @@+#pragma once+// MCPManager — Manages external MCP server lifecycle+// Stores configs in SQLite, spawns/stops servers, health checks,+// auto-restart with backoff, tool aggregation from all running servers.++#include "mcp_types.h"+#include "mcp_client.h"+#include "../core/result.h"+#include <unordered_map>+#include <mutex>+#include <thread>+#include <atomic>+#include <chrono>++namespace fincept::mcp {++using core::Result;+using core::Error;++class MCPManager {+public:+ static MCPManager& instance();++ // ── Server Configuration (SQLite persistence) ───────────────────────++ /// Add or update a server config+ Result<void> save_server(const MCPServerConfig& config);++ /// Remove a server config and stop if running+ Result<void> remove_server(const std::string& server_id);++ /// Get all configured servers+ std::vector<MCPServerConfig> get_servers() const;++ /// Get a specific server config+ std::optional<MCPServerConfig> get_server(const std::string& server_id) const;++ // ── Server Lifecycle ────────────────────────────────────────────────++ /// Start a specific server+ Result<void> start_server(const std::string& server_id);++ /// Stop a specific server+ Result<void> stop_server(const std::string& server_id);++ /// Restart a server+ Result<void> restart_server(const std::string& server_id);++ /// Start all auto-start servers+ void start_auto_servers();++ /// Stop all running servers+ void stop_all();++ /// Get status of a specific server+ ServerStatus get_server_status(const std::string& server_id) const;++ // ── Tool Aggregation ────────────────────────────────────────────────++ /// Get all tools from all running external servers+ std::vector<ExternalTool> get_all_external_tools() const;++ /// Call a tool on a specific external server+ Result<json> call_external_tool(const std::string& server_id,+ const std::string& tool_name,+ const json& args);++ // ── Health Check ────────────────────────────────────────────────────++ /// Start background health check thread+ void start_health_check(int interval_seconds = 60);++ /// Stop health check thread+ void stop_health_check();++ // ── Lifecycle ───────────────────────────────────────────────────────++ /// Initialize — load configs from DB, create schema+ void initialize();++ /// Shutdown — stop all servers, stop health check+ void shutdown();++ MCPManager(const MCPManager&) = delete;+ MCPManager& operator=(const MCPManager&) = delete;++private:+ MCPManager() = default;++ mutable std::mutex mutex_;++ // Running server clients+ std::unordered_map<std::string, std::unique_ptr<MCPClient>> clients_;++ // Cached tools per server+ mutable std::unordered_map<std::string, std::vector<ExternalTool>> tool_cache_;+ mutable std::chrono::steady_clock::time_point cache_time_;++ // Server configs (loaded from DB)+ std::unordered_map<std::string, MCPServerConfig> configs_;++ // Health check+ std::thread health_thread_;+ std::atomic<bool> health_running_{false};+ int health_interval_seconds_ = 60;+ void health_check_loop();++ // Restart tracking+ struct RestartInfo {+ int attempts = 0;+ std::chrono::steady_clock::time_point last_attempt;+ };+ std::unordered_map<std::string, RestartInfo> restart_info_;+ static constexpr int MAX_RESTART_ATTEMPTS = 3;+ static constexpr int RESTART_COOLDOWN_SECONDS = 300; // 5 minutes++ // DB operations+ void create_mcp_schema();+ void load_configs_from_db();+ void save_config_to_db(const MCPServerConfig& config);+ void delete_config_from_db(const std::string& server_id);+ void update_server_status_in_db(const std::string& server_id, ServerStatus status);++ // Tool cache refresh+ void refresh_tool_cache(const std::string& server_id);+};++} // namespace fincept::mcpdiff --git a/fincept-cpp/src/mcp/mcp_provider.cpp b/fincept-cpp/src/mcp/mcp_provider.cppnew file mode 100644index 000000000..e355ea7a8--- /dev/null+++ b/fincept-cpp/src/mcp/mcp_provider.cpp@@ -0,0 +1,186 @@+// MCPProvider — Internal tool registry and executor implementation++#include "mcp_provider.h"+#include "../core/logger.h"++namespace fincept::mcp {++static constexpr const char* TAG_PROVIDER = "MCP";++MCPProvider& MCPProvider::instance() {+ static MCPProvider s;+ return s;+}++// ============================================================================+// Registration+// ============================================================================++void MCPProvider::register_tool(ToolDef tool) {+ std::lock_guard<std::mutex> lock(mutex_);+ auto name = tool.name;+ tools_.emplace(std::move(name), std::move(tool));+}++void MCPProvider::register_tools(std::vector<ToolDef> tools) {+ std::lock_guard<std::mutex> lock(mutex_);+ for (auto& t : tools) {+ auto name = t.name;+ tools_.emplace(std::move(name), std::move(t));+ }+}++void MCPProvider::unregister_tool(const std::string& name) {+ std::lock_guard<std::mutex> lock(mutex_);+ tools_.erase(name);+}++// ============================================================================+// Enable / Disable+// ============================================================================++void MCPProvider::set_tool_enabled(const std::string& name, bool enabled) {+ std::lock_guard<std::mutex> lock(mutex_);+ if (enabled)+ disabled_tools_.erase(name);+ else+ disabled_tools_.insert(name);+}++bool MCPProvider::is_tool_enabled(const std::string& name) const {+ std::lock_guard<std::mutex> lock(mutex_);+ return disabled_tools_.find(name) == disabled_tools_.end();+}++// ============================================================================+// Discovery+// ============================================================================++std::vector<UnifiedTool> MCPProvider::list_tools() const {+ std::lock_guard<std::mutex> lock(mutex_);+ std::vector<UnifiedTool> result;+ result.reserve(tools_.size());++ for (const auto& [name, tool] : tools_) {+ if (disabled_tools_.count(name)) continue;++ result.push_back({+ INTERNAL_SERVER_ID,+ INTERNAL_SERVER_NAME,+ tool.name,+ tool.description,+ tool.input_schema.to_json(),+ true+ });+ }+ return result;+}++std::vector<UnifiedTool> MCPProvider::list_all_tools() const {+ std::lock_guard<std::mutex> lock(mutex_);+ std::vector<UnifiedTool> result;+ result.reserve(tools_.size());++ for (const auto& [name, tool] : tools_) {+ result.push_back({+ INTERNAL_SERVER_ID,+ INTERNAL_SERVER_NAME,+ tool.name,+ tool.description,+ tool.input_schema.to_json(),+ true+ });+ }+ return result;+}++size_t MCPProvider::tool_count() const {+ std::lock_guard<std::mutex> lock(mutex_);+ size_t count = 0;+ for (const auto& [name, _] : tools_) {+ if (!disabled_tools_.count(name)) ++count;+ }+ return count;+}++bool MCPProvider::has_tool(const std::string& name) const {+ std::lock_guard<std::mutex> lock(mutex_);+ return tools_.find(name) != tools_.end();+}++// ============================================================================+// Execution+// ============================================================================++ToolResult MCPProvider::call_tool(const std::string& name, const json& args) {+ ToolHandler handler;++ {+ std::lock_guard<std::mutex> lock(mutex_);++ auto it = tools_.find(name);+ if (it == tools_.end()) {+ return ToolResult::fail("Tool not found: " + name);+ }++ if (disabled_tools_.count(name)) {+ return ToolResult::fail("Tool is disabled: " + name);+ }++ handler = it->second.handler;+ }++ // Execute outside the lock to avoid deadlocks+ try {+ LOG_DEBUG(TAG_PROVIDER, "Calling tool: %s", name.c_str());+ return handler(args);+ } catch (const std::exception& e) {+ LOG_ERROR(TAG_PROVIDER, "Tool '%s' threw exception: %s", name.c_str(), e.what());+ return ToolResult::fail(std::string("Tool execution error: ") + e.what());+ } catch (...) {+ LOG_ERROR(TAG_PROVIDER, "Tool '%s' threw unknown exception", name.c_str());+ return ToolResult::fail("Unknown error during tool execution");+ }+}++// ============================================================================+// LLM Integration+// ============================================================================++json MCPProvider::format_tools_for_openai() const {+ auto tools = list_tools();+ json result = json::array();++ for (const auto& tool : tools) {+ result.push_back({+ {"type", "function"},+ {"function", {+ {"name", std::string(INTERNAL_SERVER_ID) + "__" + tool.name},+ {"description", tool.description},+ {"parameters", tool.input_schema.is_null() ? json{{"type", "object"}, {"properties", json::object()}} : tool.input_schema}+ }}+ });+ }++ return result;+}++std::pair<std::string, std::string> MCPProvider::parse_openai_function_name(const std::string& fn_name) {+ auto pos = fn_name.find("__");+ if (pos == std::string::npos || pos == 0 || pos == fn_name.size() - 2) {+ return {"", ""};+ }+ return {fn_name.substr(0, pos), fn_name.substr(pos + 2)};+}++// ============================================================================+// Lifecycle+// ============================================================================++void MCPProvider::clear() {+ std::lock_guard<std::mutex> lock(mutex_);+ tools_.clear();+ disabled_tools_.clear();+}++} // namespace fincept::mcpdiff --git a/fincept-cpp/src/mcp/mcp_provider.h b/fincept-cpp/src/mcp/mcp_provider.hnew file mode 100644index 000000000..5e97692ab--- /dev/null+++ b/fincept-cpp/src/mcp/mcp_provider.h@@ -0,0 +1,76 @@+#pragma once+// MCPProvider — Internal tool registry and executor+// Singleton that manages all built-in terminal tools.+// Tools register handlers that are invoked by AI chat, agents, or node editor.++#include "mcp_types.h"+#include <unordered_map>+#include <unordered_set>+#include <mutex>++namespace fincept::mcp {++class MCPProvider {+public:+ static MCPProvider& instance();++ // ── Tool Registration ──────────────────────────────────────────────────++ /// Register a single tool+ void register_tool(ToolDef tool);++ /// Register multiple tools at once+ void register_tools(std::vector<ToolDef> tools);++ /// Unregister a tool by name+ void unregister_tool(const std::string& name);++ // ── Tool Enable/Disable ────────────────────────────────────────────────++ void set_tool_enabled(const std::string& name, bool enabled);+ bool is_tool_enabled(const std::string& name) const;++ // ── Tool Discovery ─────────────────────────────────────────────────────++ /// List all enabled tools as UnifiedTool (for LLM consumption)+ std::vector<UnifiedTool> list_tools() const;++ /// List ALL tools including disabled (for management UI)+ std::vector<UnifiedTool> list_all_tools() const;++ /// Get tool count (enabled only)+ size_t tool_count() const;++ /// Check if a tool exists+ bool has_tool(const std::string& name) const;++ // ── Tool Execution ─────────────────────────────────────────────────────++ /// Execute a tool by name with JSON arguments+ ToolResult call_tool(const std::string& name, const json& args);++ // ── LLM Integration ────────────────────────────────────────────────────++ /// Format all enabled tools for OpenAI function calling+ json format_tools_for_openai() const;++ /// Parse an OpenAI function name "serverId__toolName" back to components+ static std::pair<std::string, std::string> parse_openai_function_name(const std::string& fn_name);++ // ── Lifecycle ──────────────────────────────────────────────────────────++ /// Clear all registered tools+ void clear();++ MCPProvider(const MCPProvider&) = delete;+ MCPProvider& operator=(const MCPProvider&) = delete;++private:+ MCPProvider() = default;++ mutable std::mutex mutex_;+ std::unordered_map<std::string, ToolDef> tools_;+ std::unordered_set<std::string> disabled_tools_;+};++} // namespace fincept::mcpdiff --git a/fincept-cpp/src/mcp/mcp_service.cpp b/fincept-cpp/src/mcp/mcp_service.cppnew file mode 100644index 000000000..90095a2ec--- /dev/null+++ b/fincept-cpp/src/mcp/mcp_service.cpp@@ -0,0 +1,219 @@+// MCPService — Unified tool interface implementation++#include "mcp_service.h"+#include "mcp_provider.h"+#include "mcp_manager.h"+#include "../core/logger.h"++namespace fincept::mcp {++static constexpr const char* TAG_SERVICE = "MCPService";++MCPService& MCPService::instance() {+ static MCPService s;+ return s;+}++// ============================================================================+// Lifecycle+// ============================================================================++void MCPService::initialize() {+ // Manager handles external servers+ MCPManager::instance().initialize();+ MCPManager::instance().start_auto_servers();+ MCPManager::instance().start_health_check();++ LOG_INFO(TAG_SERVICE, "MCPService initialized — %zu internal tools",+ MCPProvider::instance().tool_count());+}++void MCPService::shutdown() {+ MCPManager::instance().shutdown();+ MCPProvider::instance().clear();+ LOG_INFO(TAG_SERVICE, "MCPService shut down");+}++// ============================================================================+// Tool Discovery+// ============================================================================++std::vector<UnifiedTool> MCPService::get_all_tools() {+ std::lock_guard<std::mutex> lock(mutex_);++ if (!is_cache_valid()) {+ refresh_cache();+ }+ return cached_tools_;+}++json MCPService::format_tools_for_openai() {+ auto tools = get_all_tools();+ json result = json::array();++ for (const auto& tool : tools) {+ std::string fn_name = tool.server_id + "__" + tool.name;++ result.push_back({+ {"type", "function"},+ {"function", {+ {"name", fn_name},+ {"description", tool.description},+ {"parameters", tool.input_schema.is_null()+ ? json{{"type", "object"}, {"properties", json::object()}}+ : tool.input_schema}+ }}+ });+ }++ return result;+}++size_t MCPService::tool_count() {+ auto tools = get_all_tools();+ return tools.size();+}++// ============================================================================+// Tool Execution+// ============================================================================++ToolResult MCPService::execute_tool(const std::string& server_id,+ const std::string& tool_name,+ const json& args) {+ // Route to internal provider+ if (server_id == INTERNAL_SERVER_ID) {+ return MCPProvider::instance().call_tool(tool_name, args);+ }++ // Route to external server+ auto result = MCPManager::instance().call_external_tool(server_id, tool_name, args);+ if (result.failed()) {+ return ToolResult::fail(result.error().message);+ }++ // Convert external result to ToolResult+ auto& data = result.value();++ // MCP tools/call returns { content: [{type, text}], isError? }+ bool is_error = data.value("isError", false);+ json content = data.value("content", json::array());++ std::string text;+ json result_data;++ for (const auto& item : content) {+ if (item.value("type", "") == "text") {+ text += item.value("text", "");+ }+ }++ if (is_error) {+ return ToolResult::fail(text.empty() ? "External tool error" : text);+ }++ // Try to parse text as JSON data+ try {+ result_data = json::parse(text);+ } catch (...) {+ result_data = text;+ }++ return ToolResult::ok(text, result_data);+}++ToolResult MCPService::execute_openai_function(const std::string& function_name,+ const json& args) {+ auto [server_id, tool_name] = MCPProvider::parse_openai_function_name(function_name);++ if (server_id.empty() || tool_name.empty()) {+ return ToolResult::fail("Invalid function name format: " + function_name);+ }++ return execute_tool(server_id, tool_name, args);+}++// ============================================================================+// Validation+// ============================================================================++Result<void> MCPService::validate_params(const std::string& tool_name, const json& args) {+ // Find the tool+ auto tools = get_all_tools();+ for (const auto& tool : tools) {+ if (tool.name == tool_name) {+ // Basic required field validation+ if (tool.input_schema.contains("required")) {+ for (const auto& req : tool.input_schema["required"]) {+ std::string field = req.get<std::string>();+ if (!args.contains(field)) {+ return Error("Missing required parameter: " + field);+ }+ }+ }++ // Type validation for properties+ if (tool.input_schema.contains("properties") && tool.input_schema["properties"].is_object()) {+ for (auto& [key, schema] : tool.input_schema["properties"].items()) {+ if (!args.contains(key)) continue;++ std::string expected_type = schema.value("type", "");+ const auto& val = args[key];++ bool valid = true;+ if (expected_type == "string") valid = val.is_string();+ else if (expected_type == "number") valid = val.is_number();+ else if (expected_type == "integer") valid = val.is_number_integer();+ else if (expected_type == "boolean") valid = val.is_boolean();+ else if (expected_type == "array") valid = val.is_array();+ else if (expected_type == "object") valid = val.is_object();++ if (!valid) {+ return Error("Parameter '" + key + "' should be " + expected_type);+ }+ }+ }++ return {};+ }+ }++ return Error("Tool not found: " + tool_name);+}++// ============================================================================+// Cache+// ============================================================================++bool MCPService::is_cache_valid() const {+ auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(+ std::chrono::steady_clock::now() - cache_time_).count();+ return elapsed < CACHE_TTL_MS && !cached_tools_.empty();+}++void MCPService::refresh_cache() {+ cached_tools_.clear();++ // Internal tools+ auto internal = MCPProvider::instance().list_tools();+ cached_tools_.insert(cached_tools_.end(), internal.begin(), internal.end());++ // External tools+ auto external = MCPManager::instance().get_all_external_tools();+ for (auto& ext : external) {+ cached_tools_.push_back({+ ext.server_id,+ ext.server_name,+ ext.name,+ ext.description,+ ext.input_schema,+ false+ });+ }++ cache_time_ = std::chrono::steady_clock::now();+ LOG_DEBUG(TAG_SERVICE, "Refreshed tool cache: %zu total (%zu internal, %zu external)",+ cached_tools_.size(), internal.size(), external.size());+}++} // namespace fincept::mcpdiff --git a/fincept-cpp/src/mcp/mcp_service.h b/fincept-cpp/src/mcp/mcp_service.hnew file mode 100644index 000000000..ddb6f30a1--- /dev/null+++ b/fincept-cpp/src/mcp/mcp_service.h@@ -0,0 +1,72 @@+#pragma once+// MCPService — Unified tool interface merging internal + external MCP tools+// Single entry point for AI chat, agents, and node editor to discover and call tools.++#include "mcp_types.h"+#include "../core/result.h"+#include <mutex>+#include <chrono>+#include <vector>++namespace fincept::mcp {++using core::Result;+using core::Error;++class MCPService {+public:+ static MCPService& instance();++ // ── Unified Tool Discovery ──────────────────────────────────────────++ /// Get all available tools (internal + external, cached for 5s)+ std::vector<UnifiedTool> get_all_tools();++ /// Get tools formatted for OpenAI function calling+ json format_tools_for_openai();++ /// Get tool count+ size_t tool_count();++ // ── Unified Tool Execution ──────────────────────────────────────────++ /// Execute a tool by unified name (routes to internal or external)+ ToolResult execute_tool(const std::string& server_id,+ const std::string& tool_name,+ const json& args);++ /// Execute from OpenAI function call format (serverId__toolName)+ ToolResult execute_openai_function(const std::string& function_name,+ const json& args);++ // ── Validation ──────────────────────────────────────────────────────++ /// Validate tool parameters against its JSON schema+ Result<void> validate_params(const std::string& tool_name, const json& args);++ // ── Lifecycle ───────────────────────────────────────────────────────++ /// Initialize internal tools and external manager+ void initialize();++ /// Shutdown everything+ void shutdown();++ MCPService(const MCPService&) = delete;+ MCPService& operator=(const MCPService&) = delete;++private:+ MCPService() = default;++ mutable std::mutex mutex_;++ // Tool cache+ std::vector<UnifiedTool> cached_tools_;+ std::chrono::steady_clock::time_point cache_time_;+ static constexpr int CACHE_TTL_MS = 5000;++ void refresh_cache();+ bool is_cache_valid() const;+};++} // namespace fincept::mcpdiff --git a/fincept-cpp/src/mcp/mcp_types.h b/fincept-cpp/src/mcp/mcp_types.hnew file mode 100644index 000000000..0f193529a--- /dev/null+++ b/fincept-cpp/src/mcp/mcp_types.h@@ -0,0 +1,154 @@+#pragma once+// MCP Types — Core type definitions for the Model Context Protocol system+// Mirrors the TypeScript InternalTool / MCPTool / MCPToolResult types++#include <string>+#include <vector>+#include <functional>+#include <optional>+#include <nlohmann/json.hpp>++namespace fincept::mcp {++using json = nlohmann::json;++// ============================================================================+// Tool Schema — JSON Schema for tool input parameters+// ============================================================================++struct ToolSchema {+ std::string type = "object";+ json properties = json::object(); // { "param": { "type": "string", "description": "..." } }+ std::vector<std::string> required; // required parameter names++ json to_json() const {+ json j;+ j["type"] = type;+ j["properties"] = properties;+ if (!required.empty()) j["required"] = required;+ return j;+ }+};++// ============================================================================+// Tool Result — returned by tool handlers+// ============================================================================++struct ToolResult {+ bool success = false;+ json data; // arbitrary result data+ std::string message; // human-readable message+ std::string error; // error message if !success++ json to_json() const {+ json j;+ j["success"] = success;+ if (!data.is_null()) j["data"] = data;+ if (!message.empty()) j["message"] = message;+ if (!error.empty()) j["error"] = error;+ return j;+ }++ static ToolResult ok(const std::string& msg, const json& data = nullptr) {+ return {true, data, msg, ""};+ }++ static ToolResult ok_data(const json& data) {+ return {true, data, "", ""};+ }++ static ToolResult fail(const std::string& err) {+ return {false, nullptr, "", err};+ }+};++// ============================================================================+// Tool Handler — function signature for tool execution+// ============================================================================++using ToolHandler = std::function<ToolResult(const json& args)>;++// ============================================================================+// Tool Definition — a registered MCP tool+// ============================================================================++struct ToolDef {+ std::string name;+ std::string description;+ std::string category; // navigation, trading, portfolio, market-data, etc.+ ToolSchema input_schema;+ ToolHandler handler;+ bool enabled = true;+};++// ============================================================================+// Server Status — for external MCP server management+// ============================================================================++enum class ServerStatus {+ Stopped,+ Running,+ Error+};++inline const char* server_status_str(ServerStatus s) {+ switch (s) {+ case ServerStatus::Stopped: return "stopped";+ case ServerStatus::Running: return "running";+ case ServerStatus::Error: return "error";+ }+ return "unknown";+}++// ============================================================================+// MCP Server Config — persisted in SQLite+// ============================================================================++struct MCPServerConfig {+ std::string id;+ std::string name;+ std::string description;+ std::string command; // e.g., "npx", "uvx", "node"+ std::vector<std::string> args;+ std::map<std::string, std::string> env;+ std::string category;+ bool enabled = true;+ bool auto_start = false;+ ServerStatus status = ServerStatus::Stopped;+ std::string created_at;+ std::string updated_at;+};++// ============================================================================+// External Tool — tool discovered from an external MCP server+// ============================================================================++struct ExternalTool {+ std::string server_id;+ std::string server_name;+ std::string name;+ std::string description;+ json input_schema;+};++// ============================================================================+// Unified Tool — merged view for consumers (Chat, Agents, etc.)+// ============================================================================++struct UnifiedTool {+ std::string server_id; // "fincept-terminal" for internal+ std::string server_name;+ std::string name;+ std::string description;+ json input_schema;+ bool is_internal = false;+};++// ============================================================================+// Constants+// ============================================================================++inline constexpr const char* INTERNAL_SERVER_ID = "fincept-terminal";+inline constexpr const char* INTERNAL_SERVER_NAME = "Fincept Terminal";++} // namespace fincept::mcpdiff --git a/fincept-cpp/src/mcp/tools/market_data_tools.cpp b/fincept-cpp/src/mcp/tools/market_data_tools.cppnew file mode 100644index 000000000..059ebb5c0--- /dev/null+++ b/fincept-cpp/src/mcp/tools/market_data_tools.cpp@@ -0,0 +1,200 @@+// Market Data MCP Tools — quote lookup, watchlist ops, symbol search++#include "market_data_tools.h"+#include "../../core/event_bus.h"+#include "../../core/logger.h"+#include "../../storage/database.h"++namespace fincept::mcp::tools {++static constexpr const char* TAG_MARKET = "MarketTools";++std::vector<ToolDef> get_market_data_tools() {+ std::vector<ToolDef> tools;++ // ── get_quote ───────────────────────────────────────────────────────+ {+ ToolDef t;+ t.name = "get_quote";+ t.description = "Get a stock/crypto quote. Publishes a request event and returns confirmation.";+ t.category = "market-data";+ t.input_schema.properties = {+ {"symbol", {+ {"type", "string"},+ {"description", "Ticker symbol (e.g. AAPL, BTC-USD)"}+ }}+ };+ t.input_schema.required = {"symbol"};+ t.handler = [](const json& args) -> ToolResult {+ std::string symbol = args.value("symbol", "");+ if (symbol.empty()) return ToolResult::fail("Missing 'symbol'");++ core::EventBus::instance().publish("market.get_quote", {{"symbol", symbol}});+ LOG_DEBUG(TAG_MARKET, "Quote requested: %s", symbol.c_str());+ return ToolResult::ok("Quote request sent for " + symbol, {{"symbol", symbol}});+ };+ tools.push_back(std::move(t));+ }++ // ── search_symbol ───────────────────────────────────────────────────+ {+ ToolDef t;+ t.name = "search_symbol";+ t.description = "Search for a ticker symbol by company name or partial symbol.";+ t.category = "market-data";+ t.input_schema.properties = {+ {"query", {+ {"type", "string"},+ {"description", "Search query (company name or partial symbol)"}+ }}+ };+ t.input_schema.required = {"query"};+ t.handler = [](const json& args) -> ToolResult {+ std::string query = args.value("query", "");+ if (query.empty()) return ToolResult::fail("Missing 'query'");++ core::EventBus::instance().publish("market.search_symbol", {{"query", query}});+ return ToolResult::ok("Symbol search sent for: " + query);+ };+ tools.push_back(std::move(t));+ }++ // ── add_to_watchlist ────────────────────────────────────────────────+ {+ ToolDef t;+ t.name = "add_to_watchlist";+ t.description = "Add a symbol to a watchlist. If watchlist_id is omitted, uses the default watchlist.";+ t.category = "market-data";+ t.input_schema.properties = {+ {"symbol", {+ {"type", "string"},+ {"description", "Ticker symbol to add"}+ }},+ {"watchlist_id", {+ {"type", "string"},+ {"description", "Watchlist ID (optional, uses default if omitted)"}+ }},+ {"notes", {+ {"type", "string"},+ {"description", "Optional notes about this symbol"}+ }}+ };+ t.input_schema.required = {"symbol"};+ t.handler = [](const json& args) -> ToolResult {+ std::string symbol = args.value("symbol", "");+ if (symbol.empty()) return ToolResult::fail("Missing 'symbol'");++ std::string watchlist_id = args.value("watchlist_id", "");+ std::string notes = args.value("notes", "");++ // If no watchlist specified, get the first one+ if (watchlist_id.empty()) {+ auto lists = db::ops::get_watchlists();+ if (lists.empty()) {+ // Create default watchlist+ auto wl = db::ops::create_watchlist("Default", "#3b82f6");+ watchlist_id = wl.id;+ } else {+ watchlist_id = lists[0].id;+ }+ }++ db::ops::add_watchlist_stock(watchlist_id, symbol, notes);+ LOG_INFO(TAG_MARKET, "Added %s to watchlist %s", symbol.c_str(), watchlist_id.c_str());++ core::EventBus::instance().publish("watchlist.updated", {+ {"watchlist_id", watchlist_id},+ {"action", "add"},+ {"symbol", symbol}+ });++ return ToolResult::ok("Added " + symbol + " to watchlist", {+ {"symbol", symbol},+ {"watchlist_id", watchlist_id}+ });+ };+ tools.push_back(std::move(t));+ }++ // ── remove_from_watchlist ───────────────────────────────────────────+ {+ ToolDef t;+ t.name = "remove_from_watchlist";+ t.description = "Remove a symbol from a watchlist.";+ t.category = "market-data";+ t.input_schema.properties = {+ {"symbol", {+ {"type", "string"},+ {"description", "Ticker symbol to remove"}+ }},+ {"watchlist_id", {+ {"type", "string"},+ {"description", "Watchlist ID (optional, searches all if omitted)"}+ }}+ };+ t.input_schema.required = {"symbol"};+ t.handler = [](const json& args) -> ToolResult {+ std::string symbol = args.value("symbol", "");+ if (symbol.empty()) return ToolResult::fail("Missing 'symbol'");++ std::string watchlist_id = args.value("watchlist_id", "");++ if (watchlist_id.empty()) {+ // Remove from all watchlists+ auto lists = db::ops::get_watchlists();+ for (const auto& wl : lists) {+ db::ops::remove_watchlist_stock(wl.id, symbol);+ }+ } else {+ db::ops::remove_watchlist_stock(watchlist_id, symbol);+ }++ core::EventBus::instance().publish("watchlist.updated", {+ {"action", "remove"},+ {"symbol", symbol}+ });++ return ToolResult::ok("Removed " + symbol + " from watchlist");+ };+ tools.push_back(std::move(t));+ }++ // ── get_watchlists ──────────────────────────────────────────────────+ {+ ToolDef t;+ t.name = "get_watchlists";+ t.description = "Get all watchlists with their symbols.";+ t.category = "market-data";+ t.handler = [](const json&) -> ToolResult {+ auto lists = db::ops::get_watchlists();+ json result = json::array();++ for (const auto& wl : lists) {+ auto stocks = db::ops::get_watchlist_stocks(wl.id);+ json symbols = json::array();+ for (const auto& s : stocks) {+ symbols.push_back({+ {"symbol", s.symbol},+ {"added_at", s.added_at},+ {"notes", s.notes.value_or("")}+ });+ }++ result.push_back({+ {"id", wl.id},+ {"name", wl.name},+ {"color", wl.color},+ {"description", wl.description.value_or("")},+ {"symbols", symbols}+ });+ }++ return ToolResult::ok_data(result);+ };+ tools.push_back(std::move(t));+ }++ return tools;+}++} // namespace fincept::mcp::toolsdiff --git a/fincept-cpp/src/mcp/tools/market_data_tools.h b/fincept-cpp/src/mcp/tools/market_data_tools.hnew file mode 100644index 000000000..170dce0ad--- /dev/null+++ b/fincept-cpp/src/mcp/tools/market_data_tools.h@@ -0,0 +1,12 @@+#pragma once+// Market Data MCP Tools — quote lookup, watchlist management, symbol search++#include "../mcp_types.h"+#include <vector>++namespace fincept::mcp::tools {++/// Get all market data tool definitions+std::vector<ToolDef> get_market_data_tools();++} // namespace fincept::mcp::toolsdiff --git a/fincept-cpp/src/mcp/tools/navigation_tools.cpp b/fincept-cpp/src/mcp/tools/navigation_tools.cppnew file mode 100644index 000000000..1dc8616a6--- /dev/null+++ b/fincept-cpp/src/mcp/tools/navigation_tools.cpp@@ -0,0 +1,147 @@+// Navigation MCP Tools — tab switching implementation++#include "navigation_tools.h"+#include "../../core/event_bus.h"+#include "../../core/logger.h"+#include <algorithm>++namespace fincept::mcp::tools {++static constexpr const char* TAG_NAV = "NavTools";++// Tab name → tab index mapping+struct TabEntry {+ const char* name;+ const char* display_name;+ int index;+};++// Indices must match App::active_tab_ in app.cpp render()+static const TabEntry TAB_MAP[] = {+ {"dashboard", "Dashboard", 0},+ {"markets", "Markets", 1},+ {"crypto_trading", "Crypto Trading", 2},+ {"portfolio", "Portfolio", 3},+ {"news", "News", 4},+ {"ai_chat", "AI Chat", 5},+ {"backtesting", "Backtesting", 6},+ {"algo_trading", "Algo Trading", 7},+ {"node_editor", "Node Editor", 8},+ {"code_editor", "Code Editor", 9},+ {"quantlib", "QuantLib", 11},+ {"settings", "Settings", 12},+ {"profile", "Profile", 13},+ {"surface_analytics", "Surface Analytics", 14},+ {"geopolitics", "Geopolitics", 15},+ {"watchlist", "Watchlist", 16},+ {"economics", "Economics", 17},+ {"dbnomics", "DBnomics", 18},+ {"notes", "Notes", 19},+ {"data_sources", "Data Sources", 20},+ {"mna", "M&A Analytics", 21},+ {"forum", "Forum", 22},+ {"docs", "Documentation", 23},+ {"support", "Support", 24},+ {"about", "About", 25},+ {"gov_data", "Government Data", 26},+ {"agent_studio", "Agent Studio", 27},+};++static constexpr int TAB_COUNT = sizeof(TAB_MAP) / sizeof(TAB_MAP[0]);++static int find_tab_index(const std::string& name) {+ std::string lower = name;+ std::transform(lower.begin(), lower.end(), lower.begin(), ::tolower);++ // Exact match on id+ for (int i = 0; i < TAB_COUNT; ++i) {+ if (lower == TAB_MAP[i].name) return TAB_MAP[i].index;+ }++ // Partial / fuzzy match on display name+ for (int i = 0; i < TAB_COUNT; ++i) {+ std::string display = TAB_MAP[i].display_name;+ std::transform(display.begin(), display.end(), display.begin(), ::tolower);+ if (display.find(lower) != std::string::npos) return TAB_MAP[i].index;+ }++ return -1;+}++std::vector<ToolDef> get_navigation_tools() {+ std::vector<ToolDef> tools;++ // ── navigate_to_tab ─────────────────────────────────────────────────+ {+ ToolDef t;+ t.name = "navigate_to_tab";+ t.description = "Navigate to a specific terminal tab by name. Available tabs: dashboard, markets, news, watchlist, research, portfolio, crypto_trading, algo_trading, backtesting, economics, dbnomics, geopolitics, surface_analytics, quantlib, mna, agent_studio, ai_chat, node_editor, code_editor, notes, data_sources, gov_data, forum, profile, settings, docs, support, about.";+ t.category = "navigation";+ t.input_schema.properties = {+ {"tab", {+ {"type", "string"},+ {"description", "Tab name to navigate to"}+ }}+ };+ t.input_schema.required = {"tab"};+ t.handler = [](const json& args) -> ToolResult {+ std::string tab = args.value("tab", "");+ if (tab.empty()) return ToolResult::fail("Missing 'tab' parameter");++ int idx = find_tab_index(tab);+ if (idx < 0) {+ // Build list of valid tabs+ std::string valid;+ for (int i = 0; i < TAB_COUNT; ++i) {+ if (!valid.empty()) valid += ", ";+ valid += TAB_MAP[i].name;+ }+ return ToolResult::fail("Unknown tab '" + tab + "'. Valid tabs: " + valid);+ }++ core::EventBus::instance().publish("nav.switch_tab", {{"tab_index", idx}});+ LOG_INFO(TAG_NAV, "Navigating to tab: %s (index %d)", tab.c_str(), idx);+ return ToolResult::ok("Navigated to " + tab, {{"tab_index", idx}});+ };+ tools.push_back(std::move(t));+ }++ // ── list_tabs ───────────────────────────────────────────────────────+ {+ ToolDef t;+ t.name = "list_tabs";+ t.description = "List all available terminal tabs with their names and indices.";+ t.category = "navigation";+ t.handler = [](const json&) -> ToolResult {+ json tabs = json::array();+ for (int i = 0; i < TAB_COUNT; ++i) {+ tabs.push_back({+ {"name", TAB_MAP[i].name},+ {"display_name", TAB_MAP[i].display_name},+ {"index", TAB_MAP[i].index}+ });+ }+ return ToolResult::ok_data(tabs);+ };+ tools.push_back(std::move(t));+ }++ // ── get_current_tab ─────────────────────────────────────────────────+ {+ ToolDef t;+ t.name = "get_current_tab";+ t.description = "Get the currently active tab name and index.";+ t.category = "navigation";+ t.handler = [](const json&) -> ToolResult {+ // The actual tab index is managed by App, so we publish an event to request it+ // For now, we return a message indicating the event was sent+ core::EventBus::instance().publish("nav.get_current_tab", {});+ return ToolResult::ok("Current tab query sent — check response via event bus");+ };+ tools.push_back(std::move(t));+ }++ return tools;+}++} // namespace fincept::mcp::toolsdiff --git a/fincept-cpp/src/mcp/tools/navigation_tools.h b/fincept-cpp/src/mcp/tools/navigation_tools.hnew file mode 100644index 000000000..521d970ba--- /dev/null+++ b/fincept-cpp/src/mcp/tools/navigation_tools.h@@ -0,0 +1,45 @@+#pragma once+// Navigation MCP Tools — tab switching and screen navigation+// Registers tools that allow AI to navigate between terminal screens.++#include "../mcp_types.h"+#include <vector>++namespace fincept::mcp::tools {++/// Tab IDs matching App::active_tab_ indices (from app.cpp render())+enum class TabId : int {+ Dashboard = 0,+ Markets = 1,+ CryptoTrading = 2,+ Portfolio = 3,+ News = 4,+ AIChat = 5,+ Backtesting = 6,+ AlgoTrading = 7,+ NodeEditor = 8,+ CodeEditor = 9,+ // 10 unused+ QuantLib = 11,+ Settings = 12,+ Profile = 13,+ SurfaceAnalytics = 14,+ Geopolitics = 15,+ Watchlist = 16,+ Economics = 17,+ DBnomics = 18,+ Notes = 19,+ DataSources = 20,+ MNA = 21,+ Forum = 22,+ Docs = 23,+ Support = 24,+ About = 25,+ GovData = 26,+ AgentStudio = 27+};++/// Get all navigation tool definitions+std::vector<ToolDef> get_navigation_tools();++} // namespace fincept::mcp::toolsdiff --git a/fincept-cpp/src/mcp/tools/portfolio_tools.cpp b/fincept-cpp/src/mcp/tools/portfolio_tools.cppnew file mode 100644index 000000000..080ab7e65--- /dev/null+++ b/fincept-cpp/src/mcp/tools/portfolio_tools.cpp@@ -0,0 +1,161 @@+// Portfolio MCP Tools — notes, chat sessions, data management++#include "portfolio_tools.h"+#include "../../storage/database.h"+#include "../../core/event_bus.h"++namespace fincept::mcp::tools {++std::vector<ToolDef> get_portfolio_tools() {+ std::vector<ToolDef> tools;++ // ── create_note ─────────────────────────────────────────────────────+ {+ ToolDef t;+ t.name = "create_note";+ t.description = "Create a research note with optional category, priority, tickers, and sentiment.";+ t.category = "portfolio";+ t.input_schema.properties = {+ {"title", {{"type", "string"}, {"description", "Note title"}}},+ {"content", {{"type", "string"}, {"description", "Note content (markdown)"}}},+ {"category", {{"type", "string"}, {"description", "RESEARCH, TRADE_IDEA, MARKET_ANALYSIS, EARNINGS, ECONOMIC, PORTFOLIO, GENERAL"}}},+ {"priority", {{"type", "string"}, {"description", "HIGH, MEDIUM, LOW"}}},+ {"tickers", {{"type", "string"}, {"description", "Comma-separated ticker symbols"}}},+ {"sentiment", {{"type", "string"}, {"description", "BULLISH, BEARISH, NEUTRAL"}}},+ {"tags", {{"type", "string"}, {"description", "Comma-separated tags"}}}+ };+ t.input_schema.required = {"title", "content"};+ t.handler = [](const json& args) -> ToolResult {+ db::Note note;+ note.title = args.value("title", "");+ note.content = args.value("content", "");+ note.category = args.value("category", "GENERAL");+ note.priority = args.value("priority", "MEDIUM");+ note.tickers = args.value("tickers", "");+ note.sentiment = args.value("sentiment", "NEUTRAL");+ note.tags = args.value("tags", "");++ if (note.title.empty()) return ToolResult::fail("Missing 'title'");++ auto created = db::ops::create_note(note);++ core::EventBus::instance().publish("notes.created", {{"id", created.id}});++ return ToolResult::ok("Note created: " + note.title, {+ {"id", created.id}, {"title", created.title}+ });+ };+ tools.push_back(std::move(t));+ }++ // ── get_notes ───────────────────────────────────────────────────────+ {+ ToolDef t;+ t.name = "get_notes";+ t.description = "Get all research notes, optionally filtered by search query.";+ t.category = "portfolio";+ t.input_schema.properties = {+ {"query", {{"type", "string"}, {"description", "Search query (optional)"}}}+ };+ t.handler = [](const json& args) -> ToolResult {+ std::string query = args.value("query", "");++ std::vector<db::Note> notes;+ if (query.empty()) {+ notes = db::ops::get_all_notes();+ } else {+ notes = db::ops::search_notes(query);+ }++ json result = json::array();+ for (const auto& n : notes) {+ result.push_back({+ {"id", n.id},+ {"title", n.title},+ {"category", n.category},+ {"priority", n.priority},+ {"tickers", n.tickers},+ {"sentiment", n.sentiment},+ {"is_favorite", n.is_favorite},+ {"created_at", n.created_at},+ {"updated_at", n.updated_at}+ });+ }++ return ToolResult::ok_data(result);+ };+ tools.push_back(std::move(t));+ }++ // ── delete_note ─────────────────────────────────────────────────────+ {+ ToolDef t;+ t.name = "delete_note";+ t.description = "Delete a research note by ID.";+ t.category = "portfolio";+ t.input_schema.properties = {+ {"id", {{"type", "integer"}, {"description", "Note ID to delete"}}}+ };+ t.input_schema.required = {"id"};+ t.handler = [](const json& args) -> ToolResult {+ if (!args.contains("id")) return ToolResult::fail("Missing 'id'");+ int64_t id = args["id"].get<int64_t>();+ db::ops::delete_note(id);+ core::EventBus::instance().publish("notes.deleted", {{"id", id}});+ return ToolResult::ok("Note deleted");+ };+ tools.push_back(std::move(t));+ }++ // ── create_chat_session ─────────────────────────────────────────────+ {+ ToolDef t;+ t.name = "create_chat_session";+ t.description = "Create a new AI chat session.";+ t.category = "portfolio";+ t.input_schema.properties = {+ {"title", {{"type", "string"}, {"description", "Chat session title"}}}+ };+ t.input_schema.required = {"title"};+ t.handler = [](const json& args) -> ToolResult {+ std::string title = args.value("title", "New Chat");+ auto session = db::ops::create_chat_session(title);+ return ToolResult::ok("Chat session created", {+ {"session_uuid", session.session_uuid},+ {"title", session.title}+ });+ };+ tools.push_back(std::move(t));+ }++ // ── get_chat_sessions ───────────────────────────────────────────────+ {+ ToolDef t;+ t.name = "get_chat_sessions";+ t.description = "Get recent AI chat sessions.";+ t.category = "portfolio";+ t.input_schema.properties = {+ {"limit", {{"type", "integer"}, {"description", "Max sessions to return (default: 20)"}}}+ };+ t.handler = [](const json& args) -> ToolResult {+ int limit = args.value("limit", 20);+ auto sessions = db::ops::get_chat_sessions(limit);+ json result = json::array();+ for (const auto& s : sessions) {+ result.push_back({+ {"session_uuid", s.session_uuid},+ {"title", s.title},+ {"message_count", s.message_count},+ {"created_at", s.created_at},+ {"updated_at", s.updated_at}+ });+ }+ return ToolResult::ok_data(result);+ };+ tools.push_back(std::move(t));+ }++ return tools;+}++} // namespace fincept::mcp::toolsdiff --git a/fincept-cpp/src/mcp/tools/portfolio_tools.h b/fincept-cpp/src/mcp/tools/portfolio_tools.hnew file mode 100644index 000000000..068499e6e--- /dev/null+++ b/fincept-cpp/src/mcp/tools/portfolio_tools.h@@ -0,0 +1,12 @@+#pragma once+// Portfolio MCP Tools — notes CRUD, chat session management++#include "../mcp_types.h"+#include <vector>++namespace fincept::mcp::tools {++/// Get all portfolio/notes tool definitions+std::vector<ToolDef> get_portfolio_tools();++} // namespace fincept::mcp::toolsdiff --git a/fincept-cpp/src/mcp/tools/settings_tools.cpp b/fincept-cpp/src/mcp/tools/settings_tools.cppnew file mode 100644index 000000000..341e63594--- /dev/null+++ b/fincept-cpp/src/mcp/tools/settings_tools.cpp@@ -0,0 +1,157 @@+// Settings MCP Tools — settings and LLM config management++#include "settings_tools.h"+#include "../../storage/database.h"+#include "../../core/event_bus.h"+#include "../../core/logger.h"++namespace fincept::mcp::tools {++static constexpr const char* TAG_SETTINGS = "SettingsTools";++std::vector<ToolDef> get_settings_tools() {+ std::vector<ToolDef> tools;++ // ── get_setting ─────────────────────────────────────────────────────+ {+ ToolDef t;+ t.name = "get_setting";+ t.description = "Get an application setting by key.";+ t.category = "settings";+ t.input_schema.properties = {+ {"key", {+ {"type", "string"},+ {"description", "Setting key to retrieve"}+ }}+ };+ t.input_schema.required = {"key"};+ t.handler = [](const json& args) -> ToolResult {+ std::string key = args.value("key", "");+ if (key.empty()) return ToolResult::fail("Missing 'key'");++ auto val = db::ops::get_setting(key);+ if (!val.has_value()) {+ return ToolResult::fail("Setting not found: " + key);+ }+ return ToolResult::ok_data({{"key", key}, {"value", *val}});+ };+ tools.push_back(std::move(t));+ }++ // ── set_setting ─────────────────────────────────────────────────────+ {+ ToolDef t;+ t.name = "set_setting";+ t.description = "Set an application setting.";+ t.category = "settings";+ t.input_schema.properties = {+ {"key", {+ {"type", "string"},+ {"description", "Setting key"}+ }},+ {"value", {+ {"type", "string"},+ {"description", "Setting value"}+ }},+ {"category", {+ {"type", "string"},+ {"description", "Setting category (default: general)"}+ }}+ };+ t.input_schema.required = {"key", "value"};+ t.handler = [](const json& args) -> ToolResult {+ std::string key = args.value("key", "");+ std::string value = args.value("value", "");+ std::string category = args.value("category", "general");++ if (key.empty()) return ToolResult::fail("Missing 'key'");++ db::ops::save_setting(key, value, category);++ core::EventBus::instance().publish("settings.changed", {+ {"key", key}, {"value", value}+ });++ LOG_INFO(TAG_SETTINGS, "Setting saved: %s = %s", key.c_str(), value.c_str());+ return ToolResult::ok("Setting saved: " + key);+ };+ tools.push_back(std::move(t));+ }++ // ── get_all_settings ────────────────────────────────────────────────+ {+ ToolDef t;+ t.name = "get_all_settings";+ t.description = "Get all application settings.";+ t.category = "settings";+ t.handler = [](const json&) -> ToolResult {+ auto settings = db::ops::get_all_settings();+ json result = json::array();+ for (const auto& s : settings) {+ result.push_back({+ {"key", s.key},+ {"value", s.value},+ {"category", s.category},+ {"updated_at", s.updated_at}+ });+ }+ return ToolResult::ok_data(result);+ };+ tools.push_back(std::move(t));+ }++ // ── get_llm_configs ─────────────────────────────────────────────────+ {+ ToolDef t;+ t.name = "get_llm_configs";+ t.description = "Get all configured LLM providers and their settings.";+ t.category = "settings";+ t.handler = [](const json&) -> ToolResult {+ auto configs = db::ops::get_llm_configs();+ json result = json::array();+ for (const auto& c : configs) {+ result.push_back({+ {"provider", c.provider},+ {"model", c.model},+ {"is_active", c.is_active},+ {"has_api_key", c.api_key.has_value() && !c.api_key->empty()},+ {"base_url", c.base_url.value_or("")}+ });+ }+ return ToolResult::ok_data(result);+ };+ tools.push_back(std::move(t));+ }++ // ── set_active_llm ──────────────────────────────────────────────────+ {+ ToolDef t;+ t.name = "set_active_llm";+ t.description = "Set the active LLM provider.";+ t.category = "settings";+ t.input_schema.properties = {+ {"provider", {+ {"type", "string"},+ {"description", "Provider name (openai, anthropic, ollama, groq, google)"}+ }}+ };+ t.input_schema.required = {"provider"};+ t.handler = [](const json& args) -> ToolResult {+ std::string provider = args.value("provider", "");+ if (provider.empty()) return ToolResult::fail("Missing 'provider'");++ db::ops::set_active_llm_provider(provider);++ core::EventBus::instance().publish("llm.provider_changed", {+ {"provider", provider}+ });++ return ToolResult::ok("Active LLM set to: " + provider);+ };+ tools.push_back(std::move(t));+ }++ return tools;+}++} // namespace fincept::mcp::toolsdiff --git a/fincept-cpp/src/mcp/tools/settings_tools.h b/fincept-cpp/src/mcp/tools/settings_tools.hnew file mode 100644index 000000000..4516f7f81--- /dev/null+++ b/fincept-cpp/src/mcp/tools/settings_tools.h@@ -0,0 +1,12 @@+#pragma once+// Settings MCP Tools — read/write application settings, LLM config management++#include "../mcp_types.h"+#include <vector>++namespace fincept::mcp::tools {++/// Get all settings tool definitions+std::vector<ToolDef> get_settings_tools();++} // namespace fincept::mcp::toolsdiff --git a/fincept-cpp/src/media/mpv_player.cpp b/fincept-cpp/src/media/mpv_player.cppnew file mode 100644index 000000000..ae22a1e05--- /dev/null+++ b/fincept-cpp/src/media/mpv_player.cpp@@ -0,0 +1,437 @@+// MpvPlayer — libmpv render API integration for inline video playback+// Renders video frames into an OpenGL FBO, returns texture ID for ImGui::Image()++#include "mpv_player.h"+#include "core/logger.h"++#ifdef FINCEPT_HAS_MPV++#include <mpv/client.h>+#include <mpv/render_gl.h>++#ifdef _WIN32+#ifndef WIN32_LEAN_AND_MEAN+#define WIN32_LEAN_AND_MEAN+#endif+#ifndef NOMINMAX+#define NOMINMAX+#endif+#include <windows.h>+#endif++#include <GL/gl.h>+#include <GLFW/glfw3.h>++// GL extension function pointers (not in gl.h on Windows)+#ifdef _WIN32+typedef void (APIENTRY* PFNGLGENFRAMEBUFFERSPROC)(GLsizei, GLuint*);+typedef void (APIENTRY* PFNGLBINDFRAMEBUFFERPROC)(GLenum, GLuint);+typedef void (APIENTRY* PFNGLFRAMEBUFFERTEXTURE2DPROC)(GLenum, GLenum, GLenum, GLuint, GLint);+typedef void (APIENTRY* PFNGLDELETEFRAMEBUFFERSPROC)(GLsizei, const GLuint*);+typedef GLenum (APIENTRY* PFNGLCHECKFRAMEBUFFERSTATUSPROC)(GLenum);++static PFNGLGENFRAMEBUFFERSPROC glGenFramebuffers_fn = nullptr;+static PFNGLBINDFRAMEBUFFERPROC glBindFramebuffer_fn = nullptr;+static PFNGLFRAMEBUFFERTEXTURE2DPROC glFramebufferTexture2D_fn = nullptr;+static PFNGLDELETEFRAMEBUFFERSPROC glDeleteFramebuffers_fn = nullptr;+static PFNGLCHECKFRAMEBUFFERSTATUSPROC glCheckFramebufferStatus_fn = nullptr;++#define GL_FRAMEBUFFER 0x8D40+#define GL_COLOR_ATTACHMENT0 0x8CE0+#define GL_FRAMEBUFFER_COMPLETE 0x8CD5++static void load_gl_fbo_funcs() {+ if (glGenFramebuffers_fn) return;+ glGenFramebuffers_fn = (PFNGLGENFRAMEBUFFERSPROC)wglGetProcAddress("glGenFramebuffers");+ glBindFramebuffer_fn = (PFNGLBINDFRAMEBUFFERPROC)wglGetProcAddress("glBindFramebuffer");+ glFramebufferTexture2D_fn = (PFNGLFRAMEBUFFERTEXTURE2DPROC)wglGetProcAddress("glFramebufferTexture2D");+ glDeleteFramebuffers_fn = (PFNGLDELETEFRAMEBUFFERSPROC)wglGetProcAddress("glDeleteFramebuffers");+ glCheckFramebufferStatus_fn = (PFNGLCHECKFRAMEBUFFERSTATUSPROC)wglGetProcAddress("glCheckFramebufferStatus");+}++#define glGenFramebuffers glGenFramebuffers_fn+#define glBindFramebuffer glBindFramebuffer_fn+#define glFramebufferTexture2D glFramebufferTexture2D_fn+#define glDeleteFramebuffers glDeleteFramebuffers_fn+#define glCheckFramebufferStatus glCheckFramebufferStatus_fn++#elif defined(__APPLE__)+// macOS — GL3 header provides FBO functions+#include <OpenGL/gl3.h>+#else+// Linux — GL functions available via glext+#define GL_GLEXT_PROTOTYPES+#include <GL/gl.h>+#include <GL/glext.h>+#endif++namespace fincept::media {++// GL proc address callback for mpv+static void* get_proc_address(void* /*ctx*/, const char* name) {+ return (void*)glfwGetProcAddress(name);+}++// ============================================================================+// Construction / destruction+// ============================================================================+MpvPlayer::MpvPlayer() = default;++MpvPlayer::~MpvPlayer() {+ cleanup();+}++void MpvPlayer::cleanup() {+ if (mpv_gl_) {+ mpv_render_context_free(mpv_gl_);+ mpv_gl_ = nullptr;+ }+ if (mpv_) {+ mpv_terminate_destroy(mpv_);+ mpv_ = nullptr;+ }+ if (fbo_) {+ glDeleteFramebuffers(1, &fbo_);+ fbo_ = 0;+ }+ if (texture_) {+ glDeleteTextures(1, &texture_);+ texture_ = 0;+ }+ state_ = PlayerState::Idle;+}++// ============================================================================+// Initialize mpv + render context+// ============================================================================+bool MpvPlayer::init() {+ if (mpv_) return true; // Already initialized++#ifdef _WIN32+ load_gl_fbo_funcs();+ if (!glGenFramebuffers) {+ LOG_ERROR("MpvPlayer", "Failed to load GL FBO functions");+ state_ = PlayerState::Error;+ error_ = "OpenGL FBO functions not available";+ return false;+ }+#endif++ mpv_ = mpv_create();+ if (!mpv_) {+ LOG_ERROR("MpvPlayer", "mpv_create() failed");+ state_ = PlayerState::Error;+ error_ = "Failed to create mpv instance";+ return false;+ }++ // Configuration+ mpv_set_option_string(mpv_, "vo", "libmpv");+ mpv_set_option_string(mpv_, "hwdec", "auto");+ mpv_set_option_string(mpv_, "ytdl", "yes"); // Enable yt-dlp+ mpv_set_option_string(mpv_, "ytdl-format", "best[height<=720]"); // Cap at 720p+ mpv_set_option_string(mpv_, "keep-open", "yes");+ mpv_set_option_string(mpv_, "idle", "yes");+ mpv_set_option_string(mpv_, "terminal", "no");+ mpv_set_option_string(mpv_, "msg-level", "all=warn");++ if (mpv_initialize(mpv_) < 0) {+ LOG_ERROR("MpvPlayer", "mpv_initialize() failed");+ error_ = "Failed to initialize mpv";+ state_ = PlayerState::Error;+ mpv_terminate_destroy(mpv_);+ mpv_ = nullptr;+ return false;+ }++ // Set up render context with OpenGL+ mpv_opengl_init_params gl_init{get_proc_address, nullptr};+ int advanced_control = 1;++ mpv_render_param params[] = {+ {MPV_RENDER_PARAM_API_TYPE, (void*)MPV_RENDER_API_TYPE_OPENGL},+ {MPV_RENDER_PARAM_OPENGL_INIT_PARAMS, &gl_init},+ {MPV_RENDER_PARAM_ADVANCED_CONTROL, &advanced_control},+ {MPV_RENDER_PARAM_INVALID, nullptr}+ };++ if (mpv_render_context_create(&mpv_gl_, mpv_, params) < 0) {+ LOG_ERROR("MpvPlayer", "mpv_render_context_create() failed");+ error_ = "Failed to create mpv render context";+ state_ = PlayerState::Error;+ mpv_terminate_destroy(mpv_);+ mpv_ = nullptr;+ return false;+ }++ // Set wakeup callbacks+ mpv_set_wakeup_callback(mpv_, on_mpv_events, this);+ mpv_render_context_set_update_callback(mpv_gl_, on_mpv_render_update, this);++ // Observe properties we care about+ mpv_observe_property(mpv_, 0, "duration", MPV_FORMAT_DOUBLE);+ mpv_observe_property(mpv_, 0, "time-pos", MPV_FORMAT_DOUBLE);+ mpv_observe_property(mpv_, 0, "pause", MPV_FORMAT_FLAG);+ mpv_observe_property(mpv_, 0, "media-title", MPV_FORMAT_STRING);+ mpv_observe_property(mpv_, 0, "idle-active", MPV_FORMAT_FLAG);++ LOG_INFO("MpvPlayer", "Initialized successfully");+ state_ = PlayerState::Idle;+ return true;+}++// ============================================================================+// Playback controls+// ============================================================================+void MpvPlayer::play(const std::string& url) {+ if (!mpv_) return;+ LOG_INFO("MpvPlayer", "Playing: %s", url.c_str());+ state_ = PlayerState::Loading;+ const char* cmd[] = {"loadfile", url.c_str(), nullptr};+ mpv_command_async(mpv_, 0, cmd);+}++void MpvPlayer::stop() {+ if (!mpv_) return;+ const char* cmd[] = {"stop", nullptr};+ mpv_command_async(mpv_, 0, cmd);+ state_ = PlayerState::Stopped;+}++void MpvPlayer::toggle_pause() {+ if (!mpv_) return;+ const char* cmd[] = {"cycle", "pause", nullptr};+ mpv_command_async(mpv_, 0, cmd);+}++void MpvPlayer::set_volume(int vol) {+ if (!mpv_) return;+ std::string v = std::to_string(vol);+ mpv_set_option_string(mpv_, "volume", v.c_str());+}++void MpvPlayer::seek(double seconds) {+ if (!mpv_) return;+ std::string pos = std::to_string(seconds);+ const char* cmd[] = {"seek", pos.c_str(), "absolute", nullptr};+ mpv_command_async(mpv_, 0, cmd);+}++// ============================================================================+// FBO management+// ============================================================================+void MpvPlayer::ensure_fbo(int w, int h) {+ if (w <= 0) w = 1;+ if (h <= 0) h = 1;+ if (fbo_ && tex_w_ == w && tex_h_ == h) return;++ // Delete old+ if (fbo_) { glDeleteFramebuffers(1, &fbo_); fbo_ = 0; }+ if (texture_) { glDeleteTextures(1, &texture_); texture_ = 0; }++ // Create FBO first+ glGenFramebuffers(1, &fbo_);+ glBindFramebuffer(GL_FRAMEBUFFER, fbo_);++ // Create texture and attach to FBO+ glGenTextures(1, &texture_);+ glBindTexture(GL_TEXTURE_2D, texture_);+ glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);+ glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);+ glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, texture_, 0);+ glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, w, h, 0, GL_RGB, GL_UNSIGNED_BYTE, nullptr);++ if (glCheckFramebufferStatus(GL_FRAMEBUFFER) != GL_FRAMEBUFFER_COMPLETE) {+ LOG_ERROR("MpvPlayer", "FBO incomplete!");+ }++ // Unbind both+ glBindTexture(GL_TEXTURE_2D, 0);+ glBindFramebuffer(GL_FRAMEBUFFER, 0);++ tex_w_ = w;+ tex_h_ = h;+ LOG_INFO("MpvPlayer", "FBO created: %dx%d, tex=%u, fbo=%u", w, h, texture_, fbo_);+}++// ============================================================================+// Render frame — call each ImGui frame+// ============================================================================+unsigned int MpvPlayer::render_frame(int width, int height) {+ if (!mpv_gl_) return 0;++ // Process any pending mpv events+ process_events();++ // Check if mpv wants to render+ uint64_t flags = mpv_render_context_update(mpv_gl_);+ if (!(flags & MPV_RENDER_UPDATE_FRAME)) {+ return texture_; // Return last texture if no new frame+ }++ ensure_fbo(width, height);+ if (!fbo_) return 0;++ // Save current viewport+ GLint viewport[4];+ glGetIntegerv(GL_VIEWPORT, viewport);++ // Resize texture to match requested dimensions (like the working demo)+ glBindFramebuffer(GL_FRAMEBUFFER, fbo_);+ glBindTexture(GL_TEXTURE_2D, texture_);+ glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, width, height, 0, GL_RGB, GL_UNSIGNED_BYTE, nullptr);+ glBindFramebuffer(GL_FRAMEBUFFER, 0);+ glBindTexture(GL_TEXTURE_2D, 0);++ // Render mpv into our FBO+ mpv_opengl_fbo fbo_params{};+ fbo_params.fbo = (int)fbo_;+ fbo_params.w = width;+ fbo_params.h = height;+ fbo_params.internal_format = 0;++ int flip_y = 0; // No flip — matches working imgui+mpv demos++ mpv_render_param render_params[] = {+ {MPV_RENDER_PARAM_OPENGL_FBO, &fbo_params},+ {MPV_RENDER_PARAM_FLIP_Y, &flip_y},+ {MPV_RENDER_PARAM_INVALID, nullptr}+ };++ mpv_render_context_render(mpv_gl_, render_params);++ // Restore viewport (mpv changes it)+ glViewport(viewport[0], viewport[1], viewport[2], viewport[3]);++ return texture_;+}++// ============================================================================+// Event processing+// ============================================================================+void MpvPlayer::process_events() {+ if (!mpv_) return;++ while (true) {+ mpv_event* event = mpv_wait_event(mpv_, 0);+ if (event->event_id == MPV_EVENT_NONE) break;++ switch (event->event_id) {+ case MPV_EVENT_FILE_LOADED:+ state_ = PlayerState::Playing;+ break;++ case MPV_EVENT_END_FILE: {+ auto* data = (mpv_event_end_file*)event->data;+ if (data->reason == MPV_END_FILE_REASON_ERROR) {+ std::lock_guard<std::mutex> lock(prop_mutex_);+ error_ = "Playback error";+ state_ = PlayerState::Error;+ } else {+ state_ = PlayerState::Stopped;+ }+ break;+ }++ case MPV_EVENT_PROPERTY_CHANGE: {+ auto* prop = (mpv_event_property*)event->data;+ if (prop->format == MPV_FORMAT_DOUBLE) {+ double val = *(double*)prop->data;+ if (strcmp(prop->name, "duration") == 0) duration_ = val;+ else if (strcmp(prop->name, "time-pos") == 0) position_ = val;+ } else if (prop->format == MPV_FORMAT_FLAG) {+ int val = *(int*)prop->data;+ if (strcmp(prop->name, "pause") == 0) {+ if (val && state_ == PlayerState::Playing) state_ = PlayerState::Paused;+ else if (!val && state_ == PlayerState::Paused) state_ = PlayerState::Playing;+ } else if (strcmp(prop->name, "idle-active") == 0) {+ if (val) state_ = PlayerState::Idle;+ }+ } else if (prop->format == MPV_FORMAT_STRING) {+ if (strcmp(prop->name, "media-title") == 0) {+ std::lock_guard<std::mutex> lock(prop_mutex_);+ title_ = *(char**)prop->data;+ }+ }+ break;+ }++ case MPV_EVENT_LOG_MESSAGE: {+ auto* msg = (mpv_event_log_message*)event->data;+ if (msg->log_level <= MPV_LOG_LEVEL_WARN) {+ LOG_WARN("mpv", "[%s] %s", msg->prefix, msg->text);+ }+ break;+ }++ default:+ break;+ }+ }+}++// ============================================================================+// Accessors+// ============================================================================+std::string MpvPlayer::error_msg() const {+ std::lock_guard<std::mutex> lock(prop_mutex_);+ return error_;+}++std::string MpvPlayer::media_title() const {+ std::lock_guard<std::mutex> lock(prop_mutex_);+ return title_;+}++// ============================================================================+// Callbacks+// ============================================================================+void MpvPlayer::on_mpv_events(void* ctx) {+ auto* self = static_cast<MpvPlayer*>(ctx);+ self->wakeup_flag_ = true;+}++void MpvPlayer::on_mpv_render_update(void* ctx) {+ // Nothing needed — we poll in render_frame()+ (void)ctx;+}++} // namespace fincept::media++#else // !FINCEPT_HAS_MPV — stub implementation++namespace fincept::media {++MpvPlayer::MpvPlayer() = default;+MpvPlayer::~MpvPlayer() = default;++bool MpvPlayer::init() {+ error_ = "mpv not available (build without FINCEPT_HAS_MPV)";+ state_ = PlayerState::Error;+ return false;+}++void MpvPlayer::play(const std::string&) {}+void MpvPlayer::stop() {}+void MpvPlayer::toggle_pause() {}+void MpvPlayer::set_volume(int) {}+void MpvPlayer::seek(double) {}+unsigned int MpvPlayer::render_frame(int, int) { return 0; }+void MpvPlayer::ensure_fbo(int, int) {}+void MpvPlayer::process_events() {}+void MpvPlayer::cleanup() {}++std::string MpvPlayer::error_msg() const {+ return "mpv not available";+}++std::string MpvPlayer::media_title() const {+ return {};+}++void MpvPlayer::on_mpv_events(void*) {}+void MpvPlayer::on_mpv_render_update(void*) {}++} // namespace fincept::media++#endifdiff --git a/fincept-cpp/src/media/mpv_player.h b/fincept-cpp/src/media/mpv_player.hnew file mode 100644index 000000000..bb039b87d--- /dev/null+++ b/fincept-cpp/src/media/mpv_player.h@@ -0,0 +1,79 @@+#pragma once+// Lightweight mpv wrapper — renders video into an OpenGL texture for ImGui::Image()+// Uses libmpv render API with FBO offscreen rendering+// Cross-platform: Windows, Linux, macOS++#include <string>+#include <functional>+#include <mutex>+#include <atomic>++// Forward declarations — avoid pulling mpv headers into every TU+struct mpv_handle;+struct mpv_render_context;++namespace fincept::media {++enum class PlayerState { Idle, Loading, Playing, Paused, Stopped, Error };++class MpvPlayer {+public:+ MpvPlayer();+ ~MpvPlayer();++ // Non-copyable+ MpvPlayer(const MpvPlayer&) = delete;+ MpvPlayer& operator=(const MpvPlayer&) = delete;++ // Initialize mpv + render context. Call once after GL context is current.+ bool init();++ // Load and play a URL (YouTube URLs require yt-dlp in PATH)+ void play(const std::string& url);+ void stop();+ void toggle_pause();+ void set_volume(int vol); // 0-100++ // Call each frame to render into internal FBO. Returns GL texture ID (0 if not ready).+ // width/height = desired render size in pixels+ unsigned int render_frame(int width, int height);++ // State queries+ PlayerState state() const { return state_.load(); }+ bool is_playing() const { return state_ == PlayerState::Playing; }+ double duration() const { return duration_; }+ double position() const { return position_; }+ std::string error_msg() const;+ std::string media_title() const;++ // Seek to position (seconds)+ void seek(double seconds);++private:+ mpv_handle* mpv_ = nullptr;+ mpv_render_context* mpv_gl_ = nullptr;++ // OpenGL FBO for offscreen rendering+ unsigned int fbo_ = 0;+ unsigned int texture_ = 0;+ int tex_w_ = 0;+ int tex_h_ = 0;++ std::atomic<PlayerState> state_{PlayerState::Idle};+ double duration_ = 0;+ double position_ = 0;+ std::string error_;+ std::string title_;+ mutable std::mutex prop_mutex_;++ std::atomic<bool> wakeup_flag_{false};++ void ensure_fbo(int w, int h);+ void process_events();+ void cleanup();++ static void on_mpv_events(void* ctx);+ static void on_mpv_render_update(void* ctx);+};++} // namespace fincept::mediadiff --git a/fincept-cpp/src/screens/ai_chat/ai_chat_screen.cpp b/fincept-cpp/src/screens/ai_chat/ai_chat_screen.cppnew file mode 100644index 000000000..f57ddb8de--- /dev/null+++ b/fincept-cpp/src/screens/ai_chat/ai_chat_screen.cpp@@ -0,0 +1,1043 @@+#include "ai_chat_screen.h"+#include "ui/theme.h"+#include "ui/yoga_helpers.h"+#include "core/logger.h"+#include "mcp/mcp_service.h"+#include <imgui.h>+#include <cstring>+#include <cstdio>+#include <algorithm>+#include <cctype>++namespace fincept::ai_chat {++// ============================================================================+// Default quick prompts (matches TypeScript DEFAULT_QUICK_PROMPTS)+// ============================================================================+static const std::vector<QuickPrompt> DEFAULT_QUICK_PROMPTS = {+ {"MARKET TRENDS", "Analyze current market trends and key insights"},+ {"PORTFOLIO", "Portfolio diversification recommendations"},+ {"RISK", "Investment risk assessment strategies"},+ {"TECHNICAL", "Key technical analysis indicators"},+};++// ============================================================================+// Init+// ============================================================================+void AIChatScreen::init() {+ if (initialized_) return;++ quick_prompts_ = DEFAULT_QUICK_PROMPTS;+ load_config();+ load_sessions();+ load_statistics();+ status_ = "READY";+ last_config_reload_ = std::chrono::steady_clock::now();+ initialized_ = true;+}++void AIChatScreen::load_config() {+ all_configs_ = db::ops::get_llm_configs();+ global_settings_ = db::ops::get_llm_global_settings();++ active_config_ = {};+ for (auto& c : all_configs_) {+ if (c.is_active) {+ active_config_ = c;+ break;+ }+ }+ if (active_config_.provider.empty() && !all_configs_.empty()) {+ active_config_ = all_configs_[0];+ }++ LLMService::instance().reload_config();+}++void AIChatScreen::load_sessions() {+ sessions_ = db::ops::get_chat_sessions();+}++void AIChatScreen::load_messages(const std::string& session_uuid) {+ messages_ = db::ops::get_chat_messages(session_uuid);+ scroll_to_bottom_ = true;+}++void AIChatScreen::load_statistics() {+ total_sessions_ = (int)sessions_.size();+ total_messages_ = 0;+ total_tokens_ = 0;+ // Quick approximation — count from loaded sessions+ for (auto& s : sessions_) {+ total_messages_ += (int)s.message_count;+ }+}++// ============================================================================+// Session operations+// ============================================================================+void AIChatScreen::create_new_session() {+ std::string title = "New Chat";+ if (std::strlen(input_buf_) > 0) {+ title = generate_smart_title(input_buf_);+ }++ auto session = db::ops::create_chat_session(title);+ current_session_uuid_ = session.session_uuid;+ messages_.clear();+ load_sessions();+ load_statistics();++ // Select the new session+ for (int i = 0; i < (int)sessions_.size(); i++) {+ if (sessions_[i].session_uuid == current_session_uuid_) {+ selected_session_idx_ = i;+ break;+ }+ }++ status_ = "NEW SESSION CREATED";+}++void AIChatScreen::delete_session(const std::string& uuid) {+ db::ops::delete_chat_session(uuid);+ if (current_session_uuid_ == uuid) {+ current_session_uuid_.clear();+ messages_.clear();+ selected_session_idx_ = -1;+ }+ load_sessions();+ load_statistics();+ status_ = "SESSION DELETED";+}++void AIChatScreen::delete_all_sessions() {+ for (auto& s : sessions_) {+ db::ops::delete_chat_session(s.session_uuid);+ }+ sessions_.clear();+ messages_.clear();+ current_session_uuid_.clear();+ selected_session_idx_ = -1;+ load_statistics();+ status_ = "ALL SESSIONS DELETED";+}++void AIChatScreen::select_session(int idx) {+ if (idx < 0 || idx >= (int)sessions_.size()) return;+ selected_session_idx_ = idx;+ current_session_uuid_ = sessions_[idx].session_uuid;+ load_messages(current_session_uuid_);+ status_ = "READY";+}++void AIChatScreen::start_rename(const std::string& uuid, const std::string& title) {+ renaming_session_uuid_ = uuid;+ std::strncpy(rename_buf_, title.c_str(), sizeof(rename_buf_) - 1);+ rename_buf_[sizeof(rename_buf_) - 1] = '\0';+}++void AIChatScreen::save_rename() {+ std::string new_title(rename_buf_);+ if (!new_title.empty() && !renaming_session_uuid_.empty()) {+ db::ops::update_chat_session_title(renaming_session_uuid_, new_title);+ load_sessions();+ }+ renaming_session_uuid_.clear();+}++void AIChatScreen::cancel_rename() {+ renaming_session_uuid_.clear();+}++void AIChatScreen::clear_current_chat() {+ if (current_session_uuid_.empty()) return;+ db::ops::clear_chat_session_messages(current_session_uuid_);+ messages_.clear();+ load_sessions();+ load_statistics();+ status_ = "CHAT CLEARED";+}++void AIChatScreen::switch_provider(const std::string& provider) {+ db::ops::set_active_llm_provider(provider);+ load_config();+ status_ = "READY";+}++// ============================================================================+// Smart title generation (mirrors TypeScript generateSmartTitle)+// ============================================================================+std::string AIChatScreen::generate_smart_title(const std::string& message) {+ if (message.empty()) return "New Chat";++ std::string lower = message;+ std::transform(lower.begin(), lower.end(), lower.begin(), ::tolower);++ // Financial keywords+ static const char* keywords[] = {+ "market", "stock", "portfolio", "risk", "analysis",+ "trend", "trading", "investment", "price", "strategy",+ "forecast", "data", "chart", "indicator", "technical"+ };+ for (auto* kw : keywords) {+ if (lower.find(kw) != std::string::npos) {+ std::string title(kw);+ title[0] = (char)std::toupper(title[0]);+ return title + " Chat";+ }+ }++ // Question words+ if (lower.rfind("what", 0) == 0) return "What Query";+ if (lower.rfind("how", 0) == 0) return "How To";+ if (lower.rfind("why", 0) == 0) return "Why Question";+ if (lower.rfind("analyze", 0) == 0) return "Analysis";+ if (lower.rfind("explain", 0) == 0) return "Explanation";+ if (lower.rfind("compare", 0) == 0) return "Comparison";+ if (lower.rfind("calculate", 0) == 0) return "Calculation";++ // First 2 meaningful words (max 20 chars)+ std::string result;+ int word_count = 0;+ std::istringstream iss(message);+ std::string word;+ while (iss >> word && word_count < 2) {+ if (word.size() <= 2) continue;+ if (!result.empty()) result += " ";+ result += word;+ word_count++;+ }+ if (result.size() > 20) result = result.substr(0, 20);+ return result.empty() ? "New Chat" : result;+}++// ============================================================================+// Message sending+// ============================================================================+void AIChatScreen::send_message() {+ std::string content(input_buf_);+ // Trim+ auto start = content.find_first_not_of(" \t\n\r");+ if (start == std::string::npos) return;+ content = content.substr(start);+ auto end = content.find_last_not_of(" \t\n\r");+ if (end != std::string::npos) content = content.substr(0, end + 1);+ if (content.empty()) return;++ // Ensure we have a provider+ if (active_config_.provider.empty()) {+ error_ = "No LLM provider configured. Go to Settings > LLM Configuration.";+ error_time_ = ImGui::GetTime();+ return;+ }++ // Check API key+ if (provider_requires_api_key(active_config_.provider)) {+ if (!active_config_.api_key || active_config_.api_key->empty()) {+ error_ = active_config_.provider + " requires an API key. Configure in Settings.";+ error_time_ = ImGui::GetTime();+ return;+ }+ }++ // Ensure session+ if (current_session_uuid_.empty()) {+ create_new_session();+ }++ // Save user message+ db::ChatMessage user_msg;+ user_msg.session_uuid = current_session_uuid_;+ user_msg.role = "user";+ user_msg.content = content;+ user_msg = db::ops::add_chat_message(user_msg);+ messages_.push_back(user_msg);++ // Clear input+ std::memset(input_buf_, 0, sizeof(input_buf_));+ scroll_to_bottom_ = true;++ // Build conversation history+ std::vector<ConversationMessage> history;+ for (auto& m : messages_) {+ if (m.role == "user" || m.role == "assistant") {+ history.push_back({m.role, m.content});+ }+ }+ // Remove last (we pass it separately)+ if (!history.empty()) history.pop_back();++ // Status+ std::string prov_upper = active_config_.provider;+ std::transform(prov_upper.begin(), prov_upper.end(), prov_upper.begin(), ::toupper);+ status_ = "CALLING " + prov_upper + " API...";++ // Determine if we should use tool-calling mode (non-streaming)+ // Tool calling requires full responses to detect tool_calls in the JSON+ bool use_tools = mcp::MCPService::instance().tool_count() > 0 &&+ (active_config_.provider == "openai" ||+ active_config_.provider == "groq" ||+ active_config_.provider == "deepseek" ||+ active_config_.provider == "openrouter" ||+ active_config_.provider == "fincept");++ // Start streaming/processing+ is_streaming_ = true;+ {+ std::lock_guard<std::mutex> lock(stream_mutex_);+ streaming_content_.clear();+ }++ if (use_tools) {+ // Non-streaming mode with tool calling support+ streaming_future_ = std::async(std::launch::async, [this, content, history]() {+ return LLMService::instance().chat(content, history);+ });+ } else {+ // Streaming mode (no tool calling)+ streaming_future_ = LLMService::instance().chat_streaming(+ content, history,+ [this](const std::string& chunk, bool done) {+ if (!done) {+ std::lock_guard<std::mutex> lock(stream_mutex_);+ streaming_content_ += chunk;+ }+ }+ );+ }+}++void AIChatScreen::check_streaming_result() {+ if (!is_streaming_) return;+ if (!streaming_future_.valid()) return;++ // Check if future is ready (non-blocking)+ auto status = streaming_future_.wait_for(std::chrono::milliseconds(0));+ if (status != std::future_status::ready) return;++ // Get result+ auto resp = streaming_future_.get();+ is_streaming_ = false;++ std::string final_content;+ {+ std::lock_guard<std::mutex> lock(stream_mutex_);+ final_content = streaming_content_;+ streaming_content_.clear();+ }++ // Use streamed content if response content is empty+ if (resp.content.empty() && !final_content.empty()) {+ resp.content = final_content;+ }++ if (resp.success && !resp.content.empty()) {+ // Save assistant message+ db::ChatMessage ai_msg;+ ai_msg.session_uuid = current_session_uuid_;+ ai_msg.role = "assistant";+ ai_msg.content = resp.content;+ ai_msg.provider = active_config_.provider;+ ai_msg.model = active_config_.model;+ if (resp.total_tokens > 0) ai_msg.tokens_used = resp.total_tokens;+ ai_msg = db::ops::add_chat_message(ai_msg);+ messages_.push_back(ai_msg);+ total_tokens_ += resp.total_tokens;+ scroll_to_bottom_ = true;+ status_ = "READY";+ } else if (!resp.error.empty()) {+ // Save error as assistant message+ db::ChatMessage err_msg;+ err_msg.session_uuid = current_session_uuid_;+ err_msg.role = "assistant";+ err_msg.content = "[ERROR] " + resp.error + "\n\nPlease check your LLM configuration.";+ err_msg = db::ops::add_chat_message(err_msg);+ messages_.push_back(err_msg);+ scroll_to_bottom_ = true;+ status_ = "ERROR: " + resp.error;+ } else {+ status_ = "READY";+ }++ load_sessions();+ load_statistics();+}++// ============================================================================+// Main render+// ============================================================================+void AIChatScreen::render() {+ init();+ check_streaming_result();++ // Periodically reload config (every 5 seconds)+ auto now = std::chrono::steady_clock::now();+ if (std::chrono::duration_cast<std::chrono::seconds>(now - last_config_reload_).count() > 5) {+ load_config();+ last_config_reload_ = now;+ }++ using namespace theme::colors;++ // ScreenFrame gives us full-screen layout like dashboard+ ui::ScreenFrame frame("##ai_chat", ImVec2(0, 0), BG_DARKEST);+ if (!frame.begin()) { frame.end(); return; }++ float total_w = frame.width();+ float total_h = frame.height();++ // Layout: navbar (top) + main (3 panels) + statusbar (bottom)+ float navbar_h = 36.0f;+ float statusbar_h = 24.0f;+ float main_h = total_h - navbar_h - statusbar_h;++ float sessions_w = 260.0f;+ float info_w = 280.0f;+ float chat_w = total_w - sessions_w - info_w;+ if (chat_w < 300) {+ // Collapse sidebars on narrow windows+ sessions_w = 0;+ info_w = 0;+ chat_w = total_w;+ }++ // Navbar+ render_navbar(total_w);++ // Main content area+ if (sessions_w > 0) {+ render_sessions_panel(sessions_w, main_h);+ ImGui::SameLine(0, 0);+ }++ render_chat_panel(chat_w, main_h);++ if (info_w > 0) {+ ImGui::SameLine(0, 0);+ render_info_panel(info_w, main_h);+ }++ // Status bar+ render_status_bar(total_w);++ frame.end();+}++// ============================================================================+// Navbar+// ============================================================================+void AIChatScreen::render_navbar(float width) {+ using namespace theme::colors;++ ImGui::PushStyleColor(ImGuiCol_ChildBg, BG_PANEL);+ ImGui::BeginChild("##chat_navbar", ImVec2(width, 36), ImGuiChildFlags_None);++ float pad = 8.0f;+ ImGui::SetCursorPos(ImVec2(pad, 6));++ // Title+ ImGui::TextColored(ACCENT, "AI CHAT");+ ImGui::SameLine();+ ImGui::TextColored(BORDER, "|");+ ImGui::SameLine();++ // Provider selector button+ std::string prov_label = active_config_.provider.empty() ? "NO PROVIDER" : active_config_.provider;+ std::transform(prov_label.begin(), prov_label.end(), prov_label.begin(), ::toupper);++ ImGui::PushStyleColor(ImGuiCol_Button, ImVec4(WARNING.x, WARNING.y, WARNING.z, 0.15f));+ ImGui::PushStyleColor(ImGuiCol_ButtonHovered, ImVec4(WARNING.x, WARNING.y, WARNING.z, 0.3f));+ ImGui::PushStyleColor(ImGuiCol_Text, WARNING);+ if (ImGui::SmallButton((prov_label + " v##prov_btn").c_str())) {+ ImGui::OpenPopup("##prov_popup");+ }+ ImGui::PopStyleColor(3);++ // Provider dropdown popup+ ImGui::PushStyleColor(ImGuiCol_PopupBg, BG_PANEL);+ ImGui::PushStyleColor(ImGuiCol_Border, ACCENT);+ ImGui::SetNextWindowSizeConstraints(ImVec2(220, 0), ImVec2(220, 400));+ if (ImGui::BeginPopup("##prov_popup")) {+ ImGui::TextColored(TEXT_DIM, "SELECT PROVIDER");+ ImGui::Separator();+ for (auto& cfg : all_configs_) {+ bool is_active = (cfg.provider == active_config_.provider);+ std::string label = cfg.provider;+ std::transform(label.begin(), label.end(), label.begin(), ::toupper);+ if (is_active) label += " [ACTIVE]";++ if (ImGui::Selectable(label.c_str(), is_active)) {+ switch_provider(cfg.provider);+ ImGui::CloseCurrentPopup();+ }+ ImGui::TextColored(TEXT_DIM, " Model: %s", cfg.model.c_str());+ }+ if (all_configs_.empty()) {+ ImGui::TextColored(TEXT_DIM, "No providers configured.");+ }+ ImGui::EndPopup();+ }+ ImGui::PopStyleColor(2);++ ImGui::SameLine();+ ImGui::TextColored(BORDER, "|");+ ImGui::SameLine();++ // Clock+ auto t = std::time(nullptr);+ auto tm = std::localtime(&t);+ char clock_buf[16];+ std::snprintf(clock_buf, sizeof(clock_buf), "%02d:%02d:%02d",+ tm->tm_hour, tm->tm_min, tm->tm_sec);+ ImGui::TextColored(TEXT_SECONDARY, "%s", clock_buf);++ // Right side buttons+ float right_x = width - 200;+ ImGui::SameLine(right_x);++ ImGui::PushStyleColor(ImGuiCol_Button, ImVec4(0, 0, 0, 0));+ ImGui::PushStyleColor(ImGuiCol_ButtonHovered, BG_HOVER);+ ImGui::PushStyleColor(ImGuiCol_Text, TEXT_SECONDARY);+ if (ImGui::SmallButton("SETTINGS##chat")) {+ // Could navigate to settings tab — for now just note it+ }+ ImGui::PopStyleColor(3);++ ImGui::SameLine();+ if (theme::AccentButton("+ NEW CHAT")) {+ create_new_session();+ }++ ImGui::EndChild();+ ImGui::PopStyleColor(); // ChildBg+}++// ============================================================================+// Sessions panel (left sidebar)+// ============================================================================+void AIChatScreen::render_sessions_panel(float width, float height) {+ using namespace theme::colors;++ ImGui::PushStyleColor(ImGuiCol_ChildBg, BG_PANEL);+ ImGui::PushStyleColor(ImGuiCol_Border, BORDER_DIM);+ ImGui::BeginChild("##sessions_panel", ImVec2(width, height), ImGuiChildFlags_Borders);++ // Header+ ImGui::TextColored(TEXT_DIM, "SESSIONS (%d)", total_sessions_);+ ImGui::SameLine(width - 70);+ ImGui::PushStyleColor(ImGuiCol_Button, ImVec4(ERROR_RED.x, ERROR_RED.y, ERROR_RED.z, 0.15f));+ ImGui::PushStyleColor(ImGuiCol_Text, ERROR_RED);+ if (ImGui::SmallButton("CLEAR ALL") && !sessions_.empty()) {+ delete_all_sessions();+ }+ ImGui::PopStyleColor(2);++ // Search+ ImGui::SetNextItemWidth(width - 16);+ ImGui::InputTextWithHint("##sess_search", "Search sessions...", search_buf_, sizeof(search_buf_));++ // Stats+ ImGui::TextColored(INFO, "MSGS: %d | TOKENS: %d", total_messages_, total_tokens_);+ ImGui::Separator();++ // Session list+ std::string filter(search_buf_);+ std::transform(filter.begin(), filter.end(), filter.begin(), ::tolower);++ ImGui::BeginChild("##sess_list", ImVec2(0, 0));+ for (int i = 0; i < (int)sessions_.size(); i++) {+ auto& s = sessions_[i];++ // Filter+ if (!filter.empty()) {+ std::string title_lower = s.title;+ std::transform(title_lower.begin(), title_lower.end(), title_lower.begin(), ::tolower);+ if (title_lower.find(filter) == std::string::npos) continue;+ }++ bool is_selected = (s.session_uuid == current_session_uuid_);++ ImGui::PushID(i);++ // Highlight selected+ if (is_selected) {+ ImGui::PushStyleColor(ImGuiCol_ChildBg, ImVec4(ACCENT.x, ACCENT.y, ACCENT.z, 0.08f));+ }++ float item_h = 52;+ ImGui::BeginChild(("##sess_" + std::to_string(i)).c_str(),+ ImVec2(width - 16, item_h), ImGuiChildFlags_None);++ // Renaming mode+ if (renaming_session_uuid_ == s.session_uuid) {+ ImGui::SetNextItemWidth(width - 80);+ if (ImGui::InputText("##rename", rename_buf_, sizeof(rename_buf_),+ ImGuiInputTextFlags_EnterReturnsTrue)) {+ save_rename();+ }+ ImGui::SameLine();+ ImGui::PushStyleColor(ImGuiCol_Text, SUCCESS);+ if (ImGui::SmallButton("OK")) save_rename();+ ImGui::PopStyleColor();+ ImGui::SameLine();+ ImGui::PushStyleColor(ImGuiCol_Text, ERROR_RED);+ if (ImGui::SmallButton("X")) cancel_rename();+ ImGui::PopStyleColor();+ } else {+ // Title (clickable)+ if (ImGui::Selectable(("##sel_" + s.session_uuid).c_str(), is_selected,+ ImGuiSelectableFlags_AllowDoubleClick, ImVec2(width - 60, 20))) {+ select_session(i);+ }+ ImGui::SameLine(8);+ ImGui::TextColored(is_selected ? TEXT_PRIMARY : TEXT_SECONDARY, "%s", s.title.c_str());++ // Bottom row: message count + time + actions+ ImGui::TextColored(TEXT_DIM, "%lld msgs", (long long)s.message_count);+ ImGui::SameLine(width - 80);++ ImGui::PushStyleColor(ImGuiCol_Button, ImVec4(0, 0, 0, 0));+ ImGui::PushStyleColor(ImGuiCol_Text, WARNING);+ if (ImGui::SmallButton("Ren")) {+ start_rename(s.session_uuid, s.title);+ }+ ImGui::PopStyleColor(2);+ ImGui::SameLine();+ ImGui::PushStyleColor(ImGuiCol_Button, ImVec4(0, 0, 0, 0));+ ImGui::PushStyleColor(ImGuiCol_Text, ERROR_RED);+ if (ImGui::SmallButton("Del")) {+ delete_session(s.session_uuid);+ }+ ImGui::PopStyleColor(2);+ }++ ImGui::EndChild();++ if (is_selected) ImGui::PopStyleColor();++ ImGui::PopID();+ }+ ImGui::EndChild(); // sess_list++ ImGui::EndChild(); // sessions_panel+ ImGui::PopStyleColor(2); // ChildBg, Border+}++// ============================================================================+// Chat panel (center)+// ============================================================================+void AIChatScreen::render_chat_panel(float width, float height) {+ using namespace theme::colors;++ ImGui::PushStyleColor(ImGuiCol_ChildBg, BG_DARK);+ ImGui::BeginChild("##chat_panel", ImVec2(width, height), ImGuiChildFlags_None);++ // Chat header+ {+ ImGui::PushStyleColor(ImGuiCol_ChildBg, BG_PANEL);+ ImGui::BeginChild("##chat_header", ImVec2(width, 30), ImGuiChildFlags_None);+ ImGui::SetCursorPos(ImVec2(8, 6));++ if (!current_session_uuid_.empty()) {+ // Find session title+ std::string title = "CHAT";+ for (auto& s : sessions_) {+ if (s.session_uuid == current_session_uuid_) {+ title = s.title;+ break;+ }+ }+ std::transform(title.begin(), title.end(), title.begin(), ::toupper);+ ImGui::TextColored(TEXT_DIM, "%s", title.c_str());++ ImGui::SameLine(width - 60);+ ImGui::PushStyleColor(ImGuiCol_Button, ImVec4(ERROR_RED.x, ERROR_RED.y, ERROR_RED.z, 0.15f));+ ImGui::PushStyleColor(ImGuiCol_Text, ERROR_RED);+ if (ImGui::SmallButton("CLEAR")) {+ clear_current_chat();+ }+ ImGui::PopStyleColor(2);+ } else {+ ImGui::TextColored(TEXT_DIM, "NO ACTIVE SESSION");+ }++ ImGui::EndChild();+ ImGui::PopStyleColor();+ }++ // Messages area+ float input_h = 90.0f;+ float messages_h = height - 30 - input_h;++ ImGui::PushStyleColor(ImGuiCol_ChildBg, BG_DARKEST);+ ImGui::BeginChild("##messages_area", ImVec2(width, messages_h), ImGuiChildFlags_None);++ if (messages_.empty() && streaming_content_.empty() && !is_streaming_) {+ render_welcome_screen(width, messages_h);+ } else {+ ImGui::SetCursorPosX(8);+ ImGui::BeginGroup();++ for (auto& msg : messages_) {+ render_message(msg, width - 32);+ }++ // Streaming content+ if (is_streaming_) {+ render_streaming_message(width - 32);+ }++ ImGui::EndGroup();++ if (scroll_to_bottom_) {+ ImGui::SetScrollHereY(1.0f);+ scroll_to_bottom_ = false;+ }+ }++ ImGui::EndChild();+ ImGui::PopStyleColor(); // messages bg++ // Input area+ render_input_area(width);++ ImGui::EndChild(); // chat_panel+ ImGui::PopStyleColor(); // ChildBg+}++// ============================================================================+// Welcome screen (when no messages)+// ============================================================================+void AIChatScreen::render_welcome_screen(float width, float height) {+ using namespace theme::colors;++ float center_x = width / 2 - 100;+ float center_y = height / 2 - 60;+ ImGui::SetCursorPos(ImVec2(center_x, center_y));++ ImGui::BeginGroup();+ ImGui::TextColored(ACCENT, "AI CHAT");+ ImGui::TextColored(TEXT_SECONDARY, "Financial intelligence assistant");+ ImGui::Spacing();++ std::string prov_info = "PROVIDER: " ++ (active_config_.provider.empty() ? "NONE" : active_config_.provider) ++ " | MODEL: " + (active_config_.model.empty() ? "N/A" : active_config_.model);+ std::transform(prov_info.begin(), prov_info.end(), prov_info.begin(), ::toupper);++ ImGui::PushStyleColor(ImGuiCol_Text, WARNING);+ ImGui::TextWrapped("%s", prov_info.c_str());+ ImGui::PopStyleColor();++ ImGui::Spacing();+ if (theme::AccentButton("START NEW CHAT")) {+ create_new_session();+ }+ ImGui::EndGroup();+}++// ============================================================================+// Message rendering+// ============================================================================+void AIChatScreen::render_message(const db::ChatMessage& msg, float width) {+ using namespace theme::colors;++ bool is_user = (msg.role == "user");+ ImVec4 border_color = is_user ? WARNING : ACCENT;+ ImVec4 label_color = is_user ? WARNING : ACCENT;+ const char* label = is_user ? "YOU" : "AI";++ ImGui::PushID(msg.id.c_str());+ ImGui::Spacing();++ // Alignment: user right, assistant left+ float msg_max_w = width * 0.85f;+ if (is_user) {+ ImGui::SetCursorPosX(width - msg_max_w + 8);+ } else {+ ImGui::SetCursorPosX(8);+ }++ // Message box+ ImGui::PushStyleColor(ImGuiCol_ChildBg, BG_PANEL);+ ImGui::PushStyleVar(ImGuiStyleVar_ChildBorderSize, 1.0f);+ ImGui::PushStyleColor(ImGuiCol_Border, border_color);++ std::string child_id = "##msg_" + msg.id;+ ImGui::BeginChild(child_id.c_str(), ImVec2(msg_max_w, 0),+ ImGuiChildFlags_Borders | ImGuiChildFlags_AutoResizeY);++ // Header: role + timestamp + provider+ ImGui::TextColored(label_color, "%s", label);+ ImGui::SameLine();+ if (!msg.timestamp.empty()) {+ // Show just the time portion+ std::string time_str = msg.timestamp;+ auto space = time_str.find(' ');+ if (space != std::string::npos && space + 1 < time_str.size()) {+ time_str = time_str.substr(space + 1);+ }+ // Truncate to HH:MM:SS+ if (time_str.size() > 8) time_str = time_str.substr(0, 8);+ ImGui::TextColored(TEXT_DIM, "%s", time_str.c_str());+ }+ if (msg.provider) {+ ImGui::SameLine();+ std::string prov = *msg.provider;+ std::transform(prov.begin(), prov.end(), prov.begin(), ::toupper);+ ImGui::TextColored(TEXT_DIM, "| %s", prov.c_str());+ }+ ImGui::Separator();++ // Content+ ImGui::PushTextWrapPos(ImGui::GetCursorPosX() + msg_max_w - 20);++ // Check for error messages+ if (!is_user && msg.content.rfind("[ERROR]", 0) == 0) {+ ImGui::TextColored(ERROR_RED, "%s", msg.content.c_str());+ } else {+ ImGui::TextColored(TEXT_PRIMARY, "%s", msg.content.c_str());+ }++ ImGui::PopTextWrapPos();++ ImGui::EndChild();+ ImGui::PopStyleColor(2); // Border, ChildBg+ ImGui::PopStyleVar(); // ChildBorderSize++ ImGui::PopID();+}++// ============================================================================+// Streaming message (live response)+// ============================================================================+void AIChatScreen::render_streaming_message(float width) {+ using namespace theme::colors;++ std::string content;+ {+ std::lock_guard<std::mutex> lock(stream_mutex_);+ content = streaming_content_;+ }++ ImGui::Spacing();+ ImGui::SetCursorPosX(8);++ ImGui::PushStyleColor(ImGuiCol_ChildBg, BG_PANEL);+ ImGui::PushStyleVar(ImGuiStyleVar_ChildBorderSize, 2.0f);+ ImGui::PushStyleColor(ImGuiCol_Border, ACCENT);++ float msg_w = width * 0.85f;+ ImGui::BeginChild("##streaming_msg", ImVec2(msg_w, 0),+ ImGuiChildFlags_Borders | ImGuiChildFlags_AutoResizeY);++ // Animated header+ ImGui::TextColored(ACCENT, "AI");+ ImGui::SameLine();+ double t = ImGui::GetTime();+ int dots = ((int)(t * 3)) % 4;+ char dot_buf[8] = {};+ for (int i = 0; i < dots; i++) dot_buf[i] = '.';+ ImGui::TextColored(ACCENT, "TYPING%s", dot_buf);+ ImGui::Separator();++ if (!content.empty()) {+ ImGui::PushTextWrapPos(ImGui::GetCursorPosX() + msg_w - 20);+ ImGui::TextColored(TEXT_PRIMARY, "%s", content.c_str());+ ImGui::PopTextWrapPos();++ // Blinking cursor+ if (((int)(t * 2)) % 2 == 0) {+ ImGui::SameLine(0, 0);+ ImGui::TextColored(ACCENT, "|");+ }+ } else {+ ImGui::TextColored(TEXT_DIM, "Thinking...");+ }++ ImGui::EndChild();+ ImGui::PopStyleColor(2);+ ImGui::PopStyleVar();++ // Auto-scroll while streaming+ ImGui::SetScrollHereY(1.0f);+}++// ============================================================================+// Input area+// ============================================================================+void AIChatScreen::render_input_area(float width) {+ using namespace theme::colors;++ ImGui::PushStyleColor(ImGuiCol_ChildBg, BG_PANEL);+ ImGui::BeginChild("##input_area", ImVec2(width, 90), ImGuiChildFlags_None);++ float btn_w = 80;+ float input_w = width - btn_w - 24;++ ImGui::SetCursorPos(ImVec2(8, 8));++ // Multiline input+ ImGui::PushStyleColor(ImGuiCol_FrameBg, BG_INPUT);+ ImGui::PushStyleColor(ImGuiCol_Border, BORDER_DIM);+ ImGui::SetNextItemWidth(input_w);++ bool enter_pressed = ImGui::InputTextMultiline("##chat_input", input_buf_, sizeof(input_buf_),+ ImVec2(input_w, 50),+ ImGuiInputTextFlags_CtrlEnterForNewLine |+ ImGuiInputTextFlags_EnterReturnsTrue);+ ImGui::PopStyleColor(2);++ // Send on Enter (when not streaming)+ bool can_send = std::strlen(input_buf_) > 0 && !is_streaming_;++ ImGui::SameLine();+ ImGui::SetCursorPosY(8);++ if (can_send) {+ if (theme::AccentButton("SEND##chat_send") || enter_pressed) {+ send_message();+ }+ } else {+ ImGui::PushStyleColor(ImGuiCol_Button, BG_WIDGET);+ ImGui::PushStyleColor(ImGuiCol_Text, TEXT_DISABLED);+ ImGui::Button("SEND##chat_send_dis");+ ImGui::PopStyleColor(2);+ }++ // Status line+ ImGui::SetCursorPos(ImVec2(8, 65));+ size_t len = std::strlen(input_buf_);+ if (len > 0) {+ ImGui::TextColored(TEXT_DIM, "%zu CHARS", len);+ } else {+ ImGui::TextColored(TEXT_DIM, "STATUS: %s", status_.c_str());+ }++ // Error display+ if (!error_.empty() && (ImGui::GetTime() - error_time_) < 8.0) {+ ImGui::SameLine(width - 400);+ ImGui::TextColored(ERROR_RED, "%s", error_.c_str());+ }++ ImGui::EndChild();+ ImGui::PopStyleColor(); // ChildBg+}++// ============================================================================+// Info panel (right sidebar)+// ============================================================================+void AIChatScreen::render_info_panel(float width, float height) {+ using namespace theme::colors;++ ImGui::PushStyleColor(ImGuiCol_ChildBg, BG_PANEL);+ ImGui::PushStyleColor(ImGuiCol_Border, BORDER_DIM);+ ImGui::BeginChild("##info_panel", ImVec2(width, height), ImGuiChildFlags_Borders);++ // ── Quick Prompts Section ──+ ImGui::TextColored(TEXT_DIM, "QUICK PROMPTS");+ ImGui::Separator();++ for (auto& qp : quick_prompts_) {+ ImGui::PushStyleColor(ImGuiCol_Button, BG_WIDGET);+ ImGui::PushStyleColor(ImGuiCol_ButtonHovered, BG_HOVER);+ ImGui::PushStyleColor(ImGuiCol_Text, TEXT_SECONDARY);+ if (ImGui::Button(qp.label.c_str(), ImVec2(width - 16, 0))) {+ std::strncpy(input_buf_, qp.prompt.c_str(), sizeof(input_buf_) - 1);+ input_buf_[sizeof(input_buf_) - 1] = '\0';+ }+ if (ImGui::IsItemHovered()) {+ ImGui::SetTooltip("%s", qp.prompt.c_str());+ }+ ImGui::PopStyleColor(3);+ }++ ImGui::Spacing();+ ImGui::Separator();++ // ── System Info Section ──+ ImGui::TextColored(TEXT_DIM, "SYSTEM INFO");+ ImGui::Separator();++ if (!active_config_.provider.empty()) {+ std::string prov = active_config_.provider;+ std::transform(prov.begin(), prov.end(), prov.begin(), ::toupper);+ ImGui::TextColored(INFO, "PROVIDER: %s", prov.c_str());+ ImGui::TextColored(INFO, "MODEL: %s", active_config_.model.c_str());++ if (active_config_.base_url && !active_config_.base_url->empty()) {+ ImGui::TextColored(TEXT_DIM, "ENDPOINT: %s", active_config_.base_url->c_str());+ }++ ImGui::TextColored(INFO, "TEMP: %.2f | MAX TOKENS: %lld",+ global_settings_.temperature, (long long)global_settings_.max_tokens);++ ImGui::Spacing();++ // Status badges+ // Streaming+ bool supports_stream = provider_supports_streaming(active_config_.provider);+ ImGui::TextColored(supports_stream ? SUCCESS : TEXT_DIM,+ "STREAMING: %s", supports_stream ? "ENABLED" : "DISABLED");++ // API Key+ bool needs_key = provider_requires_api_key(active_config_.provider);+ if (!needs_key) {+ ImGui::TextColored(INFO, "API KEY: NOT REQUIRED");+ } else {+ bool has_key = active_config_.api_key && !active_config_.api_key->empty();+ ImGui::TextColored(has_key ? SUCCESS : ERROR_RED,+ "API KEY: %s", has_key ? "CONFIGURED" : "MISSING");+ }++ // System prompt+ if (!global_settings_.system_prompt.empty()) {+ ImGui::TextColored(ACCENT, "CUSTOM PROMPT: YES");+ }+ } else {+ ImGui::TextColored(ERROR_RED, "NO LLM PROVIDER CONFIGURED");+ }++ ImGui::EndChild();+ ImGui::PopStyleColor(2);+}++// ============================================================================+// Status bar (bottom)+// ============================================================================+void AIChatScreen::render_status_bar(float width) {+ using namespace theme::colors;++ ImGui::PushStyleColor(ImGuiCol_ChildBg, BG_PANEL);+ ImGui::BeginChild("##chat_statusbar", ImVec2(width, 24), ImGuiChildFlags_None);++ ImGui::SetCursorPos(ImVec2(8, 4));++ ImGui::TextColored(TEXT_DIM, "TAB: AI CHAT");+ ImGui::SameLine();+ ImGui::TextColored(TEXT_DIM, "|");+ ImGui::SameLine();++ std::string prov = active_config_.provider;+ std::transform(prov.begin(), prov.end(), prov.begin(), ::toupper);+ ImGui::TextColored(TEXT_DIM, "PROVIDER: %s", prov.empty() ? "NONE" : prov.c_str());+ ImGui::SameLine();+ ImGui::TextColored(TEXT_DIM, "|");+ ImGui::SameLine();+ ImGui::TextColored(TEXT_DIM, "SESSION: %s",+ current_session_uuid_.empty() ? "NONE" : "ACTIVE");++ // Right side+ float right_x = width - 250;+ ImGui::SameLine(right_x);+ ImGui::TextColored(TEXT_DIM, "MESSAGES: %d", (int)messages_.size());+ ImGui::SameLine();+ ImGui::TextColored(TEXT_DIM, "| STATUS: %s",+ is_streaming_ ? "STREAMING..." : "READY");++ ImGui::EndChild();+ ImGui::PopStyleColor();+}++} // namespace fincept::ai_chatdiff --git a/fincept-cpp/src/screens/ai_chat/ai_chat_screen.h b/fincept-cpp/src/screens/ai_chat/ai_chat_screen.hnew file mode 100644index 000000000..5eb5f5bd6--- /dev/null+++ b/fincept-cpp/src/screens/ai_chat/ai_chat_screen.h@@ -0,0 +1,118 @@+#pragma once+// AI Chat Screen — Multi-provider LLM chat with session management+// Layout: [Sessions Sidebar] [Chat Area] [Info Sidebar]+// Mirrors ChatTab.tsx from the desktop app++#include "llm_service.h"+#include "storage/database.h"+#include <imgui.h>+#include <string>+#include <vector>+#include <mutex>+#include <atomic>+#include <future>+#include <chrono>++namespace fincept::ai_chat {++// Quick prompt shortcut+struct QuickPrompt {+ std::string label;+ std::string prompt;+};++class AIChatScreen {+public:+ void render();++private:+ bool initialized_ = false;++ // ── Sessions ──+ std::vector<db::ChatSession> sessions_;+ std::string current_session_uuid_;+ int selected_session_idx_ = -1;++ // Session search+ char search_buf_[128] = {};++ // Session rename+ std::string renaming_session_uuid_;+ char rename_buf_[256] = {};++ // ── Messages ──+ std::vector<db::ChatMessage> messages_;++ // ── Input ──+ char input_buf_[4096] = {};+ bool scroll_to_bottom_ = false;++ // ── Streaming ──+ std::mutex stream_mutex_;+ std::string streaming_content_;+ std::atomic<bool> is_streaming_{false};+ std::future<LLMResponse> streaming_future_;++ // ── LLM Config (cached) ──+ db::LLMConfig active_config_;+ db::LLMGlobalSettings global_settings_;+ std::vector<db::LLMConfig> all_configs_;++ // ── Statistics ──+ int total_sessions_ = 0;+ int total_messages_ = 0;+ int total_tokens_ = 0;++ // ── Quick Prompts ──+ std::vector<QuickPrompt> quick_prompts_;++ // ── Status ──+ std::string status_ = "INITIALIZING...";+ std::string error_;+ double error_time_ = 0;++ // ── Timing ──+ std::chrono::steady_clock::time_point last_config_reload_;++ // ── Init ──+ void init();+ void load_sessions();+ void load_messages(const std::string& session_uuid);+ void load_config();+ void load_statistics();++ // ── Session operations ──+ void create_new_session();+ void delete_session(const std::string& uuid);+ void delete_all_sessions();+ void select_session(int idx);+ void start_rename(const std::string& uuid, const std::string& title);+ void save_rename();+ void cancel_rename();+ void clear_current_chat();++ // ── Message sending ──+ void send_message();+ void check_streaming_result();++ // ── Smart title ──+ static std::string generate_smart_title(const std::string& message);++ // ── Render sections ──+ void render_navbar(float width);+ void render_sessions_panel(float width, float height);+ void render_chat_panel(float width, float height);+ void render_info_panel(float width, float height);+ void render_status_bar(float width);++ // Chat sub-renders+ void render_welcome_screen(float width, float height);+ void render_message(const db::ChatMessage& msg, float width);+ void render_streaming_message(float width);+ void render_input_area(float width);++ // Provider switching+ void switch_provider(const std::string& provider);+};++} // namespace fincept::ai_chatdiff --git a/fincept-cpp/src/screens/ai_chat/llm_service.cpp b/fincept-cpp/src/screens/ai_chat/llm_service.cppnew file mode 100644index 000000000..c5e238a35--- /dev/null+++ b/fincept-cpp/src/screens/ai_chat/llm_service.cpp@@ -0,0 +1,798 @@+#include "llm_service.h"+#include "http/http_client.h"+#include "core/logger.h"+#include "mcp/mcp_service.h"+#include <curl/curl.h>+#include <sstream>+#include <algorithm>+#include <cstring>++namespace fincept::ai_chat {++// ============================================================================+// Singleton+// ============================================================================+LLMService& LLMService::instance() {+ static LLMService svc;+ return svc;+}++void LLMService::reload_config() {+ std::lock_guard<std::mutex> lock(mutex_);+ config_loaded_ = false;+}++void LLMService::ensure_config() {+ if (config_loaded_) return;++ auto configs = db::ops::get_llm_configs();+ config_ = {};+ for (auto& c : configs) {+ if (c.is_active) {+ config_ = c;+ break;+ }+ }+ // Fallback: use first config if none active+ if (config_.provider.empty() && !configs.empty()) {+ config_ = configs[0];+ }++ // Normalize provider name to lowercase for consistent matching+ std::transform(config_.provider.begin(), config_.provider.end(),+ config_.provider.begin(), ::tolower);++ global_settings_ = db::ops::get_llm_global_settings();+ config_loaded_ = true;+}++std::string LLMService::active_provider() const {+ std::lock_guard<std::mutex> lock(mutex_);+ return config_.provider;+}++std::string LLMService::active_model() const {+ std::lock_guard<std::mutex> lock(mutex_);+ return config_.model;+}++bool LLMService::is_configured() const {+ std::lock_guard<std::mutex> lock(mutex_);+ if (config_.provider.empty()) return false;+ if (provider_requires_api_key(config_.provider)) {+ return config_.api_key.has_value() && !config_.api_key->empty();+ }+ return true;+}++// ============================================================================+// Endpoint URLs+// ============================================================================+std::string LLMService::get_endpoint_url() const {+ const auto& p = config_.provider;++ // Custom base_url takes priority (except for providers with fixed endpoints)+ if (config_.base_url && !config_.base_url->empty() && p != "fincept") {+ std::string base = *config_.base_url;+ // Ensure no trailing slash+ if (!base.empty() && base.back() == '/') base.pop_back();++ if (p == "anthropic") {+ return base + "/v1/messages";+ }+ return base + "/v1/chat/completions";+ }++ if (p == "openai") return "https://api.openai.com/v1/chat/completions";+ if (p == "anthropic") return "https://api.anthropic.com/v1/messages";+ if (p == "gemini" || p == "google")+ return "https://generativelanguage.googleapis.com/v1beta/models/" ++ config_.model + ":generateContent";+ if (p == "groq") return "https://api.groq.com/openai/v1/chat/completions";+ if (p == "deepseek") return "https://api.deepseek.com/v1/chat/completions";+ if (p == "openrouter") return "https://openrouter.ai/api/v1/chat/completions";+ if (p == "ollama") return "http://localhost:11434/v1/chat/completions";+ if (p == "fincept") return "https://api.fincept.in/research/llm";++ return "";+}++std::map<std::string, std::string> LLMService::get_headers() const {+ std::map<std::string, std::string> headers;+ const auto& p = config_.provider;+ std::string key = config_.api_key.value_or("");++ if (p == "anthropic") {+ if (!key.empty()) headers["x-api-key"] = key;+ headers["anthropic-version"] = "2023-06-01";+ } else if (p == "gemini" || p == "google") {+ // Gemini uses query param, but we also set header+ if (!key.empty()) headers["x-goog-api-key"] = key;+ } else if (p == "fincept") {+ // Fincept uses X-API-Key from fincept_api_key setting (auto-set on login)+ // Also supports X-Session-Token for session-based auth+ if (key.empty()) {+ // Try to get fincept_api_key from settings+ auto stored_key = db::ops::get_setting("fincept_api_key");+ if (stored_key.has_value() && !stored_key->empty()) {+ key = *stored_key;+ }+ }+ if (!key.empty()) headers["X-API-Key"] = key;+ // Add session token if available+ auto session_token = db::ops::get_setting("session_token");+ if (session_token.has_value() && !session_token->empty()) {+ headers["X-Session-Token"] = *session_token;+ }+ } else {+ // OpenAI-compatible (openai, groq, deepseek, openrouter, ollama)+ if (!key.empty()) headers["Authorization"] = "Bearer " + key;+ }++ return headers;+}++// ============================================================================+// Request builders+// ============================================================================+json LLMService::build_openai_request(const std::string& user_message,+ const std::vector<ConversationMessage>& history,+ bool stream) {+ json messages = json::array();++ // System prompt+ if (!global_settings_.system_prompt.empty()) {+ messages.push_back({{"role", "system"}, {"content", global_settings_.system_prompt}});+ }++ // History+ for (auto& msg : history) {+ messages.push_back({{"role", msg.role}, {"content", msg.content}});+ }++ // Current message+ messages.push_back({{"role", "user"}, {"content", user_message}});++ json req;+ req["model"] = config_.model;+ req["messages"] = messages;+ req["temperature"] = global_settings_.temperature;+ req["max_tokens"] = global_settings_.max_tokens;+ if (stream) req["stream"] = true;++ // Inject MCP tools for function calling (non-streaming only for tool loop)+ if (!stream) {+ auto tools = mcp::MCPService::instance().format_tools_for_openai();+ if (!tools.empty()) {+ req["tools"] = tools;+ }+ }++ return req;+}++json LLMService::build_anthropic_request(const std::string& user_message,+ const std::vector<ConversationMessage>& history,+ bool stream) {+ json messages = json::array();++ // Anthropic doesn't use system in messages array+ for (auto& msg : history) {+ if (msg.role != "system") {+ messages.push_back({{"role", msg.role}, {"content", msg.content}});+ }+ }+ messages.push_back({{"role", "user"}, {"content", user_message}});++ json req;+ req["model"] = config_.model;+ req["messages"] = messages;+ req["max_tokens"] = global_settings_.max_tokens;+ if (global_settings_.temperature != 0.7) {+ req["temperature"] = global_settings_.temperature;+ }+ if (!global_settings_.system_prompt.empty()) {+ req["system"] = global_settings_.system_prompt;+ }+ if (stream) req["stream"] = true;++ return req;+}++json LLMService::build_gemini_request(const std::string& user_message,+ const std::vector<ConversationMessage>& history) {+ json contents = json::array();++ for (auto& msg : history) {+ if (msg.role == "system") continue;+ std::string role = (msg.role == "assistant") ? "model" : "user";+ contents.push_back({+ {"role", role},+ {"parts", json::array({{{"text", msg.content}}})}+ });+ }+ contents.push_back({+ {"role", "user"},+ {"parts", json::array({{{"text", user_message}}})}+ });++ json req;+ req["contents"] = contents;++ json gen_config;+ gen_config["temperature"] = global_settings_.temperature;+ gen_config["maxOutputTokens"] = global_settings_.max_tokens;+ req["generationConfig"] = gen_config;++ if (!global_settings_.system_prompt.empty()) {+ req["systemInstruction"] = {+ {"parts", json::array({{{"text", global_settings_.system_prompt}}})}+ };+ }++ return req;+}++json LLMService::build_fincept_request(const std::string& user_message,+ const std::vector<ConversationMessage>& history,+ bool with_tools) {+ // Fincept uses a simple { prompt, temperature, max_tokens, tools? } format+ // Conversation history is concatenated into the prompt string+ std::string prompt;++ if (!global_settings_.system_prompt.empty()) {+ prompt += "System: " + global_settings_.system_prompt + "\n\n";+ }++ for (auto& msg : history) {+ if (msg.role == "user") {+ prompt += "User: " + msg.content + "\n\n";+ } else if (msg.role == "assistant") {+ prompt += "Assistant: " + msg.content + "\n\n";+ }+ }++ prompt += "User: " + user_message;++ json req;+ req["prompt"] = prompt;+ req["temperature"] = global_settings_.temperature;+ req["max_tokens"] = global_settings_.max_tokens;++ // Add MCP tools if requested+ if (with_tools) {+ auto tools = mcp::MCPService::instance().format_tools_for_openai();+ if (!tools.empty()) {+ // Fincept expects tools in OpenAI function format (just the function part)+ json tool_fns = json::array();+ for (auto& t : tools) {+ if (t.contains("function")) {+ tool_fns.push_back(t["function"]);+ }+ }+ if (!tool_fns.empty()) {+ req["tools"] = tool_fns;+ }+ }+ }++ return req;+}++// ============================================================================+// Non-streaming request+// ============================================================================+LLMResponse LLMService::do_request(const std::string& user_message,+ const std::vector<ConversationMessage>& history) {+ LLMResponse resp;+ const auto& p = config_.provider;++ std::string url = get_endpoint_url();+ if (url.empty()) {+ resp.error = "No endpoint URL for provider: " + p;+ return resp;+ }++ auto headers = get_headers();+ json req_body;++ if (p == "anthropic") {+ req_body = build_anthropic_request(user_message, history, false);+ } else if (p == "gemini" || p == "google") {+ req_body = build_gemini_request(user_message, history);+ // Add API key as query param+ std::string key = config_.api_key.value_or("");+ if (!key.empty()) url += "?key=" + key;+ } else if (p == "fincept") {+ // Build with tools if any are available+ bool has_tools = mcp::MCPService::instance().tool_count() > 0;+ req_body = build_fincept_request(user_message, history, has_tools);+ } else {+ // OpenAI-compatible+ req_body = build_openai_request(user_message, history, false);+ }++ LOG_DEBUG("LLM", "POST %s provider=%s model=%s", url.c_str(), p.c_str(), config_.model.c_str());++ auto http_resp = http::HttpClient::instance().post_json(url, req_body, headers);++ if (!http_resp.success) {+ resp.error = http_resp.error.empty() ?+ ("HTTP " + std::to_string(http_resp.status_code)) : http_resp.error;+ // Try to extract error message from response body+ if (!http_resp.body.empty()) {+ try {+ auto err_json = json::parse(http_resp.body);+ if (err_json.contains("error")) {+ auto& e = err_json["error"];+ if (e.is_string()) resp.error = e.get<std::string>();+ else if (e.contains("message")) resp.error = e["message"].get<std::string>();+ }+ } catch (...) {}+ }+ return resp;+ }++ try {+ auto rj = json::parse(http_resp.body);++ // Extract content based on provider+ if (p == "anthropic") {+ if (rj.contains("content") && rj["content"].is_array() && !rj["content"].empty()) {+ resp.content = rj["content"][0]["text"].get<std::string>();+ }+ } else if (p == "gemini" || p == "google") {+ if (rj.contains("candidates") && !rj["candidates"].empty()) {+ auto& parts = rj["candidates"][0]["content"]["parts"];+ if (!parts.empty()) {+ resp.content = parts[0]["text"].get<std::string>();+ }+ }+ } else if (p == "fincept") {+ // Fincept response: { success, data: { response, tool_calls?, usage? } }+ auto response_data = rj.value("data", rj); // data may be nested or flat++ // Check for tool calls first+ if (response_data.contains("tool_calls") &&+ response_data["tool_calls"].is_array() &&+ !response_data["tool_calls"].empty()) {++ LOG_INFO("LLM", "Fincept returned %zu tool calls", response_data["tool_calls"].size());++ std::string tool_results_text;+ for (auto& tc : response_data["tool_calls"]) {+ std::string fn_name = tc.contains("function")+ ? tc["function"].value("name", "") : tc.value("name", "");+ std::string args_str = tc.contains("function")+ ? tc["function"].value("arguments", "{}") : tc.value("arguments", "{}");++ json fn_args;+ try { fn_args = json::parse(args_str); }+ catch (...) { fn_args = json::object(); }++ LOG_INFO("LLM", "Executing Fincept tool: %s", fn_name.c_str());+ auto tool_result = mcp::MCPService::instance().execute_openai_function(fn_name, fn_args);++ // Extract readable content from tool result+ auto tr_json = tool_result.to_json();+ std::string result_content;+ if (!tool_result.message.empty()) result_content = tool_result.message;+ else if (!tool_result.data.is_null()) result_content = tool_result.data.dump(2).substr(0, 2000);+ else result_content = tr_json.dump(2).substr(0, 2000);++ // Extract just the tool name part (after __)+ auto sep = fn_name.find("__");+ std::string short_name = (sep != std::string::npos) ? fn_name.substr(sep + 2) : fn_name;+ tool_results_text += "\n**Tool: " + short_name + "**\n" + result_content + "\n";+ }++ // Send tool results back to Fincept for final formatting+ if (!tool_results_text.empty()) {+ std::string follow_prompt = "User asked: \"" + user_message ++ "\"\n\nI retrieved this data:\n" + tool_results_text ++ "\n\nPlease provide a clear, concise summary of this data in natural language.";++ json follow_body = {+ {"prompt", follow_prompt},+ {"temperature", global_settings_.temperature},+ {"max_tokens", global_settings_.max_tokens}+ };++ auto fu_resp = http::HttpClient::instance().post_json(url, follow_body, headers);+ if (fu_resp.success) {+ try {+ auto fu_json = json::parse(fu_resp.body);+ auto fu_data = fu_json.value("data", fu_json);+ resp.content = fu_data.value("response",+ fu_data.value("content",+ fu_data.value("answer",+ fu_data.value("text", std::string("")))));+ } catch (...) {}+ }+ }+ } else {+ // No tool calls — extract text content+ resp.content = response_data.value("response",+ response_data.value("content",+ response_data.value("answer",+ response_data.value("text",+ response_data.value("result", std::string(""))))));++ // Also check nested ai_response (legacy format)+ if (resp.content.empty() && response_data.contains("ai_response")) {+ auto& ai = response_data["ai_response"];+ if (ai.contains("content")) resp.content = ai["content"].get<std::string>();+ else if (ai.is_string()) resp.content = ai.get<std::string>();+ }+ }+ } else {+ // OpenAI-compatible — check for tool calls+ if (rj.contains("choices") && !rj["choices"].empty()) {+ auto& choice = rj["choices"][0];+ auto& msg = choice["message"];++ // Check if LLM wants to call tools+ if (msg.contains("tool_calls") && msg["tool_calls"].is_array() && !msg["tool_calls"].empty()) {+ LOG_INFO("LLM", "LLM requested %zu tool calls", msg["tool_calls"].size());++ // Build messages array for the tool call loop+ json loop_messages = json::array();++ // Add system prompt+ if (!global_settings_.system_prompt.empty()) {+ loop_messages.push_back({{"role", "system"}, {"content", global_settings_.system_prompt}});+ }+ // Add history+ for (auto& h : history) {+ loop_messages.push_back({{"role", h.role}, {"content", h.content}});+ }+ // Add current user message+ loop_messages.push_back({{"role", "user"}, {"content", user_message}});+ // Add assistant message with tool_calls+ loop_messages.push_back(msg);++ // Execute each tool call and add results+ for (auto& tc : msg["tool_calls"]) {+ std::string call_id = tc.value("id", "");+ std::string fn_name = tc["function"].value("name", "");+ json fn_args;+ try {+ fn_args = json::parse(tc["function"].value("arguments", "{}"));+ } catch (...) {+ fn_args = json::object();+ }++ LOG_INFO("LLM", "Executing tool: %s", fn_name.c_str());++ auto tool_result = mcp::MCPService::instance().execute_openai_function(fn_name, fn_args);+ std::string result_str = tool_result.to_json().dump();++ loop_messages.push_back({+ {"role", "tool"},+ {"tool_call_id", call_id},+ {"content", result_str}+ });+ }++ // Send follow-up request with tool results (max 5 rounds)+ static constexpr int MAX_TOOL_ROUNDS = 5;+ for (int round = 0; round < MAX_TOOL_ROUNDS; ++round) {+ json follow_up;+ follow_up["model"] = config_.model;+ follow_up["messages"] = loop_messages;+ follow_up["temperature"] = global_settings_.temperature;+ follow_up["max_tokens"] = global_settings_.max_tokens;++ auto tools_json = mcp::MCPService::instance().format_tools_for_openai();+ if (!tools_json.empty()) follow_up["tools"] = tools_json;++ auto fu_resp = http::HttpClient::instance().post_json(url, follow_up, headers);+ if (!fu_resp.success) {+ resp.error = "Tool follow-up request failed";+ return resp;+ }++ auto fu_json = json::parse(fu_resp.body);+ if (fu_json.contains("choices") && !fu_json["choices"].empty()) {+ auto& fu_choice = fu_json["choices"][0];+ auto& fu_msg = fu_choice["message"];++ if (fu_msg.contains("tool_calls") && fu_msg["tool_calls"].is_array() && !fu_msg["tool_calls"].empty()) {+ // Another round of tool calls+ loop_messages.push_back(fu_msg);+ for (auto& tc2 : fu_msg["tool_calls"]) {+ std::string cid = tc2.value("id", "");+ std::string fname = tc2["function"].value("name", "");+ json fargs;+ try { fargs = json::parse(tc2["function"].value("arguments", "{}")); }+ catch (...) { fargs = json::object(); }++ auto tr = mcp::MCPService::instance().execute_openai_function(fname, fargs);+ loop_messages.push_back({+ {"role", "tool"},+ {"tool_call_id", cid},+ {"content", tr.to_json().dump()}+ });+ }+ continue; // Next round+ }++ // Final text response+ if (fu_msg.contains("content") && fu_msg["content"].is_string()) {+ resp.content = fu_msg["content"].get<std::string>();+ }+ parse_usage(resp, fu_json, p);+ }+ break; // Done — got text response+ }+ } else {+ // Normal text response (no tool calls)+ if (msg.contains("content") && !msg["content"].is_null()) {+ resp.content = msg["content"].get<std::string>();+ }+ }+ }+ }++ parse_usage(resp, rj, p);+ resp.success = true;++ } catch (const std::exception& ex) {+ resp.error = std::string("Parse error: ") + ex.what();+ }++ return resp;+}++// ============================================================================+// Streaming via libcurl (SSE)+// ============================================================================+struct StreamContext {+ StreamCallback callback;+ std::string provider;+ std::string buffer; // partial line buffer+ std::string accumulated; // full accumulated content+ int tokens = 0;+};++static size_t stream_write_callback(char* ptr, size_t size, size_t nmemb, void* userdata) {+ auto* ctx = static_cast<StreamContext*>(userdata);+ size_t total = size * nmemb;+ ctx->buffer.append(ptr, total);++ // Process complete lines+ size_t pos;+ while ((pos = ctx->buffer.find('\n')) != std::string::npos) {+ std::string line = ctx->buffer.substr(0, pos);+ ctx->buffer.erase(0, pos + 1);++ // Remove \r+ if (!line.empty() && line.back() == '\r') line.pop_back();++ // Skip empty lines+ if (line.empty()) continue;++ // SSE format: "data: {...}"+ if (line.rfind("data: ", 0) != 0) continue;+ std::string data = line.substr(6);++ if (data == "[DONE]") {+ ctx->callback("", true);+ continue;+ }++ std::string chunk = LLMService::parse_sse_chunk(data, ctx->provider);+ if (!chunk.empty()) {+ ctx->accumulated += chunk;+ ctx->tokens++;+ ctx->callback(chunk, false);+ }+ }++ return total;+}++LLMResponse LLMService::do_streaming_request(const std::string& user_message,+ const std::vector<ConversationMessage>& history,+ StreamCallback on_chunk) {+ LLMResponse resp;+ const auto& p = config_.provider;++ // Gemini and Fincept don't support SSE streaming, fall back to non-streaming+ if (p == "gemini" || p == "google" || p == "fincept") {+ resp = do_request(user_message, history);+ if (resp.success && !resp.content.empty()) {+ on_chunk(resp.content, false);+ }+ on_chunk("", true);+ return resp;+ }++ std::string url = get_endpoint_url();+ if (url.empty()) {+ resp.error = "No endpoint URL for provider: " + p;+ on_chunk("", true);+ return resp;+ }++ auto headers = get_headers();+ json req_body;++ if (p == "anthropic") {+ req_body = build_anthropic_request(user_message, history, true);+ } else {+ req_body = build_openai_request(user_message, history, true);+ }++ std::string body_str = req_body.dump();++ // Use raw libcurl for streaming+ CURL* curl = curl_easy_init();+ if (!curl) {+ resp.error = "Failed to initialize CURL";+ on_chunk("", true);+ return resp;+ }++ StreamContext ctx;+ ctx.callback = on_chunk;+ ctx.provider = p;++ curl_easy_setopt(curl, CURLOPT_URL, url.c_str());+ curl_easy_setopt(curl, CURLOPT_POST, 1L);+ curl_easy_setopt(curl, CURLOPT_POSTFIELDS, body_str.c_str());+ curl_easy_setopt(curl, CURLOPT_POSTFIELDSIZE, (long)body_str.size());+ curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, stream_write_callback);+ curl_easy_setopt(curl, CURLOPT_WRITEDATA, &ctx);+ curl_easy_setopt(curl, CURLOPT_TIMEOUT, 120L);+ curl_easy_setopt(curl, CURLOPT_CONNECTTIMEOUT, 15L);+ curl_easy_setopt(curl, CURLOPT_SSL_VERIFYPEER, 1L);+ curl_easy_setopt(curl, CURLOPT_SSL_VERIFYHOST, 2L);+ curl_easy_setopt(curl, CURLOPT_FOLLOWLOCATION, 1L);+ curl_easy_setopt(curl, CURLOPT_USERAGENT,+ "Mozilla/5.0 FinceptTerminal/4.0.0");++ // Build header list+ 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: text/event-stream");+ for (const auto& [key, value] : headers) {+ std::string h = key + ": " + value;+ header_list = curl_slist_append(header_list, h.c_str());+ }+ curl_easy_setopt(curl, CURLOPT_HTTPHEADER, header_list);++ LOG_DEBUG("LLM", "STREAM POST %s provider=%s", url.c_str(), p.c_str());++ CURLcode res = curl_easy_perform(curl);++ if (res != CURLE_OK) {+ resp.error = curl_easy_strerror(res);+ LOG_ERROR("LLM", "Stream request failed: %s", resp.error.c_str());+ } else {+ long http_code = 0;+ curl_easy_getinfo(curl, CURLINFO_RESPONSE_CODE, &http_code);+ if (http_code >= 200 && http_code < 300) {+ resp.content = ctx.accumulated;+ resp.completion_tokens = ctx.tokens;+ resp.success = true;+ } else {+ resp.error = "HTTP " + std::to_string(http_code);+ // If we got error text instead of stream+ if (!ctx.accumulated.empty()) {+ try {+ auto err = json::parse(ctx.buffer.empty() ? ctx.accumulated : ctx.buffer);+ if (err.contains("error")) {+ auto& e = err["error"];+ if (e.is_string()) resp.error = e.get<std::string>();+ else if (e.contains("message")) resp.error = e["message"].get<std::string>();+ }+ } catch (...) {}+ }+ }+ }++ // Ensure done callback fires+ on_chunk("", true);++ curl_slist_free_all(header_list);+ curl_easy_cleanup(curl);++ return resp;+}++// ============================================================================+// SSE chunk parsing+// ============================================================================+std::string LLMService::parse_sse_chunk(const std::string& data, const std::string& provider) {+ try {+ auto j = json::parse(data);++ if (provider == "anthropic") {+ // Anthropic: {"type":"content_block_delta","delta":{"type":"text_delta","text":"..."}}+ if (j.value("type", "") == "content_block_delta") {+ if (j.contains("delta") && j["delta"].contains("text")) {+ return j["delta"]["text"].get<std::string>();+ }+ }+ return "";+ }++ // OpenAI-compatible: {"choices":[{"delta":{"content":"..."}}]}+ if (j.contains("choices") && !j["choices"].empty()) {+ auto& delta = j["choices"][0]["delta"];+ if (delta.contains("content") && !delta["content"].is_null()) {+ return delta["content"].get<std::string>();+ }+ }+ } catch (...) {+ // Malformed chunk, skip+ }+ return "";+}++void LLMService::parse_usage(LLMResponse& resp, const json& rj, const std::string& provider) {+ try {+ if (provider == "anthropic") {+ if (rj.contains("usage")) {+ resp.prompt_tokens = rj["usage"].value("input_tokens", 0);+ resp.completion_tokens = rj["usage"].value("output_tokens", 0);+ resp.total_tokens = resp.prompt_tokens + resp.completion_tokens;+ }+ } else if (rj.contains("usage")) {+ resp.prompt_tokens = rj["usage"].value("prompt_tokens", 0);+ resp.completion_tokens = rj["usage"].value("completion_tokens", 0);+ resp.total_tokens = rj["usage"].value("total_tokens", 0);+ }+ } catch (...) {}+}++// ============================================================================+// Public API+// ============================================================================+LLMResponse LLMService::chat(const std::string& user_message,+ const std::vector<ConversationMessage>& history) {+ std::lock_guard<std::mutex> lock(mutex_);+ ensure_config();++ if (config_.provider.empty()) {+ return LLMResponse{.error = "No LLM provider configured"};+ }++ return do_request(user_message, history);+}++std::future<LLMResponse> LLMService::chat_streaming(+ const std::string& user_message,+ const std::vector<ConversationMessage>& history,+ StreamCallback on_chunk) {++ // Copy config under lock+ db::LLMConfig cfg_copy;+ db::LLMGlobalSettings gs_copy;+ {+ std::lock_guard<std::mutex> lock(mutex_);+ ensure_config();+ cfg_copy = config_;+ gs_copy = global_settings_;+ }++ return std::async(std::launch::async, [this, user_message, history, on_chunk,+ cfg_copy, gs_copy]() -> LLMResponse {+ // Use copied config (don't hold lock during network call)+ {+ std::lock_guard<std::mutex> lock(mutex_);+ config_ = cfg_copy;+ global_settings_ = gs_copy;+ }++ if (config_.provider.empty()) {+ on_chunk("", true);+ return LLMResponse{.error = "No LLM provider configured"};+ }++ return do_streaming_request(user_message, history, on_chunk);+ });+}++} // namespace fincept::ai_chatdiff --git a/fincept-cpp/src/screens/ai_chat/llm_service.h b/fincept-cpp/src/screens/ai_chat/llm_service.hnew file mode 100644index 000000000..cfa8984f7--- /dev/null+++ b/fincept-cpp/src/screens/ai_chat/llm_service.h@@ -0,0 +1,126 @@+#pragma once+// LLM Service — Multi-provider LLM API client+// Supports OpenAI-compatible APIs (OpenAI, Groq, DeepSeek, OpenRouter, Ollama),+// Anthropic, Google Gemini, and Fincept's own endpoint.+// Streaming via chunked transfer + SSE parsing.++#include <string>+#include <vector>+#include <functional>+#include <future>+#include <mutex>+#include <optional>+#include <nlohmann/json.hpp>+#include "storage/database.h"++namespace fincept::ai_chat {++using json = nlohmann::json;++// Providers that support streaming+inline bool provider_supports_streaming(const std::string& provider) {+ return provider == "openai" || provider == "anthropic" ||+ provider == "gemini" || provider == "google" ||+ provider == "groq" || provider == "deepseek" ||+ provider == "openrouter" || provider == "ollama" ||+ provider == "fincept";+}++// Providers that don't require API key+inline bool provider_requires_api_key(const std::string& provider) {+ return provider != "ollama" && provider != "fincept";+}++// Conversation message (role + content)+struct ConversationMessage {+ std::string role; // "system", "user", "assistant"+ std::string content;+};++// LLM response+struct LLMResponse {+ std::string content;+ std::string error;+ int prompt_tokens = 0;+ int completion_tokens = 0;+ int total_tokens = 0;+ bool success = false;+};++// Streaming callback: (chunk_text, is_done)+using StreamCallback = std::function<void(const std::string&, bool)>;++class LLMService {+public:+ static LLMService& instance();++ // Send a message with conversation history, returns full response+ LLMResponse chat(const std::string& user_message,+ const std::vector<ConversationMessage>& history);++ // Send a message with streaming callback (called on background thread)+ // Returns future that resolves to final response+ std::future<LLMResponse> chat_streaming(+ const std::string& user_message,+ const std::vector<ConversationMessage>& history,+ StreamCallback on_chunk);++ // Reload config from database+ void reload_config();++ // Get active config info+ std::string active_provider() const;+ std::string active_model() const;+ bool is_configured() const;++ LLMService(const LLMService&) = delete;+ LLMService& operator=(const LLMService&) = delete;++private:+ LLMService() = default;++ mutable std::mutex mutex_;+ db::LLMConfig config_;+ db::LLMGlobalSettings global_settings_;+ bool config_loaded_ = false;++ void ensure_config();++ // Provider-specific request builders+ json build_openai_request(const std::string& user_message,+ const std::vector<ConversationMessage>& history,+ bool stream);+ json build_anthropic_request(const std::string& user_message,+ const std::vector<ConversationMessage>& history,+ bool stream);+ json build_gemini_request(const std::string& user_message,+ const std::vector<ConversationMessage>& history);+ json build_fincept_request(const std::string& user_message,+ const std::vector<ConversationMessage>& history,+ bool with_tools);++ // Get the API endpoint URL for the active provider+ std::string get_endpoint_url() const;++ // Get auth headers for the active provider+ std::map<std::string, std::string> get_headers() const;++ // Non-streaming request+ LLMResponse do_request(const std::string& user_message,+ const std::vector<ConversationMessage>& history);++ // Streaming request (blocks until done, calls callback)+ LLMResponse do_streaming_request(const std::string& user_message,+ const std::vector<ConversationMessage>& history,+ StreamCallback on_chunk);++public:+ // Parse SSE stream data (public for stream_write_callback access)+ static std::string parse_sse_chunk(const std::string& line, const std::string& provider);++private:+ // Parse final response for token usage+ static void parse_usage(LLMResponse& resp, const json& response_json, const std::string& provider);+};++} // namespace fincept::ai_chatdiff --git a/fincept-cpp/src/screens/ai_quant_lab/ai_quant_lab_api.cpp b/fincept-cpp/src/screens/ai_quant_lab/ai_quant_lab_api.cppnew file mode 100644index 000000000..79922388e--- /dev/null+++ b/fincept-cpp/src/screens/ai_quant_lab/ai_quant_lab_api.cpp@@ -0,0 +1,433 @@+#include "ai_quant_lab_api.h"+#include "python/python_runner.h"+#include "http/http_client.h"+#include "storage/cache_service.h"+#include "core/logger.h"+#include <thread>++namespace fincept::ai_quant_lab {++static constexpr const char* API_BASE = "https://api.fincept.in";++QuantLabApi& QuantLabApi::instance() {+ static QuantLabApi inst;+ return inst;+}++// ============================================================================+// Python execution (mirrors BacktestData pattern)+// ============================================================================+std::future<ApiResult> QuantLabApi::run_python(const std::string& script,+ const std::string& command,+ const json& args) {+ return std::async(std::launch::async, [script, command, args]() -> ApiResult {+ ApiResult result;+ std::string args_str = args.dump();++ auto py = python::execute(script, {command, args_str});+ if (py.success) {+ std::string json_str = python::extract_json(py.output);+ if (json_str.empty()) json_str = py.output;+ try {+ auto parsed = json::parse(json_str);+ if (parsed.contains("success") && parsed["success"].is_boolean()) {+ result.success = parsed["success"].get<bool>();+ result.data = parsed.value("data", parsed);+ if (!result.success)+ result.error = parsed.value("error", "Unknown error");+ } else {+ result.success = true;+ result.data = parsed;+ }+ } catch (const json::exception& e) {+ result.error = std::string("JSON parse error: ") + e.what();+ }+ } else {+ result.error = py.error.empty()+ ? "Script failed (exit " + std::to_string(py.exit_code) + ")"+ : py.error;+ }+ return result;+ });+}++// ============================================================================+// HTTP calls+// ============================================================================+std::future<ApiResult> QuantLabApi::http_post(const std::string& path, const json& body) {+ return std::async(std::launch::async, [path, body]() -> ApiResult {+ ApiResult result;+ std::string url = std::string(API_BASE) + path;++ auto resp = http::HttpClient::instance().post_json(url, body);+ if (resp.success && resp.status_code >= 200 && resp.status_code < 300) {+ result.success = true;+ result.data = resp.json_body();+ } else {+ result.error = resp.error.empty()+ ? "HTTP " + std::to_string(resp.status_code) : resp.error;+ auto j = resp.json_body();+ if (j.contains("error"))+ result.error = j["error"].get<std::string>();+ }+ return result;+ });+}++std::future<ApiResult> QuantLabApi::http_get(const std::string& path,+ const std::map<std::string, std::string>& params) {+ return std::async(std::launch::async, [path, params]() -> ApiResult {+ ApiResult result;+ std::string url = std::string(API_BASE) + path;+ if (!params.empty()) {+ url += "?";+ bool first = true;+ for (auto& [k, v] : params) {+ if (!first) url += "&";+ url += k + "=" + v;+ first = false;+ }+ }++ auto resp = http::HttpClient::instance().get(url);+ if (resp.success && resp.status_code >= 200 && resp.status_code < 300) {+ result.success = true;+ result.data = resp.json_body();+ } else {+ result.error = resp.error.empty()+ ? "HTTP " + std::to_string(resp.status_code) : resp.error;+ }+ return result;+ });+}++// ============================================================================+// Qlib Service — ai_quant_lab/qlib_service.py+// ============================================================================+std::future<ApiResult> QuantLabApi::qlib_list_models() {+ return run_python("ai_quant_lab/qlib_service.py", "list_models", json::object());+}++std::future<ApiResult> QuantLabApi::qlib_train_model(const json& config) {+ return run_python("ai_quant_lab/qlib_service.py", "train_model", config);+}++std::future<ApiResult> QuantLabApi::qlib_run_backtest(const json& config) {+ return run_python("ai_quant_lab/qlib_service.py", "run_backtest", config);+}++std::future<ApiResult> QuantLabApi::qlib_get_live_predictions(const json& config) {+ return run_python("ai_quant_lab/qlib_service.py", "predict", config);+}++// ── Online Learning — ai_quant_lab/qlib_online_learning.py ──+std::future<ApiResult> QuantLabApi::qlib_online_create(const json& config) {+ return run_python("ai_quant_lab/qlib_online_learning.py", "create_model", config);+}++std::future<ApiResult> QuantLabApi::qlib_online_train(const json& config) {+ return run_python("ai_quant_lab/qlib_online_learning.py", "train", config);+}++std::future<ApiResult> QuantLabApi::qlib_online_performance(const std::string& model_id) {+ // Python script expects raw model_id string as sys.argv[2], not JSON+ return std::async(std::launch::async, [model_id]() -> ApiResult {+ ApiResult result;+ auto py = python::execute("ai_quant_lab/qlib_online_learning.py",+ {"performance", model_id});+ if (py.success) {+ std::string json_str = python::extract_json(py.output);+ if (json_str.empty()) json_str = py.output;+ try {+ auto parsed = json::parse(json_str);+ if (parsed.contains("success") && parsed["success"].is_boolean()) {+ result.success = parsed["success"].get<bool>();+ result.data = parsed.value("data", parsed);+ if (!result.success)+ result.error = parsed.value("error", "Unknown error");+ } else {+ result.success = true;+ result.data = parsed;+ }+ } catch (const json::exception& e) {+ result.error = std::string("JSON parse error: ") + e.what();+ }+ } else {+ result.error = py.error.empty()+ ? "Script failed (exit " + std::to_string(py.exit_code) + ")"+ : py.error;+ }+ return result;+ });+}++std::future<ApiResult> QuantLabApi::qlib_online_handle_drift(const json& config) {+ return run_python("ai_quant_lab/qlib_online_learning.py", "handle_drift", config);+}++std::future<ApiResult> QuantLabApi::qlib_online_setup_rolling(const json& config) {+ return run_python("ai_quant_lab/qlib_online_learning.py", "setup_rolling", config);+}++// ── Meta Learning — ai_quant_lab/qlib_meta_learning.py ──+std::future<ApiResult> QuantLabApi::qlib_meta_list_models() {+ return run_python("ai_quant_lab/qlib_meta_learning.py", "list_models", json::object());+}++std::future<ApiResult> QuantLabApi::qlib_meta_run_selection(const json& config) {+ return run_python("ai_quant_lab/qlib_meta_learning.py", "run_selection", config);+}++// ── Rolling Retraining — ai_quant_lab/qlib_rolling_retraining.py ──+std::future<ApiResult> QuantLabApi::qlib_rolling_list_schedules() {+ return run_python("ai_quant_lab/qlib_rolling_retraining.py", "list", json::object());+}++std::future<ApiResult> QuantLabApi::qlib_rolling_create_schedule(const json& config) {+ // Python script expects raw model_id string as sys.argv[2]+ return std::async(std::launch::async, [config]() -> ApiResult {+ ApiResult result;+ std::string model_id = config.value("model_name", "model_1");+ auto py = python::execute("ai_quant_lab/qlib_rolling_retraining.py",+ {"create", model_id});+ if (py.success) {+ std::string json_str = python::extract_json(py.output);+ if (json_str.empty()) json_str = py.output;+ try {+ auto parsed = json::parse(json_str);+ result.success = parsed.value("success", true);+ result.data = parsed;+ if (!result.success)+ result.error = parsed.value("error", "Unknown error");+ } catch (const json::exception& e) {+ result.error = std::string("JSON parse error: ") + e.what();+ }+ } else {+ result.error = py.error.empty()+ ? "Script failed (exit " + std::to_string(py.exit_code) + ")"+ : py.error;+ }+ return result;+ });+}++std::future<ApiResult> QuantLabApi::qlib_rolling_retrain(const std::string& schedule_id) {+ // Python script expects raw model_id string as sys.argv[2]+ return std::async(std::launch::async, [schedule_id]() -> ApiResult {+ ApiResult result;+ auto py = python::execute("ai_quant_lab/qlib_rolling_retraining.py",+ {"retrain", schedule_id});+ if (py.success) {+ std::string json_str = python::extract_json(py.output);+ if (json_str.empty()) json_str = py.output;+ try {+ auto parsed = json::parse(json_str);+ result.success = parsed.value("success", true);+ result.data = parsed;+ if (!result.success)+ result.error = parsed.value("error", "Unknown error");+ } catch (const json::exception& e) {+ result.error = std::string("JSON parse error: ") + e.what();+ }+ } else {+ result.error = py.error.empty()+ ? "Script failed (exit " + std::to_string(py.exit_code) + ")"+ : py.error;+ }+ return result;+ });+}++// ── Advanced Models — ai_quant_lab/qlib_advanced_models.py ──+std::future<ApiResult> QuantLabApi::qlib_advanced_list_models() {+ return run_python("ai_quant_lab/qlib_advanced_models.py", "list_models", json::object());+}++std::future<ApiResult> QuantLabApi::qlib_advanced_train(const json& config) {+ return run_python("ai_quant_lab/qlib_advanced_models.py", "train", config);+}++// ============================================================================+// RD-Agent (Factor Discovery) — ai_quant_lab/rd_agent_service.py+// ============================================================================+std::future<ApiResult> QuantLabApi::rdagent_start_mining(const json& config) {+ return run_python("ai_quant_lab/rd_agent_service.py", "start_factor_mining", config);+}++std::future<ApiResult> QuantLabApi::rdagent_get_status(const std::string& task_id) {+ // Python script expects raw task_id string as sys.argv[2], not JSON+ return std::async(std::launch::async, [task_id]() -> ApiResult {+ ApiResult result;+ auto py = python::execute("ai_quant_lab/rd_agent_service.py",+ {"get_factor_mining_status", task_id});+ if (py.success) {+ std::string json_str = python::extract_json(py.output);+ if (json_str.empty()) json_str = py.output;+ try {+ auto parsed = json::parse(json_str);+ if (parsed.contains("success") && parsed["success"].is_boolean()) {+ result.success = parsed["success"].get<bool>();+ result.data = parsed.value("data", parsed);+ if (!result.success)+ result.error = parsed.value("error", "Unknown error");+ } else {+ result.success = true;+ result.data = parsed;+ }+ } catch (const json::exception& e) {+ result.error = std::string("JSON parse error: ") + e.what();+ }+ } else {+ result.error = py.error.empty()+ ? "Script failed (exit " + std::to_string(py.exit_code) + ")"+ : py.error;+ }+ return result;+ });+}++std::future<ApiResult> QuantLabApi::rdagent_get_factors(const std::string& task_id) {+ // Python script expects raw task_id string as sys.argv[2], not JSON+ return std::async(std::launch::async, [task_id]() -> ApiResult {+ ApiResult result;+ auto py = python::execute("ai_quant_lab/rd_agent_service.py",+ {"get_discovered_factors", task_id});+ if (py.success) {+ std::string json_str = python::extract_json(py.output);+ if (json_str.empty()) json_str = py.output;+ try {+ auto parsed = json::parse(json_str);+ if (parsed.contains("success") && parsed["success"].is_boolean()) {+ result.success = parsed["success"].get<bool>();+ result.data = parsed.value("data", parsed);+ if (!result.success)+ result.error = parsed.value("error", "Unknown error");+ } else {+ result.success = true;+ result.data = parsed;+ }+ } catch (const json::exception& e) {+ result.error = std::string("JSON parse error: ") + e.what();+ }+ } else {+ result.error = py.error.empty()+ ? "Script failed (exit " + std::to_string(py.exit_code) + ")"+ : py.error;+ }+ return result;+ });+}++// ============================================================================+// Deep Agent — agents/deepagents/cli.py+// ============================================================================+std::future<ApiResult> QuantLabApi::deep_agent_create_plan(const json& config) {+ return run_python("agents/deepagents/cli.py", "create_plan", config);+}++std::future<ApiResult> QuantLabApi::deep_agent_execute_step(const json& config) {+ return run_python("agents/deepagents/cli.py", "execute_step", config);+}++std::future<ApiResult> QuantLabApi::deep_agent_synthesize(const json& config) {+ return run_python("agents/deepagents/cli.py", "synthesize_results", config);+}++// ============================================================================+// GluonTS — Analytics/gluonts_wrapper/gluonts_service.py+// ============================================================================+std::future<ApiResult> QuantLabApi::gluonts_forecast(const json& config) {+ // Python dispatch uses "forecast_<model>" as the operation name+ std::string model = config.value("model", "deepar");+ std::string command = "forecast_" + model;+ return run_python("Analytics/gluonts_wrapper/gluonts_service.py", command, config);+}++std::future<ApiResult> QuantLabApi::gluonts_evaluate(const json& config) {+ return run_python("Analytics/gluonts_wrapper/gluonts_service.py", "evaluate", config);+}++// ============================================================================+// Statsmodels — Analytics/statsmodels_cli.py+// ============================================================================+std::future<ApiResult> QuantLabApi::statsmodels_analyze(const json& config) {+ // Map UI analysis labels to Python command names+ std::string analysis = config.value("analysis_type", "descriptive");+ std::string command = "descriptive";+ if (analysis == "ARIMA") command = "arima";+ else if (analysis == "SARIMAX") command = "sarimax";+ else if (analysis == "Exp Smoothing") command = "exponential_smoothing";+ else if (analysis == "STL Decompose") command = "stl_decompose";+ else if (analysis == "ADF Test") command = "adf_test";+ else if (analysis == "KPSS Test") command = "kpss_test";+ else if (analysis == "ACF") command = "acf";+ else if (analysis == "PACF") command = "pacf";+ return run_python("Analytics/statsmodels_cli.py", command, config);+}++// ============================================================================+// GS Quant — Analytics/gs_quant_wrapper/gs_quant_service.py+// ============================================================================+std::future<ApiResult> QuantLabApi::gs_quant_analyze(const json& config) {+ return run_python("Analytics/gs_quant_wrapper/gs_quant_service.py", "analyze", config);+}++// ============================================================================+// VisionQuant (Pattern Intelligence) — vision_quant/*.py+// ============================================================================+std::future<ApiResult> QuantLabApi::visionquant_search(const json& config) {+ return run_python("vision_quant/engine.py", "search", config);+}++std::future<ApiResult> QuantLabApi::visionquant_score(const json& config) {+ return run_python("vision_quant/scorer.py", "score", config);+}++std::future<ApiResult> QuantLabApi::visionquant_backtest(const json& config) {+ return run_python("vision_quant/backtester.py", "backtest", config);+}++// ============================================================================+// Functime — Analytics/functime_wrapper/functime_service.py+// ============================================================================+std::future<ApiResult> QuantLabApi::functime_forecast(const json& config) {+ return run_python("Analytics/functime_wrapper/functime_service.py", "forecast", config);+}++// ============================================================================+// Fortitudo — Analytics/fortitudo_tech_wrapper/fortitudo_service.py+// ============================================================================+std::future<ApiResult> QuantLabApi::fortitudo_analyze(const json& config) {+ // Map UI mode labels to Python handler names+ std::string mode = config.value("mode", "full_analysis");+ std::string command = "full_analysis";+ if (mode == "Entropy Pooling") command = "entropy_pooling";+ else if (mode == "Optimization") command = "optimize_mean_variance";+ else if (mode == "Option Pricing") command = "option_pricing";+ else if (mode == "Portfolio Risk") command = "portfolio_metrics";+ return run_python("Analytics/fortitudo_tech_wrapper/fortitudo_service.py", command, config);+}++// ============================================================================+// CFA Quant — quant/cfa_quant_service.py (uses quant analytics)+// ============================================================================+std::future<ApiResult> QuantLabApi::cfa_quant_analyze(const json& config) {+ return run_python("Analytics/quant_analytics_cli.py", "analyze", config);+}++// ============================================================================+// RL Trading — ai_quant_lab/qlib_rl.py+// ============================================================================+std::future<ApiResult> QuantLabApi::rl_create_env(const json& config) {+ return run_python("ai_quant_lab/qlib_rl.py", "create_env", config);+}++std::future<ApiResult> QuantLabApi::rl_train_agent(const json& config) {+ return run_python("ai_quant_lab/qlib_rl.py", "train", config);+}++std::future<ApiResult> QuantLabApi::rl_evaluate(const json& config) {+ return run_python("ai_quant_lab/qlib_rl.py", "evaluate", config);+}++} // namespace fincept::ai_quant_labdiff --git a/fincept-cpp/src/screens/ai_quant_lab/ai_quant_lab_api.h b/fincept-cpp/src/screens/ai_quant_lab/ai_quant_lab_api.hnew file mode 100644index 000000000..b4f66e973--- /dev/null+++ b/fincept-cpp/src/screens/ai_quant_lab/ai_quant_lab_api.h@@ -0,0 +1,95 @@+#pragma once+// AI Quant Lab API — HTTP + Python bridge for all 18 modules+// Qlib, RD-Agent, Deep Agent, GluonTS, Statsmodels, VisionQuant, GS Quant++#include <string>+#include <vector>+#include <future>+#include <nlohmann/json.hpp>++namespace fincept::ai_quant_lab {++using json = nlohmann::json;++struct ApiResult {+ bool success = false;+ json data;+ std::string error;+};++class QuantLabApi {+public:+ static QuantLabApi& instance();++ // ── Qlib Service (Model Library, Backtesting, Live Signals, Online, Meta, Rolling, Advanced) ──+ std::future<ApiResult> qlib_list_models();+ std::future<ApiResult> qlib_train_model(const json& config);+ std::future<ApiResult> qlib_run_backtest(const json& config);+ std::future<ApiResult> qlib_get_live_predictions(const json& config);+ std::future<ApiResult> qlib_online_create(const json& config);+ std::future<ApiResult> qlib_online_train(const json& config);+ std::future<ApiResult> qlib_online_performance(const std::string& model_id);+ std::future<ApiResult> qlib_online_handle_drift(const json& config);+ std::future<ApiResult> qlib_online_setup_rolling(const json& config);+ std::future<ApiResult> qlib_meta_list_models();+ std::future<ApiResult> qlib_meta_run_selection(const json& config);+ std::future<ApiResult> qlib_rolling_list_schedules();+ std::future<ApiResult> qlib_rolling_create_schedule(const json& config);+ std::future<ApiResult> qlib_rolling_retrain(const std::string& schedule_id);+ std::future<ApiResult> qlib_advanced_list_models();+ std::future<ApiResult> qlib_advanced_train(const json& config);++ // ── RD-Agent Service (Factor Discovery) ──+ std::future<ApiResult> rdagent_start_mining(const json& config);+ std::future<ApiResult> rdagent_get_status(const std::string& task_id);+ std::future<ApiResult> rdagent_get_factors(const std::string& task_id);++ // ── Deep Agent Service ──+ std::future<ApiResult> deep_agent_create_plan(const json& config);+ std::future<ApiResult> deep_agent_execute_step(const json& config);+ std::future<ApiResult> deep_agent_synthesize(const json& config);++ // ── GluonTS Service ──+ std::future<ApiResult> gluonts_forecast(const json& config);+ std::future<ApiResult> gluonts_evaluate(const json& config);++ // ── Statsmodels Service ──+ std::future<ApiResult> statsmodels_analyze(const json& config);++ // ── GS Quant Service ──+ std::future<ApiResult> gs_quant_analyze(const json& config);++ // ── VisionQuant (Pattern Intelligence) ──+ std::future<ApiResult> visionquant_search(const json& config);+ std::future<ApiResult> visionquant_score(const json& config);+ std::future<ApiResult> visionquant_backtest(const json& config);++ // ── Functime Service ──+ std::future<ApiResult> functime_forecast(const json& config);++ // ── Fortitudo Service ──+ std::future<ApiResult> fortitudo_analyze(const json& config);++ // ── CFA Quant Service ──+ std::future<ApiResult> cfa_quant_analyze(const json& config);++ // ── RL Trading ──+ std::future<ApiResult> rl_create_env(const json& config);+ std::future<ApiResult> rl_train_agent(const json& config);+ std::future<ApiResult> rl_evaluate(const json& config);++private:+ QuantLabApi() = default;++ // Execute via Python script (same as backtesting pattern)+ std::future<ApiResult> run_python(const std::string& script,+ const std::string& command,+ const json& args);++ // Execute via HTTP API+ std::future<ApiResult> http_post(const std::string& path, const json& body);+ std::future<ApiResult> http_get(const std::string& path,+ const std::map<std::string, std::string>& params = {});+};++} // namespace fincept::ai_quant_labdiff --git a/fincept-cpp/src/screens/ai_quant_lab/ai_quant_lab_screen.cpp b/fincept-cpp/src/screens/ai_quant_lab/ai_quant_lab_screen.cppnew file mode 100644index 000000000..443aa62a8--- /dev/null+++ b/fincept-cpp/src/screens/ai_quant_lab/ai_quant_lab_screen.cpp@@ -0,0 +1,2044 @@+// AI Quant Lab Screen — 18-module quantitative research platform+// Three-panel layout: [Sidebar | Content | Status]+// Mirrors the Tauri AIQuantLabTab with all sub-panels++#include "ai_quant_lab_screen.h"+#include "ui/theme.h"+#include "core/logger.h"+#include <imgui.h>+#include <implot.h>+#include <cstring>+#include <cstdio>+#include <cmath>+#include <algorithm>+#include <ctime>++namespace fincept::ai_quant_lab {++// ============================================================================+// Module theme colors (per-panel accent)+// ============================================================================+namespace panel_colors {+ constexpr ImVec4 PURPLE = {0.55f, 0.26f, 0.87f, 1.0f}; // Factor Discovery, RL Trading+ constexpr ImVec4 BLUE = {0.18f, 0.53f, 0.96f, 1.0f}; // Model Library+ constexpr ImVec4 GREEN = {0.05f, 0.85f, 0.42f, 1.0f}; // Live Signals+ constexpr ImVec4 CYAN = {0.00f, 0.79f, 0.89f, 1.0f}; // Rolling Retraining+ constexpr ImVec4 RED = {0.96f, 0.25f, 0.25f, 1.0f}; // HFT+ constexpr ImVec4 MAGENTA = {0.87f, 0.26f, 0.55f, 1.0f}; // Meta Learning+ constexpr ImVec4 YELLOW = {1.0f, 0.78f, 0.08f, 1.0f}; // Online Learning+ constexpr ImVec4 TEAL = {0.00f, 0.79f, 0.65f, 1.0f}; // Statsmodels+ constexpr ImVec4 GLUON_BLUE = {0.00f, 0.63f, 0.89f, 1.0f}; // GluonTS+ constexpr ImVec4 GS_PURPLE = {0.44f, 0.26f, 0.76f, 1.0f}; // GS Quant+ constexpr ImVec4 ORANGE = {1.0f, 0.45f, 0.05f, 1.0f}; // Default / Accent+}++// ============================================================================+// Init+// ============================================================================+void AIQuantLabScreen::init() {+ if (initialized_) return;+ modules_ = get_modules();+ expanded_categories_ = {ModuleCategory::Core, ModuleCategory::AIML};+ initialized_ = true;+ log_status("AI Quant Lab initialized", theme::colors::SUCCESS);+ LOG_INFO("AIQuantLab", "Initialized with %zu modules", modules_.size());+}++void AIQuantLabScreen::log_status(const std::string& msg, ImVec4 color) {+ status_log_.push_back({ImGui::GetTime(), msg, color});+ if (status_log_.size() > 100) status_log_.erase(status_log_.begin());+}++// ============================================================================+// Main render+// ============================================================================+void AIQuantLabScreen::render() {+ init();+ using namespace theme::colors;++ ImGuiViewport* vp = ImGui::GetMainViewport();+ float tab_bar_h = ImGui::GetFrameHeight() + 4;+ float footer_h = ImGui::GetFrameHeight();++ float x = vp->WorkPos.x;+ float y = vp->WorkPos.y + tab_bar_h;+ float w = vp->WorkSize.x;+ float h = vp->WorkSize.y - tab_bar_h - footer_h;++ ImGui::SetNextWindowPos(ImVec2(x, y));+ ImGui::SetNextWindowSize(ImVec2(w, h));++ ImGui::PushStyleColor(ImGuiCol_WindowBg, BG_DARK);+ ImGui::PushStyleVar(ImGuiStyleVar_WindowPadding, ImVec2(0, 0));++ ImGui::Begin("##ai_quant_lab", nullptr,+ ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_NoResize |+ ImGuiWindowFlags_NoMove | ImGuiWindowFlags_NoScrollbar |+ ImGuiWindowFlags_NoDocking);++ float sidebar_w = left_panel_visible_ ? 220.0f : 0.0f;+ float status_w = right_panel_visible_ ? 260.0f : 0.0f;+ float content_w = w - sidebar_w - status_w - 4;++ // Left sidebar+ if (left_panel_visible_) {+ ImGui::BeginChild("##aql_sidebar", ImVec2(sidebar_w, h), true);+ render_sidebar(h);+ ImGui::EndChild();+ ImGui::SameLine();+ }++ // Center content+ ImGui::BeginChild("##aql_content", ImVec2(content_w, h), false);+ render_content(content_w, h);+ ImGui::EndChild();++ // Right status panel+ if (right_panel_visible_) {+ ImGui::SameLine();+ ImGui::BeginChild("##aql_status", ImVec2(status_w, h), true);+ render_status_panel(h);+ ImGui::EndChild();+ }++ ImGui::End();+ ImGui::PopStyleVar();+ ImGui::PopStyleColor();+}++// ============================================================================+// Sidebar — Module navigation grouped by category+// ============================================================================+void AIQuantLabScreen::render_sidebar(float /*height*/) {+ using namespace theme::colors;++ // Header+ ImGui::PushStyleColor(ImGuiCol_ChildBg, BG_DARKEST);+ ImGui::BeginChild("##aql_header", ImVec2(-1, 50), false);+ ImGui::SetCursorPos(ImVec2(12, 8));+ ImGui::TextColored(panel_colors::ORANGE, "AI QUANT LAB");+ ImGui::SetCursorPos(ImVec2(12, 28));+ ImGui::TextColored(TEXT_DIM, "18 MODULES | QUANT RESEARCH");+ ImGui::EndChild();+ ImGui::PopStyleColor();++ // Accent line+ ImVec2 p = ImGui::GetCursorScreenPos();+ ImGui::GetWindowDrawList()->AddRectFilled(p,+ ImVec2(p.x + ImGui::GetContentRegionAvail().x, p.y + 2),+ IM_COL32(255, 115, 13, 255));+ ImGui::Dummy(ImVec2(0, 4));++ // Toggle buttons+ ImGui::PushStyleVar(ImGuiStyleVar_FramePadding, ImVec2(6, 2));+ if (ImGui::SmallButton(right_panel_visible_ ? "Hide Status >>" : "<< Show Status")) {+ right_panel_visible_ = !right_panel_visible_;+ }+ ImGui::PopStyleVar();+ ImGui::Dummy(ImVec2(0, 4));++ // Category groups+ ModuleCategory categories[] = {+ ModuleCategory::Core, ModuleCategory::AIML,+ ModuleCategory::Advanced, ModuleCategory::Analytics+ };++ for (auto cat : categories) {+ bool expanded = expanded_categories_.count(cat) > 0;+ ImVec4 cat_color;+ switch (cat) {+ case ModuleCategory::Core: cat_color = panel_colors::BLUE; break;+ case ModuleCategory::AIML: cat_color = panel_colors::PURPLE; break;+ case ModuleCategory::Advanced: cat_color = panel_colors::RED; break;+ case ModuleCategory::Analytics: cat_color = panel_colors::TEAL; break;+ }++ char cat_label[64];+ std::snprintf(cat_label, sizeof(cat_label), "%s %s",+ expanded ? "v" : ">", category_label(cat));++ ImGui::PushStyleColor(ImGuiCol_Header, ImVec4(cat_color.x, cat_color.y, cat_color.z, 0.08f));+ ImGui::PushStyleColor(ImGuiCol_HeaderHovered, BG_HOVER);++ if (ImGui::Selectable(cat_label, false, ImGuiSelectableFlags_None, ImVec2(0, 22))) {+ if (expanded) expanded_categories_.erase(cat);+ else expanded_categories_.insert(cat);+ }+ ImGui::PopStyleColor(2);++ if (!expanded) continue;++ ImGui::Indent(12);+ for (auto& mod : modules_) {+ if (mod.category != cat) continue;+ bool is_active = (mod.view == active_view_);++ if (is_active) {+ ImGui::PushStyleColor(ImGuiCol_Header, ImVec4(cat_color.x, cat_color.y, cat_color.z, 0.15f));+ ImGui::PushStyleColor(ImGuiCol_Text, cat_color);+ } else {+ ImGui::PushStyleColor(ImGuiCol_Header, ImVec4(0, 0, 0, 0));+ ImGui::PushStyleColor(ImGuiCol_Text, TEXT_SECONDARY);+ }++ if (ImGui::Selectable(mod.label, is_active, ImGuiSelectableFlags_None, ImVec2(0, 20))) {+ active_view_ = mod.view;+ log_status(std::string("Switched to ") + mod.label, cat_color);+ }+ ImGui::PopStyleColor(2);++ if (ImGui::IsItemHovered()) {+ ImGui::SetTooltip("%s", mod.description);+ }+ }+ ImGui::Unindent(12);+ ImGui::Dummy(ImVec2(0, 2));+ }+}++// ============================================================================+// Content — dispatches to the active panel+// ============================================================================+void AIQuantLabScreen::render_content(float width, float height) {+ using namespace theme::colors;+ (void)width; (void)height;++ ImGui::PushStyleVar(ImGuiStyleVar_WindowPadding, ImVec2(12, 8));++ // Panel toggle for left sidebar+ ImGui::PushStyleVar(ImGuiStyleVar_FramePadding, ImVec2(4, 2));+ if (ImGui::SmallButton(left_panel_visible_ ? "<< Hide" : ">> Show")) {+ left_panel_visible_ = !left_panel_visible_;+ }+ ImGui::SameLine();++ // Current module title+ for (auto& mod : modules_) {+ if (mod.view == active_view_) {+ ImGui::TextColored(ACCENT, "%s", mod.label);+ ImGui::SameLine();+ ImGui::TextColored(TEXT_DIM, "- %s", mod.description);+ break;+ }+ }+ ImGui::PopStyleVar();+ ImGui::Separator();+ ImGui::Dummy(ImVec2(0, 4));++ // Dispatch to panel+ switch (active_view_) {+ case ViewMode::FactorDiscovery: render_factor_discovery(); break;+ case ViewMode::ModelLibrary: render_model_library(); break;+ case ViewMode::Backtesting: render_backtesting(); break;+ case ViewMode::LiveSignals: render_live_signals(); break;+ case ViewMode::Functime: render_functime(); break;+ case ViewMode::Fortitudo: render_fortitudo(); break;+ case ViewMode::Statsmodels: render_statsmodels(); break;+ case ViewMode::CFAQuant: render_cfa_quant(); break;+ case ViewMode::DeepAgent: render_deep_agent(); break;+ case ViewMode::RLTrading: render_rl_trading(); break;+ case ViewMode::OnlineLearning: render_online_learning(); break;+ case ViewMode::HFT: render_hft(); break;+ case ViewMode::MetaLearning: render_meta_learning(); break;+ case ViewMode::RollingRetraining: render_rolling_retraining(); break;+ case ViewMode::AdvancedModels: render_advanced_models(); break;+ case ViewMode::GluonTS: render_gluonts(); break;+ case ViewMode::GSQuant: render_gs_quant(); break;+ case ViewMode::PatternIntelligence: render_pattern_intelligence(); break;+ }++ ImGui::PopStyleVar();+}++// ============================================================================+// Status Panel (Right) — System status + activity log+// ============================================================================+void AIQuantLabScreen::render_status_panel(float /*height*/) {+ using namespace theme::colors;++ ImGui::PushStyleColor(ImGuiCol_ChildBg, BG_DARKEST);+ ImGui::BeginChild("##status_header", ImVec2(-1, 40), false);+ ImGui::SetCursorPos(ImVec2(8, 8));+ ImGui::TextColored(TEXT_DIM, "SYSTEM STATUS");+ ImGui::EndChild();+ ImGui::PopStyleColor();++ ImVec2 p = ImGui::GetCursorScreenPos();+ ImGui::GetWindowDrawList()->AddRectFilled(p,+ ImVec2(p.x + ImGui::GetContentRegionAvail().x, p.y + 1),+ IM_COL32(88, 88, 97, 255));+ ImGui::Dummy(ImVec2(0, 4));++ // Service status indicators+ theme::StatusIndicator("Qlib Engine", true);+ theme::StatusIndicator("RD-Agent", true);+ theme::StatusIndicator("Deep Agent", true);+ theme::StatusIndicator("Python Runtime", true);+ ImGui::Dummy(ImVec2(0, 8));++ // Active module+ ImGui::TextColored(TEXT_DIM, "Active Module:");+ for (auto& mod : modules_) {+ if (mod.view == active_view_) {+ ImGui::TextColored(ACCENT, " %s", mod.label);+ break;+ }+ }+ ImGui::Dummy(ImVec2(0, 8));++ // Activity log+ ImGui::TextColored(TEXT_DIM, "ACTIVITY LOG");+ ImGui::Separator();++ ImGui::BeginChild("##log_scroll", ImVec2(-1, -1), false);+ for (int i = (int)status_log_.size() - 1; i >= 0; i--) {+ auto& entry = status_log_[i];+ double age = ImGui::GetTime() - entry.time;+ char time_buf[16];+ if (age < 60) std::snprintf(time_buf, sizeof(time_buf), "%.0fs ago", age);+ else if (age < 3600) std::snprintf(time_buf, sizeof(time_buf), "%.0fm ago", age / 60);+ else std::snprintf(time_buf, sizeof(time_buf), "%.0fh ago", age / 3600);++ ImGui::TextColored(TEXT_DISABLED, "%s", time_buf);+ ImGui::SameLine();+ ImGui::TextColored(entry.color, "%s", entry.msg.c_str());+ }+ ImGui::EndChild();+}++// ============================================================================+// UI Helpers+// ============================================================================+void AIQuantLabScreen::metric_card(const char* label, const char* value, ImVec4 color) {+ using namespace theme::colors;+ ImGui::BeginGroup();+ ImGui::PushStyleColor(ImGuiCol_ChildBg, BG_WIDGET);+ ImGui::BeginChild(ImGui::GetID(label), ImVec2(140, 56), true);+ ImGui::TextColored(TEXT_DIM, "%s", label);+ ImGui::TextColored(color, "%s", value);+ ImGui::EndChild();+ ImGui::PopStyleColor();+ ImGui::EndGroup();+}++void AIQuantLabScreen::metric_card(const char* label, double value, const char* fmt, ImVec4 color) {+ char buf[64];+ std::snprintf(buf, sizeof(buf), fmt, value);+ metric_card(label, buf, color);+}++void AIQuantLabScreen::progress_bar(float fraction, const char* label) {+ using namespace theme::colors;+ ImGui::PushStyleColor(ImGuiCol_PlotHistogram, ACCENT);+ ImGui::PushStyleColor(ImGuiCol_FrameBg, BG_INPUT);+ if (label)+ ImGui::ProgressBar(fraction, ImVec2(-1, 18), label);+ else+ ImGui::ProgressBar(fraction, ImVec2(-1, 18));+ ImGui::PopStyleColor(2);+}++bool AIQuantLabScreen::config_input_text(const char* label, char* buf, int buf_size, float width) {+ ImGui::TextColored(theme::colors::TEXT_DIM, "%s", label);+ ImGui::SameLine(width);+ char id[128];+ std::snprintf(id, sizeof(id), "##%s", label);+ ImGui::SetNextItemWidth(ImGui::GetContentRegionAvail().x);+ return ImGui::InputText(id, buf, buf_size);+}++bool AIQuantLabScreen::config_input_float(const char* label, float* val, float width) {+ ImGui::TextColored(theme::colors::TEXT_DIM, "%s", label);+ ImGui::SameLine(width);+ char id[128];+ std::snprintf(id, sizeof(id), "##%s", label);+ ImGui::SetNextItemWidth(ImGui::GetContentRegionAvail().x);+ return ImGui::InputFloat(id, val, 0, 0, "%.4f");+}++bool AIQuantLabScreen::config_input_int(const char* label, int* val, float width) {+ ImGui::TextColored(theme::colors::TEXT_DIM, "%s", label);+ ImGui::SameLine(width);+ char id[128];+ std::snprintf(id, sizeof(id), "##%s", label);+ ImGui::SetNextItemWidth(ImGui::GetContentRegionAvail().x);+ return ImGui::InputInt(id, val);+}++bool AIQuantLabScreen::config_combo(const char* label, int* current, const char* const* items, int count, float width) {+ ImGui::TextColored(theme::colors::TEXT_DIM, "%s", label);+ ImGui::SameLine(width);+ char id[128];+ std::snprintf(id, sizeof(id), "##%s", label);+ ImGui::SetNextItemWidth(ImGui::GetContentRegionAvail().x);+ return ImGui::Combo(id, current, items, count);+}++void AIQuantLabScreen::section_header(const char* title, ImVec4 color) {+ ImGui::PushStyleColor(ImGuiCol_Text, color);+ ImGui::SeparatorText(title);+ ImGui::PopStyleColor();+}++void AIQuantLabScreen::status_badge(const char* text, ImVec4 bg_color, ImVec4 text_color) {+ ImVec2 p = ImGui::GetCursorScreenPos();+ ImVec2 sz = ImGui::CalcTextSize(text);+ ImGui::GetWindowDrawList()->AddRectFilled(p,+ ImVec2(p.x + sz.x + 12, p.y + sz.y + 6),+ ImGui::ColorConvertFloat4ToU32(bg_color), 3.0f);+ ImGui::SetCursorPosX(ImGui::GetCursorPosX() + 6);+ ImGui::TextColored(text_color, "%s", text);+ ImGui::Dummy(ImVec2(sz.x + 16, sz.y + 8));+}++// ============================================================================+// PANEL 1: Factor Discovery (RD-Agent) — PURPLE THEME+// ============================================================================+void AIQuantLabScreen::render_factor_discovery() {+ using namespace theme::colors;+ section_header("FACTOR DISCOVERY", panel_colors::PURPLE);+ ImGui::TextColored(TEXT_DIM, "RD-Agent automated alpha factor mining with AI-driven research");+ ImGui::Dummy(ImVec2(0, 8));++ // Config+ static const char* markets[] = {"US", "CN", "CRYPTO"};+ config_input_text("Task Description", fd_task_desc_, sizeof(fd_task_desc_), 130);+ config_input_text("API Key", fd_api_key_, sizeof(fd_api_key_), 130);+ config_combo("Target Market", &fd_market_idx_, markets, 3, 130);+ config_input_int("Budget", &fd_budget_, 130);++ ImGui::Dummy(ImVec2(0, 8));++ // Start button+ bool is_running = fd_op_.loading.load() || fd_polling_;+ if (is_running) {+ theme::LoadingSpinner("Mining factors...");+ progress_bar(0.5f, "Searching for alpha...");++ // Poll status every 5 seconds+ if (fd_polling_ && !fd_task_id_.empty()) {+ double now = ImGui::GetTime();+ if (now - fd_last_poll_ > 5.0) {+ fd_last_poll_ = now;+ // Check status+ auto status_future = QuantLabApi::instance().rdagent_get_status(fd_task_id_);+ if (status_future.wait_for(std::chrono::milliseconds(0)) == std::future_status::ready) {+ auto r = status_future.get();+ if (r.success && r.data.value("status", "") == "completed") {+ fd_polling_ = false;+ // Fetch factors+ auto fac_future = QuantLabApi::instance().rdagent_get_factors(fd_task_id_);+ // Will be picked up next frame+ }+ }+ }+ }+ } else {+ if (theme::AccentButton("Start Factor Mining")) {+ json config = {+ {"task_description", fd_task_desc_},+ {"api_key", fd_api_key_},+ {"target_market", markets[fd_market_idx_]},+ {"budget", fd_budget_},+ };+ fd_op_.loading.store(true);+ log_status("Starting factor mining...", panel_colors::PURPLE);++ std::thread([this, config]() {+ auto result = QuantLabApi::instance().rdagent_start_mining(config).get();+ if (result.success) {+ fd_task_id_ = result.data.value("task_id", "");+ fd_polling_ = true;+ fd_last_poll_ = 0;+ log_status("Factor mining started: " + fd_task_id_, SUCCESS);+ } else {+ fd_op_.set_error(result.error);+ log_status("Factor mining failed: " + result.error, ERROR_RED);+ }+ fd_op_.loading.store(false);+ }).detach();+ }+ }++ // Display discovered factors+ if (!fd_factors_.empty()) {+ ImGui::Dummy(ImVec2(0, 12));+ section_header("DISCOVERED FACTORS", panel_colors::PURPLE);++ for (size_t i = 0; i < fd_factors_.size(); i++) {+ auto& f = fd_factors_[i];+ ImGui::PushID((int)i);++ ImGui::PushStyleColor(ImGuiCol_ChildBg, BG_WIDGET);+ ImGui::BeginChild("##factor", ImVec2(-1, 0), ImGuiChildFlags_AutoResizeY | ImGuiChildFlags_Borders);++ ImGui::TextColored(panel_colors::PURPLE, "%s", f.name.c_str());+ ImGui::TextColored(TEXT_DIM, "%s", f.description.c_str());++ // Metrics row+ metric_card("IC", f.ic, "%.4f", f.ic > 0.03 ? MARKET_GREEN : TEXT_SECONDARY);+ ImGui::SameLine();+ metric_card("Sharpe", f.sharpe, "%.2f", f.sharpe > 1.0 ? MARKET_GREEN : TEXT_SECONDARY);+ ImGui::SameLine();+ metric_card("Annual Return", f.annual_return, "%.2f%%", f.annual_return > 0 ? MARKET_GREEN : MARKET_RED);++ // Code display+ if (ImGui::CollapsingHeader("Factor Code")) {+ ImGui::PushStyleColor(ImGuiCol_ChildBg, BG_DARKEST);+ ImGui::BeginChild("##code", ImVec2(-1, 100));+ ImGui::TextWrapped("%s", f.code.c_str());+ ImGui::EndChild();+ ImGui::PopStyleColor();++ if (ImGui::SmallButton("Copy Code")) {+ ImGui::SetClipboardText(f.code.c_str());+ log_status("Factor code copied", SUCCESS);+ }+ }++ ImGui::EndChild();+ ImGui::PopStyleColor();+ ImGui::PopID();+ ImGui::Dummy(ImVec2(0, 4));+ }+ }++ // Error display+ if (!fd_op_.error.empty()) {+ theme::ErrorMessage(fd_op_.error.c_str());+ }+}++// ============================================================================+// PANEL 2: Model Library (Qlib) — BLUE THEME+// ============================================================================+void AIQuantLabScreen::render_model_library() {+ using namespace theme::colors;+ section_header("MODEL LIBRARY", panel_colors::BLUE);+ ImGui::TextColored(TEXT_DIM, "Microsoft Qlib ML models for financial prediction");+ ImGui::Dummy(ImVec2(0, 8));++ // Filter+ static const char* filters[] = {"All", "Tree-Based", "Neural Network", "Linear", "Ensemble"};+ config_combo("Filter", &ml_filter_idx_, filters, 5, 100);++ // Load models button+ if (!ml_list_op_.loading.load()) {+ if (theme::SecondaryButton("Refresh Models")) {+ ml_list_op_.loading.store(true);+ std::thread([this]() {+ auto result = QuantLabApi::instance().qlib_list_models().get();+ if (result.success) {+ std::lock_guard<std::mutex> lock(ml_list_op_.mutex);+ ml_models_.clear();+ if (result.data.is_array()) {+ for (auto& m : result.data) {+ QlibModel model;+ model.name = m.value("name", "");+ model.type = m.value("type", "");+ model.description = m.value("description", "");+ ml_models_.push_back(model);+ }+ }+ ml_list_op_.set_result(result.data);+ } else {+ ml_list_op_.set_error(result.error);+ }+ }).detach();+ }+ } else {+ theme::LoadingSpinner("Loading models...");+ }++ ImGui::Dummy(ImVec2(0, 8));++ // Model list+ if (ml_models_.empty() && !ml_list_op_.has_result) {+ // Show default models+ static const struct { const char* name; const char* type; const char* desc; } defaults[] = {+ {"LightGBM", "tree_based", "Gradient boosting framework with high efficiency"},+ {"XGBoost", "tree_based", "Extreme gradient boosting for structured data"},+ {"CatBoost", "tree_based", "Gradient boosting with native categorical support"},+ {"LSTM", "neural_network", "Long Short-Term Memory recurrent network"},+ {"GRU", "neural_network", "Gated Recurrent Unit network"},+ {"Transformer", "neural_network", "Attention-based architecture for sequences"},+ {"Linear", "linear", "Linear regression with regularization"},+ {"Ridge", "linear", "L2-regularized linear regression"},+ {"RandomForest","ensemble", "Bagged decision tree ensemble"},+ {"AdaBoost", "ensemble", "Adaptive boosting ensemble method"},+ };++ for (auto& d : defaults) {+ if (ml_filter_idx_ > 0) {+ const char* filter_types[] = {"", "tree_based", "neural_network", "linear", "ensemble"};+ if (std::strcmp(d.type, filter_types[ml_filter_idx_]) != 0) continue;+ }++ bool selected = false;+ ImGui::PushStyleColor(ImGuiCol_Header, ImVec4(panel_colors::BLUE.x, panel_colors::BLUE.y, panel_colors::BLUE.z, 0.1f));+ if (ImGui::Selectable(d.name, &selected, ImGuiSelectableFlags_None, ImVec2(0, 28))) {+ // Select model+ }+ ImGui::PopStyleColor();+ ImGui::SameLine(200);+ ImGui::TextColored(TEXT_DIM, "[%s]", d.type);+ ImGui::SameLine(350);+ ImGui::TextColored(TEXT_SECONDARY, "%s", d.desc);+ }+ }++ ImGui::Dummy(ImVec2(0, 12));++ // Train config+ section_header("TRAIN MODEL", panel_colors::BLUE);+ config_input_text("Instruments", ml_instruments_, sizeof(ml_instruments_), 120);+ config_input_text("Start Date", ml_start_date_, sizeof(ml_start_date_), 120);+ config_input_text("End Date", ml_end_date_, sizeof(ml_end_date_), 120);++ if (!ml_train_op_.loading.load()) {+ if (theme::AccentButton("Train Model")) {+ ml_train_op_.loading.store(true);+ json config = {+ {"instruments", ml_instruments_},+ {"start_date", ml_start_date_},+ {"end_date", ml_end_date_},+ };+ log_status("Training model...", panel_colors::BLUE);+ std::thread([this, config]() {+ auto result = QuantLabApi::instance().qlib_train_model(config).get();+ if (result.success) {+ ml_train_op_.set_result(result.data);+ log_status("Model training completed", SUCCESS);+ } else {+ ml_train_op_.set_error(result.error);+ log_status("Training failed: " + result.error, ERROR_RED);+ }+ }).detach();+ }+ } else {+ theme::LoadingSpinner("Training...");+ }++ if (!ml_train_op_.error.empty()) theme::ErrorMessage(ml_train_op_.error.c_str());+}++// ============================================================================+// PANEL 3: Backtesting (Qlib)+// ============================================================================+void AIQuantLabScreen::render_backtesting() {+ using namespace theme::colors;+ section_header("STRATEGY BACKTESTING", ACCENT);+ ImGui::TextColored(TEXT_DIM, "Qlib-powered strategy backtesting engine");+ ImGui::Dummy(ImVec2(0, 8));++ static const char* strategies[] = {"TopK Dropout", "Weight Base", "Enhanced Indexing"};+ config_combo("Strategy", &bt_strategy_idx_, strategies, 3, 120);+ config_input_text("Instruments", bt_instruments_, sizeof(bt_instruments_), 120);+ config_input_text("Start Date", bt_start_, sizeof(bt_start_), 120);+ config_input_text("End Date", bt_end_, sizeof(bt_end_), 120);+ config_input_float("Initial Capital", &bt_capital_, 120);+ config_input_text("Benchmark", bt_benchmark_, sizeof(bt_benchmark_), 120);+ config_input_float("Commission", &bt_commission_, 120);+ config_input_float("Slippage", &bt_slippage_, 120);++ ImGui::Dummy(ImVec2(0, 8));++ if (!bt_op_.loading.load()) {+ if (theme::AccentButton("Run Backtest")) {+ static const char* strat_keys[] = {"topk_dropout", "weight_base", "enhanced_indexing"};+ json config = {+ {"strategy", strat_keys[bt_strategy_idx_]},+ {"instruments", bt_instruments_},+ {"start_date", bt_start_},+ {"end_date", bt_end_},+ {"initial_capital", bt_capital_},+ {"benchmark", bt_benchmark_},+ {"commission", bt_commission_},+ {"slippage", bt_slippage_},+ };+ bt_op_.loading.store(true);+ log_status("Running backtest...", ACCENT);+ std::thread([this, config]() {+ auto result = QuantLabApi::instance().qlib_run_backtest(config).get();+ if (result.success) {+ bt_op_.set_result(result.data);+ log_status("Backtest completed", SUCCESS);+ } else {+ bt_op_.set_error(result.error);+ log_status("Backtest failed: " + result.error, ERROR_RED);+ }+ }).detach();+ }+ } else {+ theme::LoadingSpinner("Running backtest...");+ }++ // Results+ if (bt_op_.has_result) {+ ImGui::Dummy(ImVec2(0, 12));+ section_header("BACKTEST RESULTS", SUCCESS);++ std::lock_guard<std::mutex> lock(bt_op_.mutex);+ auto& d = bt_op_.result;++ double ann_ret = d.value("annual_return", 0.0);+ double sharpe = d.value("sharpe_ratio", 0.0);+ double max_dd = d.value("max_drawdown", 0.0);+ double win_rate = d.value("win_rate", 0.0);+ int trades = d.value("total_trades", 0);+ double pf = d.value("profit_factor", 0.0);++ metric_card("Annual Return", ann_ret * 100, "%.2f%%", ann_ret > 0 ? MARKET_GREEN : MARKET_RED);+ ImGui::SameLine();+ metric_card("Sharpe Ratio", sharpe, "%.2f", sharpe > 1 ? MARKET_GREEN : WARNING);+ ImGui::SameLine();+ metric_card("Max Drawdown", max_dd * 100, "%.2f%%", MARKET_RED);++ metric_card("Win Rate", win_rate * 100, "%.1f%%", win_rate > 0.5 ? MARKET_GREEN : WARNING);+ ImGui::SameLine();+ char trades_buf[32];+ std::snprintf(trades_buf, sizeof(trades_buf), "%d", trades);+ metric_card("Total Trades", trades_buf, TEXT_PRIMARY);+ ImGui::SameLine();+ metric_card("Profit Factor", pf, "%.2f", pf > 1 ? MARKET_GREEN : MARKET_RED);+ }++ if (!bt_op_.error.empty()) theme::ErrorMessage(bt_op_.error.c_str());+}++// ============================================================================+// PANEL 4: Live Signals — GREEN THEME+// ============================================================================+void AIQuantLabScreen::render_live_signals() {+ using namespace theme::colors;+ section_header("LIVE SIGNALS", panel_colors::GREEN);+ ImGui::TextColored(TEXT_DIM, "Real-time model predictions & trading signals");+ ImGui::Dummy(ImVec2(0, 8));++ static const char* models[] = {"LightGBM", "XGBoost", "LSTM", "Transformer"};+ config_combo("Model", &ls_model_idx_, models, 4, 120);+ config_input_int("Refresh (sec)", &ls_refresh_sec_, 120);++ static const char* signal_filters[] = {"ALL", "BUY", "SELL"};+ config_combo("Filter", &ls_filter_idx_, signal_filters, 3, 120);++ ImGui::Dummy(ImVec2(0, 8));++ // Stream toggle+ if (ls_streaming_) {+ ImGui::PushStyleColor(ImGuiCol_Button, ImVec4(panel_colors::GREEN.x, panel_colors::GREEN.y, panel_colors::GREEN.z, 0.3f));+ if (ImGui::Button("Stop Streaming")) {+ ls_streaming_ = false;+ log_status("Signal streaming stopped", WARNING);+ }+ ImGui::PopStyleColor();+ ImGui::SameLine();+ theme::LoadingSpinner("Streaming...");++ // Auto-refresh+ double now = ImGui::GetTime();+ if (now - ls_last_refresh_ > ls_refresh_sec_ && !ls_op_.loading.load()) {+ ls_last_refresh_ = now;+ ls_op_.loading.store(true);+ json config = {{"model", models[ls_model_idx_]}};+ std::thread([this, config]() {+ auto result = QuantLabApi::instance().qlib_get_live_predictions(config).get();+ if (result.success) {+ std::lock_guard<std::mutex> lock(ls_op_.mutex);+ ls_signals_.clear();+ if (result.data.is_array()) {+ for (auto& s : result.data) {+ SignalEntry sig;+ sig.symbol = s.value("symbol", "");+ sig.signal = s.value("signal", "HOLD");+ sig.score = s.value("score", 0.0);+ sig.price = s.value("price", 0.0);+ sig.confidence = s.value("confidence", 0.0);+ sig.model = s.value("model", "");+ sig.timestamp = s.value("timestamp", "");+ ls_signals_.push_back(sig);+ }+ }+ ls_op_.set_result(result.data);+ } else {+ ls_op_.set_error(result.error);+ }+ }).detach();+ }+ } else {+ if (theme::AccentButton("Start Streaming")) {+ ls_streaming_ = true;+ ls_last_refresh_ = 0;+ log_status("Signal streaming started", panel_colors::GREEN);+ }+ }++ // Signal cards+ if (!ls_signals_.empty()) {+ ImGui::Dummy(ImVec2(0, 8));+ for (auto& sig : ls_signals_) {+ // Filter+ if (ls_filter_idx_ == 1 && sig.signal != "BUY") continue;+ if (ls_filter_idx_ == 2 && sig.signal != "SELL") continue;++ ImVec4 sig_color = sig.signal == "BUY" ? MARKET_GREEN :+ sig.signal == "SELL" ? MARKET_RED : WARNING;++ ImGui::PushStyleColor(ImGuiCol_ChildBg, ImVec4(sig_color.x, sig_color.y, sig_color.z, 0.05f));+ ImGui::BeginChild(ImGui::GetID(sig.symbol.c_str()), ImVec2(-1, 0),+ ImGuiChildFlags_AutoResizeY | ImGuiChildFlags_Borders);++ ImGui::TextColored(TEXT_PRIMARY, "%s", sig.symbol.c_str());+ ImGui::SameLine(120);+ status_badge(sig.signal.c_str(),+ ImVec4(sig_color.x, sig_color.y, sig_color.z, 0.2f), sig_color);+ ImGui::SameLine(220);+ ImGui::TextColored(TEXT_SECONDARY, "Score: %.4f", sig.score);+ ImGui::SameLine(350);+ ImGui::TextColored(TEXT_SECONDARY, "$%.2f", sig.price);+ ImGui::SameLine(440);+ ImGui::TextColored(TEXT_DIM, "Conf: %.1f%%", sig.confidence * 100);++ ImGui::EndChild();+ ImGui::PopStyleColor();+ ImGui::Dummy(ImVec2(0, 2));+ }+ } else if (!ls_op_.loading.load() && !ls_streaming_) {+ ImGui::Dummy(ImVec2(0, 20));+ ImGui::TextColored(TEXT_DIM, "Click 'Start Streaming' to receive live predictions");+ }++ if (!ls_op_.error.empty()) theme::ErrorMessage(ls_op_.error.c_str());+}++// ============================================================================+// PANEL 5: Deep Agent — LLM-powered autonomous research+// ============================================================================+void AIQuantLabScreen::render_deep_agent() {+ using namespace theme::colors;+ section_header("DEEP AGENT", ACCENT);+ ImGui::TextColored(TEXT_DIM, "LLM-powered autonomous financial research agent");+ ImGui::Dummy(ImVec2(0, 8));++ static const char* agents[] = {"Research", "Strategy Builder", "Portfolio Manager", "Risk Analyzer", "General"};+ config_combo("Agent Type", &da_agent_idx_, agents, 5, 120);+ config_input_text("Query", da_query_, sizeof(da_query_), 120);++ ImGui::Dummy(ImVec2(0, 8));++ // Phase indicator+ static const char* phases[] = {"Ready", "Planning", "Executing", "Synthesizing", "Complete"};+ ImGui::TextColored(TEXT_DIM, "Phase:");+ ImGui::SameLine();+ ImVec4 phase_color = da_phase_ == 4 ? SUCCESS :+ da_phase_ > 0 ? WARNING : TEXT_SECONDARY;+ ImGui::TextColored(phase_color, "%s", phases[da_phase_]);++ if (da_phase_ > 0 && da_phase_ < 4) {+ float prog = (float)da_phase_ / 4.0f;+ progress_bar(prog, phases[da_phase_]);+ }++ ImGui::Dummy(ImVec2(0, 8));++ if (da_phase_ == 0) {+ if (theme::AccentButton("Create Plan")) {+ if (std::strlen(da_query_) == 0) return;+ da_phase_ = 1;+ da_steps_.clear();+ da_plan_text_.clear();+ da_synthesis_.clear();+ da_op_.loading.store(true);+ log_status("Deep Agent: Creating plan...", ACCENT);++ json config = {+ {"agent_type", agents[da_agent_idx_]},+ {"query", da_query_},+ };+ std::thread([this, config]() {+ auto result = QuantLabApi::instance().deep_agent_create_plan(config).get();+ if (result.success) {+ da_plan_text_ = result.data.value("plan", "");+ if (result.data.contains("steps") && result.data["steps"].is_array()) {+ int idx = 0;+ for (auto& s : result.data["steps"]) {+ AgentStep step;+ step.index = idx++;+ step.description = s.value("description", "");+ step.status = "pending";+ da_steps_.push_back(step);+ }+ }+ da_phase_ = 2;+ da_current_step_ = 0;+ log_status("Plan created with " + std::to_string(da_steps_.size()) + " steps", SUCCESS);+ } else {+ da_phase_ = 0;+ log_status("Planning failed: " + result.error, ERROR_RED);+ }+ da_op_.loading.store(false);+ }).detach();+ }+ } else if (da_phase_ == 2) {+ // Show plan and steps+ if (!da_plan_text_.empty()) {+ ImGui::TextColored(TEXT_SECONDARY, "Plan:");+ ImGui::TextWrapped("%s", da_plan_text_.c_str());+ ImGui::Dummy(ImVec2(0, 8));+ }++ section_header("EXECUTION STEPS", ACCENT);+ for (auto& step : da_steps_) {+ ImVec4 sc = step.status == "completed" ? SUCCESS :+ step.status == "running" ? WARNING :+ step.status == "failed" ? ERROR_RED : TEXT_DIM;+ ImGui::TextColored(sc, "[%d] %s — %s",+ step.index + 1, step.description.c_str(), step.status.c_str());+ if (!step.result.empty() && step.status == "completed") {+ ImGui::Indent(20);+ ImGui::TextColored(TEXT_DIM, "%s", step.result.c_str());+ ImGui::Unindent(20);+ }+ }++ ImGui::Dummy(ImVec2(0, 8));++ if (!da_op_.loading.load() && da_current_step_ < (int)da_steps_.size()) {+ if (theme::AccentButton("Execute Next Step")) {+ da_op_.loading.store(true);+ int step_idx = da_current_step_;+ da_steps_[step_idx].status = "running";+ json config = {+ {"step_index", step_idx},+ {"description", da_steps_[step_idx].description},+ {"agent_type", agents[da_agent_idx_]},+ {"query", da_query_},+ };+ std::thread([this, config, step_idx]() {+ auto result = QuantLabApi::instance().deep_agent_execute_step(config).get();+ if (result.success) {+ da_steps_[step_idx].status = "completed";+ da_steps_[step_idx].result = result.data.value("result", "");+ da_current_step_++;+ if (da_current_step_ >= (int)da_steps_.size()) {+ da_phase_ = 3; // Ready to synthesize+ }+ } else {+ da_steps_[step_idx].status = "failed";+ da_steps_[step_idx].result = result.error;+ }+ da_op_.loading.store(false);+ }).detach();+ }+ } else if (da_op_.loading.load()) {+ theme::LoadingSpinner("Executing step...");+ }++ if (da_current_step_ >= (int)da_steps_.size() && !da_op_.loading.load()) {+ if (theme::AccentButton("Synthesize Results")) {+ da_phase_ = 3;+ da_op_.loading.store(true);+ json config = {+ {"agent_type", agents[da_agent_idx_]},+ {"query", da_query_},+ {"steps", json::array()},+ };+ for (auto& s : da_steps_) {+ config["steps"].push_back({+ {"description", s.description},+ {"result", s.result},+ });+ }+ std::thread([this, config]() {+ auto result = QuantLabApi::instance().deep_agent_synthesize(config).get();+ if (result.success) {+ da_synthesis_ = result.data.value("synthesis", "");+ da_phase_ = 4;+ log_status("Deep Agent: Synthesis complete", SUCCESS);+ } else {+ da_phase_ = 2;+ log_status("Synthesis failed: " + result.error, ERROR_RED);+ }+ da_op_.loading.store(false);+ }).detach();+ }+ }+ } else if (da_phase_ == 3) {+ theme::LoadingSpinner("Synthesizing results...");+ } else if (da_phase_ == 4) {+ section_header("SYNTHESIS", SUCCESS);+ ImGui::TextWrapped("%s", da_synthesis_.c_str());++ ImGui::Dummy(ImVec2(0, 8));+ if (theme::SecondaryButton("New Query")) {+ da_phase_ = 0;+ da_steps_.clear();+ da_plan_text_.clear();+ da_synthesis_.clear();+ }+ }+}++// ============================================================================+// PANEL 6: RL Trading — PURPLE THEME+// ============================================================================+void AIQuantLabScreen::render_rl_trading() {+ using namespace theme::colors;+ section_header("RL TRADING", panel_colors::PURPLE);+ ImGui::TextColored(TEXT_DIM, "Reinforcement learning trading strategies");+ ImGui::Dummy(ImVec2(0, 8));++ static const char* algos[] = {"PPO", "A2C", "DQN", "SAC", "TD3"};+ static const char* action_spaces[] = {"Continuous", "Discrete"};++ config_combo("Algorithm", &rl_algo_idx_, algos, 5, 130);+ config_input_text("Tickers", rl_tickers_, sizeof(rl_tickers_), 130);+ config_input_text("Start Date", rl_start_, sizeof(rl_start_), 130);+ config_input_text("End Date", rl_end_, sizeof(rl_end_), 130);+ config_input_float("Initial Cash", &rl_initial_cash_, 130);+ config_input_float("Commission", &rl_commission_, 130);+ config_combo("Action Space", &rl_action_space_, action_spaces, 2, 130);+ config_input_int("Timesteps", &rl_timesteps_, 130);+ config_input_float("Learning Rate", &rl_learning_rate_, 130);++ ImGui::Dummy(ImVec2(0, 8));++ // Phase display+ static const char* rl_phases[] = {"Configure", "Env Created", "Training", "Evaluating", "Done"};+ ImGui::TextColored(TEXT_DIM, "Phase:");+ ImGui::SameLine();+ ImGui::TextColored(rl_phase_ == 4 ? SUCCESS : WARNING, "%s", rl_phases[rl_phase_]);++ if (rl_phase_ > 0 && rl_phase_ < 4)+ progress_bar((float)rl_phase_ / 4.0f);++ ImGui::Dummy(ImVec2(0, 8));++ if (!rl_op_.loading.load()) {+ const char* btn_label = rl_phase_ == 0 ? "Create Environment" :+ rl_phase_ == 1 ? "Train Agent" :+ rl_phase_ == 3 ? "Evaluate" : "Reset";++ if (theme::AccentButton(btn_label)) {+ if (rl_phase_ >= 4) {+ rl_phase_ = 0;+ rl_op_.clear();+ return;+ }++ rl_op_.loading.store(true);+ json config = {+ {"algorithm", algos[rl_algo_idx_]},+ {"tickers", rl_tickers_},+ {"start_date", rl_start_},+ {"end_date", rl_end_},+ {"initial_cash", rl_initial_cash_},+ {"commission", rl_commission_},+ {"action_space", action_spaces[rl_action_space_]},+ {"timesteps", rl_timesteps_},+ {"learning_rate", rl_learning_rate_},+ };++ int phase = rl_phase_;+ std::thread([this, config, phase]() {+ ApiResult result;+ if (phase == 0) {+ result = QuantLabApi::instance().rl_create_env(config).get();+ if (result.success) rl_phase_ = 1;+ } else if (phase == 1) {+ result = QuantLabApi::instance().rl_train_agent(config).get();+ if (result.success) rl_phase_ = 3;+ } else if (phase == 3) {+ result = QuantLabApi::instance().rl_evaluate(config).get();+ if (result.success) rl_phase_ = 4;+ }++ if (result.success) {+ rl_op_.set_result(result.data);+ log_status("RL Phase complete", SUCCESS);+ } else {+ rl_op_.set_error(result.error);+ log_status("RL failed: " + result.error, ERROR_RED);+ }+ }).detach();+ }+ } else {+ theme::LoadingSpinner("Processing...");+ }++ // Show results+ if (rl_op_.has_result && rl_phase_ == 4) {+ ImGui::Dummy(ImVec2(0, 12));+ section_header("EVALUATION RESULTS", panel_colors::PURPLE);++ std::lock_guard<std::mutex> lock(rl_op_.mutex);+ auto& d = rl_op_.result;+ double total_ret = d.value("total_return", 0.0);+ double sharpe = d.value("sharpe_ratio", 0.0);+ double max_dd = d.value("max_drawdown", 0.0);++ metric_card("Total Return", total_ret * 100, "%.2f%%", total_ret > 0 ? MARKET_GREEN : MARKET_RED);+ ImGui::SameLine();+ metric_card("Sharpe", sharpe, "%.2f", sharpe > 1 ? MARKET_GREEN : WARNING);+ ImGui::SameLine();+ metric_card("Max Drawdown", max_dd * 100, "%.2f%%", MARKET_RED);+ }++ if (!rl_op_.error.empty()) theme::ErrorMessage(rl_op_.error.c_str());+}++// ============================================================================+// PANEL 7: Online Learning — YELLOW THEME+// ============================================================================+void AIQuantLabScreen::render_online_learning() {+ using namespace theme::colors;+ section_header("ONLINE LEARNING", panel_colors::YELLOW);+ ImGui::TextColored(TEXT_DIM, "Continuous model adaptation with drift detection");+ ImGui::Dummy(ImVec2(0, 8));++ static const char* model_types[] = {+ "LinearRegression", "RidgeRegression", "LogisticRegression",+ "DecisionTree", "RandomForest", "GradientBoosting",+ "AdaBoost", "BaggingClassifier", "VotingEnsemble"+ };+ static const char* drift_strategies[] = {"Retrain", "Adaptive"};++ config_combo("Model Type", &ol_model_idx_, model_types, 9, 130);+ config_combo("Drift Strategy", &ol_drift_strategy_, drift_strategies, 2, 130);++ ImGui::Dummy(ImVec2(0, 8));++ // Create Model+ if (!ol_create_op_.loading.load()) {+ if (theme::AccentButton("Create Model")) {+ ol_create_op_.loading.store(true);+ json config = {{"model_type", model_types[ol_model_idx_]}};+ log_status("Creating online model...", panel_colors::YELLOW);+ std::thread([this, config]() {+ auto result = QuantLabApi::instance().qlib_online_create(config).get();+ if (result.success) {+ ol_create_op_.set_result(result.data);+ log_status("Online model created", SUCCESS);+ } else {+ ol_create_op_.set_error(result.error);+ }+ }).detach();+ }+ } else {+ theme::LoadingSpinner("Creating model...");+ }++ ImGui::SameLine();++ // Train+ if (!ol_train_op_.loading.load()) {+ if (theme::SecondaryButton("Train")) {+ ol_train_op_.loading.store(true);+ json config = {{"model_type", model_types[ol_model_idx_]}};+ std::thread([this, config]() {+ auto result = QuantLabApi::instance().qlib_online_train(config).get();+ if (result.success) ol_train_op_.set_result(result.data);+ else ol_train_op_.set_error(result.error);+ }).detach();+ }+ } else {+ theme::LoadingSpinner("Training...");+ }++ ImGui::Dummy(ImVec2(0, 8));++ // Live mode toggle+ if (ImGui::Checkbox("Live Mode (2s updates)", &ol_live_mode_)) {+ log_status(ol_live_mode_ ? "Live mode enabled" : "Live mode disabled",+ ol_live_mode_ ? panel_colors::YELLOW : TEXT_DIM);+ }++ if (ol_live_mode_) {+ double now = ImGui::GetTime();+ if (now - ol_last_update_ > 2.0 && !ol_perf_op_.loading.load()) {+ ol_last_update_ = now;+ ol_perf_op_.loading.store(true);+ std::thread([this]() {+ auto result = QuantLabApi::instance().qlib_online_performance("current").get();+ if (result.success) ol_perf_op_.set_result(result.data);+ else ol_perf_op_.set_error(result.error);+ }).detach();+ }+ }++ // Performance display+ if (ol_perf_op_.has_result) {+ ImGui::Dummy(ImVec2(0, 8));+ section_header("PERFORMANCE", panel_colors::YELLOW);+ std::lock_guard<std::mutex> lock(ol_perf_op_.mutex);+ auto& d = ol_perf_op_.result;+ double acc = d.value("accuracy", 0.0);+ double loss = d.value("loss", 0.0);+ metric_card("Accuracy", acc * 100, "%.1f%%", acc > 0.6 ? MARKET_GREEN : WARNING);+ ImGui::SameLine();+ metric_card("Loss", loss, "%.4f", TEXT_SECONDARY);+ }++ if (!ol_create_op_.error.empty()) theme::ErrorMessage(ol_create_op_.error.c_str());+ if (!ol_train_op_.error.empty()) theme::ErrorMessage(ol_train_op_.error.c_str());+}++// ============================================================================+// PANEL 8: HFT Analytics — RED THEME+// ============================================================================+void AIQuantLabScreen::render_hft() {+ using namespace theme::colors;+ section_header("HFT ANALYTICS", panel_colors::RED);+ ImGui::TextColored(TEXT_DIM, "Order book visualization & microstructure analysis");+ ImGui::Dummy(ImVec2(0, 8));++ config_input_text("Symbol", hft_symbol_, sizeof(hft_symbol_), 120);+ config_input_float("Spread Target", &hft_spread_target_, 120);+ config_input_float("Position Limit", &hft_position_limit_, 120);++ ImGui::Dummy(ImVec2(0, 4));++ // Live toggle+ if (ImGui::Checkbox("Live Mode (1s updates)", &hft_live_)) {+ if (hft_live_) {+ log_status("HFT live mode started", panel_colors::RED);+ // Generate initial mock data+ hft_bids_.clear();+ hft_asks_.clear();+ double base = 185.50;+ for (int i = 0; i < 10; i++) {+ hft_bids_.push_back({base - i * 0.01, 100.0 + rand() % 500, 1 + rand() % 10});+ hft_asks_.push_back({base + 0.01 + i * 0.01, 100.0 + rand() % 500, 1 + rand() % 10});+ }+ hft_metrics_ = {0.15, base - 0.05, base + 0.05, 0.23, 0.02, base};+ }+ }++ if (hft_live_) {+ double now = ImGui::GetTime();+ if (now - hft_last_update_ > 1.0) {+ hft_last_update_ = now;+ // Update mock data with slight randomization+ for (auto& b : hft_bids_) b.size += (rand() % 100) - 50;+ for (auto& a : hft_asks_) a.size += (rand() % 100) - 50;+ hft_metrics_.depth_imbalance = 0.1 + (rand() % 30) / 100.0;+ hft_metrics_.toxicity_score = 0.15 + (rand() % 20) / 100.0;+ }+ }++ // Order Book+ if (!hft_bids_.empty()) {+ ImGui::Dummy(ImVec2(0, 8));+ section_header("ORDER BOOK", panel_colors::RED);++ // Bids and asks side by side+ ImGui::Columns(2, "##orderbook", true);++ // Bids+ ImGui::TextColored(MARKET_GREEN, "BIDS");+ ImGui::Separator();+ ImGui::TextColored(TEXT_DIM, "%-10s %-10s %-6s", "Price", "Size", "Orders");+ for (auto& b : hft_bids_) {+ float pct = (float)(b.size / 600.0);+ ImVec2 p = ImGui::GetCursorScreenPos();+ ImGui::GetWindowDrawList()->AddRectFilled(p,+ ImVec2(p.x + ImGui::GetColumnWidth() * pct, p.y + ImGui::GetTextLineHeight()),+ IM_COL32(5, 217, 107, 30));+ ImGui::TextColored(MARKET_GREEN, "%.2f %.0f %d", b.price, b.size, b.orders);+ }++ ImGui::NextColumn();++ // Asks+ ImGui::TextColored(MARKET_RED, "ASKS");+ ImGui::Separator();+ ImGui::TextColored(TEXT_DIM, "%-10s %-10s %-6s", "Price", "Size", "Orders");+ for (auto& a : hft_asks_) {+ float pct = (float)(a.size / 600.0);+ ImVec2 p2 = ImGui::GetCursorScreenPos();+ ImGui::GetWindowDrawList()->AddRectFilled(p2,+ ImVec2(p2.x + ImGui::GetColumnWidth() * pct, p2.y + ImGui::GetTextLineHeight()),+ IM_COL32(245, 64, 64, 30));+ ImGui::TextColored(MARKET_RED, "%.2f %.0f %d", a.price, a.size, a.orders);+ }++ ImGui::Columns(1);++ // Microstructure metrics+ ImGui::Dummy(ImVec2(0, 8));+ section_header("MICROSTRUCTURE", panel_colors::RED);++ metric_card("Depth Imbalance", hft_metrics_.depth_imbalance, "%.4f",+ std::abs(hft_metrics_.depth_imbalance) > 0.3 ? WARNING : TEXT_SECONDARY);+ ImGui::SameLine();+ metric_card("VWAP Bid", hft_metrics_.vwap_bid, "%.2f", MARKET_GREEN);+ ImGui::SameLine();+ metric_card("VWAP Ask", hft_metrics_.vwap_ask, "%.2f", MARKET_RED);++ metric_card("Toxicity", hft_metrics_.toxicity_score, "%.4f",+ hft_metrics_.toxicity_score > 0.5 ? MARKET_RED : TEXT_SECONDARY);+ ImGui::SameLine();+ metric_card("Spread", hft_metrics_.spread, "%.4f", TEXT_SECONDARY);+ ImGui::SameLine();+ metric_card("Mid Price", hft_metrics_.mid_price, "%.2f", TEXT_PRIMARY);++ // Market Making Quote Calculator+ ImGui::Dummy(ImVec2(0, 8));+ section_header("MARKET MAKING QUOTES", panel_colors::RED);++ double bid_quote = hft_metrics_.mid_price - hft_spread_target_ / 2;+ double ask_quote = hft_metrics_.mid_price + hft_spread_target_ / 2;+ ImGui::TextColored(MARKET_GREEN, "Bid Quote: $%.4f", bid_quote);+ ImGui::TextColored(MARKET_RED, "Ask Quote: $%.4f", ask_quote);+ ImGui::TextColored(TEXT_DIM, "Spread: $%.4f (%.2f bps)",+ ask_quote - bid_quote,+ (ask_quote - bid_quote) / hft_metrics_.mid_price * 10000);+ }+}++// ============================================================================+// PANEL 9: Meta Learning — MAGENTA THEME+// ============================================================================+void AIQuantLabScreen::render_meta_learning() {+ using namespace theme::colors;+ section_header("META LEARNING", panel_colors::MAGENTA);+ ImGui::TextColored(TEXT_DIM, "Automated model selection and comparison");+ ImGui::Dummy(ImVec2(0, 8));++ static const char* task_types[] = {"Classification", "Regression"};+ config_combo("Task Type", &meta_task_type_, task_types, 2, 130);++ ImGui::Dummy(ImVec2(0, 8));++ if (!meta_run_op_.loading.load()) {+ if (theme::AccentButton("Run Model Selection")) {+ meta_run_op_.loading.store(true);+ json config = {+ {"task_type", task_types[meta_task_type_]},+ {"models", json::array({"LightGBM", "XGBoost", "CatBoost", "RandomForest"})},+ };+ log_status("Running meta-learning selection...", panel_colors::MAGENTA);+ std::thread([this, config]() {+ auto result = QuantLabApi::instance().qlib_meta_run_selection(config).get();+ if (result.success) {+ meta_run_op_.set_result(result.data);+ log_status("Meta-learning complete", SUCCESS);+ } else {+ meta_run_op_.set_error(result.error);+ }+ }).detach();+ }+ } else {+ theme::LoadingSpinner("Running model selection...");+ }++ // Results — show default comparison if no results yet+ ImGui::Dummy(ImVec2(0, 12));+ section_header("MODEL COMPARISON", panel_colors::MAGENTA);++ if (ImGui::BeginTable("##meta_models", 7,+ ImGuiTableFlags_Borders | ImGuiTableFlags_RowBg | ImGuiTableFlags_Resizable)) {+ ImGui::TableSetupColumn("Rank", ImGuiTableColumnFlags_WidthFixed, 40);+ ImGui::TableSetupColumn("Model");+ ImGui::TableSetupColumn("Accuracy");+ ImGui::TableSetupColumn("F1 Score");+ ImGui::TableSetupColumn("AUC-ROC");+ ImGui::TableSetupColumn("MSE");+ ImGui::TableSetupColumn("R2");+ ImGui::TableHeadersRow();++ // Default data (or API results)+ struct ModelResult { const char* name; double acc; double f1; double auc; double mse; double r2; };+ ModelResult defaults[] = {+ {"LightGBM", 0.847, 0.832, 0.891, 0.0234, 0.765},+ {"XGBoost", 0.841, 0.825, 0.885, 0.0241, 0.758},+ {"CatBoost", 0.838, 0.821, 0.882, 0.0247, 0.752},+ {"RandomForest", 0.823, 0.808, 0.869, 0.0268, 0.731},+ };++ for (int i = 0; i < 4; i++) {+ auto& m = defaults[i];+ ImGui::TableNextRow();+ ImGui::TableNextColumn();+ ImGui::TextColored(i == 0 ? panel_colors::MAGENTA : TEXT_SECONDARY, "#%d", i + 1);+ ImGui::TableNextColumn();+ ImGui::TextColored(TEXT_PRIMARY, "%s", m.name);+ ImGui::TableNextColumn();+ ImGui::TextColored(m.acc > 0.84 ? MARKET_GREEN : TEXT_SECONDARY, "%.3f", m.acc);+ ImGui::TableNextColumn();+ ImGui::TextColored(TEXT_SECONDARY, "%.3f", m.f1);+ ImGui::TableNextColumn();+ ImGui::TextColored(TEXT_SECONDARY, "%.3f", m.auc);+ ImGui::TableNextColumn();+ ImGui::TextColored(TEXT_SECONDARY, "%.4f", m.mse);+ ImGui::TableNextColumn();+ ImGui::TextColored(m.r2 > 0.75 ? MARKET_GREEN : TEXT_SECONDARY, "%.3f", m.r2);+ }++ ImGui::EndTable();+ }++ if (!meta_run_op_.error.empty()) theme::ErrorMessage(meta_run_op_.error.c_str());+}++// ============================================================================+// PANEL 10: Rolling Retraining — CYAN THEME+// ============================================================================+void AIQuantLabScreen::render_rolling_retraining() {+ using namespace theme::colors;+ section_header("ROLLING RETRAINING", panel_colors::CYAN);+ ImGui::TextColored(TEXT_DIM, "Scheduled model updates and retraining pipelines");+ ImGui::Dummy(ImVec2(0, 8));++ static const char* frequencies[] = {"Hourly", "Daily", "Weekly"};++ config_input_text("Model Name", rr_model_name_, sizeof(rr_model_name_), 130);+ config_input_int("Window (days)", &rr_window_days_, 130);+ config_combo("Frequency", &rr_frequency_, frequencies, 3, 130);++ ImGui::Dummy(ImVec2(0, 8));++ if (!rr_create_op_.loading.load()) {+ if (theme::AccentButton("Create Schedule")) {+ rr_create_op_.loading.store(true);+ json config = {+ {"model_name", rr_model_name_},+ {"training_window_days", rr_window_days_},+ {"frequency", frequencies[rr_frequency_]},+ };+ log_status("Creating retraining schedule...", panel_colors::CYAN);+ std::thread([this, config]() {+ auto result = QuantLabApi::instance().qlib_rolling_create_schedule(config).get();+ if (result.success) {+ rr_create_op_.set_result(result.data);+ log_status("Schedule created", SUCCESS);+ } else {+ rr_create_op_.set_error(result.error);+ }+ }).detach();+ }+ } else {+ theme::LoadingSpinner("Creating schedule...");+ }++ ImGui::SameLine();+ if (theme::SecondaryButton("List Schedules")) {+ rr_list_op_.loading.store(true);+ std::thread([this]() {+ auto result = QuantLabApi::instance().qlib_rolling_list_schedules().get();+ if (result.success) rr_list_op_.set_result(result.data);+ else rr_list_op_.set_error(result.error);+ }).detach();+ }++ if (!rr_create_op_.error.empty()) theme::ErrorMessage(rr_create_op_.error.c_str());+ if (!rr_list_op_.error.empty()) theme::ErrorMessage(rr_list_op_.error.c_str());+}++// ============================================================================+// PANEL 11: Advanced Models+// ============================================================================+void AIQuantLabScreen::render_advanced_models() {+ using namespace theme::colors;+ section_header("ADVANCED MODELS", panel_colors::BLUE);+ ImGui::TextColored(TEXT_DIM, "LSTM, GRU, and Transformer neural network architectures");+ ImGui::Dummy(ImVec2(0, 8));++ static const char* models[] = {"LSTM", "GRU", "Transformer"};+ config_combo("Architecture", &am_model_idx_, models, 3, 130);++ // Model details+ ImGui::Dummy(ImVec2(0, 8));+ const char* descs[] = {+ "Long Short-Term Memory — excels at capturing long-range temporal dependencies in sequential financial data",+ "Gated Recurrent Unit — lightweight alternative to LSTM with comparable performance and faster training",+ "Transformer — attention-based architecture that captures complex multi-variate relationships",+ };+ ImGui::TextColored(TEXT_SECONDARY, "%s", descs[am_model_idx_]);++ ImGui::Dummy(ImVec2(0, 8));++ if (!am_train_op_.loading.load()) {+ if (theme::AccentButton("Train Model")) {+ am_train_op_.loading.store(true);+ json config = {{"model_type", models[am_model_idx_]}};+ log_status(std::string("Training ") + models[am_model_idx_] + "...", panel_colors::BLUE);+ std::thread([this, config]() {+ auto result = QuantLabApi::instance().qlib_advanced_train(config).get();+ if (result.success) {+ am_train_op_.set_result(result.data);+ log_status("Training complete", SUCCESS);+ } else {+ am_train_op_.set_error(result.error);+ }+ }).detach();+ }+ } else {+ theme::LoadingSpinner("Training neural network...");+ }++ if (am_train_op_.has_result) {+ ImGui::Dummy(ImVec2(0, 8));+ section_header("TRAINING RESULTS", SUCCESS);+ std::lock_guard<std::mutex> lock(am_train_op_.mutex);+ auto& d = am_train_op_.result;+ double loss = d.value("final_loss", 0.0);+ int epochs = d.value("epochs", 0);+ double val_acc = d.value("val_accuracy", 0.0);+ char epochs_buf[16];+ std::snprintf(epochs_buf, sizeof(epochs_buf), "%d", epochs);+ metric_card("Final Loss", loss, "%.6f", TEXT_SECONDARY);+ ImGui::SameLine();+ metric_card("Epochs", epochs_buf, TEXT_PRIMARY);+ ImGui::SameLine();+ metric_card("Val Accuracy", val_acc * 100, "%.1f%%", val_acc > 0.6 ? MARKET_GREEN : WARNING);+ }++ if (!am_train_op_.error.empty()) theme::ErrorMessage(am_train_op_.error.c_str());+}++// ============================================================================+// PANEL 12: GluonTS — GLUON BLUE THEME+// ============================================================================+void AIQuantLabScreen::render_gluonts() {+ using namespace theme::colors;+ section_header("GLUONTS", panel_colors::GLUON_BLUE);+ ImGui::TextColored(TEXT_DIM, "Deep learning time series forecasting");+ ImGui::Dummy(ImVec2(0, 8));++ auto models = get_gluonts_models();+ // Build combo items+ std::vector<const char*> model_names;+ for (auto& m : models) model_names.push_back(m.label);++ config_combo("Model", >s_model_idx_, model_names.data(), (int)model_names.size(), 130);+ config_input_text("Data Path (CSV)", gts_data_path_, sizeof(gts_data_path_), 130);+ config_input_int("Prediction Length", >s_pred_length_, 130);++ static const char* freqs[] = {"H (Hourly)", "D (Daily)", "W (Weekly)", "M (Monthly)"};+ config_combo("Frequency", >s_freq_idx_, freqs, 4, 130);+ config_input_int("Epochs", >s_epochs_, 130);++ ImGui::Dummy(ImVec2(0, 8));++ if (!gts_op_.loading.load()) {+ if (theme::AccentButton("Run Forecast")) {+ gts_op_.loading.store(true);+ static const char* freq_codes[] = {"H", "D", "W", "M"};+ json config = {+ {"model", models[gts_model_idx_].name},+ {"data_path", gts_data_path_},+ {"prediction_length", gts_pred_length_},+ {"freq", freq_codes[gts_freq_idx_]},+ {"epochs", gts_epochs_},+ };+ log_status("Running GluonTS forecast...", panel_colors::GLUON_BLUE);+ std::thread([this, config]() {+ auto result = QuantLabApi::instance().gluonts_forecast(config).get();+ if (result.success) {+ gts_op_.set_result(result.data);+ log_status("Forecast complete", SUCCESS);+ } else {+ gts_op_.set_error(result.error);+ log_status("Forecast failed", ERROR_RED);+ }+ }).detach();+ }+ } else {+ theme::LoadingSpinner("Forecasting...");+ }++ // Forecast results+ if (gts_op_.has_result) {+ ImGui::Dummy(ImVec2(0, 12));+ section_header("FORECAST RESULTS", panel_colors::GLUON_BLUE);++ std::lock_guard<std::mutex> lock(gts_op_.mutex);+ auto& d = gts_op_.result;++ // Metrics+ double mse = d.value("mse", 0.0);+ double mae = d.value("mae", 0.0);+ double mape = d.value("mape", 0.0);+ metric_card("MSE", mse, "%.4f", TEXT_SECONDARY);+ ImGui::SameLine();+ metric_card("MAE", mae, "%.4f", TEXT_SECONDARY);+ ImGui::SameLine();+ metric_card("MAPE", mape * 100, "%.2f%%", mape < 0.1 ? MARKET_GREEN : WARNING);++ // Forecast plot with ImPlot+ if (d.contains("forecast") && d["forecast"].is_array()) {+ ImGui::Dummy(ImVec2(0, 8));+ auto& fc = d["forecast"];+ std::vector<double> values;+ for (auto& v : fc) values.push_back(v.get<double>());++ if (ImPlot::BeginPlot("##forecast_plot", ImVec2(-1, 250))) {+ ImPlot::SetupAxes("Time", "Value");+ ImPlot::PushStyleColor(ImPlotCol_Line, panel_colors::GLUON_BLUE);+ std::vector<double> xs(values.size());+ for (size_t i = 0; i < xs.size(); i++) xs[i] = (double)i;+ ImPlot::PlotLine("Forecast", xs.data(), values.data(), (int)values.size());+ ImPlot::PopStyleColor();+ ImPlot::EndPlot();+ }+ }+ }++ if (!gts_op_.error.empty()) theme::ErrorMessage(gts_op_.error.c_str());+}++// ============================================================================+// PANEL 13: GS Quant — GS PURPLE THEME+// ============================================================================+void AIQuantLabScreen::render_gs_quant() {+ using namespace theme::colors;+ section_header("GS QUANT", panel_colors::GS_PURPLE);+ ImGui::TextColored(TEXT_DIM, "Goldman Sachs-style quantitative analytics");+ ImGui::Dummy(ImVec2(0, 8));++ static const char* modes[] = {+ "Risk Metrics", "Portfolio Analytics", "Greeks",+ "VaR", "Stress Testing", "Backtesting", "Statistics"+ };+ config_combo("Analysis Mode", &gsq_mode_idx_, modes, 7, 130);+ config_input_text("Symbols", gsq_symbols_, sizeof(gsq_symbols_), 130);++ ImGui::Dummy(ImVec2(0, 8));++ if (!gsq_op_.loading.load()) {+ if (theme::AccentButton("Run Analysis")) {+ gsq_op_.loading.store(true);+ json config = {+ {"mode", modes[gsq_mode_idx_]},+ {"symbols", gsq_symbols_},+ };+ log_status("Running GS Quant analysis...", panel_colors::GS_PURPLE);+ std::thread([this, config]() {+ auto result = QuantLabApi::instance().gs_quant_analyze(config).get();+ if (result.success) {+ gsq_op_.set_result(result.data);+ log_status("GS Quant analysis complete", SUCCESS);+ } else {+ gsq_op_.set_error(result.error);+ }+ }).detach();+ }+ } else {+ theme::LoadingSpinner("Analyzing...");+ }++ // Results+ if (gsq_op_.has_result) {+ ImGui::Dummy(ImVec2(0, 12));+ section_header("ANALYSIS RESULTS", panel_colors::GS_PURPLE);++ std::lock_guard<std::mutex> lock(gsq_op_.mutex);+ // Render JSON results in a structured way+ if (gsq_op_.result.is_object()) {+ for (auto& [key, val] : gsq_op_.result.items()) {+ if (val.is_number()) {+ ImGui::TextColored(TEXT_DIM, "%s:", key.c_str());+ ImGui::SameLine(200);+ ImGui::TextColored(TEXT_PRIMARY, "%.4f", val.get<double>());+ } else if (val.is_string()) {+ ImGui::TextColored(TEXT_DIM, "%s:", key.c_str());+ ImGui::SameLine(200);+ ImGui::TextColored(TEXT_SECONDARY, "%s", val.get<std::string>().c_str());+ }+ }+ }+ }++ if (!gsq_op_.error.empty()) theme::ErrorMessage(gsq_op_.error.c_str());+}++// ============================================================================+// PANEL 14: Statsmodels — TEAL THEME+// ============================================================================+void AIQuantLabScreen::render_statsmodels() {+ using namespace theme::colors;+ section_header("STATSMODELS", panel_colors::TEAL);+ ImGui::TextColored(TEXT_DIM, "Statistical time series analysis (ARIMA, SARIMAX, decomposition)");+ ImGui::Dummy(ImVec2(0, 8));++ static const char* analyses[] = {+ "ARIMA", "SARIMAX", "Exp Smoothing", "STL Decompose",+ "ADF Test", "KPSS Test", "ACF", "PACF"+ };+ static const char* data_sources[] = {"Manual Data", "Symbol (Yahoo Finance)"};++ config_combo("Analysis", &sm_analysis_idx_, analyses, 8, 130);+ config_combo("Data Source", &sm_data_source_, data_sources, 2, 130);++ if (sm_data_source_ == 1) {+ config_input_text("Symbol", sm_symbol_, sizeof(sm_symbol_), 130);+ } else {+ ImGui::TextColored(TEXT_DIM, "Data (CSV):");+ ImGui::InputTextMultiline("##sm_data", sm_data_, sizeof(sm_data_), ImVec2(-1, 80));+ }++ // ARIMA params+ if (sm_analysis_idx_ <= 1) {+ ImGui::Dummy(ImVec2(0, 4));+ ImGui::TextColored(TEXT_DIM, "ARIMA Order:");+ ImGui::SameLine(130);+ ImGui::SetNextItemWidth(50);+ ImGui::InputInt("##p", &sm_arima_p_);+ ImGui::SameLine();+ ImGui::SetNextItemWidth(50);+ ImGui::InputInt("##d", &sm_arima_d_);+ ImGui::SameLine();+ ImGui::SetNextItemWidth(50);+ ImGui::InputInt("##q", &sm_arima_q_);+ }++ ImGui::Dummy(ImVec2(0, 8));++ if (!sm_op_.loading.load()) {+ if (theme::AccentButton("Run Analysis")) {+ sm_op_.loading.store(true);+ json config = {+ {"analysis_type", analyses[sm_analysis_idx_]},+ {"data_source", sm_data_source_ == 1 ? "symbol" : "manual"},+ {"symbol", sm_symbol_},+ {"data", sm_data_},+ {"p", sm_arima_p_},+ {"d", sm_arima_d_},+ {"q", sm_arima_q_},+ };+ log_status("Running statsmodels analysis...", panel_colors::TEAL);+ std::thread([this, config]() {+ auto result = QuantLabApi::instance().statsmodels_analyze(config).get();+ if (result.success) {+ sm_op_.set_result(result.data);+ log_status("Analysis complete", SUCCESS);+ } else {+ sm_op_.set_error(result.error);+ }+ }).detach();+ }+ } else {+ theme::LoadingSpinner("Analyzing...");+ }++ // Results+ if (sm_op_.has_result) {+ ImGui::Dummy(ImVec2(0, 12));+ section_header("RESULTS", panel_colors::TEAL);+ std::lock_guard<std::mutex> lock(sm_op_.mutex);+ if (sm_op_.result.is_object()) {+ for (auto& [key, val] : sm_op_.result.items()) {+ if (val.is_number()) {+ ImGui::TextColored(TEXT_DIM, "%s:", key.c_str());+ ImGui::SameLine(200);+ ImGui::TextColored(TEXT_PRIMARY, "%.6f", val.get<double>());+ } else if (val.is_string()) {+ ImGui::TextColored(TEXT_DIM, "%s:", key.c_str());+ ImGui::SameLine(200);+ ImGui::TextColored(TEXT_SECONDARY, "%s", val.get<std::string>().c_str());+ }+ }+ }+ }++ if (!sm_op_.error.empty()) theme::ErrorMessage(sm_op_.error.c_str());+}++// ============================================================================+// PANEL 15: Functime+// ============================================================================+void AIQuantLabScreen::render_functime() {+ using namespace theme::colors;+ section_header("FUNCTIME", ACCENT);+ ImGui::TextColored(TEXT_DIM, "Fast time series forecasting with Functime library");+ ImGui::Dummy(ImVec2(0, 8));++ static const char* models[] = {+ "Naive", "SeasonalNaive", "LinearForecaster",+ "LightGBMForecaster", "AutoARIMA", "AutoETS",+ };+ config_input_text("Symbol", ft_symbol_, sizeof(ft_symbol_), 130);+ config_combo("Model", &ft_model_idx_, models, 6, 130);+ config_input_int("Horizon", &ft_horizon_, 130);++ ImGui::Dummy(ImVec2(0, 8));++ if (!ft_op_.loading.load()) {+ if (theme::AccentButton("Forecast")) {+ ft_op_.loading.store(true);+ json config = {+ {"symbol", ft_symbol_},+ {"model", models[ft_model_idx_]},+ {"horizon", ft_horizon_},+ };+ log_status("Running functime forecast...", ACCENT);+ std::thread([this, config]() {+ auto result = QuantLabApi::instance().functime_forecast(config).get();+ if (result.success) ft_op_.set_result(result.data);+ else ft_op_.set_error(result.error);+ }).detach();+ }+ } else {+ theme::LoadingSpinner("Forecasting...");+ }++ if (ft_op_.has_result) {+ ImGui::Dummy(ImVec2(0, 8));+ section_header("FORECAST", SUCCESS);+ std::lock_guard<std::mutex> lock(ft_op_.mutex);+ auto& d = ft_op_.result;++ // Plot forecast if available+ if (d.contains("forecast") && d["forecast"].is_array()) {+ std::vector<double> values;+ for (auto& v : d["forecast"]) values.push_back(v.get<double>());++ if (ImPlot::BeginPlot("##ft_forecast", ImVec2(-1, 200))) {+ ImPlot::SetupAxes("Step", "Value");+ std::vector<double> xs(values.size());+ for (size_t i = 0; i < xs.size(); i++) xs[i] = (double)i;+ ImPlot::PlotLine("Forecast", xs.data(), values.data(), (int)values.size());+ ImPlot::EndPlot();+ }+ }+ }++ if (!ft_op_.error.empty()) theme::ErrorMessage(ft_op_.error.c_str());+}++// ============================================================================+// PANEL 16: Fortitudo+// ============================================================================+void AIQuantLabScreen::render_fortitudo() {+ using namespace theme::colors;+ section_header("FORTITUDO", ACCENT);+ ImGui::TextColored(TEXT_DIM, "Entropy pooling, portfolio optimization, and risk analysis");+ ImGui::Dummy(ImVec2(0, 8));++ static const char* modes[] = {"Entropy Pooling", "Optimization", "Option Pricing", "Portfolio Risk"};+ config_combo("Mode", &fort_mode_idx_, modes, 4, 130);+ config_input_text("Symbols", fort_symbols_, sizeof(fort_symbols_), 130);++ ImGui::Dummy(ImVec2(0, 8));++ if (!fort_op_.loading.load()) {+ if (theme::AccentButton("Run Analysis")) {+ fort_op_.loading.store(true);+ json config = {+ {"mode", modes[fort_mode_idx_]},+ {"symbols", fort_symbols_},+ };+ log_status("Running Fortitudo analysis...", ACCENT);+ std::thread([this, config]() {+ auto result = QuantLabApi::instance().fortitudo_analyze(config).get();+ if (result.success) fort_op_.set_result(result.data);+ else fort_op_.set_error(result.error);+ }).detach();+ }+ } else {+ theme::LoadingSpinner("Analyzing...");+ }++ if (fort_op_.has_result) {+ ImGui::Dummy(ImVec2(0, 8));+ section_header("RESULTS", SUCCESS);+ std::lock_guard<std::mutex> lock(fort_op_.mutex);+ if (fort_op_.result.is_object()) {+ for (auto& [key, val] : fort_op_.result.items()) {+ if (val.is_number()) {+ ImGui::TextColored(TEXT_DIM, "%s:", key.c_str());+ ImGui::SameLine(200);+ ImGui::TextColored(TEXT_PRIMARY, "%.6f", val.get<double>());+ }+ }+ }+ }++ if (!fort_op_.error.empty()) theme::ErrorMessage(fort_op_.error.c_str());+}++// ============================================================================+// PANEL 17: CFA Quant+// ============================================================================+void AIQuantLabScreen::render_cfa_quant() {+ using namespace theme::colors;+ section_header("CFA QUANT", ACCENT);+ ImGui::TextColored(TEXT_DIM, "CFA-level quantitative financial analysis");+ ImGui::Dummy(ImVec2(0, 8));++ static const char* analyses[] = {+ "Equity Valuation", "Fixed Income", "Derivatives",+ "Portfolio Management", "Corporate Finance", "Economics",+ };+ config_input_text("Symbol", cfa_symbol_, sizeof(cfa_symbol_), 130);+ config_combo("Analysis", &cfa_analysis_idx_, analyses, 6, 130);++ ImGui::Dummy(ImVec2(0, 8));++ if (!cfa_op_.loading.load()) {+ if (theme::AccentButton("Run Analysis")) {+ cfa_op_.loading.store(true);+ json config = {+ {"symbol", cfa_symbol_},+ {"analysis_type", analyses[cfa_analysis_idx_]},+ };+ log_status("Running CFA analysis...", ACCENT);+ std::thread([this, config]() {+ auto result = QuantLabApi::instance().cfa_quant_analyze(config).get();+ if (result.success) cfa_op_.set_result(result.data);+ else cfa_op_.set_error(result.error);+ }).detach();+ }+ } else {+ theme::LoadingSpinner("Analyzing...");+ }++ if (cfa_op_.has_result) {+ ImGui::Dummy(ImVec2(0, 8));+ section_header("RESULTS", SUCCESS);+ std::lock_guard<std::mutex> lock(cfa_op_.mutex);+ if (cfa_op_.result.is_object()) {+ for (auto& [key, val] : cfa_op_.result.items()) {+ if (val.is_number()) {+ ImGui::TextColored(TEXT_DIM, "%s:", key.c_str());+ ImGui::SameLine(200);+ ImGui::TextColored(TEXT_PRIMARY, "%.4f", val.get<double>());+ }+ }+ }+ }++ if (!cfa_op_.error.empty()) theme::ErrorMessage(cfa_op_.error.c_str());+}++// ============================================================================+// PANEL 18: Pattern Intelligence — VisionQuant+// ============================================================================+void AIQuantLabScreen::render_pattern_intelligence() {+ using namespace theme::colors;+ section_header("PATTERN INTELLIGENCE", panel_colors::PURPLE);+ ImGui::TextColored(TEXT_DIM, "VisionQuant K-line pattern recognition and analysis");+ ImGui::Dummy(ImVec2(0, 8));++ static const char* patterns[] = {+ "Doji", "Hammer", "Engulfing", "Morning Star", "Evening Star",+ "Three White Soldiers", "Three Black Crows", "Harami",+ "Piercing Line", "Dark Cloud Cover",+ };+ config_input_text("Symbol", pi_symbol_, sizeof(pi_symbol_), 130);+ config_combo("Pattern", &pi_pattern_idx_, patterns, 10, 130);++ ImGui::Dummy(ImVec2(0, 8));++ // Three action buttons+ if (!pi_search_op_.loading.load()) {+ if (theme::AccentButton("Search Patterns")) {+ pi_search_op_.loading.store(true);+ json config = {+ {"symbol", pi_symbol_},+ {"pattern", patterns[pi_pattern_idx_]},+ };+ log_status("Searching patterns...", panel_colors::PURPLE);+ std::thread([this, config]() {+ auto result = QuantLabApi::instance().visionquant_search(config).get();+ if (result.success) pi_search_op_.set_result(result.data);+ else pi_search_op_.set_error(result.error);+ }).detach();+ }+ } else {+ theme::LoadingSpinner("Searching...");+ }++ ImGui::SameLine();++ if (!pi_score_op_.loading.load()) {+ if (theme::SecondaryButton("Score Pattern")) {+ pi_score_op_.loading.store(true);+ json config = {+ {"symbol", pi_symbol_},+ {"pattern", patterns[pi_pattern_idx_]},+ };+ std::thread([this, config]() {+ auto result = QuantLabApi::instance().visionquant_score(config).get();+ if (result.success) pi_score_op_.set_result(result.data);+ else pi_score_op_.set_error(result.error);+ }).detach();+ }+ } else {+ theme::LoadingSpinner("Scoring...");+ }++ ImGui::SameLine();++ if (!pi_backtest_op_.loading.load()) {+ if (theme::SecondaryButton("Backtest Pattern")) {+ pi_backtest_op_.loading.store(true);+ json config = {+ {"symbol", pi_symbol_},+ {"pattern", patterns[pi_pattern_idx_]},+ };+ std::thread([this, config]() {+ auto result = QuantLabApi::instance().visionquant_backtest(config).get();+ if (result.success) pi_backtest_op_.set_result(result.data);+ else pi_backtest_op_.set_error(result.error);+ }).detach();+ }+ } else {+ theme::LoadingSpinner("Backtesting...");+ }++ // Search results+ if (pi_search_op_.has_result) {+ ImGui::Dummy(ImVec2(0, 8));+ section_header("PATTERN MATCHES", panel_colors::PURPLE);+ std::lock_guard<std::mutex> lock(pi_search_op_.mutex);+ if (pi_search_op_.result.contains("matches") && pi_search_op_.result["matches"].is_array()) {+ for (auto& m : pi_search_op_.result["matches"]) {+ ImGui::TextColored(TEXT_PRIMARY, "%s at %s",+ m.value("pattern", "").c_str(),+ m.value("date", "").c_str());+ ImGui::SameLine(300);+ double conf = m.value("confidence", 0.0);+ ImGui::TextColored(conf > 0.8 ? MARKET_GREEN : WARNING, "%.1f%%", conf * 100);+ }+ }+ }++ // Score results+ if (pi_score_op_.has_result) {+ ImGui::Dummy(ImVec2(0, 8));+ section_header("PATTERN SCORE", panel_colors::PURPLE);+ std::lock_guard<std::mutex> lock(pi_score_op_.mutex);+ auto& d = pi_score_op_.result;+ double score = d.value("score", 0.0);+ double reliability = d.value("reliability", 0.0);+ metric_card("Score", score, "%.2f", score > 0.7 ? MARKET_GREEN : WARNING);+ ImGui::SameLine();+ metric_card("Reliability", reliability * 100, "%.1f%%", reliability > 0.6 ? MARKET_GREEN : WARNING);+ }++ // Backtest results+ if (pi_backtest_op_.has_result) {+ ImGui::Dummy(ImVec2(0, 8));+ section_header("PATTERN BACKTEST", panel_colors::PURPLE);+ std::lock_guard<std::mutex> lock(pi_backtest_op_.mutex);+ auto& d = pi_backtest_op_.result;+ double win_rate = d.value("win_rate", 0.0);+ double avg_return = d.value("avg_return", 0.0);+ int occurrences = d.value("occurrences", 0);+ metric_card("Win Rate", win_rate * 100, "%.1f%%", win_rate > 0.5 ? MARKET_GREEN : WARNING);+ ImGui::SameLine();+ metric_card("Avg Return", avg_return * 100, "%.2f%%", avg_return > 0 ? MARKET_GREEN : MARKET_RED);+ ImGui::SameLine();+ char occ_buf[16];+ std::snprintf(occ_buf, sizeof(occ_buf), "%d", occurrences);+ metric_card("Occurrences", occ_buf, TEXT_PRIMARY);+ }++ if (!pi_search_op_.error.empty()) theme::ErrorMessage(pi_search_op_.error.c_str());+ if (!pi_score_op_.error.empty()) theme::ErrorMessage(pi_score_op_.error.c_str());+ if (!pi_backtest_op_.error.empty()) theme::ErrorMessage(pi_backtest_op_.error.c_str());+}++} // namespace fincept::ai_quant_labdiff --git a/fincept-cpp/src/screens/ai_quant_lab/ai_quant_lab_screen.h b/fincept-cpp/src/screens/ai_quant_lab/ai_quant_lab_screen.hnew file mode 100644index 000000000..b6afc5767--- /dev/null+++ b/fincept-cpp/src/screens/ai_quant_lab/ai_quant_lab_screen.h@@ -0,0 +1,215 @@+#pragma once+// AI Quant Lab Screen — 18-module quantitative research platform+// Layout: [Left: Module sidebar] [Center: Active panel] [Right: System status]+// Mirrors the Tauri AIQuantLabTab with all sub-panels++#include "ai_quant_lab_types.h"+#include "ai_quant_lab_api.h"+#include <imgui.h>+#include <set>++namespace fincept::ai_quant_lab {++class AIQuantLabScreen {+public:+ void render();++private:+ void init();++ // ── Layout ──+ void render_sidebar(float height);+ void render_content(float width, float height);+ void render_status_panel(float height);++ // ── 18 Panel renderers ──+ void render_factor_discovery();+ void render_model_library();+ void render_backtesting();+ void render_live_signals();+ void render_functime();+ void render_fortitudo();+ void render_statsmodels();+ void render_cfa_quant();+ void render_deep_agent();+ void render_rl_trading();+ void render_online_learning();+ void render_hft();+ void render_meta_learning();+ void render_rolling_retraining();+ void render_advanced_models();+ void render_gluonts();+ void render_gs_quant();+ void render_pattern_intelligence();++ // ── UI Helpers ──+ void metric_card(const char* label, const char* value, ImVec4 color);+ void metric_card(const char* label, double value, const char* fmt, ImVec4 color);+ void progress_bar(float fraction, const char* label = nullptr);+ bool config_input_text(const char* label, char* buf, int buf_size, float width = 200.0f);+ bool config_input_float(const char* label, float* val, float width = 120.0f);+ bool config_input_int(const char* label, int* val, float width = 120.0f);+ bool config_combo(const char* label, int* current, const char* const* items, int count, float width = 150.0f);+ void section_header(const char* title, ImVec4 color);+ void status_badge(const char* text, ImVec4 bg_color, ImVec4 text_color);++ // ── State ──+ bool initialized_ = false;+ ViewMode active_view_ = ViewMode::FactorDiscovery;+ SystemStatus system_status_ = SystemStatus::Idle;+ bool left_panel_visible_ = true;+ bool right_panel_visible_ = true;+ std::vector<ModuleItem> modules_;+ std::set<ModuleCategory> expanded_categories_;++ // ── Factor Discovery state ──+ char fd_task_desc_[512] = "Find alpha factors for US equity market";+ char fd_api_key_[256] = "";+ int fd_market_idx_ = 0; // 0=US, 1=CN, 2=CRYPTO+ int fd_budget_ = 10;+ std::string fd_task_id_;+ AsyncOp fd_op_;+ std::vector<DiscoveredFactor> fd_factors_;+ bool fd_polling_ = false;+ double fd_last_poll_ = 0;++ // ── Model Library state ──+ int ml_filter_idx_ = 0; // 0=all, 1=tree, 2=neural, 3=linear, 4=ensemble+ AsyncOp ml_list_op_;+ std::vector<QlibModel> ml_models_;+ int ml_selected_ = -1;+ char ml_instruments_[128] = "csi300";+ char ml_start_date_[16] = "2020-01-01";+ char ml_end_date_[16] = "2024-01-01";+ AsyncOp ml_train_op_;++ // ── Backtesting state ──+ int bt_strategy_idx_ = 0; // topk_dropout, weight_base, enhanced_indexing+ char bt_instruments_[128] = "csi300";+ char bt_start_[16] = "2020-01-01";+ char bt_end_[16] = "2024-01-01";+ float bt_capital_ = 1000000.0f;+ char bt_benchmark_[32] = "SH000300";+ float bt_commission_ = 0.001f;+ float bt_slippage_ = 0.001f;+ AsyncOp bt_op_;++ // ── Live Signals state ──+ int ls_model_idx_ = 0; // LightGBM, XGBoost, LSTM, Transformer+ int ls_refresh_sec_ = 30;+ bool ls_streaming_ = false;+ double ls_last_refresh_ = 0;+ int ls_filter_idx_ = 0; // 0=ALL, 1=BUY, 2=SELL+ AsyncOp ls_op_;+ std::vector<SignalEntry> ls_signals_;++ // ── Deep Agent state ──+ int da_agent_idx_ = 0;+ char da_query_[1024] = "";+ int da_phase_ = 0; // 0=idle, 1=planning, 2=executing, 3=synthesizing, 4=done+ std::vector<AgentStep> da_steps_;+ int da_current_step_ = 0;+ AsyncOp da_op_;+ std::string da_plan_text_;+ std::string da_synthesis_;++ // ── RL Trading state ──+ int rl_algo_idx_ = 0;+ int rl_phase_ = 0; // 0=config, 1=env_created, 2=training, 3=evaluating, 4=done+ char rl_tickers_[128] = "AAPL,MSFT,GOOGL";+ char rl_start_[16] = "2020-01-01";+ char rl_end_[16] = "2024-01-01";+ float rl_initial_cash_ = 100000.0f;+ float rl_commission_ = 0.001f;+ int rl_action_space_ = 0; // 0=continuous, 1=discrete+ int rl_timesteps_ = 100000;+ float rl_learning_rate_ = 0.0003f;+ AsyncOp rl_op_;++ // ── Online Learning state ──+ int ol_model_idx_ = 0;+ bool ol_live_mode_ = false;+ double ol_last_update_ = 0;+ int ol_drift_strategy_ = 0; // 0=retrain, 1=adaptive+ AsyncOp ol_create_op_;+ AsyncOp ol_train_op_;+ AsyncOp ol_perf_op_;++ // ── HFT state ──+ bool hft_live_ = false;+ double hft_last_update_ = 0;+ std::vector<OrderLevel> hft_bids_;+ std::vector<OrderLevel> hft_asks_;+ MicrostructureMetrics hft_metrics_;+ char hft_symbol_[32] = "AAPL";+ float hft_spread_target_ = 0.02f;+ float hft_position_limit_ = 1000.0f;++ // ── Meta Learning state ──+ AsyncOp meta_list_op_;+ AsyncOp meta_run_op_;+ int meta_task_type_ = 0; // 0=classification, 1=regression++ // ── Rolling Retraining state ──+ AsyncOp rr_list_op_;+ AsyncOp rr_create_op_;+ char rr_model_name_[128] = "LightGBM_v1";+ int rr_window_days_ = 252;+ int rr_frequency_ = 1; // 0=hourly, 1=daily, 2=weekly++ // ── Advanced Models state ──+ AsyncOp am_list_op_;+ AsyncOp am_train_op_;+ int am_model_idx_ = 0; // 0=LSTM, 1=GRU, 2=Transformer++ // ── GluonTS state ──+ int gts_model_idx_ = 0;+ char gts_data_path_[512] = "";+ int gts_pred_length_ = 30;+ int gts_freq_idx_ = 1; // 0=H, 1=D, 2=W, 3=M+ int gts_epochs_ = 50;+ AsyncOp gts_op_;++ // ── GS Quant state ──+ int gsq_mode_idx_ = 0;+ char gsq_symbols_[256] = "AAPL,MSFT,GOOGL";+ AsyncOp gsq_op_;++ // ── Statsmodels state ──+ int sm_analysis_idx_ = 0;+ int sm_data_source_ = 0; // 0=manual, 1=symbol+ char sm_symbol_[32] = "AAPL";+ char sm_data_[2048] = "";+ int sm_arima_p_ = 1, sm_arima_d_ = 1, sm_arima_q_ = 1;+ AsyncOp sm_op_;++ // ── Functime state ──+ char ft_symbol_[32] = "AAPL";+ int ft_horizon_ = 30;+ int ft_model_idx_ = 0;+ AsyncOp ft_op_;++ // ── Fortitudo state ──+ int fort_mode_idx_ = 0;+ char fort_symbols_[256] = "AAPL,MSFT,GOOGL,AMZN";+ AsyncOp fort_op_;++ // ── CFA Quant state ──+ char cfa_symbol_[32] = "AAPL";+ int cfa_analysis_idx_ = 0;+ AsyncOp cfa_op_;++ // ── Pattern Intelligence state ──+ char pi_symbol_[32] = "AAPL";+ int pi_pattern_idx_ = 0;+ AsyncOp pi_search_op_;+ AsyncOp pi_score_op_;+ AsyncOp pi_backtest_op_;++ // ── Status log ──+ struct LogEntry { double time; std::string msg; ImVec4 color; };+ std::vector<LogEntry> status_log_;+ void log_status(const std::string& msg, ImVec4 color = {0.72f, 0.72f, 0.75f, 1.0f});+};++} // namespace fincept::ai_quant_labdiff --git a/fincept-cpp/src/screens/ai_quant_lab/ai_quant_lab_types.h b/fincept-cpp/src/screens/ai_quant_lab/ai_quant_lab_types.hnew file mode 100644index 000000000..a8f2485a7--- /dev/null+++ b/fincept-cpp/src/screens/ai_quant_lab/ai_quant_lab_types.h@@ -0,0 +1,336 @@+#pragma once+// AI Quant Lab Types — Shared data types for the 18-module quant research platform+// Mirrors the Tauri AIQuantLabTab's module definitions and state types++#include <string>+#include <vector>+#include <map>+#include <mutex>+#include <atomic>+#include <future>+#include <nlohmann/json.hpp>++namespace fincept::ai_quant_lab {++using json = nlohmann::json;++// ============================================================================+// View modes — one per sub-panel (matches Tauri ViewMode type)+// ============================================================================+enum class ViewMode {+ FactorDiscovery,+ ModelLibrary,+ Backtesting,+ LiveSignals,+ Functime,+ Fortitudo,+ Statsmodels,+ CFAQuant,+ DeepAgent,+ RLTrading,+ OnlineLearning,+ HFT,+ MetaLearning,+ RollingRetraining,+ AdvancedModels,+ GluonTS,+ GSQuant,+ PatternIntelligence,+};++// ============================================================================+// Module categories (matches Tauri's 4 categories)+// ============================================================================+enum class ModuleCategory {+ Core,+ AIML,+ Advanced,+ Analytics,+};++inline const char* category_label(ModuleCategory c) {+ switch (c) {+ case ModuleCategory::Core: return "CORE";+ case ModuleCategory::AIML: return "AI / ML";+ case ModuleCategory::Advanced: return "ADVANCED";+ case ModuleCategory::Analytics: return "ANALYTICS";+ }+ return "";+}++// ============================================================================+// Module definition — matches Tauri's ModuleItem interface+// ============================================================================+struct ModuleItem {+ ViewMode view;+ const char* label;+ const char* description;+ ModuleCategory category;+};++inline std::vector<ModuleItem> get_modules() {+ return {+ // Core+ {ViewMode::FactorDiscovery, "Factor Discovery", "RD-Agent automated factor mining", ModuleCategory::Core},+ {ViewMode::ModelLibrary, "Model Library", "Microsoft Qlib ML models", ModuleCategory::Core},+ {ViewMode::Backtesting, "Backtesting", "Qlib strategy backtesting engine", ModuleCategory::Core},+ {ViewMode::LiveSignals, "Live Signals", "Real-time model predictions", ModuleCategory::Core},+ // AI/ML+ {ViewMode::DeepAgent, "Deep Agent", "LLM-powered autonomous research", ModuleCategory::AIML},+ {ViewMode::RLTrading, "RL Trading", "Reinforcement learning strategies", ModuleCategory::AIML},+ {ViewMode::OnlineLearning, "Online Learning", "Continuous model adaptation", ModuleCategory::AIML},+ {ViewMode::MetaLearning, "Meta Learning", "Automated model selection", ModuleCategory::AIML},+ {ViewMode::AdvancedModels, "Advanced Models", "LSTM, GRU, Transformer networks", ModuleCategory::AIML},+ // Advanced+ {ViewMode::HFT, "HFT Analytics", "Order book & microstructure", ModuleCategory::Advanced},+ {ViewMode::RollingRetraining, "Rolling Retraining", "Scheduled model updates", ModuleCategory::Advanced},+ {ViewMode::PatternIntelligence,"Pattern Intelligence", "VisionQuant K-line recognition", ModuleCategory::Advanced},+ // Analytics+ {ViewMode::GluonTS, "GluonTS", "Deep learning time series", ModuleCategory::Analytics},+ {ViewMode::GSQuant, "GS Quant", "Goldman Sachs-style analytics", ModuleCategory::Analytics},+ {ViewMode::Statsmodels, "Statsmodels", "ARIMA, SARIMAX, decomposition", ModuleCategory::Analytics},+ {ViewMode::Functime, "Functime", "Fast time series forecasting", ModuleCategory::Analytics},+ {ViewMode::Fortitudo, "Fortitudo", "Entropy pooling & optimization", ModuleCategory::Analytics},+ {ViewMode::CFAQuant, "CFA Quant", "CFA-level quantitative analysis", ModuleCategory::Analytics},+ };+}++// ============================================================================+// System status — matches Tauri's SystemStatus state machine+// ============================================================================+enum class SystemStatus {+ Idle,+ Loading,+ Ready,+ Error,+};++// ============================================================================+// Async operation state — tracks a single async task (API call / Python exec)+// ============================================================================+struct AsyncOp {+ std::atomic<bool> loading{false};+ json result;+ std::string error;+ bool has_result = false;+ std::mutex mutex;++ void clear() {+ std::lock_guard<std::mutex> lock(mutex);+ result = json();+ error.clear();+ has_result = false;+ }++ void set_result(const json& data) {+ std::lock_guard<std::mutex> lock(mutex);+ result = data;+ has_result = true;+ error.clear();+ loading.store(false);+ }++ void set_error(const std::string& err) {+ std::lock_guard<std::mutex> lock(mutex);+ error = err;+ has_result = false;+ loading.store(false);+ }+};++// ============================================================================+// Factor Discovery types+// ============================================================================+struct DiscoveredFactor {+ std::string name;+ std::string code;+ double ic = 0.0;+ double sharpe = 0.0;+ double annual_return = 0.0;+ std::string description;+};++// ============================================================================+// Model Library types+// ============================================================================+struct QlibModel {+ std::string name;+ std::string type; // tree_based, neural_network, linear, ensemble+ std::string description;+ std::vector<std::string> features;+ std::vector<std::string> use_cases;+};++// ============================================================================+// Live Signals types+// ============================================================================+struct SignalEntry {+ std::string symbol;+ std::string signal; // BUY, SELL, HOLD+ double score = 0.0;+ double price = 0.0;+ double confidence = 0.0;+ std::string model;+ std::string timestamp;+};++// ============================================================================+// Deep Agent types+// ============================================================================+enum class AgentType {+ Research,+ StrategyBuilder,+ PortfolioManager,+ RiskAnalyzer,+ General,+};++inline const char* agent_type_label(AgentType t) {+ switch (t) {+ case AgentType::Research: return "Research";+ case AgentType::StrategyBuilder: return "Strategy Builder";+ case AgentType::PortfolioManager: return "Portfolio Manager";+ case AgentType::RiskAnalyzer: return "Risk Analyzer";+ case AgentType::General: return "General";+ }+ return "";+}++struct AgentStep {+ int index = 0;+ std::string description;+ std::string status; // pending, running, completed, failed+ std::string result;+};++// ============================================================================+// RL Trading types+// ============================================================================+enum class RLAlgorithm {+ PPO, A2C, DQN, SAC, TD3,+};++inline const char* rl_algo_label(RLAlgorithm a) {+ switch (a) {+ case RLAlgorithm::PPO: return "PPO";+ case RLAlgorithm::A2C: return "A2C";+ case RLAlgorithm::DQN: return "DQN";+ case RLAlgorithm::SAC: return "SAC";+ case RLAlgorithm::TD3: return "TD3";+ }+ return "";+}++// ============================================================================+// HFT Order Book types+// ============================================================================+struct OrderLevel {+ double price = 0.0;+ double size = 0.0;+ int orders = 0;+};++struct MicrostructureMetrics {+ double depth_imbalance = 0.0;+ double vwap_bid = 0.0;+ double vwap_ask = 0.0;+ double toxicity_score = 0.0;+ double spread = 0.0;+ double mid_price = 0.0;+};++// ============================================================================+// GluonTS model types+// ============================================================================+struct GluonTSModel {+ const char* name;+ const char* label;+ const char* category; // "deep_learning" or "baseline"+};++inline std::vector<GluonTSModel> get_gluonts_models() {+ return {+ {"deepar", "DeepAR", "deep_learning"},+ {"tft", "TFT", "deep_learning"},+ {"wavenet", "WaveNet", "deep_learning"},+ {"patchtst", "PatchTST", "deep_learning"},+ {"nbeats", "N-BEATS", "deep_learning"},+ {"nhits", "N-HiTS", "deep_learning"},+ {"informer", "Informer", "deep_learning"},+ {"autoformer","Autoformer", "deep_learning"},+ {"fedformer", "FEDformer", "deep_learning"},+ {"naive", "Naive (Baseline)","baseline"},+ {"seasonal", "Seasonal Naive", "baseline"},+ {"ets", "ETS", "baseline"},+ };+}++// ============================================================================+// GS Quant analysis modes+// ============================================================================+enum class GSQuantMode {+ RiskMetrics,+ PortfolioAnalytics,+ Greeks,+ VaR,+ StressTesting,+ Backtesting,+ Statistics,+};++inline const char* gs_quant_mode_label(GSQuantMode m) {+ switch (m) {+ case GSQuantMode::RiskMetrics: return "Risk Metrics";+ case GSQuantMode::PortfolioAnalytics: return "Portfolio Analytics";+ case GSQuantMode::Greeks: return "Greeks";+ case GSQuantMode::VaR: return "VaR";+ case GSQuantMode::StressTesting: return "Stress Testing";+ case GSQuantMode::Backtesting: return "Backtesting";+ case GSQuantMode::Statistics: return "Statistics";+ }+ return "";+}++// ============================================================================+// Statsmodels analysis types+// ============================================================================+enum class StatsAnalysis {+ ARIMA, SARIMAX, ExpSmoothing, STLDecompose,+ ADFTest, KPSSTest, ACF, PACF,+};++inline const char* stats_analysis_label(StatsAnalysis a) {+ switch (a) {+ case StatsAnalysis::ARIMA: return "ARIMA";+ case StatsAnalysis::SARIMAX: return "SARIMAX";+ case StatsAnalysis::ExpSmoothing: return "Exp Smoothing";+ case StatsAnalysis::STLDecompose: return "STL Decompose";+ case StatsAnalysis::ADFTest: return "ADF Test";+ case StatsAnalysis::KPSSTest: return "KPSS Test";+ case StatsAnalysis::ACF: return "ACF";+ case StatsAnalysis::PACF: return "PACF";+ }+ return "";+}++// ============================================================================+// Fortitudo modes+// ============================================================================+enum class FortitudoMode {+ EntropyPooling,+ Optimization,+ OptionPricing,+ PortfolioRisk,+};++inline const char* fortitudo_mode_label(FortitudoMode m) {+ switch (m) {+ case FortitudoMode::EntropyPooling: return "Entropy Pooling";+ case FortitudoMode::Optimization: return "Optimization";+ case FortitudoMode::OptionPricing: return "Option Pricing";+ case FortitudoMode::PortfolioRisk: return "Portfolio Risk";+ }+ return "";+}++} // namespace fincept::ai_quant_labdiff --git a/fincept-cpp/src/screens/algo_trading/algo_service.cpp b/fincept-cpp/src/screens/algo_trading/algo_service.cppindex 726e25e52..0c9040285 100644--- a/fincept-cpp/src/screens/algo_trading/algo_service.cpp+++ b/fincept-cpp/src/screens/algo_trading/algo_service.cpp@@ -1,6 +1,7 @@#include "algo_service.h"#include "storage/database.h"#include "python/python_runner.h"+#include "storage/cache_service.h"#include "trading/unified_trading.h"#include "core/logger.h"#include <nlohmann/json.hpp>@@ -483,11 +484,22 @@ std::vector<ScanResult> AlgoService::run_scan(const std::string& conditions_json"--db", get_db_path()};- auto py_result = python::execute("algo_trading/scanner_engine.py", args);- if (!py_result.success) return results;+ auto& cache = CacheService::instance();+ std::string scan_key = CacheService::make_key("market-quotes", "algo-scan",+ syms.substr(0, std::min((size_t)48, syms.size())) + "_" + timeframe);++ std::string scan_out;+ auto cached_scan = cache.get(scan_key);+ if (cached_scan && !cached_scan->empty()) { scan_out = *cached_scan; }+ else {+ auto py_result = python::execute("algo_trading/scanner_engine.py", args);+ if (!py_result.success) return results;+ scan_out = py_result.output;+ cache.set(scan_key, scan_out, "market-quotes", CacheTTL::FIVE_MIN);+ }try {- auto j = json::parse(py_result.output);+ auto j = json::parse(scan_out);for (auto& r : j.value("results", json::array())) {ScanResult sr;sr.symbol = r.value("symbol", "");diff --git a/fincept-cpp/src/screens/algo_trading/algo_trading_screen.cpp b/fincept-cpp/src/screens/algo_trading/algo_trading_screen.cppindex 9dd8d65c8..0cceb7424 100644--- a/fincept-cpp/src/screens/algo_trading/algo_trading_screen.cpp+++ b/fincept-cpp/src/screens/algo_trading/algo_trading_screen.cpp@@ -630,11 +630,21 @@ void AlgoTradingScreen::render_library(float w, float h) {ImGui::InputText("##clone_name", custom_name_, sizeof(custom_name_));ImGui::SameLine();- if (ImGui::Button("Validate Syntax")) {- std::string err;- bool valid = AlgoService::instance().validate_python_syntax(custom_code_, err);- syntax_error_ = valid ? "" : err;- status_msg_ = valid ? "Syntax OK" : "Syntax error";+ if (validating_syntax_.load()) {+ ImGui::Button("Validating...");+ } else if (ImGui::Button("Validate Syntax")) {+ validating_syntax_.store(true);+ std::string code_copy(custom_code_);+ std::thread([this, code_copy]() {+ std::string err;+ bool valid = AlgoService::instance().validate_python_syntax(code_copy, err);+ {+ std::lock_guard<std::mutex> lock(data_mutex_);+ syntax_error_ = valid ? "" : err;+ status_msg_ = valid ? "Syntax OK" : "Syntax error";+ }+ validating_syntax_.store(false);+ }).detach();}ImGui::SameLine();if (ImGui::Button("Save as Custom")) {diff --git a/fincept-cpp/src/screens/algo_trading/algo_trading_screen.h b/fincept-cpp/src/screens/algo_trading/algo_trading_screen.hindex c2aed5956..a4b3dfe47 100644--- a/fincept-cpp/src/screens/algo_trading/algo_trading_screen.h+++ b/fincept-cpp/src/screens/algo_trading/algo_trading_screen.h@@ -66,6 +66,7 @@ private:char custom_name_[128] = "";char custom_desc_[256] = "";std::string syntax_error_;+ std::atomic<bool> validating_syntax_{false};// --- Scanner state ---char scan_symbols_[512] = "";diff --git a/fincept-cpp/src/screens/backtesting/backtesting_data.cpp b/fincept-cpp/src/screens/backtesting/backtesting_data.cppindex cd737fb2d..f0715b252 100644--- a/fincept-cpp/src/screens/backtesting/backtesting_data.cpp+++ b/fincept-cpp/src/screens/backtesting/backtesting_data.cpp@@ -1,5 +1,6 @@#include "backtesting_data.h"#include "python/python_runner.h"+#include "storage/cache_service.h"#include "core/logger.h"#include <thread>#include <nlohmann/json.hpp>@@ -11,7 +12,11 @@ using json = nlohmann::json;void BacktestData::run(const std::string& provider_dir,const std::string& command,const std::string& args_json) {- if (loading_.load()) return;+ if (loading_.load()) {+ LOG_WARN("BacktestData", "Already running, ignoring new request");+ return;+ }+ LOG_INFO("BacktestData", "Starting: provider=%s command=%s", provider_dir.c_str(), command.c_str());loading_.store(true);{std::lock_guard<std::mutex> lock(mutex_);@@ -24,12 +29,29 @@ void BacktestData::run(const std::string& provider_dir,std::string script = "Analytics/backtesting/" + provider_dir + "/" + provider_dir + "_provider.py";std::thread([this, script, command, args_json]() {+ auto& cache = CacheService::instance();+ std::string cache_key = CacheService::make_key("reference", "backtest",+ script + "_" + command + "_" + args_json.substr(0, std::min((size_t)64, args_json.size())));++ auto cached = cache.get(cache_key);+ if (cached && !cached->empty()) {+ LOG_INFO("BacktestData", "Cache hit for: %s", cache_key.c_str());+ std::lock_guard<std::mutex> lock(mutex_);+ parse_result(*cached);+ loading_.store(false);+ return;+ }+std::vector<std::string> args = {command, args_json};auto py_result = python::execute(script, args);{std::lock_guard<std::mutex> lock(mutex_);if (py_result.success) {+ LOG_INFO("BacktestData", "Script completed successfully, parsing result");parse_result(py_result.output);+ if (has_result_ && !py_result.output.empty()) {+ cache.set(cache_key, py_result.output, "reference", CacheTTL::FIFTEEN_MIN);+ }} else {error_ = py_result.error.empty()? "Script failed (exit " + std::to_string(py_result.exit_code) + ")"diff --git a/fincept-cpp/src/screens/backtesting/backtesting_screen.cpp b/fincept-cpp/src/screens/backtesting/backtesting_screen.cppindex a42530d54..405633fb4 100644--- a/fincept-cpp/src/screens/backtesting/backtesting_screen.cpp+++ b/fincept-cpp/src/screens/backtesting/backtesting_screen.cpp@@ -1,6 +1,7 @@#include "backtesting_screen.h"#include "backtesting_constants.h"#include "ui/theme.h"+#include "core/logger.h"#include <imgui.h>#include <cstdio>#include <cstring>@@ -78,6 +79,7 @@ void BacktestingScreen::render_top_nav() {for (auto& p : provider_list()) {if (ProviderTab(p.display_name, provider_color(p.slug), selected_provider_ == p.slug)) {selected_provider_ = p.slug;+ LOG_INFO("Backtesting", "Provider switched to: %s", p.display_name);// Reset to first available commandauto cmds = provider_commands(selected_provider_);if (!cmds.empty()) active_command_ = cmds[0];@@ -2055,12 +2057,14 @@ void BacktestingScreen::pickup_result() {error_msg_.clear();status_ = "Data loaded";status_time_ = ImGui::GetTime();+ LOG_INFO("Backtesting", "Result received for command: %s", command_label(active_command_));} else if (!data_.error().empty()) {has_error_ = true;error_msg_ = data_.error();result_ = json();status_ = "Error: " + data_.error();status_time_ = ImGui::GetTime();+ LOG_ERROR("Backtesting", "Command failed: %s — %s", command_label(active_command_), error_msg_.c_str());}data_.clear();}@@ -2073,6 +2077,10 @@ void BacktestingScreen::execute_command() {std::string py_command = command_to_python(selected_provider_, active_command_);std::string args_json = build_args_json();+ LOG_INFO("Backtesting", "Executing: provider=%s command=%s py_cmd=%s",+ info.display_name, command_label(active_command_), py_command.c_str());+ LOG_DEBUG("Backtesting", "Args JSON: %s", args_json.c_str());+result_ = json();has_error_ = false;error_msg_.clear();diff --git a/fincept-cpp/src/screens/code_editor/code_editor_screen.cpp b/fincept-cpp/src/screens/code_editor/code_editor_screen.cppindex 5771355c9..9e00f8aea 100644--- a/fincept-cpp/src/screens/code_editor/code_editor_screen.cpp+++ b/fincept-cpp/src/screens/code_editor/code_editor_screen.cpp@@ -1,6 +1,7 @@#include "code_editor_screen.h"#include "notebook_io.h"#include "ui/theme.h"+#include "ui/yoga_helpers.h"#include "core/config.h"#include "python/python_runner.h"#include <imgui.h>@@ -698,20 +699,8 @@ void CodeEditorScreen::render() {// Handle keyboard navigation (point 17)handle_keyboard_navigation();- 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("##code_editor_screen", nullptr,- ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_NoResize | ImGuiWindowFlags_NoMove |- ImGuiWindowFlags_NoCollapse | ImGuiWindowFlags_NoDocking |- ImGuiWindowFlags_NoBringToFrontOnFocus);+ ui::ScreenFrame frame("##code_editor_screen", ImVec2(0, 0), BG_DARK);+ if (!frame.begin()) { frame.end(); return; }render_tab_bar();render_toolbar();@@ -721,9 +710,7 @@ void CodeEditorScreen::render() {render_file_dialog();render_pip_dialog();- ImGui::End();- ImGui::PopStyleVar();- ImGui::PopStyleColor();+ frame.end();} catch (const std::exception& e) {file_log("FATAL EXCEPTION in render(): " + std::string(e.what()));@@ -739,10 +726,10 @@ void CodeEditorScreen::render_tab_bar() {using namespace theme::colors;ImGui::PushStyleColor(ImGuiCol_ChildBg, BG_DARKEST);- ImGui::BeginChild("##ce_tabbar", ImVec2(0, 28), ImGuiChildFlags_Borders);+ ImGui::BeginChild("##ce_tabbar", ImVec2(0, 26), ImGuiChildFlags_Borders);- ImGui::SetCursorPos(ImVec2(4, 3));- ImGui::PushStyleVar(ImGuiStyleVar_FramePadding, ImVec2(8, 3));+ ImGui::SetCursorPos(ImVec2(4, 2));+ ImGui::PushStyleVar(ImGuiStyleVar_FramePadding, ImVec2(8, 2));ImGui::PushStyleVar(ImGuiStyleVar_ItemSpacing, ImVec2(2, 0));int close_idx = -1;@@ -804,8 +791,9 @@ void CodeEditorScreen::render_toolbar() {using namespace theme::colors;ImGui::PushStyleColor(ImGuiCol_ChildBg, BG_DARKEST);- ImGui::BeginChild("##ce_toolbar", ImVec2(0, 42), ImGuiChildFlags_Borders);- ImGui::SetCursorPos(ImVec2(12, 7));+ ImGui::BeginChild("##ce_toolbar", ImVec2(0, 34), ImGuiChildFlags_Borders);+ ImGui::SetCursorPos(ImVec2(8, 4));+ ImGui::PushStyleVar(ImGuiStyleVar_FramePadding, ImVec2(6, 3));// File actionsif (theme::SecondaryButton("NEW")) { new_tab(); }@@ -913,6 +901,7 @@ void CodeEditorScreen::render_toolbar() {}}+ ImGui::PopStyleVar(); // FramePaddingImGui::EndChild();ImGui::PopStyleColor();}@@ -924,8 +913,8 @@ void CodeEditorScreen::render_search_bar() {using namespace theme::colors;ImGui::PushStyleColor(ImGuiCol_ChildBg, BG_PANEL);- ImGui::BeginChild("##ce_search", ImVec2(0, 32), ImGuiChildFlags_Borders);- ImGui::SetCursorPos(ImVec2(12, 5));+ ImGui::BeginChild("##ce_search", ImVec2(0, 28), ImGuiChildFlags_Borders);+ ImGui::SetCursorPos(ImVec2(8, 4));ImGui::TextColored(TEXT_DIM, "Find:");ImGui::SameLine(0, 4);@@ -985,13 +974,15 @@ void CodeEditorScreen::render_search_bar() {void CodeEditorScreen::render_cells() {using namespace theme::colors;- float status_h = 28.0f;+ float status_h = 24.0f;float avail_h = ImGui::GetContentRegionAvail().y - status_h;- ImGui::BeginChild("##ce_cells_area", ImVec2(0, avail_h), ImGuiChildFlags_None);+ ImGui::BeginChild("##ce_cells_area", ImVec2(0, avail_h), ImGuiChildFlags_None,+ ImGuiWindowFlags_HorizontalScrollbar);+ // Use full width with small padding — no artificial max-width centeringfloat avail_w = ImGui::GetContentRegionAvail().x;- float pad_x = (avail_w > 900.0f) ? (avail_w - 860.0f) * 0.5f : 20.0f;+ float pad_x = std::min(12.0f, avail_w * 0.01f);ImGui::SetCursorPosX(pad_x);ImGui::BeginChild("##ce_cells_inner", ImVec2(avail_w - pad_x * 2, 0), ImGuiChildFlags_None);@@ -1089,8 +1080,6 @@ void CodeEditorScreen::render_cell(int idx) {// Cell headerrender_cell_header(idx);- ImGui::Spacing();-// Cell editor / previewrender_cell_editor(idx);@@ -1111,7 +1100,7 @@ void CodeEditorScreen::render_cell(int idx) {// Execution order warning badge (point 15)if (order_warn) {- ImGui::SetCursorPosX(16);+ ImGui::SetCursorPosX(10);ImGui::TextColored(WARNING, "[!] Cells executed out of order");}@@ -1144,7 +1133,7 @@ void CodeEditorScreen::render_cell_header(int idx) {}bool has_success = has_output && !has_error;- ImGui::SetCursorPos(ImVec2(16, 6));+ ImGui::SetCursorPos(ImVec2(10, 4));// Execution count badge with timer (point 8)if (cell.cell_type == "code") {@@ -1296,7 +1285,7 @@ void CodeEditorScreen::render_cell_editor(int idx) {auto& cell = nb().cells[idx];bool is_selected = (idx == tab().selected_cell);- ImGui::SetCursorPosX(16);+ ImGui::SetCursorPosX(10);ImGui::PushStyleColor(ImGuiCol_FrameBg, BG_DARKEST);char editor_id[32];@@ -1305,7 +1294,7 @@ void CodeEditorScreen::render_cell_editor(int idx) {int line_count = 1;for (char c : cell.source) if (c == '\n') line_count++;float line_h = ImGui::GetTextLineHeight();- float editor_h = std::max(3, std::min(line_count + 1, 30)) * line_h + 12;+ float editor_h = std::max(3, std::min(line_count + 1, 30)) * line_h + 8;if (is_selected || active_edit_cell_ == idx) {if (active_edit_cell_ != idx) {@@ -1317,7 +1306,7 @@ void CodeEditorScreen::render_cell_editor(int idx) {// Line numbers (point 12)char gutter_id[32];std::snprintf(gutter_id, sizeof(gutter_id), "##gutter_%d", idx);- ImGui::BeginChild(gutter_id, ImVec2(35, editor_h), ImGuiChildFlags_None);+ ImGui::BeginChild(gutter_id, ImVec2(32, editor_h), ImGuiChildFlags_None);ImGui::PushStyleColor(ImGuiCol_Text, TEXT_DISABLED);for (int i = 1; i <= line_count; i++) {ImGui::Text("%3d", i);@@ -1327,7 +1316,7 @@ void CodeEditorScreen::render_cell_editor(int idx) {ImGui::SameLine(0, 0);- float edit_w = ImGui::GetContentRegionAvail().x - 16;+ float edit_w = ImGui::GetContentRegionAvail().x - 4;if (ImGui::InputTextMultiline(editor_id, edit_buf_.data(), edit_buf_.size(),ImVec2(edit_w, editor_h),ImGuiInputTextFlags_AllowTabInput)) {@@ -1355,12 +1344,12 @@ void CodeEditorScreen::render_cell_editor(int idx) {}} else {// Read-only preview with syntax highlighting- ImGui::SetCursorPosX(16);+ ImGui::SetCursorPosX(10);// Line numbers for preview toochar gutter_id[32];std::snprintf(gutter_id, sizeof(gutter_id), "##gutter_p_%d", idx);- ImGui::BeginChild(gutter_id, ImVec2(35, editor_h), ImGuiChildFlags_None);+ ImGui::BeginChild(gutter_id, ImVec2(32, editor_h), ImGuiChildFlags_None);ImGui::PushStyleColor(ImGuiCol_Text, TEXT_DISABLED);for (int i = 1; i <= line_count; i++) {ImGui::Text("%3d", i);@@ -1370,7 +1359,7 @@ void CodeEditorScreen::render_cell_editor(int idx) {ImGui::SameLine(0, 0);- float preview_w = ImGui::GetContentRegionAvail().x - 16;+ float preview_w = ImGui::GetContentRegionAvail().x - 4;char prev_id[32];std::snprintf(prev_id, sizeof(prev_id), "##preview_%d", idx);ImGui::BeginChild(prev_id, ImVec2(preview_w, editor_h), ImGuiChildFlags_None);@@ -1403,7 +1392,7 @@ void CodeEditorScreen::render_cell_output(int idx) {if (o.output_type == "error") { has_error = true; break; }}- ImGui::SetCursorPosX(16);+ ImGui::SetCursorPosX(10);ImGui::TextColored(has_error ? ERROR_RED : SUCCESS,has_error ? "ERROR OUTPUT" : "OUTPUT");if (cell.execution_count >= 0) {@@ -1429,8 +1418,8 @@ void CodeEditorScreen::render_cell_output(int idx) {char scroll_id[32];std::snprintf(scroll_id, sizeof(scroll_id), "##out_scroll_%d", idx);- ImGui::SetCursorPosX(16);- ImGui::BeginChild(scroll_id, ImVec2(ImGui::GetContentRegionAvail().x - 16, max_output_h),+ ImGui::SetCursorPosX(10);+ ImGui::BeginChild(scroll_id, ImVec2(ImGui::GetContentRegionAvail().x - 4, max_output_h),ImGuiChildFlags_Borders, ImGuiWindowFlags_HorizontalScrollbar);for (auto& out : cell.outputs) {@@ -1512,8 +1501,8 @@ void CodeEditorScreen::render_status_bar() {using namespace theme::colors;ImGui::PushStyleColor(ImGuiCol_ChildBg, BG_DARKEST);- ImGui::BeginChild("##ce_status", ImVec2(0, 28), ImGuiChildFlags_Borders);- ImGui::SetCursorPos(ImVec2(12, 6));+ ImGui::BeginChild("##ce_status", ImVec2(0, 24), ImGuiChildFlags_Borders);+ ImGui::SetCursorPos(ImVec2(8, 4));// Python version badgeif (!python_version_.empty()) {diff --git a/fincept-cpp/src/screens/crypto_trading/crypto_trading_screen.cpp b/fincept-cpp/src/screens/crypto_trading/crypto_trading_screen.cppindex d01d2e614..1e079d55a 100644--- a/fincept-cpp/src/screens/crypto_trading/crypto_trading_screen.cpp+++ b/fincept-cpp/src/screens/crypto_trading/crypto_trading_screen.cpp@@ -15,7 +15,18 @@namespace fincept::crypto {using namespace theme::colors;-static const char* TAG = "CryptoTrading";+static constexpr const char* TAG = "CryptoTrading";++// Named constants (ES.45: avoid magic numbers)+static constexpr int OHLCV_FETCH_COUNT = 200;+static constexpr double DEFAULT_PAPER_BALANCE = 100000.0;+static constexpr int PORTFOLIO_CLEANUP_THRESH = 10;+static constexpr float TICKER_POLL_INTERVAL = 3.0f; // seconds (REST fallback)+static constexpr float ORDERBOOK_POLL_INTERVAL = 3.0f;+static constexpr float WATCHLIST_POLL_INTERVAL = 15.0f;+static constexpr float PORTFOLIO_REFRESH_INTERVAL = 1.5f;+static constexpr float MARKET_INFO_INTERVAL = 30.0f;+static constexpr int PRICE_FEED_POLL_SEC = 3;// ============================================================================// Default watchlist — top crypto pairs@@ -92,7 +103,7 @@ void CryptoTradingScreen::init() {// Start the price feed for watched symbols (drives OrderMatcher + position updates)if (!svc.is_feed_running()) {- svc.start_price_feed(3);+ svc.start_price_feed(PRICE_FEED_POLL_SEC);}initialized_ = true;@@ -113,7 +124,7 @@ void CryptoTradingScreen::init() {std::string sym = selected_symbol_;std::thread([this, sym]() {try {- auto ohlcv = trading::ExchangeService::instance().fetch_ohlcv(sym, "1m", 200);+ auto ohlcv = trading::ExchangeService::instance().fetch_ohlcv(sym, "1m", OHLCV_FETCH_COUNT);LOG_INFO(TAG, "<<< Initial OHLCV received: %d candles", (int)ohlcv.size());{std::lock_guard<std::mutex> lock(data_mutex_);@@ -131,95 +142,8 @@ void CryptoTradingScreen::init() {}).detach();// Start WebSocket streaming for real-time updates- try {- LOG_INFO(TAG, "Registering WS callbacks...");- auto& svc2 = trading::ExchangeService::instance();-- // Register price callback- ws_price_cb_id_ = svc2.on_price_update([this](const std::string& symbol, const trading::TickerData& ticker) {- std::lock_guard<std::mutex> lock(data_mutex_);- if (symbol == selected_symbol_) {- current_ticker_ = ticker;- ticker_loading_ = false;- }- for (auto& w : watchlist_) {- if (w.symbol == symbol) {- w.price = ticker.last;- w.change = ticker.change;- w.change_pct = ticker.percentage;- w.volume = ticker.base_volume;- w.has_data = true;- break;- }- }- last_data_update_ = time(nullptr);- });-- // Register orderbook callback- ws_ob_cb_id_ = svc2.on_orderbook_update([this](const std::string& symbol, const trading::OrderBookData& ob) {- if (symbol != selected_symbol_) return;- std::lock_guard<std::mutex> lock(data_mutex_);-- ob_bids_.clear();- ob_asks_.clear();- double cum = 0;- for (auto& [price, amount] : ob.bids) {- cum += amount;- ob_bids_.push_back({price, amount, cum});- }- cum = 0;- for (auto& [price, amount] : ob.asks) {- cum += amount;- ob_asks_.push_back({price, amount, cum});- }- ob_spread_ = ob.spread;- ob_spread_pct_ = ob.spread_pct;- ob_loading_ = false;- last_data_update_ = time(nullptr);- });-- // Register candle callback- ws_candle_cb_id_ = svc2.on_candle_update([this](const std::string& symbol, const trading::Candle& candle) {- if (symbol != selected_symbol_) return;- std::lock_guard<std::mutex> lock(data_mutex_);-- if (!candles_.empty() && candles_.back().timestamp == candle.timestamp) {- candles_.back() = candle;- } else {- candles_.push_back(candle);- if (candles_.size() > 500) {- candles_.erase(candles_.begin());- }- }- });-- // Register trade callback for Time & Sales- ws_trade_cb_id_ = svc2.on_trade_update([this](const std::string& symbol, const trading::TradeData& trade) {- if (symbol != selected_symbol_) return;- std::lock_guard<std::mutex> lock(data_mutex_);- recent_trades_.insert(recent_trades_.begin(), TradeEntry{- trade.id, trade.side, trade.price, trade.amount, trade.timestamp- });- if ((int)recent_trades_.size() > MAX_TRADES) {- recent_trades_.resize(MAX_TRADES);- }- });-- LOG_INFO(TAG, "WS callbacks registered, starting stream...");-- // Collect all watchlist symbols for WS- std::vector<std::string> all_symbols;- for (auto& w : watchlist_) all_symbols.push_back(w.symbol);-- svc2.start_ws_stream(selected_symbol_, all_symbols);- ws_started_ = true;- LOG_INFO(TAG, "WebSocket stream started for %s + %d symbols",- selected_symbol_.c_str(), (int)all_symbols.size());- } catch (const std::exception& e) {- LOG_ERROR(TAG, "Failed to start WS stream: %s", e.what());- last_error_ = std::string("WS start failed: ") + e.what();- error_count_++;- }+ // restart_ws_stream() handles callback registration + stream start+ restart_ws_stream();// Fetch initial trades and market info via RESTasync_fetch_trades();@@ -249,14 +173,14 @@ void CryptoTradingScreen::load_portfolio() {// Create if not foundif (portfolio_id_.empty()) {portfolio_ = trading::pt_create_portfolio(- "Crypto Paper Trading", 100000.0, "USDT", 1.0, "cross", 0.001);+ "Crypto Paper Trading", DEFAULT_PAPER_BALANCE, "USDT", 1.0, "cross", 0.001);portfolio_id_ = portfolio_.id;LOG_INFO(TAG, "Created new portfolio: %s (balance=%.2f)",portfolio_id_.c_str(), portfolio_.balance);}// Cleanup: delete empty portfolios (not ours) to prevent DB bloat- if (portfolios.size() > 10) {+ if (portfolios.size() > PORTFOLIO_CLEANUP_THRESH) {int cleaned = 0;for (const auto& p : portfolios) {if (p.id == portfolio_id_) continue;@@ -288,6 +212,248 @@ void CryptoTradingScreen::load_portfolio() {}}+// ============================================================================+// Exchange & symbol switching — proper lifecycle management+// ============================================================================++void CryptoTradingScreen::clear_market_data() {+ std::lock_guard<std::mutex> lock(data_mutex_);+ current_ticker_ = {};+ ob_bids_.clear();+ ob_asks_.clear();+ ob_spread_ = 0.0;+ ob_spread_pct_ = 0.0;+ candles_.clear();+ recent_trades_.clear();+ market_info_ = {};+ for (auto& w : watchlist_) {+ w.price = 0.0;+ w.change = 0.0;+ w.change_pct = 0.0;+ w.volume = 0.0;+ w.has_data = false;+ }+ last_error_.clear();+ error_count_ = 0;+ success_count_ = 0;+}++void CryptoTradingScreen::restart_ws_stream() {+ auto& svc = trading::ExchangeService::instance();++ // Tear down existing WS+ if (ws_started_) {+ svc.stop_ws_stream();+ ws_started_ = false;+ }++ // Remove old callbacks+ if (ws_price_cb_id_ >= 0) { svc.remove_price_callback(ws_price_cb_id_); ws_price_cb_id_ = -1; }+ if (ws_ob_cb_id_ >= 0) { svc.remove_orderbook_callback(ws_ob_cb_id_); ws_ob_cb_id_ = -1; }+ if (ws_candle_cb_id_ >= 0) { svc.remove_candle_callback(ws_candle_cb_id_); ws_candle_cb_id_ = -1; }+ if (ws_trade_cb_id_ >= 0) { svc.remove_trade_callback(ws_trade_cb_id_); ws_trade_cb_id_ = -1; }++ // Re-register callbacks (same as in init())+ ws_price_cb_id_ = svc.on_price_update([this](const std::string& symbol, const trading::TickerData& ticker) {+ std::lock_guard<std::mutex> lock(data_mutex_);+ if (symbol == selected_symbol_) {+ current_ticker_ = ticker;+ ticker_loading_ = false;+ }+ for (auto& w : watchlist_) {+ if (w.symbol == symbol) {+ w.price = ticker.last;+ w.change = ticker.change;+ w.change_pct = ticker.percentage;+ w.volume = ticker.base_volume;+ w.has_data = true;+ break;+ }+ }+ last_data_update_ = time(nullptr);+ });++ ws_ob_cb_id_ = svc.on_orderbook_update([this](const std::string& symbol, const trading::OrderBookData& ob) {+ if (symbol != selected_symbol_) return;+ std::lock_guard<std::mutex> lock(data_mutex_);+ ob_bids_.clear();+ ob_asks_.clear();+ double cum = 0;+ for (auto& [price, amount] : ob.bids) {+ cum += amount;+ ob_bids_.push_back({price, amount, cum});+ }+ cum = 0;+ for (auto& [price, amount] : ob.asks) {+ cum += amount;+ ob_asks_.push_back({price, amount, cum});+ }+ ob_spread_ = ob.spread;+ ob_spread_pct_ = ob.spread_pct;+ ob_loading_ = false;+ last_data_update_ = time(nullptr);+ });++ ws_candle_cb_id_ = svc.on_candle_update([this](const std::string& symbol, const trading::Candle& candle) {+ if (symbol != selected_symbol_) return;+ std::lock_guard<std::mutex> lock(data_mutex_);+ if (!candles_.empty() && candles_.back().timestamp == candle.timestamp) {+ candles_.back() = candle;+ } else {+ candles_.push_back(candle);+ if (candles_.size() > 500) candles_.erase(candles_.begin());+ }+ });++ ws_trade_cb_id_ = svc.on_trade_update([this](const std::string& symbol, const trading::TradeData& trade) {+ if (symbol != selected_symbol_) return;+ std::lock_guard<std::mutex> lock(data_mutex_);+ recent_trades_.insert(recent_trades_.begin(), TradeEntry{+ trade.id, trade.side, trade.price, trade.amount, trade.timestamp+ });+ if ((int)recent_trades_.size() > MAX_TRADES) recent_trades_.resize(MAX_TRADES);+ });++ // Start new WS stream+ std::vector<std::string> all_symbols;+ for (auto& w : watchlist_) all_symbols.push_back(w.symbol);++ try {+ svc.start_ws_stream(selected_symbol_, all_symbols);+ ws_started_ = true;+ LOG_INFO(TAG, "WS stream restarted for %s + %d symbols on %s",+ selected_symbol_.c_str(), (int)all_symbols.size(), exchange_id_.c_str());+ } catch (const std::exception& e) {+ LOG_ERROR(TAG, "Failed to restart WS: %s", e.what());+ last_error_ = std::string("WS restart failed: ") + e.what();+ }+}++void CryptoTradingScreen::switch_exchange(const std::string& exchange_id) {+ if (exchange_id == exchange_id_) return;++ LOG_INFO(TAG, "Switching exchange: %s -> %s", exchange_id_.c_str(), exchange_id.c_str());++ // Stop price feed before switching (it uses the old exchange)+ auto& svc = trading::ExchangeService::instance();+ svc.stop_price_feed();++ // Update exchange+ exchange_id_ = exchange_id;+ svc.set_exchange(exchange_id);++ // Invalidate search cache — new exchange has different markets+ search_markets_loaded_ = false;+ search_cache_exchange_.clear();+ all_markets_.clear();+ search_results_.clear();++ // Clear all stale market data from previous exchange+ clear_market_data();++ // Reset loading states+ ticker_loading_ = true;+ ob_loading_ = true;+ candles_loading_ = true;++ // Restart price feed with new exchange+ svc.start_price_feed(PRICE_FEED_POLL_SEC);++ // Re-watch the selected symbol for paper trading+ if (!portfolio_id_.empty()) {+ svc.watch_symbol(selected_symbol_, portfolio_id_);+ }++ // Restart WebSocket stream for new exchange+ restart_ws_stream();++ // Kick off REST fetches for immediate data+ async_refresh_ticker();+ async_refresh_orderbook();+ async_refresh_watchlist_prices();+ async_fetch_trades();+ async_fetch_market_info();++ // Fetch fresh candles+ candles_fetching_ = true;+ std::string sym = selected_symbol_;+ std::thread([this, sym]() {+ try {+ auto ohlcv = trading::ExchangeService::instance().fetch_ohlcv(sym, "1m", OHLCV_FETCH_COUNT);+ {+ std::lock_guard<std::mutex> lock(data_mutex_);+ candles_ = std::move(ohlcv);+ }+ candles_loading_ = false;+ candles_fetching_ = false;+ } catch (const std::exception& e) {+ LOG_ERROR(TAG, "OHLCV fetch failed on exchange switch: %s", e.what());+ candles_loading_ = false;+ candles_fetching_ = false;+ }+ }).detach();++ LOG_INFO(TAG, "Exchange switch complete: %s", exchange_id.c_str());+}++void CryptoTradingScreen::switch_symbol(const std::string& symbol) {+ if (symbol == selected_symbol_) return;++ LOG_INFO(TAG, "Switching symbol: %s -> %s", selected_symbol_.c_str(), symbol.c_str());++ selected_symbol_ = symbol;++ // Clear symbol-specific data (keep watchlist prices intact)+ {+ std::lock_guard<std::mutex> lock(data_mutex_);+ current_ticker_ = {};+ ob_bids_.clear();+ ob_asks_.clear();+ ob_spread_ = 0.0;+ ob_spread_pct_ = 0.0;+ candles_.clear();+ recent_trades_.clear();+ market_info_ = {};+ }++ ticker_loading_ = true;+ ob_loading_ = true;+ candles_loading_ = true;++ // Watch new symbol for paper trading price updates+ if (!portfolio_id_.empty()) {+ trading::ExchangeService::instance().watch_symbol(symbol, portfolio_id_);+ }++ // Restart WS with new primary symbol+ restart_ws_stream();++ // Immediate REST fetches while WS connects+ async_refresh_ticker();+ async_refresh_orderbook();+ async_fetch_trades();+ async_fetch_market_info();++ // Fetch candles for new symbol+ candles_fetching_ = true;+ std::string sym = symbol;+ std::thread([this, sym]() {+ try {+ auto ohlcv = trading::ExchangeService::instance().fetch_ohlcv(sym, "1m", OHLCV_FETCH_COUNT);+ {+ std::lock_guard<std::mutex> lock(data_mutex_);+ candles_ = std::move(ohlcv);+ }+ candles_loading_ = false;+ candles_fetching_ = false;+ } catch (const std::exception& e) {+ LOG_ERROR(TAG, "OHLCV fetch failed on symbol switch: %s", e.what());+ candles_loading_ = false;+ candles_fetching_ = false;+ }+ }).detach();+}+// ============================================================================// Async data fetchers — run in detached threads// ============================================================================@@ -492,6 +658,13 @@ void CryptoTradingScreen::refresh_portfolio_data() {void CryptoTradingScreen::render() {if (!initialized_) init();+ // Handle deferred symbol switch (set from search results while holding data_mutex_)+ if (!pending_symbol_switch_.empty()) {+ std::string sym = pending_symbol_switch_;+ pending_symbol_switch_.clear();+ switch_symbol(sym);+ }+ui::ScreenFrame frame("##crypto_trading", ImVec2(0, 0), BG_DARKEST);if (!frame.begin()) { frame.end(); return; }@@ -558,28 +731,28 @@ void CryptoTradingScreen::render() {ob_timer_ += dt;wl_timer_ += dt;- if (ticker_timer_ >= 3.0f) {+ if (ticker_timer_ >= TICKER_POLL_INTERVAL) {ticker_timer_ = 0;async_refresh_ticker();}- if (ob_timer_ >= 3.0f) {+ if (ob_timer_ >= ORDERBOOK_POLL_INTERVAL) {ob_timer_ = 0;async_refresh_orderbook();}- if (wl_timer_ >= 15.0f) {+ if (wl_timer_ >= WATCHLIST_POLL_INTERVAL) {wl_timer_ = 0;async_refresh_watchlist_prices();}}- if (portfolio_timer_ >= 1.5f) {+ if (portfolio_timer_ >= PORTFOLIO_REFRESH_INTERVAL) {portfolio_timer_ = 0;refresh_portfolio_data();}// Market info refresh (every 30s)market_info_timer_ += dt;- if (market_info_timer_ >= 30.0f) {+ if (market_info_timer_ >= MARKET_INFO_INTERVAL) {market_info_timer_ = 0;async_fetch_market_info();}@@ -614,15 +787,13 @@ void CryptoTradingScreen::render_top_nav(float w, float h) {ImGui::PushItemWidth(100);ImGui::PushStyleColor(ImGuiCol_FrameBg, BG_INPUT);static const char* exchanges[] = {"binance", "kraken", "bybit", "okx", "coinbase"};- static int ex_idx = 0;+ // Find current index from exchange_id_ (not static — stays in sync)+ int ex_idx = 0;+ for (int i = 0; i < 5; ++i) {+ if (exchange_id_ == exchanges[i]) { ex_idx = i; break; }+ }if (ImGui::Combo("##exchange", &ex_idx, exchanges, 5)) {- exchange_id_ = exchanges[ex_idx];- trading::ExchangeService::instance().set_exchange(exchange_id_);- LOG_INFO(TAG, "Exchange changed to: %s", exchange_id_.c_str());- // Force refresh with new exchange- ticker_timer_ = 99;- ob_timer_ = 99;- wl_timer_ = 99;+ switch_exchange(exchanges[ex_idx]);}ImGui::PopStyleColor();ImGui::PopItemWidth();@@ -646,15 +817,25 @@ void CryptoTradingScreen::render_top_nav(float w, float h) {if (ImGui::SmallButton("LIVE")) trading_mode_ = TradingMode::Live;ImGui::PopStyleColor(2);- // Right side: balance- float balance_w = 200;+ // Right side: mode badge + balance+ float balance_w = 280;float avail = ImGui::GetContentRegionAvail().x;if (avail > balance_w + 20) {ImGui::SameLine(ImGui::GetCursorPosX() + avail - balance_w);+ if (is_paper) {+ ImGui::TextColored(ImVec4(0.0f, 0.7f, 0.3f, 1.0f), "PAPER");+ } else {+ ImGui::TextColored(ImVec4(0.9f, 0.2f, 0.2f, 1.0f), "LIVE");+ }+ ImGui::SameLine(0, 8);ImGui::TextColored(TEXT_DIM, "Balance:");ImGui::SameLine(0, 4);char bal_buf[32];- std::snprintf(bal_buf, sizeof(bal_buf), "%.2f USDT", portfolio_.balance);+ if (is_paper) {+ std::snprintf(bal_buf, sizeof(bal_buf), "%.2f %s", portfolio_.balance, portfolio_.currency.c_str());+ } else {+ std::snprintf(bal_buf, sizeof(bal_buf), "-- (Live)");+ }ImGui::TextColored(MARKET_GREEN, "%s", bal_buf);}@@ -797,24 +978,73 @@ void CryptoTradingScreen::render_watchlist(float w, float h) {ImGui::TextColored(WARNING, "[*]");}- // Filter+ // Search / Filter fieldImGui::PushItemWidth(-1);ImGui::PushStyleColor(ImGuiCol_FrameBg, BG_INPUT);- ImGui::InputTextWithHint("##wl_filter", "Filter...", watchlist_filter_, sizeof(watchlist_filter_));+ bool search_changed = ImGui::InputTextWithHint("##wl_filter", "Search symbol...",+ watchlist_filter_, sizeof(watchlist_filter_));ImGui::PopStyleColor();ImGui::PopItemWidth();+ std::string filter_str(watchlist_filter_);+ for (auto& c : filter_str) c = (char)std::toupper((unsigned char)c);++ // Fetch exchange markets for search (lazy, cached per exchange)+ if (search_changed && filter_str.length() >= 2 && !search_fetching_) {+ // Load markets if not cached for this exchange+ if (search_cache_exchange_ != exchange_id_ || !search_markets_loaded_) {+ search_fetching_ = true;+ std::string ex_id = exchange_id_;+ std::thread([this, ex_id]() {+ try {+ auto markets = trading::ExchangeService::instance().fetch_markets("spot");+ LOG_INFO(TAG, "Loaded %d markets for search from %s",+ (int)markets.size(), ex_id.c_str());+ std::lock_guard<std::mutex> lock(data_mutex_);+ all_markets_ = std::move(markets);+ search_cache_exchange_ = ex_id;+ search_markets_loaded_ = true;+ } catch (const std::exception& e) {+ LOG_ERROR(TAG, "Failed to load markets for search: %s", e.what());+ }+ search_fetching_ = false;+ }).detach();+ }+ }++ // Build search results from cached markets+ bool has_search = filter_str.length() >= 2 && search_markets_loaded_;+ std::vector<trading::MarketInfo> filtered_markets;+ if (has_search) {+ std::lock_guard<std::mutex> lock(data_mutex_);+ int count = 0;+ for (const auto& m : all_markets_) {+ if (!m.active) continue;+ std::string sym_upper = m.symbol;+ for (auto& c : sym_upper) c = (char)std::toupper((unsigned char)c);+ if (sym_upper.find(filter_str) != std::string::npos) {+ // Skip if already in watchlist+ bool in_wl = false;+ for (const auto& w : watchlist_) {+ if (w.symbol == m.symbol) { in_wl = true; break; }+ }+ if (!in_wl) {+ filtered_markets.push_back(m);+ if (++count >= 20) break; // limit results+ }+ }+ }+ }+ImGui::Separator();// Scrollable listImGui::BeginChild("##wl_scroll", ImVec2(0, 0), false);- std::string filter_str(watchlist_filter_);- for (auto& c : filter_str) c = (char)std::toupper((unsigned char)c);-char buf[64];std::lock_guard<std::mutex> lock(data_mutex_);+ // --- Watchlist entries ---for (int i = 0; i < (int)watchlist_.size(); i++) {auto& entry = watchlist_[i];@@ -833,15 +1063,7 @@ void CryptoTradingScreen::render_watchlist(float w, float h) {if (ImGui::Selectable("##wl_sel", is_selected, ImGuiSelectableFlags_SpanAllColumns, ImVec2(0, 22))) {watchlist_selected_ = i;- // Watch new symbol for position price updates- if (!portfolio_id_.empty() && entry.symbol != selected_symbol_) {- trading::ExchangeService::instance().watch_symbol(entry.symbol, portfolio_id_);- }- selected_symbol_ = entry.symbol;- LOG_INFO(TAG, "Symbol selected: %s", selected_symbol_.c_str());- // Force immediate refresh- ticker_timer_ = 99;- ob_timer_ = 99;+ switch_symbol(entry.symbol);}ImGui::PopStyleColor(2);@@ -890,6 +1112,75 @@ void CryptoTradingScreen::render_watchlist(float w, float h) {ImGui::PopID();}+ // --- Exchange search results (symbols not in watchlist) ---+ if (!filtered_markets.empty()) {+ ImGui::Separator();+ ImGui::TextColored(TEXT_DIM, "Exchange results:");+ ImGui::Spacing();++ for (int i = 0; i < (int)filtered_markets.size(); i++) {+ const auto& m = filtered_markets[i];+ ImGui::PushID(10000 + i);++ ImGui::PushStyleColor(ImGuiCol_Header, ImVec4(0.1f, 0.15f, 0.2f, 1.0f));+ ImGui::PushStyleColor(ImGuiCol_HeaderHovered, BG_HOVER);++ if (ImGui::Selectable("##search_sel", false, ImGuiSelectableFlags_SpanAllColumns, ImVec2(0, 22))) {+ // Add to watchlist+ WatchlistEntry new_entry;+ new_entry.symbol = m.symbol;+ watchlist_.push_back(new_entry);+ watchlist_selected_ = (int)watchlist_.size() - 1;+ LOG_INFO(TAG, "Added %s to watchlist from search", m.symbol.c_str());++ // Clear search field+ watchlist_filter_[0] = '\0';++ // Defer symbol switch — we hold data_mutex_ here,+ // switch_symbol() will run in the render loop next frame+ pending_symbol_switch_ = m.symbol;+ }++ ImGui::PopStyleColor(2);++ ImGui::SameLine(4);++ // Show base/quote+ std::string base = m.base;+ ImGui::TextColored(ACCENT, "%s", base.c_str());+ ImGui::SameLine(0, 2);+ ImGui::TextColored(TEXT_DIM, "/%s", m.quote.c_str());++ // Type on right+ float type_w = ImGui::CalcTextSize(m.type.c_str()).x;+ float avail = ImGui::GetContentRegionAvail().x;+ if (avail > type_w + 4) {+ ImGui::SameLine(w - type_w - 16);+ ImGui::TextColored(TEXT_DIM, "%s", m.type.c_str());+ }++ ImGui::PopID();+ }+ } else if (filter_str.length() >= 2 && search_fetching_) {+ ImGui::Separator();+ ImGui::TextColored(TEXT_DIM, "Searching...");+ } else if (filter_str.length() >= 2 && search_markets_loaded_ && filtered_markets.empty()) {+ // Check if all matches are in watchlist already+ bool any_watchlist_match = false;+ for (const auto& w : watchlist_) {+ std::string sym_upper = w.symbol;+ for (auto& c : sym_upper) c = (char)std::toupper((unsigned char)c);+ if (sym_upper.find(filter_str) != std::string::npos) {+ any_watchlist_match = true;+ break;+ }+ }+ if (!any_watchlist_match) {+ ImGui::Separator();+ ImGui::TextColored(TEXT_DIM, "No results");+ }+ }+ImGui::EndChild();ImGui::EndChild();ImGui::PopStyleColor();@@ -931,7 +1222,7 @@ void CryptoTradingScreen::render_chart_area(float w, float h) {std::string tf = candle_timeframe_;std::thread([this, sym, tf]() {try {- auto ohlcv = trading::ExchangeService::instance().fetch_ohlcv(sym, tf, 200);+ auto ohlcv = trading::ExchangeService::instance().fetch_ohlcv(sym, tf, OHLCV_FETCH_COUNT);LOG_INFO(TAG, "<<< OHLCV %s received: %d candles", tf.c_str(), (int)ohlcv.size());{std::lock_guard<std::mutex> lock(data_mutex_);@@ -1208,8 +1499,8 @@ void CryptoTradingScreen::render_bottom_panel(float w, float h) {ImGui::PopStyleColor(2);}- // Count badges- {+ // Count badges (paper mode only — live data would come from exchange)+ if (trading_mode_ == TradingMode::Paper) {std::lock_guard<std::mutex> lock(data_mutex_);ImGui::SameLine(0, 8);if (!positions_.empty()) {@@ -1245,6 +1536,20 @@ void CryptoTradingScreen::render_bottom_panel(float w, float h) {}void CryptoTradingScreen::render_positions_tab() {+ bool is_live = (trading_mode_ == TradingMode::Live);++ // Mode label+ ImGui::TextColored(is_live ? ImVec4(0.9f, 0.2f, 0.2f, 1.0f) : ImVec4(0.0f, 0.7f, 0.3f, 1.0f),+ is_live ? "[LIVE POSITIONS]" : "[PAPER POSITIONS]");++ if (is_live) {+ // Live mode — show positions from exchange+ ImGui::TextColored(TEXT_DIM, "Live positions require API credentials.");+ ImGui::TextColored(TEXT_DIM, "Configure in Settings > Exchange API.");+ return;+ }++ // Paper mode — show simulated positionsstd::lock_guard<std::mutex> lock(data_mutex_);if (!portfolio_loaded_) {@@ -1312,6 +1617,17 @@ void CryptoTradingScreen::render_positions_tab() {}void CryptoTradingScreen::render_orders_tab() {+ bool is_live = (trading_mode_ == TradingMode::Live);++ ImGui::TextColored(is_live ? ImVec4(0.9f, 0.2f, 0.2f, 1.0f) : ImVec4(0.0f, 0.7f, 0.3f, 1.0f),+ is_live ? "[LIVE ORDERS]" : "[PAPER ORDERS]");++ if (is_live) {+ ImGui::TextColored(TEXT_DIM, "Live orders require API credentials.");+ ImGui::TextColored(TEXT_DIM, "Configure in Settings > Exchange API.");+ return;+ }+std::lock_guard<std::mutex> lock(data_mutex_);if (!portfolio_loaded_) {@@ -1392,6 +1708,15 @@ void CryptoTradingScreen::render_orders_tab() {}void CryptoTradingScreen::render_history_tab() {+ bool is_live = (trading_mode_ == TradingMode::Live);+ ImGui::TextColored(is_live ? ImVec4(0.9f, 0.2f, 0.2f, 1.0f) : ImVec4(0.0f, 0.7f, 0.3f, 1.0f),+ is_live ? "[LIVE HISTORY]" : "[PAPER HISTORY]");++ if (is_live) {+ ImGui::TextColored(TEXT_DIM, "Live trade history requires API credentials.");+ return;+ }+std::lock_guard<std::mutex> lock(data_mutex_);if (!portfolio_loaded_) {@@ -1453,6 +1778,15 @@ void CryptoTradingScreen::render_history_tab() {}void CryptoTradingScreen::render_stats_tab() {+ bool is_live = (trading_mode_ == TradingMode::Live);+ ImGui::TextColored(is_live ? ImVec4(0.9f, 0.2f, 0.2f, 1.0f) : ImVec4(0.0f, 0.7f, 0.3f, 1.0f),+ is_live ? "[LIVE STATS]" : "[PAPER STATS]");++ if (is_live) {+ ImGui::TextColored(TEXT_DIM, "Live statistics not available yet.");+ return;+ }+std::lock_guard<std::mutex> lock(data_mutex_);char buf[32];@@ -1709,7 +2043,15 @@ void CryptoTradingScreen::render_order_entry(float w, float h) {ImGui::PushStyleColor(ImGuiCol_ChildBg, BG_PANEL);ImGui::BeginChild("##crypto_order_entry", ImVec2(w, h), true);+ // Mode indicator+ bool is_paper = (trading_mode_ == TradingMode::Paper);ImGui::TextColored(ACCENT, "ORDER ENTRY");+ ImGui::SameLine(0, 6);+ if (is_paper) {+ ImGui::TextColored(ImVec4(0.0f, 0.7f, 0.3f, 1.0f), "[PAPER]");+ } else {+ ImGui::TextColored(ImVec4(0.9f, 0.2f, 0.2f, 1.0f), "[LIVE]");+ }ImGui::Separator();float input_w = w - 24;@@ -1807,20 +2149,41 @@ void CryptoTradingScreen::render_order_entry(float w, float h) {ImGui::Spacing();- // Submit button+ // Submit button — clearly labeled with mode{bool is_buy = (order_form_.side_idx == 0);ImVec4 btn_col = is_buy ? ImVec4(0.0f, 0.55f, 0.25f, 1.0f) : ImVec4(0.65f, 0.1f, 0.1f, 1.0f);++ // Show base symbol without quote (e.g., "BTC" not "BTC/USDT")+ std::string base_sym = selected_symbol_;+ auto slash_pos = base_sym.find('/');+ if (slash_pos != std::string::npos) base_sym = base_sym.substr(0, slash_pos);+char label[64];- std::snprintf(label, sizeof(label), "%s %s", is_buy ? "BUY" : "SELL", selected_symbol_.c_str());+ if (is_paper) {+ std::snprintf(label, sizeof(label), "%s %s (Paper)",+ is_buy ? "BUY" : "SELL", base_sym.c_str());+ } else {+ std::snprintf(label, sizeof(label), "%s %s (LIVE)",+ is_buy ? "BUY" : "SELL", base_sym.c_str());+ // Add red border for live orders as a safety indicator+ btn_col = is_buy ? ImVec4(0.0f, 0.4f, 0.2f, 1.0f) : ImVec4(0.6f, 0.05f, 0.05f, 1.0f);+ }ImGui::PushStyleColor(ImGuiCol_Button, btn_col);ImGui::PushStyleColor(ImGuiCol_ButtonHovered, ImVec4(btn_col.x + 0.1f, btn_col.y + 0.1f, btn_col.z + 0.1f, 1.0f));ImGui::PushStyleColor(ImGuiCol_Text, TEXT_PRIMARY);- if (ImGui::Button(label, ImVec2(input_w, 28))) {+ if (order_submitting_.load()) {+ ImGui::Button("Submitting...", ImVec2(input_w, 28));+ } else if (ImGui::Button(label, ImVec2(input_w, 28))) {submit_order();}ImGui::PopStyleColor(3);++ // Warning for live mode+ if (!is_paper) {+ ImGui::TextColored(ImVec4(0.9f, 0.5f, 0.1f, 1.0f), "Real money at risk!");+ }}// Error / Success messages@@ -2047,10 +2410,21 @@ void CryptoTradingScreen::submit_order() {order_form_.error.clear();order_form_.success.clear();- LOG_INFO(TAG, "Submitting order: symbol=%s side=%d type=%d qty='%s' price='%s'",+ bool is_live = (trading_mode_ == TradingMode::Live);+ LOG_INFO(TAG, "Submitting %s order: symbol=%s side=%d type=%d qty='%s' price='%s'",+ is_live ? "LIVE" : "PAPER",selected_symbol_.c_str(), order_form_.side_idx, order_form_.type_idx,order_form_.quantity_buf, order_form_.price_buf);+ // Live mode guard — require credentials+ if (is_live) {+ // Check if exchange has credentials configured+ // (credentials are stored in ExchangeService)+ auto& svc = trading::ExchangeService::instance();+ // For now, just warn — the actual API call will fail if no creds+ LOG_INFO(TAG, "Live order being routed to %s exchange API", exchange_id_.c_str());+ }+// Parse quantitydouble qty = 0;try {@@ -2121,13 +2495,36 @@ void CryptoTradingScreen::submit_order() {try {if (trading_mode_ == TradingMode::Live) {- // Live trading — route through exchange API- auto& svc = trading::ExchangeService::instance();- auto result = svc.place_order(selected_symbol_, side, order_type, qty,- price.value_or(0.0));- LOG_INFO(TAG, "Live order placed: %s", result.dump(2).c_str());- order_form_.success = "Live order sent!";- order_form_.msg_timer = 3.0f;+ // Live trading — route through exchange API on background thread+ order_submitting_.store(true);+ std::string sym = selected_symbol_;+ std::string pid = portfolio_id_;+ std::thread([this, sym, side, order_type, qty, price, pid]() {+ try {+ auto& svc = trading::ExchangeService::instance();+ auto result = svc.place_order(sym, side, order_type, qty,+ price.value_or(0.0));+ LOG_INFO(TAG, "Live order placed: %s", result.dump(2).c_str());+ {+ std::lock_guard<std::mutex> lock(data_mutex_);+ order_form_.success = "Live order sent!";+ order_form_.msg_timer = 3.0f;+ }+ trading::ExchangeService::instance().watch_symbol(sym, pid);+ refresh_portfolio_data();+ } catch (const std::exception& e) {+ std::lock_guard<std::mutex> lock(data_mutex_);+ order_form_.error = e.what();+ order_form_.msg_timer = 5.0f;+ LOG_ERROR(TAG, "Live order FAILED: %s", e.what());+ }+ order_submitting_.store(false);+ }).detach();+ // Clear form immediately+ order_form_.quantity_buf[0] = '\0';+ order_form_.price_buf[0] = '\0';+ order_form_.stop_price_buf[0] = '\0';+ return; // skip the rest — thread handles result} else {// Paper tradingauto order = trading::pt_place_order(@@ -2170,7 +2567,11 @@ void CryptoTradingScreen::submit_order() {}void CryptoTradingScreen::cancel_order(const std::string& order_id) {- LOG_INFO(TAG, "Cancelling order: %s", order_id.c_str());+ if (trading_mode_ != TradingMode::Paper) {+ LOG_WARN(TAG, "cancel_order called in Live mode — not yet supported");+ return;+ }+ LOG_INFO(TAG, "Cancelling paper order: %s", order_id.c_str());try {trading::pt_cancel_order(order_id);trading::OrderMatcher::instance().remove_order(order_id);diff --git a/fincept-cpp/src/screens/crypto_trading/crypto_trading_screen.h b/fincept-cpp/src/screens/crypto_trading/crypto_trading_screen.hindex a0795348b..7f7ea78e3 100644--- a/fincept-cpp/src/screens/crypto_trading/crypto_trading_screen.h+++ b/fincept-cpp/src/screens/crypto_trading/crypto_trading_screen.h@@ -26,6 +26,12 @@ private:void init();void load_portfolio();+ // Exchange & symbol switching — proper lifecycle management+ void switch_exchange(const std::string& exchange_id);+ void switch_symbol(const std::string& symbol);+ void restart_ws_stream();+ void clear_market_data();+// Async data fetchers — run in background threadsvoid async_refresh_ticker();void async_refresh_orderbook();@@ -71,6 +77,14 @@ private:int watchlist_selected_ = 0;char watchlist_filter_[64] = "";+ // --- Symbol search (exchange-wide) ---+ std::vector<trading::MarketInfo> search_results_;+ std::atomic<bool> search_fetching_{false};+ bool search_markets_loaded_ = false;+ std::vector<trading::MarketInfo> all_markets_; // cached market list for current exchange+ std::string search_cache_exchange_; // exchange_id when markets were fetched+ std::string pending_symbol_switch_; // deferred switch (set inside locked section)+// --- Ticker (selected symbol) ---trading::TickerData current_ticker_;std::atomic<bool> ticker_loading_{false};@@ -89,6 +103,7 @@ private:// --- Order entry ---OrderFormState order_form_;+ std::atomic<bool> order_submitting_{false};// --- Paper trading portfolio ---std::string portfolio_id_;diff --git a/fincept-cpp/src/screens/dashboard/dashboard_data.cpp b/fincept-cpp/src/screens/dashboard/dashboard_data.cppindex e87d929a0..0dba18138 100644--- a/fincept-cpp/src/screens/dashboard/dashboard_data.cpp+++ b/fincept-cpp/src/screens/dashboard/dashboard_data.cpp@@ -1,6 +1,7 @@#include "dashboard_data.h"#include "python/python_runner.h"#include "http/http_client.h"+#include "storage/cache_service.h"#include <nlohmann/json.hpp>#include <thread>#include <sstream>@@ -288,7 +289,6 @@ void DashboardData::fetch_category(DataCategory cat) {auto syms = symbols_for(cat);if (syms.empty()) {- // No symbols to fetch (e.g. Ticker assembles from other categories)state.has_data = true;state.last_fetch = std::chrono::steady_clock::now();return;@@ -298,11 +298,22 @@ void DashboardData::fetch_category(DataCategory 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& cache = CacheService::instance();+ std::string cache_key = CacheService::make_key("market-quotes", "dashboard", std::to_string(idx));++ std::string output;+ auto cached = cache.get(cache_key);+ if (cached && !cached->empty()) {+ output = *cached;+ } else {+ output = run_yfinance(args);+ if (!output.empty()) {+ cache.set(cache_key, output, "market-quotes", CacheTTL::FIVE_MIN);+ }+ }auto parsed = parse_quotes(output, lbls);{@@ -313,7 +324,6 @@ void DashboardData::fetch_category(DataCategory cat) {} else if (categories_[idx].quotes.empty()) {categories_[idx].error = "Failed to fetch data";}- // Keep stale data if fetch fails but we had data beforecategories_[idx].has_data = !categories_[idx].quotes.empty();categories_[idx].last_fetch = std::chrono::steady_clock::now();}@@ -336,12 +346,11 @@ void DashboardData::fetch_news_feeds() {// Tier 1-2 financial RSS feeds (same as NewsScreen)FeedDef feeds[] = {- {"https://feeds.reuters.com/reuters/businessNews", "Reuters", "MARKETS", 1},- {"https://feeds.reuters.com/reuters/financialsNews", "Reuters", "MARKETS", 1},- {"https://feeds.bloomberg.com/markets/news.rss", "Bloomberg", "MARKETS", 2},{"https://feeds.a.dj.com/rss/RSSMarketsMain.xml", "WSJ", "MARKETS", 2},{"https://search.cnbc.com/rs/search/combinedcms/view.xml?partnerId=wrss01&id=100003114", "CNBC", "MARKETS", 2},{"https://feeds.marketwatch.com/marketwatch/topstories/", "MarketWatch", "MARKETS", 2},+ {"https://finance.yahoo.com/news/rssindex", "Yahoo Finance","MARKETS", 2},+ {"https://www.investing.com/rss/news.rss", "Investing.com","MARKETS", 2},{"https://www.coindesk.com/arc/outboundfeeds/rss/", "CoinDesk", "CRYPTO", 2},{"https://www.federalreserve.gov/feeds/press_all.xml","Fed Reserve", "ECONOMIC", 1},};@@ -353,12 +362,21 @@ void DashboardData::fetch_news_feeds() {hdrs["User-Agent"] = "FinceptTerminal/4.0.0";hdrs["Accept"] = "application/rss+xml, application/xml, text/xml, */*";- for (auto& feed : feeds) {- auto resp = http.get(feed.url, hdrs);- if (!resp.success || resp.body.empty()) continue;+ auto& cache = CacheService::instance();- // Simple RSS XML parsing — extract <item> blocks- std::string& xml = resp.body;+ for (auto& feed : feeds) {+ std::string feed_cache_key = CacheService::make_key("news", "dashboard-rss", feed.source);+ std::string xml;++ auto feed_cached = cache.get(feed_cache_key);+ if (feed_cached && !feed_cached->empty()) {+ xml = *feed_cached;+ } else {+ auto resp = http.get(feed.url, hdrs);+ if (!resp.success || resp.body.empty()) continue;+ xml = resp.body;+ cache.set(feed_cache_key, xml, "news", CacheTTL::TEN_MIN);+ }size_t pos = 0;int count = 0;while (count < 5 && pos < xml.size()) { // Max 5 items per feeddiff --git a/fincept-cpp/src/screens/dashboard/dashboard_panels.cpp b/fincept-cpp/src/screens/dashboard/dashboard_panels.cppindex 476f781f1..24ebd5fca 100644--- a/fincept-cpp/src/screens/dashboard/dashboard_panels.cpp+++ b/fincept-cpp/src/screens/dashboard/dashboard_panels.cpp@@ -493,10 +493,62 @@ void DashboardScreen::render_market_pulse(float width, float height) {}// ============================================================================-// Widget Grid — positions widgets using absolute cursor positions+// Widget Grid — scrollable, drag-to-rearrange, resizable widgets// ============================================================================++// Check if placing a widget at (col, row) with (cs, rs) span would overlap+// any other widget. skip_id is the widget being moved/resized (excluded).+static bool would_overlap(const std::vector<WidgetInstance>& widgets,+ const std::string& skip_id,+ int col, int row, int cs, int rs) {+ for (const auto& other : widgets) {+ if (!other.visible || other.id == skip_id) continue;+ // Axis-aligned rect overlap test+ bool h_overlap = col < other.col + other.col_span && col + cs > other.col;+ bool v_overlap = row < other.row + other.row_span && row + rs > other.row;+ if (h_overlap && v_overlap) return true;+ }+ return false;+}++// Find the maximum col_span a widget can grow to without overlapping others+// or exceeding grid bounds.+static int max_col_span_for(const std::vector<WidgetInstance>& widgets,+ const std::string& wid, int col, int row,+ int row_span, int grid_cols) {+ int max_cs = grid_cols - col;+ for (const auto& other : widgets) {+ if (!other.visible || other.id == wid) continue;+ bool v_overlap = row < other.row + other.row_span && row + row_span > other.row;+ if (v_overlap && other.col >= col) {+ max_cs = std::min(max_cs, other.col - col);+ }+ }+ return std::max(1, max_cs);+}++// Find the maximum row_span a widget can grow to without overlapping others+// or exceeding grid bounds.+static int max_row_span_for(const std::vector<WidgetInstance>& widgets,+ const std::string& wid, int col, int row,+ int col_span, int grid_rows) {+ int max_rs = grid_rows - row;+ for (const auto& other : widgets) {+ if (!other.visible || other.id == wid) continue;+ bool h_overlap = col < other.col + other.col_span && col + col_span > other.col;+ if (h_overlap && other.row >= row) {+ max_rs = std::min(max_rs, other.row - row);+ }+ }+ return std::max(1, max_rs);+}+void DashboardScreen::render_widget_grid(float width, float height) {float gap = 4.0f;+ grid_gap_ = gap;++ const int grid_cols = layout_.grid_cols;+ const int grid_rows = layout_.grid_rows;int max_col = 0, max_row = 0;for (auto& w : layout_.widgets) {@@ -504,20 +556,155 @@ void DashboardScreen::render_widget_grid(float width, float height) {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;-+ if (max_col == 0) max_col = grid_cols;+ if (max_row == 0) max_row = grid_rows;+ // Ensure computed max doesn't exceed configured grid+ max_col = std::max(max_col, grid_cols);+ max_row = std::max(max_row, grid_rows);++ // Fixed cell height — widgets keep their size, scrollbar handles overflow.+ // Use the viewport height divided by the *configured* grid rows (not max_row)+ // so adding more widgets doesn't shrink existing ones.+ float base_rows = (float)grid_rows;float cell_w = (width - (max_col + 1) * gap) / max_col;- float cell_h = (height - (max_row + 1) * gap) / max_row;+ float cell_h = (height - (base_rows + 1) * gap) / base_rows;+ // Enforce minimum sizes for usabilitycell_w = std::max(100.0f, cell_w);- cell_h = std::max(60.0f, cell_h);+ cell_h = std::max(180.0f, cell_h);++ grid_cell_w_ = cell_w;+ grid_cell_h_ = cell_h;- bool needs_scroll = (max_row * (cell_h + gap) + gap) > height;- ImGuiWindowFlags flags = needs_scroll ? 0 : ImGuiWindowFlags_NoScrollbar;+ // Total content height — always allow scroll if content exceeds view+ float content_h = max_row * (cell_h + gap) + gap;+ ImGuiWindowFlags flags = ImGuiWindowFlags_AlwaysVerticalScrollbar;+ ImGui::PushStyleColor(ImGuiCol_ScrollbarBg, ImVec4(0.03f, 0.03f, 0.03f, 0.8f));+ ImGui::PushStyleColor(ImGuiCol_ScrollbarGrab, ImVec4(1.0f, 0.533f, 0.0f, 0.35f));+ ImGui::PushStyleColor(ImGuiCol_ScrollbarGrabHovered, ImVec4(1.0f, 0.533f, 0.0f, 0.55f));+ ImGui::PushStyleColor(ImGuiCol_ScrollbarGrabActive, ImVec4(1.0f, 0.533f, 0.0f, 0.75f));ImGui::BeginChild("##grid", ImVec2(width, height), false, flags);+ // Reserve content space so scroll range is correct+ ImGui::Dummy(ImVec2(width - 16, content_h));+ ImGui::SetCursorPos(ImVec2(0, 0));++ ImVec2 grid_origin = ImGui::GetCursorScreenPos();+ ImVec2 mouse_pos = ImGui::GetIO().MousePos;+ bool mouse_down = ImGui::GetIO().MouseDown[0];+ bool mouse_released = ImGui::IsMouseReleased(0);++ // --- Handle drag/resize: snap to grid on release, smooth pixel offset while dragging ---+ // Track pixel offsets for smooth visual feedback during drag/resize+ float drag_pixel_dx = 0, drag_pixel_dy = 0;+ float resize_pixel_dw = 0, resize_pixel_dh = 0;++ if (mouse_released) {+ if (!dragging_widget_id_.empty()) {+ // Snap final position to grid on release+ ImVec2 delta = ImVec2(mouse_pos.x - drag_start_mouse_.x,+ mouse_pos.y - drag_start_mouse_.y);+ int col_delta = (int)std::round(delta.x / (cell_w + gap));+ int row_delta = (int)std::round(delta.y / (cell_h + gap));++ // Find the widget being dragged+ for (auto& w : layout_.widgets) {+ if (w.id == dragging_widget_id_) {+ int new_col = drag_start_col_ + col_delta;+ int new_row = drag_start_row_ + row_delta;+ // Clamp to grid bounds+ new_col = std::clamp(new_col, 0, grid_cols - w.col_span);+ new_row = std::clamp(new_row, 0, grid_rows - w.row_span);+ // Only apply if no overlap at new position+ if (!would_overlap(layout_.widgets, w.id,+ new_col, new_row, w.col_span, w.row_span)) {+ w.col = new_col;+ w.row = new_row;+ }+ break;+ }+ }+ save_layout();+ dragging_widget_id_.clear();+ }+ if (!resizing_widget_id_.empty()) {+ // Snap final span to grid on release+ ImVec2 delta = ImVec2(mouse_pos.x - drag_start_mouse_.x,+ mouse_pos.y - drag_start_mouse_.y);+ int cs_delta = (int)std::round(delta.x / (cell_w + gap));+ int rs_delta = (int)std::round(delta.y / (cell_h + gap));++ for (auto& w : layout_.widgets) {+ if (w.id == resizing_widget_id_) {+ // Clamp col_span to grid boundary+ int new_cs = std::clamp(resize_start_col_span_ + cs_delta,+ 1, grid_cols - w.col);+ // Clamp row_span to grid boundary+ int new_rs = std::clamp(resize_start_row_span_ + rs_delta,+ 1, grid_rows - w.row);+ // Further clamp to prevent overlap with other widgets+ int limit_cs = max_col_span_for(layout_.widgets, w.id,+ w.col, w.row, new_rs, grid_cols);+ new_cs = std::min(new_cs, limit_cs);+ int limit_rs = max_row_span_for(layout_.widgets, w.id,+ w.col, w.row, new_cs, grid_rows);+ new_rs = std::min(new_rs, limit_rs);++ w.col_span = new_cs;+ w.row_span = new_rs;+ break;+ }+ }+ save_layout();+ resizing_widget_id_.clear();+ }+ }++ // --- Compute smooth pixel offsets while dragging (don't modify grid pos yet) ---+ if (!dragging_widget_id_.empty() && mouse_down) {+ drag_pixel_dx = mouse_pos.x - drag_start_mouse_.x;+ drag_pixel_dy = mouse_pos.y - drag_start_mouse_.y;+ }++ // --- Compute smooth pixel offsets while resizing (don't modify span yet) ---+ // Clamp visual resize to grid boundaries and overlap limits+ if (!resizing_widget_id_.empty() && mouse_down) {+ resize_pixel_dw = mouse_pos.x - drag_start_mouse_.x;+ resize_pixel_dh = mouse_pos.y - drag_start_mouse_.y;++ // Find the widget being resized and compute clamped visual size+ for (const auto& w : layout_.widgets) {+ if (w.id == resizing_widget_id_) {+ // Compute what the snapped span would be+ int preview_cs = std::clamp(+ resize_start_col_span_ + (int)std::round(resize_pixel_dw / (cell_w + gap)),+ 1, grid_cols - w.col);+ int preview_rs = std::clamp(+ resize_start_row_span_ + (int)std::round(resize_pixel_dh / (cell_h + gap)),+ 1, grid_rows - w.row);+ // Clamp to overlap limits+ int limit_cs = max_col_span_for(layout_.widgets, w.id,+ w.col, w.row, preview_rs, grid_cols);+ preview_cs = std::min(preview_cs, limit_cs);+ int limit_rs = max_row_span_for(layout_.widgets, w.id,+ w.col, w.row, preview_cs, grid_rows);+ preview_rs = std::min(preview_rs, limit_rs);+ // Convert clamped span back to pixel delta+ float max_w = preview_cs * cell_w + (preview_cs - 1) * gap;+ float max_h = preview_rs * cell_h + (preview_rs - 1) * gap;+ float base_w = w.col_span * cell_w + (w.col_span - 1) * gap;+ float base_h = w.row_span * cell_h + (w.row_span - 1) * gap;+ resize_pixel_dw = std::clamp(resize_pixel_dw,+ cell_w - base_w, max_w - base_w);+ resize_pixel_dh = std::clamp(resize_pixel_dh,+ cell_h - base_h, max_h - base_h);+ break;+ }+ }+ }++ // --- Render widgets ---for (auto& w : layout_.widgets) {if (!w.visible) continue;@@ -526,11 +713,59 @@ void DashboardScreen::render_widget_grid(float width, float height) {float ww = w.col_span * cell_w + (w.col_span - 1) * gap;float wh = w.row_span * cell_h + (w.row_span - 1) * gap;+ bool is_dragging = (w.id == dragging_widget_id_);+ bool is_resizing = (w.id == resizing_widget_id_);++ // Apply smooth pixel offset during drag (visual only)+ if (is_dragging) {+ wx += drag_pixel_dx;+ wy += drag_pixel_dy;+ }++ // Apply smooth pixel offset during resize (visual only, already clamped above)+ if (is_resizing) {+ ww = std::max(cell_w, ww + resize_pixel_dw);+ wh = std::max(cell_h, wh + resize_pixel_dh);+ }+ImGui::SetCursorPos(ImVec2(wx, wy));- render_widget_frame(w.title.c_str(), accent_for(w.type), ww, wh, w.type);++ // Draw drop-target ghost showing snapped position while dragging+ if (is_dragging) {+ int snap_col = drag_start_col_ + (int)std::round(drag_pixel_dx / (cell_w + gap));+ int snap_row = drag_start_row_ + (int)std::round(drag_pixel_dy / (cell_h + gap));+ // Clamp ghost to grid bounds+ snap_col = std::clamp(snap_col, 0, grid_cols - w.col_span);+ snap_row = std::clamp(snap_row, 0, grid_rows - w.row_span);++ float ghost_x = gap + snap_col * (cell_w + gap);+ float ghost_y = gap + snap_row * (cell_h + gap);+ float ghost_w = w.col_span * cell_w + (w.col_span - 1) * gap;+ float ghost_h = w.row_span * cell_h + (w.row_span - 1) * gap;+ ImVec2 go = ImGui::GetWindowPos();+ float scroll_y = ImGui::GetScrollY();++ // Color ghost red if it would overlap, orange if valid+ bool overlap = would_overlap(layout_.widgets, w.id,+ snap_col, snap_row, w.col_span, w.row_span);+ ImU32 fill_col = overlap ? IM_COL32(255, 50, 50, 30) : IM_COL32(255, 136, 0, 30);+ ImU32 border_col = overlap ? IM_COL32(255, 50, 50, 120) : IM_COL32(255, 136, 0, 120);++ ImGui::GetWindowDrawList()->AddRectFilled(+ ImVec2(go.x + ghost_x, go.y + ghost_y - scroll_y),+ ImVec2(go.x + ghost_x + ghost_w, go.y + ghost_y + ghost_h - scroll_y),+ fill_col, 3.0f);+ ImGui::GetWindowDrawList()->AddRect(+ ImVec2(go.x + ghost_x, go.y + ghost_y - scroll_y),+ ImVec2(go.x + ghost_x + ghost_w, go.y + ghost_y + ghost_h - scroll_y),+ border_col, 3.0f, 0, 1.5f);+ }++ render_widget_frame(w.title.c_str(), accent_for(w.type), ww, wh, w.type, w.id);}ImGui::EndChild();+ ImGui::PopStyleColor(4);}// ============================================================================diff --git a/fincept-cpp/src/screens/dashboard/dashboard_screen.cpp b/fincept-cpp/src/screens/dashboard/dashboard_screen.cppindex ecde47ba5..4dc539a54 100644--- a/fincept-cpp/src/screens/dashboard/dashboard_screen.cpp+++ b/fincept-cpp/src/screens/dashboard/dashboard_screen.cpp@@ -28,6 +28,7 @@ ImVec4 DashboardScreen::accent_for(WidgetType type) {case WidgetType::Performance: return FC_GREEN;case WidgetType::TopMovers: return FC_PURPLE;case WidgetType::MarketData: return FC_BLUE;+ case WidgetType::YouTubeStream: return FC_RED;default: return FC_ORANGE;}}@@ -134,6 +135,16 @@ void DashboardScreen::load_layout() {layout_ = DashboardLayout::from_json(j);}} catch (...) {}++ // Sanitize widget positions: clamp to grid bounds+ const int gc = std::max(1, layout_.grid_cols);+ const int gr = std::max(1, layout_.grid_rows);+ for (auto& w : layout_.widgets) {+ w.col_span = std::clamp(w.col_span, 1, gc);+ w.row_span = std::clamp(w.row_span, 1, gr);+ w.col = std::clamp(w.col, 0, gc - w.col_span);+ w.row = std::clamp(w.row, 0, gr - w.row_span);+ }}// ============================================================================@@ -144,12 +155,50 @@ void DashboardScreen::add_widget(WidgetType type) {w.id = generate_widget_id();w.type = type;w.title = widget_type_name(type);++ // Find first empty cell in the grid by scanning row-by-row, col-by-col+ // Build an occupancy grid to find gaps+ int grid_cols = std::max(layout_.grid_cols, 1);int max_row = 0;for (auto& existing : layout_.widgets) {+ if (!existing.visible) continue;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;+ // Search up to max_row+1 to allow placing in a new row if grid is full+ int search_rows = std::max(max_row + 1, layout_.grid_rows);++ // Build occupancy map+ std::vector<std::vector<bool>> occupied(search_rows, std::vector<bool>(grid_cols, false));+ for (auto& existing : layout_.widgets) {+ if (!existing.visible) continue;+ for (int r = existing.row; r < existing.row + existing.row_span && r < search_rows; r++) {+ for (int c = existing.col; c < existing.col + existing.col_span && c < grid_cols; c++) {+ occupied[r][c] = true;+ }+ }+ }++ // Find first empty cell+ bool found = false;+ for (int r = 0; r < search_rows && !found; r++) {+ for (int c = 0; c < grid_cols && !found; c++) {+ if (!occupied[r][c]) {+ w.col = c;+ w.row = r;+ found = true;+ }+ }+ }++ // If grid is completely full, add a new row+ if (!found) {+ w.col = 0;+ w.row = max_row;+ }++ w.col_span = 1;+ w.row_span = 1;layout_.widgets.push_back(w);save_layout();}diff --git a/fincept-cpp/src/screens/dashboard/dashboard_screen.h b/fincept-cpp/src/screens/dashboard/dashboard_screen.hindex eb159952e..e714edc0b 100644--- a/fincept-cpp/src/screens/dashboard/dashboard_screen.h+++ b/fincept-cpp/src/screens/dashboard/dashboard_screen.h@@ -5,10 +5,12 @@#include "dashboard_data.h"#include "widget_registry.h"+#include "media/mpv_player.h"#include <imgui.h>#include <string>#include <vector>#include <chrono>+#include <memory>namespace fincept::dashboard {@@ -54,7 +56,8 @@ private:// Widget frame — wraps any widget with header, accent, close buttonvoid render_widget_frame(const char* title, const ImVec4& accent,- float w, float h, WidgetType type);+ float w, float h, WidgetType type,+ const std::string& widget_id);// Individual widget renderers (read from DashboardData)void widget_global_indices(float w, float h);@@ -68,6 +71,34 @@ private:void widget_performance(float w, float h);void widget_top_movers(float w, float h);void widget_market_data(float w, float h);+ void widget_youtube_stream(float w, float h);++ // Drag & resize state+ std::string dragging_widget_id_; // widget being dragged+ std::string resizing_widget_id_; // widget being resized+ ImVec2 drag_start_mouse_; // mouse pos at drag start+ int drag_start_col_ = 0; // original col at drag start+ int drag_start_row_ = 0; // original row at drag start+ int resize_start_col_span_ = 1; // original col_span at resize start+ int resize_start_row_span_ = 1; // original row_span at resize start+ float grid_cell_w_ = 100.0f; // current cell width (for drag calc)+ float grid_cell_h_ = 100.0f; // current cell height (for drag calc)+ float grid_gap_ = 4.0f; // grid gap++ // YouTube widget state+ struct YouTubeEntry {+ std::string url;+ std::string title;+ std::string author;+ bool fetched = false;+ bool fetching = false;+ };+ char yt_url_buf_[512] = {};+ std::vector<YouTubeEntry> yt_entries_;+ int yt_active_player_ = -1; // index of entry currently playing (-1 = none)+ int yt_volume_ = 80; // 0-100+ std::unique_ptr<media::MpvPlayer> yt_player_;+ void yt_fetch_metadata(int index);// Render a generic quote table (reused by many widgets)void render_quote_table(const char* table_id,diff --git a/fincept-cpp/src/screens/dashboard/dashboard_widgets.cpp b/fincept-cpp/src/screens/dashboard/dashboard_widgets.cppindex c5640ed5e..a0decf11b 100644--- a/fincept-cpp/src/screens/dashboard/dashboard_widgets.cpp+++ b/fincept-cpp/src/screens/dashboard/dashboard_widgets.cpp@@ -1,8 +1,17 @@#include "dashboard_screen.h"#include "dashboard_helpers.h"+#include "http/http_client.h"+#include "storage/cache_service.h"#include <imgui.h>#include <cmath>#include <algorithm>+#include <thread>+#include <regex>++#ifdef _WIN32+#include <windows.h>+#include <shellapi.h>+#endifnamespace fincept::dashboard {@@ -15,7 +24,8 @@ void DashboardScreen::render_quote_table(const char* col1, const char* col2, const char* col3,bool show_volume, int price_decimals){- int num_cols = show_volume ? 4 : 3;+ // Add a "Range" column for intraday high/low bar visualization+ int num_cols = (show_volume ? 4 : 3) + 1; // +1 for range barImGuiTableFlags flags = ImGuiTableFlags_RowBg | ImGuiTableFlags_ScrollY |ImGuiTableFlags_SizingStretchProp;@@ -24,6 +34,7 @@ void DashboardScreen::render_quote_table(ImGui::TableSetupColumn(col1, 0, 2.0f);ImGui::TableSetupColumn(col2, 0, 1.5f);ImGui::TableSetupColumn(col3, 0, 1.0f);+ ImGui::TableSetupColumn("Range", 0, 1.2f);if (show_volume) ImGui::TableSetupColumn("Vol", 0, 1.0f);ImGui::TableSetupScrollFreeze(0, 1);ImGui::TableHeadersRow();@@ -36,6 +47,75 @@ void DashboardScreen::render_quote_table(ImGui::Text("%s", fmt_price(q.price, price_decimals).c_str());ImGui::TableNextColumn();ImGui::TextColored(chg_col(q.change_percent), "%+.2f%%", q.change_percent);++ // Range bar: shows intraday high-low range with current price marker+ ImGui::TableNextColumn();+ if (q.high > 0 && q.low > 0 && q.high >= q.low) {+ ImVec2 p = ImGui::GetCursorScreenPos();+ float bar_w = ImGui::GetContentRegionAvail().x - 4;+ float bar_h = 6.0f;+ float y_center = p.y + ImGui::GetTextLineHeight() * 0.5f - bar_h * 0.5f;+ ImDrawList* dl = ImGui::GetWindowDrawList();++ // Background track+ dl->AddRectFilled(+ ImVec2(p.x, y_center),+ ImVec2(p.x + bar_w, y_center + bar_h),+ IM_COL32(40, 40, 40, 200), 2.0f);++ // Filled range from open to current+ float range = q.high - q.low;+ if (range > 0 && bar_w > 4) {+ float open_frac = (q.open > 0)+ ? (float)((q.open - q.low) / range) : 0.0f;+ float cur_frac = (float)((q.price - q.low) / range);+ open_frac = std::clamp(open_frac, 0.0f, 1.0f);+ cur_frac = std::clamp(cur_frac, 0.0f, 1.0f);++ float x1 = p.x + std::min(open_frac, cur_frac) * bar_w;+ float x2 = p.x + std::max(open_frac, cur_frac) * bar_w;+ bool up = q.price >= q.open;+ ImU32 fill_col = up ? IM_COL32(0, 180, 100, 200) : IM_COL32(220, 50, 50, 200);+ dl->AddRectFilled(ImVec2(x1, y_center), ImVec2(x2, y_center + bar_h),+ fill_col, 2.0f);++ // Current price marker (white triangle/line)+ float cx = p.x + cur_frac * bar_w;+ dl->AddRectFilled(+ ImVec2(cx - 1, y_center - 1),+ ImVec2(cx + 1, y_center + bar_h + 1),+ IM_COL32(255, 255, 255, 220));+ }+ ImGui::Dummy(ImVec2(bar_w, ImGui::GetTextLineHeight()));+ } else {+ // No high/low data — show a change-direction bar+ float bar_w = ImGui::GetContentRegionAvail().x - 4;+ ImVec2 p = ImGui::GetCursorScreenPos();+ float bar_h = 6.0f;+ float y_center = p.y + ImGui::GetTextLineHeight() * 0.5f - bar_h * 0.5f;+ ImDrawList* dl = ImGui::GetWindowDrawList();++ dl->AddRectFilled(ImVec2(p.x, y_center), ImVec2(p.x + bar_w, y_center + bar_h),+ IM_COL32(40, 40, 40, 200), 2.0f);++ // Change magnitude bar from center+ float mid = p.x + bar_w * 0.5f;+ float mag = std::clamp(std::abs((float)q.change_percent) / 5.0f, 0.0f, 1.0f);+ float extent = mag * bar_w * 0.5f;+ bool up = q.change_percent >= 0;+ ImU32 col = up ? IM_COL32(0, 180, 100, 200) : IM_COL32(220, 50, 50, 200);+ if (up)+ dl->AddRectFilled(ImVec2(mid, y_center), ImVec2(mid + extent, y_center + bar_h), col, 2.0f);+ else+ dl->AddRectFilled(ImVec2(mid - extent, y_center), ImVec2(mid, y_center + bar_h), col, 2.0f);++ // Center line+ dl->AddLine(ImVec2(mid, y_center - 1), ImVec2(mid, y_center + bar_h + 1),+ IM_COL32(100, 100, 100, 180));++ ImGui::Dummy(ImVec2(bar_w, ImGui::GetTextLineHeight()));+ }+if (show_volume) {ImGui::TableNextColumn();ImGui::TextColored(FC_MUTED, "%s", fmt_volume(q.volume).c_str());@@ -245,11 +325,12 @@ void DashboardScreen::widget_news(float w, float h) {}void DashboardScreen::widget_economic(float w, float h) {- if (ImGui::BeginTable("##eco", 3, ImGuiTableFlags_RowBg | ImGuiTableFlags_ScrollY |+ if (ImGui::BeginTable("##eco", 4, 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::TableSetupColumn("", 0, 1.2f);ImGui::TableSetupScrollFreeze(0, 1);ImGui::TableHeadersRow();for (auto& e : econ_data_) {@@ -257,17 +338,39 @@ void DashboardScreen::widget_economic(float w, float h) {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);+ // Change bar+ ImGui::TableNextColumn();+ float bar_w = ImGui::GetContentRegionAvail().x - 4;+ if (bar_w > 8) {+ ImVec2 p = ImGui::GetCursorScreenPos();+ float bar_h = 6.0f;+ float yc = p.y + ImGui::GetTextLineHeight() * 0.5f - bar_h * 0.5f;+ ImDrawList* dl = ImGui::GetWindowDrawList();+ dl->AddRectFilled(ImVec2(p.x, yc), ImVec2(p.x + bar_w, yc + bar_h),+ IM_COL32(40, 40, 40, 200), 2.0f);+ float mid = p.x + bar_w * 0.5f;+ float mag = std::clamp(std::abs(e.change) / 3.0f, 0.0f, 1.0f);+ float ext = mag * bar_w * 0.5f;+ ImU32 col = e.change >= 0 ? IM_COL32(0, 180, 100, 200) : IM_COL32(220, 50, 50, 200);+ if (e.change >= 0)+ dl->AddRectFilled(ImVec2(mid, yc), ImVec2(mid + ext, yc + bar_h), col, 2.0f);+ else+ dl->AddRectFilled(ImVec2(mid - ext, yc), ImVec2(mid, yc + bar_h), col, 2.0f);+ dl->AddLine(ImVec2(mid, yc - 1), ImVec2(mid, yc + bar_h + 1), IM_COL32(100, 100, 100, 180));+ ImGui::Dummy(ImVec2(bar_w, ImGui::GetTextLineHeight()));+ }}ImGui::EndTable();}}void DashboardScreen::widget_geopolitics(float w, float h) {- if (ImGui::BeginTable("##geo", 3, ImGuiTableFlags_RowBg | ImGuiTableFlags_ScrollY |+ if (ImGui::BeginTable("##geo", 4, 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::TableSetupColumn("Risk", 0, 0.7f);+ ImGui::TableSetupColumn("Level", 0, 1.4f);+ ImGui::TableSetupColumn("Trend", 0, 0.8f);ImGui::TableSetupScrollFreeze(0, 1);ImGui::TableHeadersRow();for (auto& g : geo_data_) {@@ -275,7 +378,35 @@ void DashboardScreen::widget_geopolitics(float w, float h) {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::TextColored(rc, "%.0f", g.risk);+ // Risk level bar+ ImGui::TableNextColumn();+ {+ float bar_w = ImGui::GetContentRegionAvail().x - 4;+ if (bar_w > 8) {+ ImVec2 p = ImGui::GetCursorScreenPos();+ float bar_h = 8.0f;+ float yc = p.y + ImGui::GetTextLineHeight() * 0.5f - bar_h * 0.5f;+ ImDrawList* dl = ImGui::GetWindowDrawList();+ // Background+ dl->AddRectFilled(ImVec2(p.x, yc), ImVec2(p.x + bar_w, yc + bar_h),+ IM_COL32(30, 30, 30, 220), 3.0f);+ // Filled portion based on risk 0-100+ float frac = std::clamp(g.risk / 100.0f, 0.0f, 1.0f);+ // Color gradient: green -> yellow -> red+ int r_val, g_val;+ if (frac < 0.5f) {+ r_val = (int)(frac * 2 * 220);+ g_val = 180;+ } else {+ r_val = 220;+ g_val = (int)((1.0f - frac) * 2 * 180);+ }+ dl->AddRectFilled(ImVec2(p.x, yc), ImVec2(p.x + frac * bar_w, yc + bar_h),+ IM_COL32(r_val, g_val, 0, 220), 3.0f);+ ImGui::Dummy(ImVec2(bar_w, ImGui::GetTextLineHeight()));+ }+ }ImGui::TableNextColumn();ImGui::TextColored(chg_col(g.trend), "%+.1f", g.trend);}@@ -284,10 +415,11 @@ void DashboardScreen::widget_geopolitics(float w, float h) {}void DashboardScreen::widget_performance(float w, float h) {- if (ImGui::BeginTable("##perf", 2, ImGuiTableFlags_RowBg | ImGuiTableFlags_ScrollY |+ if (ImGui::BeginTable("##perf", 3, ImGuiTableFlags_RowBg | ImGuiTableFlags_ScrollY |ImGuiTableFlags_SizingStretchProp, ImVec2(0, ImGui::GetContentRegionAvail().y))) {ImGui::TableSetupColumn("Metric", 0, 2.0f);ImGui::TableSetupColumn("Value", 0, 1.5f);+ ImGui::TableSetupColumn("", 0, 1.0f);ImGui::TableSetupScrollFreeze(0, 1);ImGui::TableHeadersRow();for (auto& p : perf_data_) {@@ -298,6 +430,27 @@ void DashboardScreen::widget_performance(float w, float h) {ImGui::TextColored(chg_col(p.change), "$%s (%+.2f%%)", fmt_price(p.value).c_str(), p.change);elseImGui::TextColored(chg_col(p.change), "%+.2f%%", p.change);+ // Change bar+ ImGui::TableNextColumn();+ float bar_w = ImGui::GetContentRegionAvail().x - 4;+ if (bar_w > 8) {+ ImVec2 bp = ImGui::GetCursorScreenPos();+ float bar_h = 6.0f;+ float yc = bp.y + ImGui::GetTextLineHeight() * 0.5f - bar_h * 0.5f;+ ImDrawList* dl = ImGui::GetWindowDrawList();+ dl->AddRectFilled(ImVec2(bp.x, yc), ImVec2(bp.x + bar_w, yc + bar_h),+ IM_COL32(40, 40, 40, 200), 2.0f);+ float mid = bp.x + bar_w * 0.5f;+ float mag = std::clamp(std::abs(p.change) / 5.0f, 0.0f, 1.0f);+ float ext = mag * bar_w * 0.5f;+ ImU32 col = p.change >= 0 ? IM_COL32(0, 180, 100, 200) : IM_COL32(220, 50, 50, 200);+ if (p.change >= 0)+ dl->AddRectFilled(ImVec2(mid, yc), ImVec2(mid + ext, yc + bar_h), col, 2.0f);+ else+ dl->AddRectFilled(ImVec2(mid - ext, yc), ImVec2(mid, yc + bar_h), col, 2.0f);+ dl->AddLine(ImVec2(mid, yc - 1), ImVec2(mid, yc + bar_h + 1), IM_COL32(100, 100, 100, 180));+ ImGui::Dummy(ImVec2(bar_w, ImGui::GetTextLineHeight()));+ }}ImGui::EndTable();}@@ -320,11 +473,333 @@ void DashboardScreen::widget_market_data(float w, float h) {render_quote_table("##mktdata", quotes, "Symbol", "Price", "Chg%", true, 2);}+// ============================================================================+// YouTube Stream Widget — link launcher with metadata fetch+// ============================================================================+static void yt_open_url(const char* url) {+#ifdef _WIN32+ ShellExecuteA(nullptr, "open", url, nullptr, nullptr, SW_SHOWNORMAL);+#elif defined(__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 std::string extract_video_id(const std::string& url) {+ // Match youtube.com/watch?v=ID, youtu.be/ID, youtube.com/live/ID+ std::regex patterns[] = {+ std::regex(R"((?:youtube\.com/watch\?.*v=)([a-zA-Z0-9_-]{11}))"),+ std::regex(R"((?:youtu\.be/)([a-zA-Z0-9_-]{11}))"),+ std::regex(R"((?:youtube\.com/live/)([a-zA-Z0-9_-]{11}))"),+ };+ for (auto& pat : patterns) {+ std::smatch m;+ if (std::regex_search(url, m, pat) && m.size() > 1) return m[1].str();+ }+ return {};+}++void DashboardScreen::yt_fetch_metadata(int index) {+ if (index < 0 || index >= (int)yt_entries_.size()) return;+ auto& entry = yt_entries_[index];+ if (entry.fetching || entry.fetched) return;+ entry.fetching = true;++ std::string url = entry.url;+ std::thread([this, index, url]() {+ // Use YouTube oEmbed API (no API key needed)+ auto& cache = CacheService::instance();+ std::string oembed_ck = CacheService::make_key("api-response", "yt-oembed", url);++ std::string body;+ auto cached_oembed = cache.get(oembed_ck);+ if (cached_oembed && !cached_oembed->empty()) {+ body = *cached_oembed;+ } else {+ std::string oembed_url = "https://www.youtube.com/oembed?url=" + url + "&format=json";+ http::Headers headers;+ headers["accept"] = "application/json";+ auto resp = http::HttpClient::instance().get(oembed_url, headers);+ if (resp.success && !resp.body.empty()) {+ body = resp.body;+ cache.set(oembed_ck, body, "api-response", CacheTTL::ONE_DAY);+ }+ }++ if (index < (int)yt_entries_.size()) {+ auto& e = yt_entries_[index];+ if (!body.empty()) {+ try {+ auto j = nlohmann::json::parse(body);+ e.title = j.value("title", "");+ e.author = j.value("author_name", "");+ } catch (...) {+ e.title = "(Could not load metadata)";+ }+ } else {+ e.title = "(Could not load metadata)";+ }+ e.fetched = true;+ e.fetching = false;+ }+ }).detach();+}++void DashboardScreen::widget_youtube_stream(float w, float h) {+ float avail_w = ImGui::GetContentRegionAvail().x;++ // ---- Video player area (when playing) ----+#ifdef FINCEPT_HAS_MPV+ if (yt_active_player_ >= 0 && yt_active_player_ < (int)yt_entries_.size() && yt_player_) {+ auto& active = yt_entries_[yt_active_player_];+ auto state = yt_player_->state();++ // Video display area — fill all available space minus controls+ float controls_h = 54.0f;+ ImVec2 avail = ImGui::GetContentRegionAvail();+ float video_w = avail.x;+ float video_h = avail.y - controls_h;+ if (video_h < 60) video_h = 60;+ if (video_w < 60) video_w = 60;++ // Render mpv frame into texture+ unsigned int tex = yt_player_->render_frame((int)video_w, (int)video_h);+ if (tex) {+ ImGui::Image((ImTextureID)(intptr_t)tex, ImVec2(video_w, video_h));+ } else {+ // Loading / error state+ ImGui::PushStyleColor(ImGuiCol_ChildBg, ImVec4(0.0f, 0.0f, 0.0f, 1.0f));+ ImGui::BeginChild("##yt_vid_placeholder", ImVec2(video_w, video_h), false);+ float cy = video_h * 0.4f;+ ImGui::Dummy(ImVec2(0, cy));+ const char* status_text = "Loading video...";+ if (state == media::PlayerState::Error)+ status_text = yt_player_->error_msg().c_str();+ else if (state == media::PlayerState::Stopped)+ status_text = "Stopped";+ float tw = ImGui::CalcTextSize(status_text).x;+ ImGui::SetCursorPosX((video_w - tw) * 0.5f);+ ImGui::TextColored(state == media::PlayerState::Error ? FC_RED : FC_YELLOW, "%s", status_text);+ ImGui::EndChild();+ ImGui::PopStyleColor();+ }++ // Controls bar+ ImGui::Spacing();++ // Title+ ImGui::TextColored(FC_WHITE, "%s", active.title.empty() ? active.url.c_str() : active.title.c_str());+ if (!active.author.empty()) {+ ImGui::SameLine(0, 8);+ ImGui::TextColored(FC_GRAY, "by %s", active.author.c_str());+ }++ // Playback controls+ bool is_playing = (state == media::PlayerState::Playing);+ bool is_paused = (state == media::PlayerState::Paused);++ ImGui::PushStyleColor(ImGuiCol_Button, ImVec4(0.15f, 0.15f, 0.15f, 1.0f));+ ImGui::PushStyleColor(ImGuiCol_ButtonHovered, ImVec4(0.25f, 0.25f, 0.25f, 1.0f));++ if (ImGui::SmallButton(is_paused ? "[>] PLAY" : "[||] PAUSE")) {+ yt_player_->toggle_pause();+ }+ ImGui::SameLine(0, 6);+ if (ImGui::SmallButton("[x] STOP")) {+ yt_player_->stop();+ yt_active_player_ = -1;+ }+ ImGui::SameLine(0, 6);++ // Volume slider+ ImGui::PushItemWidth(60);+ if (ImGui::SliderInt("##yt_vol", &yt_volume_, 0, 100, "Vol:%d")) {+ yt_player_->set_volume(yt_volume_);+ }+ ImGui::PopItemWidth();++ ImGui::SameLine(0, 6);+ if (ImGui::SmallButton("[^] OPEN")) {+ yt_open_url(active.url.c_str());+ }++ ImGui::PopStyleColor(2);++ // Progress bar+ double dur = yt_player_->duration();+ double pos = yt_player_->position();+ if (dur > 0) {+ float frac = (float)(pos / dur);+ char time_buf[32];+ int pm = (int)pos / 60, ps = (int)pos % 60;+ int dm = (int)dur / 60, ds = (int)dur % 60;+ std::snprintf(time_buf, sizeof(time_buf), "%d:%02d / %d:%02d", pm, ps, dm, ds);+ ImGui::ProgressBar(frac, ImVec2(-1, 14), time_buf);+ }++ return;+ }+#endif++ // ---- URL input row ----+ ImGui::TextColored(FC_RED, ">>"); ImGui::SameLine(0, 4);+ ImGui::TextColored(FC_WHITE, "Add YouTube Link:");++ ImGui::PushItemWidth(avail_w - 70);+ ImGui::PushStyleColor(ImGuiCol_FrameBg, ImVec4(0.08f, 0.08f, 0.08f, 1.0f));+ ImGui::PushStyleColor(ImGuiCol_Text, FC_WHITE);+ bool entered = ImGui::InputText("##yt_url", yt_url_buf_, sizeof(yt_url_buf_),+ ImGuiInputTextFlags_EnterReturnsTrue);+ ImGui::PopStyleColor(2);+ ImGui::PopItemWidth();++ ImGui::SameLine(0, 4);+ bool add_clicked = false;+ ImGui::PushStyleColor(ImGuiCol_Button, ImVec4(0.6f, 0.0f, 0.0f, 1.0f));+ ImGui::PushStyleColor(ImGuiCol_ButtonHovered, ImVec4(0.8f, 0.1f, 0.1f, 1.0f));+ ImGui::PushStyleColor(ImGuiCol_Text, FC_WHITE);+ add_clicked = ImGui::Button("ADD##yt", ImVec2(54, 0));+ ImGui::PopStyleColor(3);++ if ((entered || add_clicked) && yt_url_buf_[0] != '\0') {+ std::string url_str(yt_url_buf_);+ auto vid_id = extract_video_id(url_str);+ if (!vid_id.empty()) {+ YouTubeEntry entry;+ entry.url = url_str;+ entry.title = "Loading...";+ yt_entries_.push_back(std::move(entry));+ yt_fetch_metadata((int)yt_entries_.size() - 1);+ yt_url_buf_[0] = '\0';+ } else {+ std::strncpy(yt_url_buf_, "Invalid YouTube URL!", sizeof(yt_url_buf_) - 1);+ }+ }++ ImGui::Spacing();+ ImGui::Separator();+ ImGui::Spacing();++ // ---- Stream list ----+ if (yt_entries_.empty()) {+ float center_y = ImGui::GetContentRegionAvail().y * 0.3f;+ ImGui::Dummy(ImVec2(0, center_y));+ float text_w = ImGui::CalcTextSize("Paste a YouTube link above to get started").x;+ ImGui::SetCursorPosX((avail_w - text_w) * 0.5f);+ ImGui::TextColored(FC_MUTED, "Paste a YouTube link above to get started");++#ifdef FINCEPT_HAS_MPV+ ImGui::Spacing();+ float note_w = ImGui::CalcTextSize("Inline video playback enabled (mpv)").x;+ ImGui::SetCursorPosX((avail_w - note_w) * 0.5f);+ ImGui::TextColored(ImVec4(0.3f, 0.6f, 0.3f, 1.0f), "Inline video playback enabled (mpv)");+#endif+ return;+ }++ ImGui::BeginChild("##yt_list", ImVec2(0, 0), false);+ int remove_idx = -1;+ for (int i = 0; i < (int)yt_entries_.size(); i++) {+ auto& e = yt_entries_[i];+ ImGui::PushID(i);++ // Card background+ bool is_active = (i == yt_active_player_);+ ImVec2 card_start = ImGui::GetCursorScreenPos();+ float card_h = 52;+ ImDrawList* dl = ImGui::GetWindowDrawList();+ dl->AddRectFilled(card_start, ImVec2(card_start.x + avail_w - 4, card_start.y + card_h),+ is_active ? IM_COL32(30, 15, 15, 255) : IM_COL32(20, 20, 20, 255), 3.0f);+ dl->AddRect(card_start, ImVec2(card_start.x + avail_w - 4, card_start.y + card_h),+ is_active ? IM_COL32(180, 40, 40, 200) : IM_COL32(60, 20, 20, 180), 3.0f);++ ImGui::SetCursorPosX(ImGui::GetCursorPosX() + 8);+ ImGui::SetCursorPosY(ImGui::GetCursorPosY() + 4);++ // YouTube play icon+ ImGui::TextColored(is_active ? FC_GREEN : FC_RED, is_active ? "[=]" : "[>]");+ ImGui::SameLine(0, 6);++ // Title + author+ if (e.fetching) {+ ImGui::TextColored(FC_YELLOW, "Loading metadata...");+ } else {+ ImGui::TextColored(FC_WHITE, "%s", e.title.empty() ? e.url.c_str() : e.title.c_str());+ }+ if (!e.author.empty()) {+ ImGui::SetCursorPosX(ImGui::GetCursorPosX() + 32);+ ImGui::TextColored(FC_GRAY, "by %s", e.author.c_str());+ }++ // Buttons row+ ImGui::SetCursorPosX(ImGui::GetCursorPosX() + 8);++#ifdef FINCEPT_HAS_MPV+ // PLAY button — inline playback+ ImGui::PushStyleColor(ImGuiCol_Button, ImVec4(0.0f, 0.5f, 0.0f, 1.0f));+ ImGui::PushStyleColor(ImGuiCol_ButtonHovered, ImVec4(0.0f, 0.7f, 0.0f, 1.0f));+ ImGui::PushStyleColor(ImGuiCol_Text, FC_WHITE);+ if (ImGui::SmallButton("PLAY")) {+ if (!yt_player_) {+ yt_player_ = std::make_unique<media::MpvPlayer>();+ yt_player_->init();+ yt_player_->set_volume(yt_volume_);+ }+ yt_player_->play(e.url);+ yt_active_player_ = i;+ }+ ImGui::PopStyleColor(3);+ ImGui::SameLine(0, 4);+#endif++ // WATCH button — open in browser+ ImGui::PushStyleColor(ImGuiCol_Button, ImVec4(0.6f, 0.0f, 0.0f, 1.0f));+ ImGui::PushStyleColor(ImGuiCol_ButtonHovered, ImVec4(0.9f, 0.1f, 0.1f, 1.0f));+ ImGui::PushStyleColor(ImGuiCol_Text, FC_WHITE);+ if (ImGui::SmallButton("WATCH")) {+ yt_open_url(e.url.c_str());+ }+ ImGui::PopStyleColor(3);++ ImGui::SameLine(0, 8);+ ImGui::PushStyleColor(ImGuiCol_Button, ImVec4(0.15f, 0.15f, 0.15f, 1.0f));+ ImGui::PushStyleColor(ImGuiCol_ButtonHovered, ImVec4(0.3f, 0.1f, 0.1f, 1.0f));+ ImGui::PushStyleColor(ImGuiCol_Text, FC_MUTED);+ if (ImGui::SmallButton("REMOVE")) {+ remove_idx = i;+ }+ ImGui::PopStyleColor(3);++ // Ensure card height+ float cur_y = ImGui::GetCursorPosY();+ float expected_end = card_start.y - ImGui::GetWindowPos().y + card_h + 4;+ if (cur_y < expected_end) ImGui::SetCursorPosY(expected_end);++ ImGui::PopID();+ ImGui::Spacing();+ }+ if (remove_idx >= 0) {+ if (remove_idx == yt_active_player_) {+ if (yt_player_) yt_player_->stop();+ yt_active_player_ = -1;+ } else if (remove_idx < yt_active_player_) {+ yt_active_player_--;+ }+ yt_entries_.erase(yt_entries_.begin() + remove_idx);+ }+ ImGui::EndChild();+}+// ============================================================================// Widget Frame — wraps any widget with header, accent, close button+// + drag handle (header) + resize grip (bottom-right corner)// ============================================================================void DashboardScreen::render_widget_frame(const char* title, const ImVec4& accent,- float w, float h, WidgetType type) {+ float w, float h, WidgetType type,+ const std::string& widget_id) {if (w < 20 || h < 20) return;ImGui::PushStyleColor(ImGuiCol_ChildBg, FC_PANEL);@@ -332,7 +807,7 @@ void DashboardScreen::render_widget_frame(const char* title, const ImVec4& accenImGui::PushStyleVar(ImGuiStyleVar_ChildBorderSize, 1.0f);ImGui::PushStyleVar(ImGuiStyleVar_ChildRounding, 2.0f);- std::string id = std::string("##wf_") + title;+ std::string id = std::string("##wf_") + widget_id;ImGui::BeginChild(id.c_str(), ImVec2(w, h), ImGuiChildFlags_Borders);float hdr_h = 22.0f;@@ -346,11 +821,42 @@ void DashboardScreen::render_widget_frame(const char* title, const ImVec4& accendl->AddRectFilled(hdr_start, ImVec2(hdr_start.x + w, hdr_start.y + 2),ImGui::ColorConvertFloat4ToU32(accent));- // Title- ImGui::SetCursorPosX(6);+ // Drag handle icon (left side of header)+ ImGui::SetCursorPosX(4);ImGui::SetCursorPosY(4);+ ImGui::TextColored(FC_MUTED, "::"); // grip dots+ ImGui::SameLine(0, 4);++ // TitleImGui::TextColored(accent, "%s", title);+ // --- Drag-to-rearrange: click header to drag ---+ {+ ImVec2 hdr_min = hdr_start;+ ImVec2 hdr_max = ImVec2(hdr_start.x + w - 22, hdr_start.y + hdr_h);+ ImVec2 mouse = ImGui::GetIO().MousePos;+ bool hover_hdr = (mouse.x >= hdr_min.x && mouse.x <= hdr_max.x &&+ mouse.y >= hdr_min.y && mouse.y <= hdr_max.y);++ if (hover_hdr && ImGui::IsMouseClicked(0) && dragging_widget_id_.empty()+ && resizing_widget_id_.empty()) {+ dragging_widget_id_ = widget_id;+ drag_start_mouse_ = mouse;+ for (auto& wi : layout_.widgets) {+ if (wi.id == widget_id) {+ drag_start_col_ = wi.col;+ drag_start_row_ = wi.row;+ break;+ }+ }+ }++ // Cursor hint+ if (hover_hdr || dragging_widget_id_ == widget_id) {+ ImGui::SetMouseCursor(ImGuiMouseCursor_Hand);+ }+ }+// Loading indicatorDataCategory data_cat = DataCategory::Indices;switch (type) {@@ -375,11 +881,9 @@ void DashboardScreen::render_widget_frame(const char* title, const ImVec4& accenImGui::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;+ std::string close_id = std::string("x##c_") + widget_id;if (ImGui::SmallButton(close_id.c_str())) {- for (auto& wi : layout_.widgets) {- if (wi.title == title) { remove_widget(wi.id); break; }- }+ remove_widget(widget_id);}ImGui::PopStyleColor(3);}@@ -390,7 +894,7 @@ void DashboardScreen::render_widget_frame(const char* title, const ImVec4& accenif (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);+ ImGui::BeginChild((std::string("##wc_") + widget_id).c_str(), ImVec2(w - 2, content_h), false);switch (type) {case WidgetType::GlobalIndices: widget_global_indices(w, content_h); break;@@ -404,12 +908,49 @@ void DashboardScreen::render_widget_frame(const char* title, const ImVec4& accencase 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;+ case WidgetType::YouTubeStream: widget_youtube_stream(w, content_h); break;default: ImGui::TextColored(FC_MUTED, "Unknown widget"); break;}ImGui::EndChild();ImGui::PopStyleVar();+ // --- Resize grip (bottom-right corner) ---+ {+ float grip_sz = 14.0f;+ ImVec2 widget_screen_br = ImVec2(hdr_start.x + w, hdr_start.y + h);+ ImVec2 grip_min = ImVec2(widget_screen_br.x - grip_sz, widget_screen_br.y - grip_sz);+ ImVec2 grip_max = widget_screen_br;+ ImVec2 mouse = ImGui::GetIO().MousePos;+ bool hover_grip = (mouse.x >= grip_min.x && mouse.x <= grip_max.x &&+ mouse.y >= grip_min.y && mouse.y <= grip_max.y);++ // Draw resize triangle+ ImU32 grip_col = hover_grip || resizing_widget_id_ == widget_id+ ? IM_COL32(255, 136, 0, 200) : IM_COL32(120, 120, 120, 100);+ dl->AddTriangleFilled(+ ImVec2(grip_max.x, grip_max.y - grip_sz),+ ImVec2(grip_max.x - grip_sz, grip_max.y),+ grip_max, grip_col);++ if (hover_grip && ImGui::IsMouseClicked(0) && resizing_widget_id_.empty()+ && dragging_widget_id_.empty()) {+ resizing_widget_id_ = widget_id;+ drag_start_mouse_ = mouse;+ for (auto& wi : layout_.widgets) {+ if (wi.id == widget_id) {+ resize_start_col_span_ = wi.col_span;+ resize_start_row_span_ = wi.row_span;+ break;+ }+ }+ }++ if (hover_grip || resizing_widget_id_ == widget_id) {+ ImGui::SetMouseCursor(ImGuiMouseCursor_ResizeNWSE);+ }+ }+ImGui::EndChild();ImGui::PopStyleVar(2);ImGui::PopStyleColor(2);diff --git a/fincept-cpp/src/screens/dashboard/widget_registry.h b/fincept-cpp/src/screens/dashboard/widget_registry.hindex 6377d6fd3..d667f195b 100644--- a/fincept-cpp/src/screens/dashboard/widget_registry.h+++ b/fincept-cpp/src/screens/dashboard/widget_registry.h@@ -21,6 +21,7 @@ enum class WidgetType {Performance,TopMovers,MarketData, // generic quote table+ YouTubeStream, // YouTube link launcher — opens in browserCount};@@ -37,6 +38,7 @@ inline const char* widget_type_name(WidgetType t) {case WidgetType::Performance: return "Performance";case WidgetType::TopMovers: return "Top Movers";case WidgetType::MarketData: return "Market Data";+ case WidgetType::YouTubeStream: return "YouTube Stream";default: return "Unknown";}}@@ -54,6 +56,7 @@ inline const char* widget_type_id(WidgetType t) {case WidgetType::Performance: return "performance";case WidgetType::TopMovers: return "topmovers";case WidgetType::MarketData: return "marketdata";+ case WidgetType::YouTubeStream: return "youtube";default: return "unknown";}}@@ -70,6 +73,7 @@ inline WidgetType widget_type_from_id(const std::string& id) {if (id == "performance") return WidgetType::Performance;if (id == "topmovers") return WidgetType::TopMovers;if (id == "marketdata") return WidgetType::MarketData;+ if (id == "youtube") return WidgetType::YouTubeStream;return WidgetType::GlobalIndices;}diff --git a/fincept-cpp/src/screens/data_mapping/data_mapping_db.cpp b/fincept-cpp/src/screens/data_mapping/data_mapping_db.cppnew file mode 100644index 000000000..609d4bd31--- /dev/null+++ b/fincept-cpp/src/screens/data_mapping/data_mapping_db.cpp@@ -0,0 +1,523 @@+// Data Mapping Database — SQLite persistence implementation++#include "data_mapping_db.h"+#include "storage/database.h"+#include "core/logger.h"+#include <nlohmann/json.hpp>+#include <chrono>++namespace fincept::data_mapping {+namespace mapping_ops {++using json = nlohmann::json;++// ============================================================================+// Serialization helpers — MappingConfig <-> JSON+// ============================================================================++static json serialize_api_config(const ApiConfig& c) {+ json j;+ j["id"] = c.id;+ j["name"] = c.name;+ j["description"] = c.description;+ j["base_url"] = c.base_url;+ j["endpoint"] = c.endpoint;+ j["method"] = http_method_label(c.method);+ j["timeout_ms"] = c.timeout_ms;+ j["cache_enabled"] = c.cache_enabled;+ j["cache_ttl_seconds"] = c.cache_ttl_seconds;++ // Auth+ json auth;+ auth["type"] = auth_type_id(c.authentication.type);+ if (c.authentication.apikey) {+ auth["apikey_location"] = (c.authentication.apikey->location == ApiKeyLocation::header)+ ? "header" : "query";+ auth["apikey_name"] = c.authentication.apikey->key_name;+ auth["apikey_value"] = c.authentication.apikey->value;+ }+ if (c.authentication.bearer) {+ auth["bearer_token"] = c.authentication.bearer->token;+ }+ if (c.authentication.basic) {+ auth["basic_user"] = c.authentication.basic->username;+ auth["basic_pass"] = c.authentication.basic->password;+ }+ if (c.authentication.oauth2) {+ auth["oauth2_token"] = c.authentication.oauth2->access_token;+ if (c.authentication.oauth2->refresh_token) {+ auth["oauth2_refresh"] = *c.authentication.oauth2->refresh_token;+ }+ }+ j["authentication"] = auth;++ // Headers+ j["headers"] = json(c.headers);+ j["query_params"] = json(c.query_params);+ if (c.body) j["body"] = *c.body;+ return j;+}++static ApiConfig deserialize_api_config(const json& j) {+ ApiConfig c;+ c.id = j.value("id", "");+ c.name = j.value("name", "");+ c.description = j.value("description", "");+ c.base_url = j.value("base_url", "");+ c.endpoint = j.value("endpoint", "");+ c.method = http_method_from_string(j.value("method", "GET"));+ c.timeout_ms = j.value("timeout_ms", 30000);+ c.cache_enabled = j.value("cache_enabled", true);+ c.cache_ttl_seconds = j.value("cache_ttl_seconds", 300);++ if (j.contains("authentication")) {+ const auto& auth = j["authentication"];+ c.authentication.type = auth_type_from_string(auth.value("type", "none"));+ if (auth.contains("apikey_name")) {+ ApiKeyConfig ak;+ ak.location = (auth.value("apikey_location", "header") == "query")+ ? ApiKeyLocation::query : ApiKeyLocation::header;+ ak.key_name = auth.value("apikey_name", "");+ ak.value = auth.value("apikey_value", "");+ c.authentication.apikey = ak;+ }+ if (auth.contains("bearer_token")) {+ c.authentication.bearer = BearerConfig{auth.value("bearer_token", "")};+ }+ if (auth.contains("basic_user")) {+ c.authentication.basic = BasicAuthConfig{+ auth.value("basic_user", ""), auth.value("basic_pass", "")};+ }+ if (auth.contains("oauth2_token")) {+ OAuth2Config oa;+ oa.access_token = auth.value("oauth2_token", "");+ if (auth.contains("oauth2_refresh")) {+ oa.refresh_token = auth.value("oauth2_refresh", "");+ }+ c.authentication.oauth2 = oa;+ }+ }++ if (j.contains("headers") && j["headers"].is_object()) {+ for (auto& [k, v] : j["headers"].items()) {+ c.headers[k] = v.get<std::string>();+ }+ }+ if (j.contains("query_params") && j["query_params"].is_object()) {+ for (auto& [k, v] : j["query_params"].items()) {+ c.query_params[k] = v.get<std::string>();+ }+ }+ if (j.contains("body")) c.body = j["body"].get<std::string>();+ return c;+}++static json serialize_field_mapping(const FieldMapping& fm) {+ json j;+ j["target_field"] = fm.target_field;+ j["source_type"] = static_cast<int>(fm.source_type);+ j["source_path"] = fm.source_path;+ j["static_value"] = fm.static_value;+ j["parser"] = parser_engine_id(fm.parser);+ j["transforms"] = fm.transforms;+ if (fm.default_value) j["default_value"] = *fm.default_value;+ j["required"] = fm.required;+ j["confidence"] = fm.confidence;+ return j;+}++static FieldMapping deserialize_field_mapping(const json& j) {+ FieldMapping fm;+ fm.target_field = j.value("target_field", "");+ fm.source_type = static_cast<FieldSourceType>(j.value("source_type", 0));+ fm.source_path = j.value("source_path", "");+ fm.static_value = j.value("static_value", "");+ fm.parser = parser_engine_from_string(j.value("parser", "direct"));+ if (j.contains("transforms") && j["transforms"].is_array()) {+ for (const auto& t : j["transforms"]) {+ fm.transforms.push_back(t.get<std::string>());+ }+ }+ if (j.contains("default_value")) fm.default_value = j["default_value"].get<std::string>();+ fm.required = j.value("required", false);+ fm.confidence = j.value("confidence", 0.0f);+ return fm;+}++static json serialize_custom_field(const FieldSpec& f) {+ json j;+ j["name"] = f.name;+ j["type"] = field_type_label(f.type);+ j["required"] = f.required;+ j["description"] = f.description;+ j["enum_values"] = f.enum_values;+ if (f.default_value) j["default_value"] = *f.default_value;+ if (f.validation.min) j["min"] = *f.validation.min;+ if (f.validation.max) j["max"] = *f.validation.max;+ if (f.validation.pattern) j["pattern"] = *f.validation.pattern;+ return j;+}++static FieldSpec deserialize_custom_field(const json& j) {+ FieldSpec f;+ f.name = j.value("name", "");+ f.type = field_type_from_string(j.value("type", "string"));+ f.required = j.value("required", false);+ f.description = j.value("description", "");+ if (j.contains("enum_values") && j["enum_values"].is_array()) {+ for (const auto& v : j["enum_values"]) {+ f.enum_values.push_back(v.get<std::string>());+ }+ }+ if (j.contains("default_value")) f.default_value = j["default_value"].get<std::string>();+ if (j.contains("min")) f.validation.min = j["min"].get<double>();+ if (j.contains("max")) f.validation.max = j["max"].get<double>();+ if (j.contains("pattern")) f.validation.pattern = j["pattern"].get<std::string>();+ return f;+}++static json serialize_mapping(const MappingConfig& m) {+ json j;+ j["id"] = m.id;+ j["name"] = m.name;+ j["description"] = m.description;+ j["is_api_source"] = m.is_api_source;+ j["api_config"] = serialize_api_config(m.api_config);+ j["sample_data_json"] = m.sample_data_json;+ j["is_predefined_schema"] = m.is_predefined_schema;+ j["schema_type"] = schema_type_id(m.schema_type);++ json custom_fields_arr = json::array();+ for (const auto& f : m.custom_fields) {+ custom_fields_arr.push_back(serialize_custom_field(f));+ }+ j["custom_fields"] = custom_fields_arr;++ j["extraction"] = json{+ {"engine", parser_engine_id(m.extraction.engine)},+ {"root_path", m.extraction.root_path},+ {"is_array", m.extraction.is_array},+ {"is_array_of_arrays", m.extraction.is_array_of_arrays},+ };++ json mappings_arr = json::array();+ for (const auto& fm : m.field_mappings) {+ mappings_arr.push_back(serialize_field_mapping(fm));+ }+ j["field_mappings"] = mappings_arr;++ // Post-processing+ json pp;+ if (m.post_processing.filter) pp["filter"] = *m.post_processing.filter;+ if (m.post_processing.sort) {+ pp["sort_field"] = m.post_processing.sort->field;+ pp["sort_desc"] = m.post_processing.sort->descending;+ }+ if (m.post_processing.limit) pp["limit"] = *m.post_processing.limit;+ if (m.post_processing.deduplicate_field) pp["deduplicate"] = *m.post_processing.deduplicate_field;+ j["post_processing"] = pp;++ j["validation_enabled"] = m.validation.enabled;+ j["validation_strict"] = m.validation.strict_mode;+ j["version"] = m.version;+ j["tags"] = m.tags;+ j["ai_generated"] = m.ai_generated;+ j["created_at"] = m.created_at;+ j["updated_at"] = m.updated_at;+ return j;+}++static MappingConfig deserialize_mapping(const json& j) {+ MappingConfig m;+ m.id = j.value("id", "");+ m.name = j.value("name", "");+ m.description = j.value("description", "");+ m.is_api_source = j.value("is_api_source", true);+ if (j.contains("api_config")) m.api_config = deserialize_api_config(j["api_config"]);+ m.sample_data_json = j.value("sample_data_json", "");+ m.is_predefined_schema = j.value("is_predefined_schema", true);+ m.schema_type = schema_type_from_string(j.value("schema_type", "OHLCV"));++ if (j.contains("custom_fields") && j["custom_fields"].is_array()) {+ for (const auto& f : j["custom_fields"]) {+ m.custom_fields.push_back(deserialize_custom_field(f));+ }+ }++ if (j.contains("extraction")) {+ const auto& e = j["extraction"];+ m.extraction.engine = parser_engine_from_string(e.value("engine", "direct"));+ m.extraction.root_path = e.value("root_path", "");+ m.extraction.is_array = e.value("is_array", true);+ m.extraction.is_array_of_arrays = e.value("is_array_of_arrays", false);+ }++ if (j.contains("field_mappings") && j["field_mappings"].is_array()) {+ for (const auto& fm : j["field_mappings"]) {+ m.field_mappings.push_back(deserialize_field_mapping(fm));+ }+ }++ if (j.contains("post_processing")) {+ const auto& pp = j["post_processing"];+ if (pp.contains("filter")) m.post_processing.filter = pp["filter"].get<std::string>();+ if (pp.contains("sort_field")) {+ m.post_processing.sort = SortConfig{+ pp["sort_field"].get<std::string>(),+ pp.value("sort_desc", false)+ };+ }+ if (pp.contains("limit")) m.post_processing.limit = pp["limit"].get<int>();+ if (pp.contains("deduplicate")) m.post_processing.deduplicate_field = pp["deduplicate"].get<std::string>();+ }++ m.validation.enabled = j.value("validation_enabled", true);+ m.validation.strict_mode = j.value("validation_strict", false);+ m.version = j.value("version", 1);+ m.tags = j.value("tags", "");+ m.ai_generated = j.value("ai_generated", false);+ m.created_at = j.value("created_at", "");+ m.updated_at = j.value("updated_at", "");+ return m;+}++// ============================================================================+// Table initialization+// ============================================================================++void initialize_tables() {+ auto& database = db::Database::instance();+ std::lock_guard<std::recursive_mutex> lock(database.mutex());++ database.exec(R"(+ CREATE TABLE IF NOT EXISTS data_mappings (+ id TEXT PRIMARY KEY,+ name TEXT NOT NULL,+ description TEXT,+ config_json TEXT NOT NULL,+ created_at TEXT NOT NULL,+ updated_at TEXT NOT NULL+ )+ )");++ database.exec(R"(+ CREATE TABLE IF NOT EXISTS mapping_cache (+ cache_key TEXT PRIMARY KEY,+ mapping_id TEXT NOT NULL,+ params_hash TEXT NOT NULL,+ response_json TEXT NOT NULL,+ cached_at INTEGER NOT NULL,+ expires_at INTEGER NOT NULL+ )+ )");++ database.exec(R"(+ CREATE INDEX IF NOT EXISTS idx_mapping_cache_lookup+ ON mapping_cache(mapping_id, params_hash)+ )");++ database.exec(R"(+ CREATE TABLE IF NOT EXISTS mapping_preferences (+ key TEXT PRIMARY KEY,+ value TEXT NOT NULL+ )+ )");++ LOG_INFO("DataMapping", "Data mapping tables initialized");+}++// ============================================================================+// Mapping CRUD+// ============================================================================++void save_mapping(const MappingConfig& config) {+ auto& database = db::Database::instance();+ std::lock_guard<std::recursive_mutex> lock(database.mutex());++ const json config_json = serialize_mapping(config);+ const std::string json_str = config_json.dump();++ auto stmt = database.prepare(+ "INSERT OR REPLACE INTO data_mappings (id, name, description, config_json, created_at, updated_at) "+ "VALUES (?, ?, ?, ?, ?, ?)");+ stmt.bind_text(1, config.id);+ stmt.bind_text(2, config.name);+ stmt.bind_text(3, config.description);+ stmt.bind_text(4, json_str);+ stmt.bind_text(5, config.created_at);+ stmt.bind_text(6, config.updated_at);+ stmt.execute();+}++std::vector<MappingConfig> get_all_mappings() {+ auto& database = db::Database::instance();+ std::lock_guard<std::recursive_mutex> lock(database.mutex());++ std::vector<MappingConfig> result;+ auto stmt = database.prepare(+ "SELECT config_json FROM data_mappings ORDER BY updated_at DESC");++ while (stmt.step()) {+ try {+ const auto j = json::parse(stmt.col_text(0));+ result.push_back(deserialize_mapping(j));+ } catch (const std::exception& e) {+ LOG_WARN("DataMapping", "Failed to parse mapping: %s", e.what());+ }+ }+ return result;+}++std::optional<MappingConfig> get_mapping(const std::string& id) {+ auto& database = db::Database::instance();+ std::lock_guard<std::recursive_mutex> lock(database.mutex());++ auto stmt = database.prepare(+ "SELECT config_json FROM data_mappings WHERE id = ?");+ stmt.bind_text(1, id);++ if (stmt.step()) {+ try {+ const auto j = json::parse(stmt.col_text(0));+ return deserialize_mapping(j);+ } catch (...) {}+ }+ return std::nullopt;+}++void delete_mapping(const std::string& id) {+ auto& database = db::Database::instance();+ std::lock_guard<std::recursive_mutex> lock(database.mutex());++ auto stmt = database.prepare("DELETE FROM data_mappings WHERE id = ?");+ stmt.bind_text(1, id);+ stmt.execute();++ // Also clear associated cache+ clear_cache(id);+}++MappingConfig duplicate_mapping(const std::string& id) {+ const auto original = get_mapping(id);+ if (!original) return {};++ MappingConfig copy = *original;+ copy.id = db::generate_uuid();+ copy.name = original->name + " (Copy)";++ const auto now = std::chrono::system_clock::now();+ const auto tt = std::chrono::system_clock::to_time_t(now);+ std::tm tm_buf{};+#ifdef _WIN32+ gmtime_s(&tm_buf, &tt);+#else+ gmtime_r(&tt, &tm_buf);+#endif+ char buf[64];+ std::strftime(buf, sizeof(buf), "%Y-%m-%dT%H:%M:%SZ", &tm_buf);+ copy.created_at = buf;+ copy.updated_at = buf;++ save_mapping(copy);+ return copy;+}++// ============================================================================+// Cache+// ============================================================================++std::optional<std::string> get_cached_response(const std::string& mapping_id,+ const std::string& params_hash) {+ auto& database = db::Database::instance();+ std::lock_guard<std::recursive_mutex> lock(database.mutex());++ const std::string cache_key = mapping_id + "_" + params_hash;+ const auto now_ts = db::now_timestamp();++ auto stmt = database.prepare(+ "SELECT response_json FROM mapping_cache WHERE cache_key = ? AND expires_at > ?");+ stmt.bind_text(1, cache_key);+ stmt.bind_int(2, now_ts);++ if (stmt.step()) {+ return stmt.col_text(0);+ }+ return std::nullopt;+}++void set_cached_response(const std::string& mapping_id,+ const std::string& params_hash,+ const std::string& response_json,+ int ttl_seconds) {+ auto& database = db::Database::instance();+ std::lock_guard<std::recursive_mutex> lock(database.mutex());++ const std::string cache_key = mapping_id + "_" + params_hash;+ const auto now_ts = db::now_timestamp();+ const auto expires_ts = now_ts + static_cast<int64_t>(ttl_seconds);++ auto stmt = database.prepare(+ "INSERT OR REPLACE INTO mapping_cache "+ "(cache_key, mapping_id, params_hash, response_json, cached_at, expires_at) "+ "VALUES (?, ?, ?, ?, ?, ?)");+ stmt.bind_text(1, cache_key);+ stmt.bind_text(2, mapping_id);+ stmt.bind_text(3, params_hash);+ stmt.bind_text(4, response_json);+ stmt.bind_int(5, now_ts);+ stmt.bind_int(6, expires_ts);+ stmt.execute();+}++void clear_cache(const std::string& mapping_id) {+ auto& database = db::Database::instance();+ std::lock_guard<std::recursive_mutex> lock(database.mutex());++ if (mapping_id.empty()) {+ database.exec("DELETE FROM mapping_cache");+ } else {+ auto stmt = database.prepare("DELETE FROM mapping_cache WHERE mapping_id = ?");+ stmt.bind_text(1, mapping_id);+ stmt.execute();+ }+}++void clean_expired_cache() {+ auto& database = db::Database::instance();+ std::lock_guard<std::recursive_mutex> lock(database.mutex());++ const auto now_ts = db::now_timestamp();+ auto stmt = database.prepare("DELETE FROM mapping_cache WHERE expires_at < ?");+ stmt.bind_int(1, now_ts);+ stmt.execute();+}++// ============================================================================+// Preferences+// ============================================================================++std::optional<std::string> get_preference(const std::string& key) {+ auto& database = db::Database::instance();+ std::lock_guard<std::recursive_mutex> lock(database.mutex());++ auto stmt = database.prepare("SELECT value FROM mapping_preferences WHERE key = ?");+ stmt.bind_text(1, key);+ if (stmt.step()) {+ return stmt.col_text(0);+ }+ return std::nullopt;+}++void set_preference(const std::string& key, const std::string& value) {+ auto& database = db::Database::instance();+ std::lock_guard<std::recursive_mutex> lock(database.mutex());++ auto stmt = database.prepare(+ "INSERT OR REPLACE INTO mapping_preferences (key, value) VALUES (?, ?)");+ stmt.bind_text(1, key);+ stmt.bind_text(2, value);+ stmt.execute();+}++} // namespace mapping_ops+} // namespace fincept::data_mappingdiff --git a/fincept-cpp/src/screens/data_mapping/data_mapping_db.h b/fincept-cpp/src/screens/data_mapping/data_mapping_db.hnew file mode 100644index 000000000..54beb2cd9--- /dev/null+++ b/fincept-cpp/src/screens/data_mapping/data_mapping_db.h@@ -0,0 +1,42 @@+#pragma once+// Data Mapping Database — SQLite persistence for mapping configs and cache.+// Mirrors Tauri desktop MappingDatabase service.++#include "data_mapping_types.h"+#include <string>+#include <vector>+#include <optional>++namespace fincept::data_mapping {++// ============================================================================+// Database operations for data mappings+// ============================================================================+namespace mapping_ops {++// Initialize tables (called once at startup)+void initialize_tables();++// --- Mapping CRUD ---+void save_mapping(const MappingConfig& config);+std::vector<MappingConfig> get_all_mappings();+std::optional<MappingConfig> get_mapping(const std::string& id);+void delete_mapping(const std::string& id);+MappingConfig duplicate_mapping(const std::string& id);++// --- Cache ---+std::optional<std::string> get_cached_response(const std::string& mapping_id,+ const std::string& params_hash);+void set_cached_response(const std::string& mapping_id,+ const std::string& params_hash,+ const std::string& response_json,+ int ttl_seconds);+void clear_cache(const std::string& mapping_id = "");+void clean_expired_cache();++// --- Preferences ---+std::optional<std::string> get_preference(const std::string& key);+void set_preference(const std::string& key, const std::string& value);++} // namespace mapping_ops+} // namespace fincept::data_mappingdiff --git a/fincept-cpp/src/screens/data_mapping/data_mapping_engine.cpp b/fincept-cpp/src/screens/data_mapping/data_mapping_engine.cppnew file mode 100644index 000000000..4bbd8fdf1--- /dev/null+++ b/fincept-cpp/src/screens/data_mapping/data_mapping_engine.cpp@@ -0,0 +1,778 @@+// Data Mapping Engine — implementation of transform pipeline, JSON extraction,+// URL building, API execution, validation, and post-processing.++#include "data_mapping_engine.h"+#include "http/http_client.h"+#include "storage/database.h"+#include "core/logger.h"+#include <algorithm>+#include <cmath>+#include <chrono>+#include <regex>+#include <sstream>+#include <cctype>+#include <set>++namespace fincept::data_mapping {++using json = nlohmann::json;++// ============================================================================+// Transform Registry+// ============================================================================++json TransformRegistry::apply(const std::string& name, const json& value,+ const json& params) {+ // --- Type conversions ---+ if (name == "toNumber") {+ if (value.is_number()) return value;+ if (value.is_string()) {+ std::string s = value.get<std::string>();+ // Remove commas+ s.erase(std::remove(s.begin(), s.end(), ','), s.end());+ try {+ return json(std::stod(s));+ } catch (...) {+ return json(nullptr);+ }+ }+ return json(nullptr);+ }+ if (name == "toString") {+ if (value.is_string()) return value;+ if (value.is_number_integer()) return json(std::to_string(value.get<int64_t>()));+ if (value.is_number_float()) return json(std::to_string(value.get<double>()));+ if (value.is_boolean()) return json(value.get<bool>() ? "true" : "false");+ return json(value.dump());+ }+ if (name == "toBoolean") {+ if (value.is_boolean()) return value;+ if (value.is_number()) return json(value.get<double>() != 0.0);+ if (value.is_string()) return json(!value.get<std::string>().empty());+ return json(false);+ }++ // --- Date conversions ---+ if (name == "fromUnixTimestamp") {+ if (value.is_number()) {+ const auto ts = value.get<int64_t>();+ // Convert Unix seconds to ISO string (simplified)+ const auto tp = std::chrono::system_clock::from_time_t(static_cast<time_t>(ts));+ const auto tt = std::chrono::system_clock::to_time_t(tp);+ std::tm tm_buf{};+#ifdef _WIN32+ gmtime_s(&tm_buf, &tt);+#else+ gmtime_r(&tt, &tm_buf);+#endif+ char buf[64];+ std::strftime(buf, sizeof(buf), "%Y-%m-%dT%H:%M:%S.000Z", &tm_buf);+ return json(std::string(buf));+ }+ return json(nullptr);+ }+ if (name == "fromUnixTimestampMs") {+ if (value.is_number()) {+ const auto ts_ms = value.get<int64_t>();+ const auto ts = ts_ms / 1000;+ const auto tp = std::chrono::system_clock::from_time_t(static_cast<time_t>(ts));+ const auto tt = std::chrono::system_clock::to_time_t(tp);+ std::tm tm_buf{};+#ifdef _WIN32+ gmtime_s(&tm_buf, &tt);+#else+ gmtime_r(&tt, &tm_buf);+#endif+ char buf[64];+ std::strftime(buf, sizeof(buf), "%Y-%m-%dT%H:%M:%S.000Z", &tm_buf);+ return json(std::string(buf));+ }+ return json(nullptr);+ }+ if (name == "toISODate") {+ // Pass-through strings, convert timestamps+ if (value.is_string()) return value;+ if (value.is_number()) return apply("fromUnixTimestampMs", value, params);+ return json(nullptr);+ }++ // --- Math operations ---+ if (name == "round") {+ if (value.is_number()) {+ const int decimals = params.contains("decimals") ? params["decimals"].get<int>() : 2;+ const double multiplier = std::pow(10.0, decimals);+ return json(std::round(value.get<double>() * multiplier) / multiplier);+ }+ return value;+ }+ if (name == "multiply") {+ if (value.is_number() && params.contains("multiplier")) {+ return json(value.get<double>() * params["multiplier"].get<double>());+ }+ return value;+ }+ if (name == "divide") {+ if (value.is_number() && params.contains("divisor")) {+ const double divisor = params["divisor"].get<double>();+ if (divisor != 0.0) return json(value.get<double>() / divisor);+ }+ return value;+ }+ if (name == "add") {+ if (value.is_number() && params.contains("addend")) {+ return json(value.get<double>() + params["addend"].get<double>());+ }+ return value;+ }+ if (name == "subtract") {+ if (value.is_number() && params.contains("subtrahend")) {+ return json(value.get<double>() - params["subtrahend"].get<double>());+ }+ return value;+ }++ // --- String operations ---+ if (name == "uppercase") {+ if (value.is_string()) {+ std::string s = value.get<std::string>();+ std::transform(s.begin(), s.end(), s.begin(),+ [](unsigned char c) { return std::toupper(c); });+ return json(s);+ }+ return value;+ }+ if (name == "lowercase") {+ if (value.is_string()) {+ std::string s = value.get<std::string>();+ std::transform(s.begin(), s.end(), s.begin(),+ [](unsigned char c) { return std::tolower(c); });+ return json(s);+ }+ return value;+ }+ if (name == "trim") {+ if (value.is_string()) {+ std::string s = value.get<std::string>();+ const auto start = s.find_first_not_of(" \t\n\r");+ if (start == std::string::npos) return json("");+ const auto end = s.find_last_not_of(" \t\n\r");+ return json(s.substr(start, end - start + 1));+ }+ return value;+ }+ if (name == "replace") {+ if (value.is_string() && params.contains("find") && params.contains("replace")) {+ std::string s = value.get<std::string>();+ const std::string find_str = params["find"].get<std::string>();+ const std::string replace_str = params["replace"].get<std::string>();+ size_t pos = 0;+ while ((pos = s.find(find_str, pos)) != std::string::npos) {+ s.replace(pos, find_str.length(), replace_str);+ pos += replace_str.length();+ }+ return json(s);+ }+ return value;+ }+ if (name == "substring") {+ if (value.is_string()) {+ const std::string s = value.get<std::string>();+ const auto start = static_cast<size_t>(+ params.contains("start") ? params["start"].get<int>() : 0);+ if (params.contains("end")) {+ const auto end = static_cast<size_t>(params["end"].get<int>());+ return json(s.substr(start, end - start));+ }+ return json(s.substr(start));+ }+ return value;+ }++ // --- Financial operations ---+ if (name == "bpsToPercent") {+ if (value.is_number()) return json(value.get<double>() / 100.0);+ return value;+ }+ if (name == "percentToBps") {+ if (value.is_number()) return json(value.get<double>() * 100.0);+ return value;+ }+ if (name == "roundPrice") {+ if (value.is_number()) {+ return json(std::round(value.get<double>() * 100.0) / 100.0);+ }+ return value;+ }++ LOG_WARN("DataMapping", "Unknown transform: %s", name.c_str());+ return value;+}++std::vector<TransformDef> TransformRegistry::all_transforms() {+ return {+ {"toNumber", "Convert value to number", TransformCategory::type_conv},+ {"toString", "Convert value to string", TransformCategory::type_conv},+ {"toBoolean", "Convert value to boolean", TransformCategory::type_conv},+ {"toISODate", "Convert to ISO 8601 date string", TransformCategory::date},+ {"fromUnixTimestamp", "Unix timestamp (seconds) to ISO date", TransformCategory::date},+ {"fromUnixTimestampMs", "Unix timestamp (ms) to ISO date", TransformCategory::date},+ {"round", "Round to N decimal places", TransformCategory::math},+ {"multiply", "Multiply by a constant", TransformCategory::math},+ {"divide", "Divide by a constant", TransformCategory::math},+ {"add", "Add a constant", TransformCategory::math},+ {"subtract", "Subtract a constant", TransformCategory::math},+ {"uppercase", "Convert string to uppercase", TransformCategory::string_op},+ {"lowercase", "Convert string to lowercase", TransformCategory::string_op},+ {"trim", "Remove leading/trailing whitespace", TransformCategory::string_op},+ {"replace", "Replace text in string", TransformCategory::string_op},+ {"substring", "Extract substring", TransformCategory::string_op},+ {"bpsToPercent", "Basis points to percentage", TransformCategory::math},+ {"percentToBps", "Percentage to basis points", TransformCategory::math},+ {"roundPrice", "Round price to 2 decimals", TransformCategory::format},+ };+}++// ============================================================================+// Direct Parser — dot-path based JSON extraction+// ============================================================================++json DirectParser::extract(const json& data, const std::string& path) {+ if (path.empty() || data.is_null()) return data;++ json current = data;+ std::istringstream stream(path);+ std::string token;++ while (std::getline(stream, token, '.')) {+ if (token.empty()) continue;++ // Check for array index notation: field[0]+ const auto bracket_pos = token.find('[');+ if (bracket_pos != std::string::npos) {+ const std::string field_name = token.substr(0, bracket_pos);+ if (!field_name.empty()) {+ if (!current.contains(field_name)) return json(nullptr);+ current = current[field_name];+ }++ // Extract array index+ const auto close_pos = token.find(']', bracket_pos);+ if (close_pos != std::string::npos) {+ const std::string idx_str = token.substr(bracket_pos + 1,+ close_pos - bracket_pos - 1);+ if (idx_str == "*") {+ continue; // wildcard — keep as array+ }+ try {+ const auto idx = static_cast<size_t>(std::stoi(idx_str));+ if (current.is_array() && idx < current.size()) {+ current = current[idx];+ } else {+ return json(nullptr);+ }+ } catch (...) {+ return json(nullptr);+ }+ }+ } else {+ // Simple field access+ if (current.is_object() && current.contains(token)) {+ current = current[token];+ } else if (current.is_array()) {+ // Apply field access to each element+ json result = json::array();+ for (const auto& item : current) {+ if (item.is_object() && item.contains(token)) {+ result.push_back(item[token]);+ }+ }+ current = result;+ } else {+ return json(nullptr);+ }+ }+ }+ return current;+}++// ============================================================================+// URL Builder+// ============================================================================++std::string UrlBuilder::replace_placeholders(const std::string& text,+ const std::map<std::string, std::string>& params) {+ std::string result = text;+ for (const auto& [key, val] : params) {+ const std::string placeholder = "{" + key + "}";+ size_t pos = 0;+ while ((pos = result.find(placeholder, pos)) != std::string::npos) {+ result.replace(pos, placeholder.length(), val);+ pos += val.length();+ }+ }+ return result;+}++std::string UrlBuilder::build_url(const ApiConfig& config,+ const std::map<std::string, std::string>& params) {+ std::string url = config.base_url;+ // Remove trailing slash+ if (!url.empty() && url.back() == '/') url.pop_back();++ // Add endpoint with placeholder substitution+ std::string endpoint = config.endpoint;+ if (!endpoint.empty() && endpoint.front() != '/') endpoint = "/" + endpoint;+ endpoint = replace_placeholders(endpoint, params);+ url += endpoint;++ // Build query string+ std::string query;+ for (const auto& [key, val] : config.query_params) {+ const std::string processed = replace_placeholders(val, params);+ if (!query.empty()) query += "&";+ query += key + "=" + processed;+ }++ // Add API key to query if configured+ if (config.authentication.type == AuthType::apikey &&+ config.authentication.apikey &&+ config.authentication.apikey->location == ApiKeyLocation::query) {+ if (!query.empty()) query += "&";+ query += config.authentication.apikey->key_name + "=" ++ config.authentication.apikey->value;+ }++ if (!query.empty()) url += "?" + query;+ return url;+}++std::map<std::string, std::string> UrlBuilder::build_headers(const ApiConfig& config) {+ std::map<std::string, std::string> headers = {+ {"Content-Type", "application/json"},+ {"Accept", "application/json"},+ };++ // Merge user headers+ for (const auto& [k, v] : config.headers) {+ headers[k] = v;+ }++ // Add auth headers+ const auto& auth = config.authentication;+ if (auth.type == AuthType::apikey && auth.apikey &&+ auth.apikey->location == ApiKeyLocation::header) {+ headers[auth.apikey->key_name] = auth.apikey->value;+ } else if (auth.type == AuthType::bearer && auth.bearer) {+ headers["Authorization"] = "Bearer " + auth.bearer->token;+ } else if (auth.type == AuthType::basic && auth.basic) {+ // Simple base64 placeholder — in production use proper base64 encoding+ headers["Authorization"] = "Basic " + auth.basic->username + ":" + auth.basic->password;+ } else if (auth.type == AuthType::oauth2 && auth.oauth2) {+ headers["Authorization"] = "Bearer " + auth.oauth2->access_token;+ }++ return headers;+}++std::vector<std::string> UrlBuilder::extract_placeholders(const std::string& text) {+ std::vector<std::string> result;+ std::regex re(R"(\{([^}]+)\})");+ std::sregex_iterator it(text.begin(), text.end(), re);+ const std::sregex_iterator end;+ for (; it != end; ++it) {+ result.push_back((*it)[1].str());+ }+ return result;+}++bool UrlBuilder::is_valid_url(const std::string& url) {+ return url.size() > 8 &&+ (url.substr(0, 7) == "http://" || url.substr(0, 8) == "https://");+}++// ============================================================================+// Mapping Engine — execute full pipeline+// ============================================================================++ApiResponse MappingEngine::fetch_api(const ApiConfig& config,+ const std::map<std::string, std::string>& params) {+ ApiResponse result;+ const auto start = std::chrono::steady_clock::now();++ try {+ const std::string url = UrlBuilder::build_url(config, params);+ const auto headers = UrlBuilder::build_headers(config);++ result.url = url;+ result.method = http_method_label(config.method);++ // Convert to http::Headers+ http::Headers http_headers;+ for (const auto& [k, v] : headers) {+ http_headers[k] = v;+ }++ const std::string body = config.body.value_or("");+ auto& client = http::HttpClient::instance();++ http::HttpResponse response;+ const auto method_str = http_method_label(config.method);+ if (method_str == "GET") response = client.get(url, http_headers);+ else if (method_str == "POST") response = client.post(url, body, http_headers);+ else if (method_str == "PUT") response = client.put(url, body, http_headers);+ else if (method_str == "DELETE")response = client.del(url, body, http_headers);+ else response = client.get(url, http_headers);++ const auto end = std::chrono::steady_clock::now();+ result.duration_ms = std::chrono::duration_cast<std::chrono::milliseconds>(+ end - start).count();+ result.status_code = response.status_code;++ if (response.status_code >= 200 && response.status_code < 300) {+ result.success = true;+ result.data_json = response.body;+ } else if (response.status_code == 401 || response.status_code == 403) {+ result.error_type = ApiErrorType::auth;+ result.error_message = "HTTP " + std::to_string(response.status_code) ++ ": " + response.body.substr(0, 200);+ } else if (response.status_code >= 400 && response.status_code < 500) {+ result.error_type = ApiErrorType::client;+ result.error_message = "HTTP " + std::to_string(response.status_code) ++ ": " + response.body.substr(0, 200);+ } else {+ result.error_type = ApiErrorType::server;+ result.error_message = "HTTP " + std::to_string(response.status_code) ++ ": " + response.body.substr(0, 200);+ }+ } catch (const std::exception& e) {+ const auto end = std::chrono::steady_clock::now();+ result.duration_ms = std::chrono::duration_cast<std::chrono::milliseconds>(+ end - start).count();+ result.error_type = ApiErrorType::network;+ result.error_message = e.what();+ }++ return result;+}++json MappingEngine::extract_data(const json& raw_data, const MappingConfig& mapping) {+ json data = raw_data;++ // Apply root path extraction+ if (!mapping.extraction.root_path.empty()) {+ data = DirectParser::extract(raw_data, mapping.extraction.root_path);+ }++ // Ensure array if expected+ if (mapping.extraction.is_array && !data.is_array()) {+ json arr = json::array();+ arr.push_back(data);+ data = arr;+ }++ return data;+}++json MappingEngine::extract_field_value(const json& source, const FieldMapping& mapping) {+ if (mapping.source_type == FieldSourceType::static_value) {+ try {+ return json::parse(mapping.static_value);+ } catch (...) {+ return json(mapping.static_value);+ }+ }++ if (mapping.source_path.empty()) {+ if (mapping.default_value) {+ try {+ return json::parse(*mapping.default_value);+ } catch (...) {+ return json(*mapping.default_value);+ }+ }+ return json(nullptr);+ }++ // Use direct parser for extraction+ json result = DirectParser::extract(source, mapping.source_path);++ // Handle array-of-arrays indexing (e.g., "$[0]" for first element)+ if (result.is_null() && mapping.source_path.size() >= 2 &&+ mapping.source_path[0] == '$' && mapping.source_path[1] == '[') {+ // Try as array index on source itself+ try {+ const auto idx_str = mapping.source_path.substr(2,+ mapping.source_path.find(']') - 2);+ const auto idx = static_cast<size_t>(std::stoi(idx_str));+ if (source.is_array() && idx < source.size()) {+ result = source[idx];+ }+ } catch (...) {}+ }++ return result;+}++json MappingEngine::transform_single(const json& source, const MappingConfig& mapping) {+ json result = json::object();++ for (const auto& fm : mapping.field_mappings) {+ try {+ json value = extract_field_value(source, fm);++ // Apply transforms+ for (const auto& transform_name : fm.transforms) {+ if (!value.is_null()) {+ value = TransformRegistry::apply(transform_name, value);+ }+ }++ // Use default if null+ if (value.is_null() && fm.default_value) {+ try {+ value = json::parse(*fm.default_value);+ } catch (...) {+ value = json(*fm.default_value);+ }+ }++ // Required check+ if (value.is_null() && fm.required) {+ LOG_WARN("DataMapping", "Required field %s is missing", fm.target_field.c_str());+ }++ result[fm.target_field] = value;+ } catch (const std::exception& e) {+ LOG_WARN("DataMapping", "Error mapping field %s: %s", fm.target_field.c_str(), e.what());+ if (fm.default_value) {+ result[fm.target_field] = json(*fm.default_value);+ } else {+ result[fm.target_field] = json(nullptr);+ }+ }+ }++ return result;+}++json MappingEngine::apply_post_processing(const json& data, const MappingConfig& mapping) {+ if (!data.is_array()) return data;++ json processed = data;+ const auto& pp = mapping.post_processing;++ // Sort+ if (pp.sort) {+ const std::string sort_field = pp.sort->field;+ const bool desc = pp.sort->descending;+ std::vector<json> items(processed.begin(), processed.end());+ std::sort(items.begin(), items.end(),+ [&](const json& a, const json& b) {+ const auto& va = a.contains(sort_field) ? a[sort_field] : json(nullptr);+ const auto& vb = b.contains(sort_field) ? b[sort_field] : json(nullptr);+ if (va.is_number() && vb.is_number()) {+ return desc ? va.get<double>() > vb.get<double>()+ : va.get<double>() < vb.get<double>();+ }+ if (va.is_string() && vb.is_string()) {+ return desc ? va.get<std::string>() > vb.get<std::string>()+ : va.get<std::string>() < vb.get<std::string>();+ }+ return false;+ });+ processed = json(items);+ }++ // Deduplicate+ if (pp.deduplicate_field) {+ std::vector<json> unique_items;+ std::set<std::string> seen;+ for (const auto& item : processed) {+ std::string key;+ if (item.contains(*pp.deduplicate_field)) {+ key = item[*pp.deduplicate_field].dump();+ }+ if (seen.find(key) == seen.end()) {+ seen.insert(key);+ unique_items.push_back(item);+ }+ }+ processed = json(unique_items);+ }++ // Limit+ if (pp.limit && *pp.limit > 0 && processed.size() > static_cast<size_t>(*pp.limit)) {+ json limited = json::array();+ for (size_t i = 0; i < static_cast<size_t>(*pp.limit); ++i) {+ limited.push_back(processed[i]);+ }+ processed = limited;+ }++ return processed;+}++ValidationResult MappingEngine::validate_data(const json& data,+ const MappingConfig& mapping) {+ ValidationResult result;+ result.valid = true;++ if (!mapping.validation.enabled) return result;++ // Get field specs from schema+ std::vector<FieldSpec> fields;+ if (mapping.is_predefined_schema) {+ const auto* schema = get_schema_for_type(mapping.schema_type);+ if (schema) fields = schema->fields;+ } else {+ fields = mapping.custom_fields;+ }++ if (fields.empty()) return result;++ // Validate each item+ const auto items = data.is_array() ? data : json::array({data});+ for (const auto& item : items) {+ for (const auto& field : fields) {+ const bool has_field = item.contains(field.name) && !item[field.name].is_null();++ // Required check+ if (field.required && !has_field) {+ result.valid = false;+ result.errors.push_back({field.name,+ "Field '" + field.name + "' is required but missing", "required"});+ continue;+ }++ if (!has_field) continue;++ const auto& value = item[field.name];++ // Type check (basic)+ if (field.type == FieldType::number_type && !value.is_number()) {+ result.valid = false;+ result.errors.push_back({field.name,+ "Field '" + field.name + "' should be number", "type"});+ }+ if (field.type == FieldType::string_type && !value.is_string()) {+ result.valid = false;+ result.errors.push_back({field.name,+ "Field '" + field.name + "' should be string", "type"});+ }++ // Range validation+ if (value.is_number() && field.validation.min &&+ value.get<double>() < *field.validation.min) {+ result.valid = false;+ result.errors.push_back({field.name,+ "Field '" + field.name + "' must be >= " ++ std::to_string(*field.validation.min), "range"});+ }+ if (value.is_number() && field.validation.max &&+ value.get<double>() > *field.validation.max) {+ result.valid = false;+ result.errors.push_back({field.name,+ "Field '" + field.name + "' must be <= " ++ std::to_string(*field.validation.max), "range"});+ }+ }+ }++ return result;+}++ExecutionResult MappingEngine::execute(const MappingConfig& mapping,+ const json& sample_data,+ const std::map<std::string, std::string>& params) {+ ExecutionResult result;+ const auto start = std::chrono::steady_clock::now();++ try {+ // 1. Get data+ json raw_data;+ if (!sample_data.is_null()) {+ raw_data = sample_data;+ } else if (mapping.is_api_source) {+ const auto api_response = fetch_api(mapping.api_config, params);+ if (!api_response.success) {+ result.errors.push_back("API request failed: " + api_response.error_message);+ const auto end = std::chrono::steady_clock::now();+ result.duration_ms = std::chrono::duration_cast<std::chrono::milliseconds>(+ end - start).count();+ return result;+ }+ try {+ raw_data = json::parse(api_response.data_json);+ } catch (const std::exception& e) {+ result.errors.push_back(std::string("Failed to parse API response: ") + e.what());+ const auto end = std::chrono::steady_clock::now();+ result.duration_ms = std::chrono::duration_cast<std::chrono::milliseconds>(+ end - start).count();+ return result;+ }+ } else if (!mapping.sample_data_json.empty()) {+ try {+ raw_data = json::parse(mapping.sample_data_json);+ } catch (...) {+ result.errors.push_back("Failed to parse sample data");+ return result;+ }+ } else {+ result.errors.push_back("No data source provided");+ return result;+ }++ result.raw_data_json = raw_data.dump();++ // 2. Extract data+ json extracted = extract_data(raw_data, mapping);++ // 3. Transform+ json transformed;+ if (extracted.is_array()) {+ transformed = json::array();+ for (const auto& item : extracted) {+ transformed.push_back(transform_single(item, mapping));+ }+ result.records_processed = static_cast<int>(extracted.size());+ } else {+ transformed = transform_single(extracted, mapping);+ result.records_processed = 1;+ }++ // 4. Post-processing+ transformed = apply_post_processing(transformed, mapping);++ // 5. Validate+ if (mapping.validation.enabled) {+ result.validation = validate_data(transformed, mapping);+ if (mapping.validation.strict_mode && !result.validation.valid) {+ result.errors.push_back("Validation failed");+ const auto end = std::chrono::steady_clock::now();+ result.duration_ms = std::chrono::duration_cast<std::chrono::milliseconds>(+ end - start).count();+ return result;+ }+ }++ result.success = true;+ result.data_json = transformed.dump(2);+ result.records_returned = transformed.is_array()+ ? static_cast<int>(transformed.size()) : 1;++ } catch (const std::exception& e) {+ result.errors.push_back(e.what());+ }++ const auto end = std::chrono::steady_clock::now();+ result.duration_ms = std::chrono::duration_cast<std::chrono::milliseconds>(+ end - start).count();+ return result;+}++ExecutionResult MappingEngine::test(const MappingConfig& mapping, const json& sample_data,+ const std::map<std::string, std::string>& params) {+ return execute(mapping, sample_data, params);+}++} // namespace fincept::data_mappingdiff --git a/fincept-cpp/src/screens/data_mapping/data_mapping_engine.h b/fincept-cpp/src/screens/data_mapping/data_mapping_engine.hnew file mode 100644index 000000000..193e40875--- /dev/null+++ b/fincept-cpp/src/screens/data_mapping/data_mapping_engine.h@@ -0,0 +1,96 @@+#pragma once+// Data Mapping Engine — transform functions, JSON data extraction,+// field mapping execution, validation, and post-processing.+// Mirrors Tauri desktop MappingEngine + transformFunctions + parsers.++#include "data_mapping_types.h"+#include "data_mapping_schemas.h"+#include <nlohmann/json.hpp>+#include <string>+#include <vector>+#include <functional>+#include <map>+#include <optional>++namespace fincept::data_mapping {++using json = nlohmann::json;++// ============================================================================+// Transform Registry — built-in transform functions+// ============================================================================+struct TransformRegistry {+ // Apply a named transform to a JSON value+ static json apply(const std::string& name, const json& value,+ const json& params = json::object());++ // Get all available transform definitions (for UI)+ static std::vector<TransformDef> all_transforms();+};++// ============================================================================+// JSON Direct Parser — extract values using dot-separated paths+// ============================================================================+struct DirectParser {+ // Extract value at path like "data.candles" or "results[0].price"+ static json extract(const json& data, const std::string& path);+};++// ============================================================================+// URL Builder — build URLs from ApiConfig + runtime parameters+// ============================================================================+struct UrlBuilder {+ // Replace {placeholder} tokens in text with parameter values+ static std::string replace_placeholders(const std::string& text,+ const std::map<std::string, std::string>& params);++ // Build full URL from ApiConfig and runtime parameters+ static std::string build_url(const ApiConfig& config,+ const std::map<std::string, std::string>& params = {});++ // Build HTTP headers from ApiConfig+ static std::map<std::string, std::string> build_headers(const ApiConfig& config);++ // Extract placeholder names from a string+ static std::vector<std::string> extract_placeholders(const std::string& text);++ // Validate URL format (simple check)+ static bool is_valid_url(const std::string& url);+};++// ============================================================================+// Mapping Engine — execute a full mapping pipeline+// ============================================================================+class MappingEngine {+public:+ // Execute full mapping: fetch/use data -> extract -> transform -> validate+ ExecutionResult execute(const MappingConfig& mapping,+ const json& sample_data = json(),+ const std::map<std::string, std::string>& params = {});++ // Test mapping with sample data+ ExecutionResult test(const MappingConfig& mapping, const json& sample_data,+ const std::map<std::string, std::string>& params = {});++ // Execute API request+ ApiResponse fetch_api(const ApiConfig& config,+ const std::map<std::string, std::string>& params = {});++private:+ // Extract data using configured root path+ json extract_data(const json& raw_data, const MappingConfig& mapping);++ // Transform a single record using field mappings+ json transform_single(const json& source, const MappingConfig& mapping);++ // Extract a single field value from source data+ json extract_field_value(const json& source, const FieldMapping& mapping);++ // Apply post-processing (sort, filter, deduplicate, limit)+ json apply_post_processing(const json& data, const MappingConfig& mapping);++ // Validate transformed data against schema+ ValidationResult validate_data(const json& data, const MappingConfig& mapping);+};++} // namespace fincept::data_mappingdiff --git a/fincept-cpp/src/screens/data_mapping/data_mapping_schemas.h b/fincept-cpp/src/screens/data_mapping/data_mapping_schemas.hnew file mode 100644index 000000000..92b2671ce--- /dev/null+++ b/fincept-cpp/src/screens/data_mapping/data_mapping_schemas.h@@ -0,0 +1,158 @@+#pragma once+// Unified Financial Data Schemas — standardized formats for all data sources+// Mirrors the Tauri desktop schemas/index.ts++#include "data_mapping_types.h"+#include <vector>+#include <string>++namespace fincept::data_mapping {++// ============================================================================+// Get all predefined unified schemas+// ============================================================================+inline std::vector<UnifiedSchema> get_all_schemas() {+ return {+ // --- OHLCV ---+ {+ "OHLCV (Candlestick Data)", SchemaCategory::market_data,+ "Open, High, Low, Close, Volume - Standard candlestick/bar data",+ {+ {"symbol", FieldType::string_type, true, "Trading symbol", {}, {}, {}},+ {"timestamp", FieldType::datetime_type, true, "Bar timestamp (start time)", {}, {}, {}},+ {"open", FieldType::number_type, true, "Opening price", {}, {}, {0.0, {}, {}}},+ {"high", FieldType::number_type, true, "Highest price in the period", {}, {}, {0.0, {}, {}}},+ {"low", FieldType::number_type, true, "Lowest price in the period", {}, {}, {0.0, {}, {}}},+ {"close", FieldType::number_type, true, "Closing price", {}, {}, {0.0, {}, {}}},+ {"volume", FieldType::number_type, true, "Trading volume", {}, {}, {0.0, {}, {}}},+ {"vwap", FieldType::number_type, false, "Volume weighted average price", {}, {}, {0.0, {}, {}}},+ {"trades", FieldType::number_type, false, "Number of trades", {}, {}, {0.0, {}, {}}},+ }+ },+ // --- QUOTE ---+ {+ "Real-time Quote", SchemaCategory::market_data,+ "Real-time or delayed quote with bid/ask spreads",+ {+ {"symbol", FieldType::string_type, true, "Trading symbol", {}, {}, {}},+ {"timestamp", FieldType::datetime_type, true, "Quote timestamp", {}, {}, {}},+ {"price", FieldType::number_type, true, "Last traded price", {}, {}, {0.0, {}, {}}},+ {"bid", FieldType::number_type, false, "Best bid price", {}, {}, {0.0, {}, {}}},+ {"ask", FieldType::number_type, false, "Best ask price", {}, {}, {0.0, {}, {}}},+ {"bidSize", FieldType::number_type, false, "Bid quantity", {}, {}, {0.0, {}, {}}},+ {"askSize", FieldType::number_type, false, "Ask quantity", {}, {}, {0.0, {}, {}}},+ {"volume", FieldType::number_type, false, "Total volume", {}, {}, {0.0, {}, {}}},+ {"change", FieldType::number_type, false, "Change from prev close", {}, {}, {}},+ {"changePercent", FieldType::number_type, false, "Percentage change", {}, {}, {}},+ {"open", FieldType::number_type, false, "Day open price", {}, {}, {0.0, {}, {}}},+ {"high", FieldType::number_type, false, "Day high price", {}, {}, {0.0, {}, {}}},+ {"low", FieldType::number_type, false, "Day low price", {}, {}, {0.0, {}, {}}},+ {"previousClose", FieldType::number_type, false, "Previous day close", {}, {}, {0.0, {}, {}}},+ }+ },+ // --- TICK ---+ {+ "Tick Data", SchemaCategory::market_data,+ "Individual trade ticks",+ {+ {"symbol", FieldType::string_type, true, "Trading symbol", {}, {}, {}},+ {"timestamp", FieldType::datetime_type, true, "Trade timestamp", {}, {}, {}},+ {"price", FieldType::number_type, true, "Trade price", {}, {}, {0.0, {}, {}}},+ {"quantity", FieldType::number_type, true, "Trade quantity", {}, {}, {0.0, {}, {}}},+ {"side", FieldType::enum_type, false, "Buy or Sell", {"BUY", "SELL", "UNKNOWN"}, {}, {}},+ {"tradeId", FieldType::string_type, false, "Unique trade ID", {}, {}, {}},+ }+ },+ // --- ORDER ---+ {+ "Order", SchemaCategory::trading,+ "Trading order (placed, pending, filled, cancelled)",+ {+ {"orderId", FieldType::string_type, true, "Unique order ID", {}, {}, {}},+ {"symbol", FieldType::string_type, true, "Trading symbol", {}, {}, {}},+ {"side", FieldType::enum_type, true, "Buy or Sell", {"BUY", "SELL"}, {}, {}},+ {"type", FieldType::enum_type, true, "Order type", {"MARKET", "LIMIT", "STOP", "STOP_LIMIT"}, {}, {}},+ {"quantity", FieldType::number_type, true, "Order quantity", {}, {}, {0.0, {}, {}}},+ {"filledQuantity", FieldType::number_type, false, "Filled quantity", {}, {}, {0.0, {}, {}}},+ {"price", FieldType::number_type, false, "Limit price", {}, {}, {0.0, {}, {}}},+ {"stopPrice", FieldType::number_type, false, "Stop price", {}, {}, {0.0, {}, {}}},+ {"averagePrice", FieldType::number_type, false, "Average fill price", {}, {}, {0.0, {}, {}}},+ {"status", FieldType::enum_type, true, "Order status", {"PENDING", "OPEN", "PARTIALLY_FILLED", "FILLED", "CANCELLED", "REJECTED"}, {}, {}},+ {"timestamp", FieldType::datetime_type, true, "Placement timestamp", {}, {}, {}},+ {"updatedAt", FieldType::datetime_type, false, "Last update timestamp", {}, {}, {}},+ {"timeInForce", FieldType::enum_type, false, "Time in force", {"DAY", "GTC", "IOC", "FOK"}, {}, {}},+ {"exchange", FieldType::string_type, false, "Exchange name", {}, {}, {}},+ }+ },+ // --- POSITION ---+ {+ "Position", SchemaCategory::portfolio_cat,+ "Open position in portfolio",+ {+ {"symbol", FieldType::string_type, true, "Trading symbol", {}, {}, {}},+ {"quantity", FieldType::number_type, true, "Position quantity", {}, {}, {}},+ {"averagePrice", FieldType::number_type, true, "Average entry price", {}, {}, {0.0, {}, {}}},+ {"currentPrice", FieldType::number_type, true, "Current market price", {}, {}, {0.0, {}, {}}},+ {"marketValue", FieldType::number_type, true, "Current market value", {}, {}, {}},+ {"costBasis", FieldType::number_type, true, "Total cost basis", {}, {}, {}},+ {"pnl", FieldType::number_type, true, "Unrealized P&L", {}, {}, {}},+ {"pnlPercent", FieldType::number_type, true, "Unrealized P&L %", {}, {}, {}},+ {"realizedPnl", FieldType::number_type, false, "Realized P&L", {}, {}, {}},+ {"exchange", FieldType::string_type, false, "Exchange name", {}, {}, {}},+ {"productType", FieldType::enum_type, false, "Product type", {"DELIVERY", "INTRADAY", "MARGIN"}, {}, {}},+ }+ },+ // --- PORTFOLIO ---+ {+ "Portfolio Summary", SchemaCategory::portfolio_cat,+ "Overall portfolio summary",+ {+ {"totalValue", FieldType::number_type, true, "Total portfolio value", {}, {}, {}},+ {"cash", FieldType::number_type, true, "Available cash balance", {}, {}, {}},+ {"invested", FieldType::number_type, true, "Total invested amount", {}, {}, {}},+ {"marketValue", FieldType::number_type, true, "Total market value", {}, {}, {}},+ {"pnl", FieldType::number_type, true, "Total unrealized P&L", {}, {}, {}},+ {"pnlPercent", FieldType::number_type, true, "Total P&L %", {}, {}, {}},+ {"realizedPnl", FieldType::number_type, false, "Total realized P&L", {}, {}, {}},+ {"dayPnl", FieldType::number_type, false, "Today's P&L", {}, {}, {}},+ {"buyingPower", FieldType::number_type, false, "Available buying power", {}, {}, {}},+ {"marginUsed", FieldType::number_type, false, "Margin used", {}, {}, {}},+ {"timestamp", FieldType::datetime_type, true, "Snapshot timestamp", {}, {}, {}},+ }+ },+ // --- INSTRUMENT ---+ {+ "Instrument", SchemaCategory::reference,+ "Security/instrument master data",+ {+ {"symbol", FieldType::string_type, true, "Trading symbol", {}, {}, {}},+ {"name", FieldType::string_type, true, "Instrument name", {}, {}, {}},+ {"exchange", FieldType::string_type, true, "Exchange", {}, {}, {}},+ {"instrumentType", FieldType::enum_type, true, "Type of instrument", {"EQUITY", "FUTURES", "OPTIONS", "CURRENCY", "COMMODITY", "INDEX"}, {}, {}},+ {"isin", FieldType::string_type, false, "ISIN code", {}, {}, {}},+ {"lotSize", FieldType::number_type, false, "Lot size", {}, {}, {1.0, {}, {}}},+ {"tickSize", FieldType::number_type, false, "Min price movement", {}, {}, {0.0, {}, {}}},+ {"expiry", FieldType::datetime_type, false, "Expiry date", {}, {}, {}},+ {"strike", FieldType::number_type, false, "Strike price", {}, {}, {0.0, {}, {}}},+ {"optionType", FieldType::enum_type, false, "Call or Put", {"CALL", "PUT"}, {}, {}},+ }+ },+ };+}++// Schema lookup by SchemaType enum+inline const UnifiedSchema* get_schema_for_type(SchemaType type) {+ static const auto schemas = get_all_schemas();+ const auto idx = static_cast<int>(type);+ if (idx >= 0 && idx < static_cast<int>(schemas.size())) {+ return &schemas[static_cast<size_t>(idx)];+ }+ return nullptr;+}++// Get list of available schema type names+inline std::vector<std::string> get_schema_type_names() {+ return {"OHLCV", "QUOTE", "TICK", "ORDER", "POSITION", "PORTFOLIO", "INSTRUMENT"};+}++} // namespace fincept::data_mappingdiff --git a/fincept-cpp/src/screens/data_mapping/data_mapping_screen.cpp b/fincept-cpp/src/screens/data_mapping/data_mapping_screen.cppnew file mode 100644index 000000000..017a2e229--- /dev/null+++ b/fincept-cpp/src/screens/data_mapping/data_mapping_screen.cpp@@ -0,0 +1,1676 @@+// Data Mapping Screen — Bloomberg Terminal-inspired API mapping UI+// Dense, data-focused layout matching the project's visual language++#include "data_mapping_screen.h"+#include "data_mapping_schemas.h"+#include "ui/theme.h"+#include "storage/database.h"+#include "core/logger.h"+#include <imgui.h>+#include <nlohmann/json.hpp>+#include <algorithm>+#include <cstring>+#include <chrono>++namespace fincept::data_mapping {++using json = nlohmann::json;+using namespace theme::colors;++// Bloomberg-style colors (matching data_sources_screen)+static constexpr ImVec4 BB_BG = {0.055f, 0.055f, 0.060f, 1.0f};+static constexpr ImVec4 BB_PANEL = {0.075f, 0.075f, 0.082f, 1.0f};+static constexpr ImVec4 BB_SIDEBAR = {0.062f, 0.062f, 0.068f, 1.0f};+static constexpr ImVec4 BB_ROW_ALT = {0.082f, 0.082f, 0.090f, 1.0f};+static constexpr ImVec4 BB_HEADER_BG = {0.090f, 0.090f, 0.098f, 1.0f};+static constexpr ImVec4 BB_CMD_BG = {0.067f, 0.067f, 0.073f, 1.0f};+static constexpr ImVec4 BB_AMBER = {1.0f, 0.65f, 0.0f, 1.0f};+static constexpr ImVec4 BB_GREEN = {0.0f, 0.85f, 0.35f, 1.0f};+static constexpr ImVec4 BB_RED = {1.0f, 0.25f, 0.20f, 1.0f};+static constexpr ImVec4 BB_CYAN = {0.0f, 0.75f, 0.85f, 1.0f};+static constexpr ImVec4 BB_WHITE = {0.92f, 0.92f, 0.93f, 1.0f};+static constexpr ImVec4 BB_GRAY = {0.50f, 0.50f, 0.54f, 1.0f};+static constexpr ImVec4 BB_DIM = {0.35f, 0.35f, 0.38f, 1.0f};+static constexpr ImVec4 BB_BORDER = {0.16f, 0.16f, 0.18f, 1.0f};++// Step definitions+static constexpr CreateStep ALL_STEPS[] = {+ CreateStep::api_config, CreateStep::schema_select,+ CreateStep::field_mapping, CreateStep::cache_settings,+ CreateStep::test_save+};+static constexpr int NUM_STEPS = 5;++// ============================================================================+// Initialization+// ============================================================================++void DataMappingScreen::init() {+ if (initialized_) return;+ mapping_ops::initialize_tables();+ load_mappings();+ load_templates();+ reset_create_form();+ initialized_ = true;+}++// ============================================================================+// Main render+// ============================================================================++void DataMappingScreen::render() {+ init();++ // Check async operations+ if (testing_ && test_future_.valid() &&+ test_future_.wait_for(std::chrono::milliseconds(0)) == std::future_status::ready) {+ test_result_ = test_future_.get();+ testing_ = false;+ }+ if (fetching_ && fetch_future_.valid() &&+ fetch_future_.wait_for(std::chrono::milliseconds(0)) == std::future_status::ready) {+ const auto response = fetch_future_.get();+ fetching_ = false;+ if (response.success) {+ sample_data_json_ = response.data_json;+ }+ }++ const ImGuiViewport* vp = ImGui::GetMainViewport();+ const float w = vp->WorkSize.x;+ const float h = vp->WorkSize.y;++ // Background+ ImGui::GetWindowDrawList()->AddRectFilled(+ vp->WorkPos, {vp->WorkPos.x + w, vp->WorkPos.y + h},+ ImGui::ColorConvertFloat4ToU32(BB_BG));++ // Layout: command bar (top) | sidebar + content + status | footer+ const float cmd_h = 28.0f;+ const float footer_h = 22.0f;+ const float sidebar_w = sidebar_minimized_ ? 32.0f : 180.0f;+ const float status_w = 240.0f;+ const float content_x = vp->WorkPos.x + sidebar_w;+ const float content_y = vp->WorkPos.y + cmd_h;+ const float content_w = w - sidebar_w - status_w;+ const float content_h = h - cmd_h - footer_h;++ render_command_bar(w);+ render_sidebar(vp->WorkPos.x, content_y, sidebar_w, content_h);+ render_content(content_x, content_y, content_w, content_h);+ render_status_panel(content_x + content_w, content_y, status_w, content_h);+ render_footer(w, footer_h);+}++// ============================================================================+// Command bar+// ============================================================================++void DataMappingScreen::render_command_bar(float w) {+ const ImGuiViewport* vp = ImGui::GetMainViewport();+ ImGui::SetNextWindowPos(vp->WorkPos);+ ImGui::SetNextWindowSize({w, 28.0f});+ ImGui::PushStyleColor(ImGuiCol_WindowBg, BB_CMD_BG);+ ImGui::PushStyleVar(ImGuiStyleVar_WindowPadding, {8, 4});++ ImGui::Begin("##dm_cmdbar", nullptr,+ ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_NoResize | ImGuiWindowFlags_NoMove |+ ImGuiWindowFlags_NoScrollbar | ImGuiWindowFlags_NoDocking);++ // Title+ ImGui::PushStyleColor(ImGuiCol_Text, BB_AMBER);+ ImGui::Text("DATA MAPPING");+ ImGui::PopStyleColor();+ ImGui::SameLine();++ // View buttons+ ImGui::SameLine(160);+ const bool on_list = (view_ == MappingView::list);+ const bool on_create = (view_ == MappingView::create);+ const bool on_templates = (view_ == MappingView::templates);++ if (on_list) ImGui::PushStyleColor(ImGuiCol_Text, BB_AMBER);+ if (ImGui::SmallButton("LIST")) { view_ = MappingView::list; load_mappings(); }+ if (on_list) ImGui::PopStyleColor();++ ImGui::SameLine();+ if (on_create) ImGui::PushStyleColor(ImGuiCol_Text, BB_AMBER);+ if (ImGui::SmallButton("+ NEW")) { view_ = MappingView::create; reset_create_form(); }+ if (on_create) ImGui::PopStyleColor();++ ImGui::SameLine();+ if (on_templates) ImGui::PushStyleColor(ImGuiCol_Text, BB_AMBER);+ if (ImGui::SmallButton("TEMPLATES")) { view_ = MappingView::templates; }+ if (on_templates) ImGui::PopStyleColor();++ // Search+ ImGui::SameLine(w - 260);+ ImGui::PushItemWidth(200);+ ImGui::PushStyleColor(ImGuiCol_FrameBg, BB_PANEL);+ ImGui::InputTextWithHint("##dm_search", "Search mappings...", search_buf_, sizeof(search_buf_));+ ImGui::PopStyleColor();+ ImGui::PopItemWidth();++ ImGui::End();+ ImGui::PopStyleVar();+ ImGui::PopStyleColor();+}++// ============================================================================+// Sidebar — step navigation in create mode, quick actions in list mode+// ============================================================================++void DataMappingScreen::render_sidebar(float x, float y, float w, float h) {+ ImGui::SetNextWindowPos({x, y});+ ImGui::SetNextWindowSize({w, h});+ ImGui::PushStyleColor(ImGuiCol_WindowBg, BB_SIDEBAR);+ ImGui::PushStyleVar(ImGuiStyleVar_WindowPadding, {6, 6});++ ImGui::Begin("##dm_sidebar", nullptr,+ ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_NoResize | ImGuiWindowFlags_NoMove |+ ImGuiWindowFlags_NoScrollbar | ImGuiWindowFlags_NoDocking);++ if (sidebar_minimized_) {+ if (ImGui::SmallButton(">")) sidebar_minimized_ = false;+ ImGui::End();+ ImGui::PopStyleVar();+ ImGui::PopStyleColor();+ return;+ }++ if (ImGui::SmallButton("<")) { sidebar_minimized_ = true; }++ ImGui::Separator();++ if (view_ == MappingView::create) {+ // Step navigation+ ImGui::PushStyleColor(ImGuiCol_Text, BB_AMBER);+ ImGui::Text("WIZARD STEPS");+ ImGui::PopStyleColor();+ ImGui::Spacing();++ for (int i = 0; i < NUM_STEPS; ++i) {+ const bool is_current = (ALL_STEPS[i] == current_step_);+ const bool is_past = (i < static_cast<int>(current_step_));++ if (is_current) ImGui::PushStyleColor(ImGuiCol_Text, BB_AMBER);+ else if (is_past) ImGui::PushStyleColor(ImGuiCol_Text, BB_GREEN);+ else ImGui::PushStyleColor(ImGuiCol_Text, BB_DIM);++ char label[64];+ std::snprintf(label, sizeof(label), "%d. %s", i + 1, create_step_label(ALL_STEPS[i]));+ if (ImGui::Selectable(label, is_current)) {+ current_step_ = ALL_STEPS[i];+ }+ ImGui::PopStyleColor();+ }++ ImGui::Spacing();+ ImGui::Separator();+ ImGui::Spacing();++ // Navigation buttons+ const int step_idx = static_cast<int>(current_step_);+ if (step_idx > 0) {+ if (ImGui::Button("< Back", {w - 16, 0})) {+ current_step_ = ALL_STEPS[step_idx - 1];+ }+ }+ if (step_idx < NUM_STEPS - 1) {+ if (ImGui::Button("Next >", {w - 16, 0})) {+ current_step_ = ALL_STEPS[step_idx + 1];+ }+ }+ } else {+ // List mode sidebar — stats+ ImGui::PushStyleColor(ImGuiCol_Text, BB_AMBER);+ ImGui::Text("OVERVIEW");+ ImGui::PopStyleColor();+ ImGui::Spacing();++ ImGui::PushStyleColor(ImGuiCol_Text, BB_WHITE);+ ImGui::Text("Mappings: %d", static_cast<int>(saved_mappings_.size()));+ ImGui::PopStyleColor();++ ImGui::Spacing();+ ImGui::Separator();+ ImGui::Spacing();++ // Schema type filter+ ImGui::PushStyleColor(ImGuiCol_Text, BB_CYAN);+ ImGui::Text("SCHEMAS");+ ImGui::PopStyleColor();++ const auto schema_names = get_schema_type_names();+ for (const auto& name : schema_names) {+ int count = 0;+ for (const auto& m : saved_mappings_) {+ if (m.is_predefined_schema && schema_type_id(m.schema_type) == name) {+ ++count;+ }+ }+ ImGui::PushStyleColor(ImGuiCol_Text, count > 0 ? BB_WHITE : BB_DIM);+ ImGui::Text(" %s (%d)", name.c_str(), count);+ ImGui::PopStyleColor();+ }+ }++ ImGui::End();+ ImGui::PopStyleVar();+ ImGui::PopStyleColor();+}++// ============================================================================+// Main content area — dispatches to current view+// ============================================================================++void DataMappingScreen::render_content(float x, float y, float w, float h) {+ ImGui::SetNextWindowPos({x, y});+ ImGui::SetNextWindowSize({w, h});+ ImGui::PushStyleColor(ImGuiCol_WindowBg, BB_BG);+ ImGui::PushStyleVar(ImGuiStyleVar_WindowPadding, {8, 8});++ ImGui::Begin("##dm_content", nullptr,+ ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_NoResize | ImGuiWindowFlags_NoMove |+ ImGuiWindowFlags_NoDocking);++ switch (view_) {+ case MappingView::list: render_list_view(w, h); break;+ case MappingView::create: render_create_view(w, h); break;+ case MappingView::templates: render_templates_view(w, h); break;+ }++ ImGui::End();+ ImGui::PopStyleVar();+ ImGui::PopStyleColor();+}++// ============================================================================+// List View — table of saved mappings+// ============================================================================++void DataMappingScreen::render_list_view(float w, float /*h*/) {+ if (saved_mappings_.empty()) {+ ImGui::PushStyleColor(ImGuiCol_Text, BB_DIM);+ ImGui::Text("No mappings configured yet. Click '+ NEW' to create one.");+ ImGui::PopStyleColor();+ return;+ }++ const std::string filter(search_buf_);++ // Table header+ if (ImGui::BeginTable("##mappings_table", 6,+ ImGuiTableFlags_RowBg | ImGuiTableFlags_Borders | ImGuiTableFlags_Resizable |+ ImGuiTableFlags_ScrollY)) {++ ImGui::TableSetupColumn("Name", ImGuiTableColumnFlags_None, w * 0.22f);+ ImGui::TableSetupColumn("Schema", ImGuiTableColumnFlags_None, w * 0.12f);+ ImGui::TableSetupColumn("API Endpoint", ImGuiTableColumnFlags_None, w * 0.25f);+ ImGui::TableSetupColumn("Fields", ImGuiTableColumnFlags_None, w * 0.08f);+ ImGui::TableSetupColumn("Updated", ImGuiTableColumnFlags_None, w * 0.15f);+ ImGui::TableSetupColumn("Actions", ImGuiTableColumnFlags_None, w * 0.16f);++ ImGui::PushStyleColor(ImGuiCol_TableHeaderBg, BB_HEADER_BG);+ ImGui::TableHeadersRow();+ ImGui::PopStyleColor();++ for (size_t i = 0; i < saved_mappings_.size(); ++i) {+ const auto& m = saved_mappings_[i];++ // Filter+ if (!filter.empty()) {+ const std::string name_lower = [&] {+ std::string s = m.name;+ std::transform(s.begin(), s.end(), s.begin(),+ [](unsigned char c) { return std::tolower(c); });+ return s;+ }();+ std::string filter_lower = filter;+ std::transform(filter_lower.begin(), filter_lower.end(),+ filter_lower.begin(), [](unsigned char c) { return std::tolower(c); });+ if (name_lower.find(filter_lower) == std::string::npos) continue;+ }++ ImGui::TableNextRow();+ if (i % 2 == 1) {+ ImGui::TableSetBgColor(ImGuiTableBgTarget_RowBg0,+ ImGui::ColorConvertFloat4ToU32(BB_ROW_ALT));+ }++ // Name+ ImGui::TableNextColumn();+ ImGui::PushStyleColor(ImGuiCol_Text, BB_WHITE);+ ImGui::Text("%s", m.name.c_str());+ ImGui::PopStyleColor();++ // Schema+ ImGui::TableNextColumn();+ ImGui::PushStyleColor(ImGuiCol_Text, BB_CYAN);+ if (m.is_predefined_schema) {+ ImGui::Text("%s", schema_type_id(m.schema_type));+ } else {+ ImGui::Text("Custom");+ }+ ImGui::PopStyleColor();++ // Endpoint+ ImGui::TableNextColumn();+ ImGui::PushStyleColor(ImGuiCol_Text, BB_GRAY);+ const std::string endpoint = m.api_config.base_url.substr(0,+ std::min<size_t>(30, m.api_config.base_url.size())) + m.api_config.endpoint;+ ImGui::Text("%s", endpoint.c_str());+ ImGui::PopStyleColor();++ // Fields count+ ImGui::TableNextColumn();+ ImGui::Text("%d", static_cast<int>(m.field_mappings.size()));++ // Updated+ ImGui::TableNextColumn();+ ImGui::PushStyleColor(ImGuiCol_Text, BB_DIM);+ ImGui::Text("%s", m.updated_at.substr(0, 10).c_str());+ ImGui::PopStyleColor();++ // Actions+ ImGui::TableNextColumn();+ ImGui::PushID(static_cast<int>(i));+ if (ImGui::SmallButton("Edit")) {+ edit_mapping(m);+ }+ ImGui::SameLine();+ if (ImGui::SmallButton("Dup")) {+ mapping_ops::duplicate_mapping(m.id);+ load_mappings();+ }+ ImGui::SameLine();+ ImGui::PushStyleColor(ImGuiCol_Text, BB_RED);+ if (ImGui::SmallButton("Del")) {+ delete_mapping_by_id(m.id);+ }+ ImGui::PopStyleColor();+ ImGui::PopID();+ }++ ImGui::EndTable();+ }+}++// ============================================================================+// Create View — 5-step wizard+// ============================================================================++void DataMappingScreen::render_create_view(float w, float h) {+ // Step indicator bar+ ImGui::PushStyleColor(ImGuiCol_Text, BB_AMBER);+ ImGui::Text("Step %d/%d: %s", static_cast<int>(current_step_) + 1, NUM_STEPS,+ create_step_label(current_step_));+ ImGui::PopStyleColor();+ ImGui::Separator();+ ImGui::Spacing();++ switch (current_step_) {+ case CreateStep::api_config: render_step_api_config(w, h); break;+ case CreateStep::schema_select: render_step_schema_select(w, h); break;+ case CreateStep::field_mapping: render_step_field_mapping(w, h); break;+ case CreateStep::cache_settings: render_step_cache_settings(w, h); break;+ case CreateStep::test_save: render_step_test_save(w, h); break;+ }+}++// ============================================================================+// Step 1: API Configuration+// ============================================================================++void DataMappingScreen::render_step_api_config(float w, float /*h*/) {+ ImGui::PushStyleColor(ImGuiCol_Text, BB_CYAN);+ ImGui::Text("API CONNECTION");+ ImGui::PopStyleColor();+ ImGui::Spacing();++ // Name & Description+ ImGui::Text("Name:");+ ImGui::SameLine(80);+ ImGui::PushItemWidth(w * 0.5f);+ ImGui::InputText("##api_name", api_name_buf_, sizeof(api_name_buf_));+ ImGui::PopItemWidth();++ ImGui::Text("Desc:");+ ImGui::SameLine(80);+ ImGui::PushItemWidth(w * 0.5f);+ ImGui::InputText("##api_desc", api_desc_buf_, sizeof(api_desc_buf_));+ ImGui::PopItemWidth();++ ImGui::Spacing();+ ImGui::Separator();+ ImGui::Spacing();++ // URL & Method+ static const char* methods[] = {"GET", "POST", "PUT", "DELETE", "PATCH"};+ ImGui::Text("Method:");+ ImGui::SameLine(80);+ ImGui::PushItemWidth(80);+ ImGui::Combo("##method", &api_method_idx_, methods, 5);+ ImGui::PopItemWidth();++ ImGui::Text("Base URL:");+ ImGui::SameLine(80);+ ImGui::PushItemWidth(w * 0.5f);+ ImGui::InputText("##base_url", api_base_url_buf_, sizeof(api_base_url_buf_));+ ImGui::PopItemWidth();++ ImGui::Text("Endpoint:");+ ImGui::SameLine(80);+ ImGui::PushItemWidth(w * 0.5f);+ ImGui::InputText("##endpoint", api_endpoint_buf_, sizeof(api_endpoint_buf_));+ ImGui::PopItemWidth();++ ImGui::PushStyleColor(ImGuiCol_Text, BB_DIM);+ ImGui::Text(" Use {placeholders} for runtime parameters, e.g. /ticker/{symbol}");+ ImGui::PopStyleColor();++ // Body (for POST/PUT/PATCH)+ if (api_method_idx_ >= 1 && api_method_idx_ <= 3) {+ ImGui::Spacing();+ ImGui::Text("Body (JSON):");+ ImGui::InputTextMultiline("##body", api_body_buf_, sizeof(api_body_buf_),+ {w * 0.6f, 80});+ }++ ImGui::Spacing();+ ImGui::Separator();+ ImGui::Spacing();++ // Authentication+ render_auth_config();++ ImGui::Spacing();+ ImGui::Separator();+ ImGui::Spacing();++ // Headers+ render_headers_editor();++ ImGui::Spacing();+ ImGui::Separator();+ ImGui::Spacing();++ // Query params+ render_query_params_editor();++ // Fetch sample button+ ImGui::Spacing();+ ImGui::Spacing();+ if (fetching_) {+ ImGui::PushStyleColor(ImGuiCol_Text, BB_AMBER);+ ImGui::Text("Fetching...");+ ImGui::PopStyleColor();+ } else {+ if (ImGui::Button("Fetch Sample Data")) {+ fetch_sample_data();+ }+ }+}++// ============================================================================+// Auth config section+// ============================================================================++void DataMappingScreen::render_auth_config() {+ static const char* auth_types[] = {"None", "API Key", "Bearer Token", "Basic Auth", "OAuth2"};++ ImGui::PushStyleColor(ImGuiCol_Text, BB_CYAN);+ ImGui::Text("AUTHENTICATION");+ ImGui::PopStyleColor();+ ImGui::Spacing();++ ImGui::Text("Type:");+ ImGui::SameLine(80);+ ImGui::PushItemWidth(150);+ ImGui::Combo("##auth_type", &api_auth_type_idx_, auth_types, 5);+ ImGui::PopItemWidth();++ switch (api_auth_type_idx_) {+ case 1: { // API Key+ static const char* locations[] = {"Header", "Query Param"};+ ImGui::Text("Location:");+ ImGui::SameLine(80);+ ImGui::PushItemWidth(120);+ ImGui::Combo("##key_loc", &auth_key_location_idx_, locations, 2);+ ImGui::PopItemWidth();++ ImGui::Text("Key Name:");+ ImGui::SameLine(80);+ ImGui::PushItemWidth(200);+ ImGui::InputText("##key_name", auth_key_name_buf_, sizeof(auth_key_name_buf_));+ ImGui::PopItemWidth();++ ImGui::Text("Value:");+ ImGui::SameLine(80);+ ImGui::PushItemWidth(300);+ ImGui::InputText("##key_val", auth_key_value_buf_, sizeof(auth_key_value_buf_),+ ImGuiInputTextFlags_Password);+ ImGui::PopItemWidth();+ break;+ }+ case 2: { // Bearer+ ImGui::Text("Token:");+ ImGui::SameLine(80);+ ImGui::PushItemWidth(400);+ ImGui::InputText("##bearer", auth_bearer_buf_, sizeof(auth_bearer_buf_),+ ImGuiInputTextFlags_Password);+ ImGui::PopItemWidth();+ break;+ }+ case 3: { // Basic+ ImGui::Text("Username:");+ ImGui::SameLine(80);+ ImGui::PushItemWidth(200);+ ImGui::InputText("##basic_user", auth_basic_user_buf_, sizeof(auth_basic_user_buf_));+ ImGui::PopItemWidth();++ ImGui::Text("Password:");+ ImGui::SameLine(80);+ ImGui::PushItemWidth(200);+ ImGui::InputText("##basic_pass", auth_basic_pass_buf_, sizeof(auth_basic_pass_buf_),+ ImGuiInputTextFlags_Password);+ ImGui::PopItemWidth();+ break;+ }+ default: break;+ }+}++// ============================================================================+// Headers editor+// ============================================================================++void DataMappingScreen::render_headers_editor() {+ ImGui::PushStyleColor(ImGuiCol_Text, BB_CYAN);+ ImGui::Text("HEADERS");+ ImGui::PopStyleColor();++ // Show existing headers+ auto& hdrs = current_mapping_.api_config.headers;+ std::string to_remove;+ for (const auto& [k, v] : hdrs) {+ ImGui::PushStyleColor(ImGuiCol_Text, BB_WHITE);+ ImGui::Text(" %s:", k.c_str());+ ImGui::PopStyleColor();+ ImGui::SameLine();+ ImGui::PushStyleColor(ImGuiCol_Text, BB_GRAY);+ ImGui::Text("%s", v.c_str());+ ImGui::PopStyleColor();+ ImGui::SameLine();+ ImGui::PushID(k.c_str());+ if (ImGui::SmallButton("x")) to_remove = k;+ ImGui::PopID();+ }+ if (!to_remove.empty()) hdrs.erase(to_remove);++ // Add new header+ ImGui::PushItemWidth(120);+ ImGui::InputTextWithHint("##hdr_key", "Key", header_key_buf_, sizeof(header_key_buf_));+ ImGui::PopItemWidth();+ ImGui::SameLine();+ ImGui::PushItemWidth(200);+ ImGui::InputTextWithHint("##hdr_val", "Value", header_val_buf_, sizeof(header_val_buf_));+ ImGui::PopItemWidth();+ ImGui::SameLine();+ if (ImGui::SmallButton("+ Add Header")) {+ if (std::strlen(header_key_buf_) > 0) {+ hdrs[header_key_buf_] = header_val_buf_;+ header_key_buf_[0] = '\0';+ header_val_buf_[0] = '\0';+ }+ }+}++// ============================================================================+// Query params editor+// ============================================================================++void DataMappingScreen::render_query_params_editor() {+ ImGui::PushStyleColor(ImGuiCol_Text, BB_CYAN);+ ImGui::Text("QUERY PARAMETERS");+ ImGui::PopStyleColor();++ auto& qparams = current_mapping_.api_config.query_params;+ std::string to_remove;+ for (const auto& [k, v] : qparams) {+ ImGui::PushStyleColor(ImGuiCol_Text, BB_WHITE);+ ImGui::Text(" %s:", k.c_str());+ ImGui::PopStyleColor();+ ImGui::SameLine();+ ImGui::PushStyleColor(ImGuiCol_Text, BB_GRAY);+ ImGui::Text("%s", v.c_str());+ ImGui::PopStyleColor();+ ImGui::SameLine();+ ImGui::PushID(("qp_" + k).c_str());+ if (ImGui::SmallButton("x")) to_remove = k;+ ImGui::PopID();+ }+ if (!to_remove.empty()) qparams.erase(to_remove);++ ImGui::PushItemWidth(120);+ ImGui::InputTextWithHint("##qp_key", "Key", qparam_key_buf_, sizeof(qparam_key_buf_));+ ImGui::PopItemWidth();+ ImGui::SameLine();+ ImGui::PushItemWidth(200);+ ImGui::InputTextWithHint("##qp_val", "Value", qparam_val_buf_, sizeof(qparam_val_buf_));+ ImGui::PopItemWidth();+ ImGui::SameLine();+ if (ImGui::SmallButton("+ Add Param")) {+ if (std::strlen(qparam_key_buf_) > 0) {+ qparams[qparam_key_buf_] = qparam_val_buf_;+ qparam_key_buf_[0] = '\0';+ qparam_val_buf_[0] = '\0';+ }+ }+}++// ============================================================================+// Step 2: Schema Selection+// ============================================================================++void DataMappingScreen::render_step_schema_select(float w, float /*h*/) {+ ImGui::PushStyleColor(ImGuiCol_Text, BB_CYAN);+ ImGui::Text("TARGET SCHEMA");+ ImGui::PopStyleColor();+ ImGui::Spacing();++ ImGui::Checkbox("Use predefined schema", ¤t_mapping_.is_predefined_schema);+ is_custom_schema_ = !current_mapping_.is_predefined_schema;++ ImGui::Spacing();++ if (current_mapping_.is_predefined_schema) {+ const auto names = get_schema_type_names();+ static const char* schema_items[] = {"OHLCV", "QUOTE", "TICK", "ORDER", "POSITION", "PORTFOLIO", "INSTRUMENT"};+ ImGui::Text("Schema:");+ ImGui::SameLine(80);+ ImGui::PushItemWidth(200);+ if (ImGui::Combo("##schema_type", &schema_type_idx_, schema_items, 7)) {+ current_mapping_.schema_type = static_cast<SchemaType>(schema_type_idx_);+ }+ ImGui::PopItemWidth();++ // Show schema fields+ const auto* schema = get_schema_for_type(current_mapping_.schema_type);+ if (schema) {+ ImGui::Spacing();+ ImGui::PushStyleColor(ImGuiCol_Text, BB_AMBER);+ ImGui::Text("Fields in %s:", schema->name.c_str());+ ImGui::PopStyleColor();++ if (ImGui::BeginTable("##schema_fields", 4, ImGuiTableFlags_RowBg | ImGuiTableFlags_Borders)) {+ ImGui::TableSetupColumn("Field", ImGuiTableColumnFlags_None, w * 0.25f);+ ImGui::TableSetupColumn("Type", ImGuiTableColumnFlags_None, w * 0.12f);+ ImGui::TableSetupColumn("Required", ImGuiTableColumnFlags_None, w * 0.1f);+ ImGui::TableSetupColumn("Description", ImGuiTableColumnFlags_None, w * 0.4f);+ ImGui::PushStyleColor(ImGuiCol_TableHeaderBg, BB_HEADER_BG);+ ImGui::TableHeadersRow();+ ImGui::PopStyleColor();++ for (const auto& f : schema->fields) {+ ImGui::TableNextRow();+ ImGui::TableNextColumn();+ ImGui::PushStyleColor(ImGuiCol_Text, BB_WHITE);+ ImGui::Text("%s", f.name.c_str());+ ImGui::PopStyleColor();++ ImGui::TableNextColumn();+ ImGui::PushStyleColor(ImGuiCol_Text, BB_CYAN);+ ImGui::Text("%s", field_type_label(f.type));+ ImGui::PopStyleColor();++ ImGui::TableNextColumn();+ ImGui::PushStyleColor(ImGuiCol_Text, f.required ? BB_AMBER : BB_DIM);+ ImGui::Text("%s", f.required ? "YES" : "no");+ ImGui::PopStyleColor();++ ImGui::TableNextColumn();+ ImGui::PushStyleColor(ImGuiCol_Text, BB_GRAY);+ ImGui::Text("%s", f.description.c_str());+ ImGui::PopStyleColor();+ }+ ImGui::EndTable();+ }+ }+ } else {+ ImGui::Text("Custom schema fields are configured in the Field Mapping step.");+ }++ // Extraction config+ ImGui::Spacing();+ ImGui::Separator();+ ImGui::Spacing();++ ImGui::PushStyleColor(ImGuiCol_Text, BB_CYAN);+ ImGui::Text("DATA EXTRACTION");+ ImGui::PopStyleColor();+ ImGui::Spacing();++ ImGui::Text("Root Path:");+ ImGui::SameLine(100);+ ImGui::PushItemWidth(300);+ ImGui::InputTextWithHint("##root_path", "e.g. data.candles", root_path_buf_, sizeof(root_path_buf_));+ ImGui::PopItemWidth();++ ImGui::Checkbox("Source is array", ¤t_mapping_.extraction.is_array);+ ImGui::SameLine();+ ImGui::Checkbox("Array of arrays", ¤t_mapping_.extraction.is_array_of_arrays);+}++// ============================================================================+// Step 3: Field Mapping+// ============================================================================++void DataMappingScreen::render_step_field_mapping(float w, float /*h*/) {+ ImGui::PushStyleColor(ImGuiCol_Text, BB_CYAN);+ ImGui::Text("FIELD MAPPINGS");+ ImGui::PopStyleColor();+ ImGui::Spacing();++ // Auto-populate from schema if empty+ if (current_mapping_.field_mappings.empty() && current_mapping_.is_predefined_schema) {+ const auto* schema = get_schema_for_type(current_mapping_.schema_type);+ if (schema) {+ for (const auto& f : schema->fields) {+ FieldMapping fm;+ fm.target_field = f.name;+ fm.source_path = f.name;+ fm.required = f.required;+ current_mapping_.field_mappings.push_back(fm);+ }+ }+ }++ // Add mapping button+ if (ImGui::Button("+ Add Field Mapping")) {+ current_mapping_.field_mappings.push_back({});+ }++ ImGui::Spacing();++ // Field mapping table+ if (!current_mapping_.field_mappings.empty() &&+ ImGui::BeginTable("##field_map_table", 6,+ ImGuiTableFlags_RowBg | ImGuiTableFlags_Borders | ImGuiTableFlags_ScrollY)) {++ ImGui::TableSetupColumn("Target Field", ImGuiTableColumnFlags_None, w * 0.18f);+ ImGui::TableSetupColumn("Source Path", ImGuiTableColumnFlags_None, w * 0.25f);+ ImGui::TableSetupColumn("Parser", ImGuiTableColumnFlags_None, w * 0.10f);+ ImGui::TableSetupColumn("Transform", ImGuiTableColumnFlags_None, w * 0.15f);+ ImGui::TableSetupColumn("Req?", ImGuiTableColumnFlags_None, w * 0.06f);+ ImGui::TableSetupColumn("", ImGuiTableColumnFlags_None, w * 0.06f);+ ImGui::PushStyleColor(ImGuiCol_TableHeaderBg, BB_HEADER_BG);+ ImGui::TableHeadersRow();+ ImGui::PopStyleColor();++ int to_delete = -1;+ for (size_t i = 0; i < current_mapping_.field_mappings.size(); ++i) {+ auto& fm = current_mapping_.field_mappings[i];+ ImGui::PushID(static_cast<int>(i));+ ImGui::TableNextRow();++ // Target field+ ImGui::TableNextColumn();+ char target_buf[64] = {};+ std::strncpy(target_buf, fm.target_field.c_str(), sizeof(target_buf) - 1);+ ImGui::PushItemWidth(-1);+ if (ImGui::InputText("##target", target_buf, sizeof(target_buf))) {+ fm.target_field = target_buf;+ }+ ImGui::PopItemWidth();++ // Source path+ ImGui::TableNextColumn();+ char source_buf[128] = {};+ std::strncpy(source_buf, fm.source_path.c_str(), sizeof(source_buf) - 1);+ ImGui::PushItemWidth(-1);+ if (ImGui::InputText("##source", source_buf, sizeof(source_buf))) {+ fm.source_path = source_buf;+ }+ ImGui::PopItemWidth();++ // Parser+ ImGui::TableNextColumn();+ static const char* parsers[] = {"Direct", "JSONPath", "Regex"};+ int parser_idx = static_cast<int>(fm.parser);+ ImGui::PushItemWidth(-1);+ if (ImGui::Combo("##parser", &parser_idx, parsers, 3)) {+ fm.parser = static_cast<ParserEngine>(parser_idx);+ }+ ImGui::PopItemWidth();++ // Transform (first one)+ ImGui::TableNextColumn();+ ImGui::PushItemWidth(-1);+ char xform_buf[64] = {};+ if (!fm.transforms.empty()) {+ std::strncpy(xform_buf, fm.transforms[0].c_str(), sizeof(xform_buf) - 1);+ }+ if (ImGui::InputText("##xform", xform_buf, sizeof(xform_buf))) {+ if (std::strlen(xform_buf) > 0) {+ if (fm.transforms.empty()) fm.transforms.push_back(xform_buf);+ else fm.transforms[0] = xform_buf;+ } else {+ fm.transforms.clear();+ }+ }+ ImGui::PopItemWidth();++ // Required+ ImGui::TableNextColumn();+ ImGui::Checkbox("##req", &fm.required);++ // Delete+ ImGui::TableNextColumn();+ ImGui::PushStyleColor(ImGuiCol_Text, BB_RED);+ if (ImGui::SmallButton("X")) to_delete = static_cast<int>(i);+ ImGui::PopStyleColor();++ ImGui::PopID();+ }++ if (to_delete >= 0) {+ current_mapping_.field_mappings.erase(+ current_mapping_.field_mappings.begin() + to_delete);+ }++ ImGui::EndTable();+ }+}++// ============================================================================+// Step 4: Cache Settings+// ============================================================================++void DataMappingScreen::render_step_cache_settings(float /*w*/, float /*h*/) {+ ImGui::PushStyleColor(ImGuiCol_Text, BB_CYAN);+ ImGui::Text("CACHE SETTINGS");+ ImGui::PopStyleColor();+ ImGui::Spacing();++ ImGui::Checkbox("Enable caching", ¤t_mapping_.api_config.cache_enabled);++ if (current_mapping_.api_config.cache_enabled) {+ ImGui::Text("TTL (seconds):");+ ImGui::SameLine(120);+ ImGui::PushItemWidth(100);+ ImGui::InputInt("##cache_ttl", ¤t_mapping_.api_config.cache_ttl_seconds);+ ImGui::PopItemWidth();++ if (current_mapping_.api_config.cache_ttl_seconds < 0) {+ current_mapping_.api_config.cache_ttl_seconds = 0;+ }+ }++ ImGui::Spacing();+ ImGui::Separator();+ ImGui::Spacing();++ ImGui::PushStyleColor(ImGuiCol_Text, BB_CYAN);+ ImGui::Text("VALIDATION");+ ImGui::PopStyleColor();+ ImGui::Spacing();++ ImGui::Checkbox("Enable validation", ¤t_mapping_.validation.enabled);+ if (current_mapping_.validation.enabled) {+ ImGui::Checkbox("Strict mode (fail on errors)", ¤t_mapping_.validation.strict_mode);+ }++ ImGui::Spacing();+ ImGui::Separator();+ ImGui::Spacing();++ // Post-processing+ ImGui::PushStyleColor(ImGuiCol_Text, BB_CYAN);+ ImGui::Text("POST-PROCESSING");+ ImGui::PopStyleColor();+ ImGui::Spacing();++ // Limit+ int limit_val = current_mapping_.post_processing.limit.value_or(0);+ ImGui::Text("Limit:");+ ImGui::SameLine(80);+ ImGui::PushItemWidth(100);+ if (ImGui::InputInt("##pp_limit", &limit_val)) {+ current_mapping_.post_processing.limit = (limit_val > 0) ? std::optional<int>(limit_val) : std::nullopt;+ }+ ImGui::PopItemWidth();++ ImGui::PushStyleColor(ImGuiCol_Text, BB_DIM);+ ImGui::Text(" 0 = no limit");+ ImGui::PopStyleColor();+}++// ============================================================================+// Step 5: Test & Save+// ============================================================================++void DataMappingScreen::render_step_test_save(float w, float h) {+ // Mapping name/description+ ImGui::PushStyleColor(ImGuiCol_Text, BB_CYAN);+ ImGui::Text("MAPPING DETAILS");+ ImGui::PopStyleColor();+ ImGui::Spacing();++ ImGui::Text("Name:");+ ImGui::SameLine(80);+ ImGui::PushItemWidth(w * 0.4f);+ ImGui::InputText("##map_name", mapping_name_buf_, sizeof(mapping_name_buf_));+ ImGui::PopItemWidth();++ ImGui::Text("Desc:");+ ImGui::SameLine(80);+ ImGui::PushItemWidth(w * 0.4f);+ ImGui::InputText("##map_desc", mapping_desc_buf_, sizeof(mapping_desc_buf_));+ ImGui::PopItemWidth();++ ImGui::Spacing();+ ImGui::Separator();+ ImGui::Spacing();++ // Test section+ ImGui::PushStyleColor(ImGuiCol_Text, BB_CYAN);+ ImGui::Text("TEST MAPPING");+ ImGui::PopStyleColor();+ ImGui::Spacing();++ // Sample data input+ ImGui::Text("Sample JSON Data:");+ static char sample_buf[8192] = {};+ if (!sample_data_json_.empty() && sample_buf[0] == '\0') {+ std::strncpy(sample_buf, sample_data_json_.c_str(),+ std::min<size_t>(sizeof(sample_buf) - 1, sample_data_json_.size()));+ }+ ImGui::InputTextMultiline("##sample_json", sample_buf, sizeof(sample_buf),+ {w * 0.7f, 120});++ ImGui::Spacing();++ if (testing_) {+ ImGui::PushStyleColor(ImGuiCol_Text, BB_AMBER);+ ImGui::Text("Testing...");+ ImGui::PopStyleColor();+ } else {+ if (ImGui::Button("Run Test")) {+ sample_data_json_ = sample_buf;+ start_test();+ }+ }++ // Test results+ if (test_result_) {+ ImGui::Spacing();+ ImGui::Separator();+ ImGui::Spacing();++ if (test_result_->success) {+ ImGui::PushStyleColor(ImGuiCol_Text, BB_GREEN);+ ImGui::Text("SUCCESS - %d records in %lldms",+ test_result_->records_returned, static_cast<long long>(test_result_->duration_ms));+ ImGui::PopStyleColor();++ // Show preview+ render_json_preview("Transformed Data", test_result_->data_json, 200);+ } else {+ ImGui::PushStyleColor(ImGuiCol_Text, BB_RED);+ ImGui::Text("FAILED");+ ImGui::PopStyleColor();+ for (const auto& err : test_result_->errors) {+ ImGui::PushStyleColor(ImGuiCol_Text, BB_RED);+ ImGui::Text(" - %s", err.c_str());+ ImGui::PopStyleColor();+ }+ }++ render_validation_results();+ }++ // Save button+ ImGui::Spacing();+ ImGui::Spacing();+ ImGui::PushStyleColor(ImGuiCol_Button, ImVec4{0.0f, 0.5f, 0.2f, 1.0f});+ if (ImGui::Button("Save Mapping", {140, 30})) {+ save_current_mapping();+ }+ ImGui::PopStyleColor();+}++// ============================================================================+// Templates view+// ============================================================================++void DataMappingScreen::render_templates_view(float w, float /*h*/) {+ ImGui::PushStyleColor(ImGuiCol_Text, BB_AMBER);+ ImGui::Text("MAPPING TEMPLATES");+ ImGui::PopStyleColor();+ ImGui::Spacing();++ if (templates_.empty()) {+ ImGui::PushStyleColor(ImGuiCol_Text, BB_DIM);+ ImGui::Text("No templates available.");+ ImGui::PopStyleColor();+ return;+ }++ if (ImGui::BeginTable("##templates_table", 5,+ ImGuiTableFlags_RowBg | ImGuiTableFlags_Borders | ImGuiTableFlags_ScrollY)) {++ ImGui::TableSetupColumn("Name", ImGuiTableColumnFlags_None, w * 0.25f);+ ImGui::TableSetupColumn("Category", ImGuiTableColumnFlags_None, w * 0.12f);+ ImGui::TableSetupColumn("Description", ImGuiTableColumnFlags_None, w * 0.35f);+ ImGui::TableSetupColumn("Tags", ImGuiTableColumnFlags_None, w * 0.15f);+ ImGui::TableSetupColumn("", ImGuiTableColumnFlags_None, w * 0.1f);+ ImGui::PushStyleColor(ImGuiCol_TableHeaderBg, BB_HEADER_BG);+ ImGui::TableHeadersRow();+ ImGui::PopStyleColor();++ for (size_t i = 0; i < templates_.size(); ++i) {+ const auto& t = templates_[i];+ ImGui::TableNextRow();++ ImGui::TableNextColumn();+ ImGui::PushStyleColor(ImGuiCol_Text, BB_WHITE);+ ImGui::Text("%s", t.name.c_str());+ ImGui::PopStyleColor();++ ImGui::TableNextColumn();+ ImGui::PushStyleColor(ImGuiCol_Text, BB_CYAN);+ ImGui::Text("%s", t.category.c_str());+ ImGui::PopStyleColor();++ ImGui::TableNextColumn();+ ImGui::PushStyleColor(ImGuiCol_Text, BB_GRAY);+ ImGui::Text("%s", t.description.c_str());+ ImGui::PopStyleColor();++ ImGui::TableNextColumn();+ ImGui::PushStyleColor(ImGuiCol_Text, BB_DIM);+ std::string tags_str;+ for (const auto& tag : t.tags) {+ if (!tags_str.empty()) tags_str += ", ";+ tags_str += tag;+ }+ ImGui::Text("%s", tags_str.c_str());+ ImGui::PopStyleColor();++ ImGui::TableNextColumn();+ ImGui::PushID(static_cast<int>(i));+ if (ImGui::SmallButton("Use")) {+ load_template(t);+ }+ ImGui::PopID();+ }+ ImGui::EndTable();+ }+}++// ============================================================================+// Status panel (right side)+// ============================================================================++void DataMappingScreen::render_status_panel(float x, float y, float w, float h) {+ ImGui::SetNextWindowPos({x, y});+ ImGui::SetNextWindowSize({w, h});+ ImGui::PushStyleColor(ImGuiCol_WindowBg, BB_PANEL);+ ImGui::PushStyleVar(ImGuiStyleVar_WindowPadding, {8, 8});++ ImGui::Begin("##dm_status", nullptr,+ ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_NoResize | ImGuiWindowFlags_NoMove |+ ImGuiWindowFlags_NoDocking);++ ImGui::PushStyleColor(ImGuiCol_Text, BB_AMBER);+ ImGui::Text("STATUS");+ ImGui::PopStyleColor();+ ImGui::Separator();+ ImGui::Spacing();++ // Current view+ ImGui::PushStyleColor(ImGuiCol_Text, BB_GRAY);+ ImGui::Text("View:");+ ImGui::PopStyleColor();+ ImGui::SameLine();+ ImGui::PushStyleColor(ImGuiCol_Text, BB_WHITE);+ switch (view_) {+ case MappingView::list: ImGui::Text("List"); break;+ case MappingView::create: ImGui::Text("Create/Edit"); break;+ case MappingView::templates: ImGui::Text("Templates"); break;+ }+ ImGui::PopStyleColor();++ ImGui::Spacing();++ // Mapping count+ ImGui::PushStyleColor(ImGuiCol_Text, BB_GRAY);+ ImGui::Text("Saved:");+ ImGui::PopStyleColor();+ ImGui::SameLine();+ ImGui::PushStyleColor(ImGuiCol_Text, BB_GREEN);+ ImGui::Text("%d", static_cast<int>(saved_mappings_.size()));+ ImGui::PopStyleColor();++ // If in create mode, show current config summary+ if (view_ == MappingView::create) {+ ImGui::Spacing();+ ImGui::Separator();+ ImGui::Spacing();++ ImGui::PushStyleColor(ImGuiCol_Text, BB_CYAN);+ ImGui::Text("CURRENT CONFIG");+ ImGui::PopStyleColor();+ ImGui::Spacing();++ if (api_base_url_buf_[0] != '\0') {+ ImGui::PushStyleColor(ImGuiCol_Text, BB_GRAY);+ ImGui::Text("URL:");+ ImGui::PopStyleColor();+ ImGui::PushStyleColor(ImGuiCol_Text, BB_DIM);+ ImGui::TextWrapped("%s%s", api_base_url_buf_, api_endpoint_buf_);+ ImGui::PopStyleColor();+ }++ ImGui::Spacing();++ ImGui::PushStyleColor(ImGuiCol_Text, BB_GRAY);+ ImGui::Text("Fields: %d", static_cast<int>(current_mapping_.field_mappings.size()));+ ImGui::PopStyleColor();++ // Sample data status+ ImGui::Spacing();+ if (!sample_data_json_.empty()) {+ ImGui::PushStyleColor(ImGuiCol_Text, BB_GREEN);+ ImGui::Text("Sample data loaded");+ ImGui::PopStyleColor();+ } else {+ ImGui::PushStyleColor(ImGuiCol_Text, BB_DIM);+ ImGui::Text("No sample data");+ ImGui::PopStyleColor();+ }+ }++ ImGui::End();+ ImGui::PopStyleVar();+ ImGui::PopStyleColor();+}++// ============================================================================+// Footer+// ============================================================================++void DataMappingScreen::render_footer(float w, float footer_h) {+ const ImGuiViewport* vp = ImGui::GetMainViewport();+ ImGui::SetNextWindowPos({vp->WorkPos.x, vp->WorkPos.y + vp->WorkSize.y - footer_h});+ ImGui::SetNextWindowSize({w, footer_h});+ ImGui::PushStyleColor(ImGuiCol_WindowBg, BB_CMD_BG);+ ImGui::PushStyleVar(ImGuiStyleVar_WindowPadding, {8, 2});++ ImGui::Begin("##dm_footer", nullptr,+ ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_NoResize | ImGuiWindowFlags_NoMove |+ ImGuiWindowFlags_NoScrollbar | ImGuiWindowFlags_NoDocking);++ ImGui::PushStyleColor(ImGuiCol_Text, BB_DIM);+ ImGui::Text("DATA MAPPING | %d mappings | %d templates",+ static_cast<int>(saved_mappings_.size()),+ static_cast<int>(templates_.size()));+ ImGui::PopStyleColor();++ ImGui::End();+ ImGui::PopStyleVar();+ ImGui::PopStyleColor();+}++// ============================================================================+// JSON Preview helper+// ============================================================================++void DataMappingScreen::render_json_preview(const std::string& label,+ const std::string& json_str,+ float height) {+ ImGui::PushStyleColor(ImGuiCol_Text, BB_AMBER);+ ImGui::Text("%s:", label.c_str());+ ImGui::PopStyleColor();++ ImGui::PushStyleColor(ImGuiCol_FrameBg, BB_PANEL);+ ImGui::PushStyleColor(ImGuiCol_Text, BB_WHITE);+ // Truncate for display+ const std::string display = (json_str.size() > 4000)+ ? json_str.substr(0, 4000) + "\n... (truncated)"+ : json_str;+ char preview_buf[4096] = {};+ std::strncpy(preview_buf, display.c_str(),+ std::min<size_t>(sizeof(preview_buf) - 1, display.size()));+ ImGui::InputTextMultiline("##json_preview", preview_buf, sizeof(preview_buf),+ {-1, height}, ImGuiInputTextFlags_ReadOnly);+ ImGui::PopStyleColor(2);+}++// ============================================================================+// Validation results display+// ============================================================================++void DataMappingScreen::render_validation_results() {+ if (!test_result_ || !test_result_->validation.valid) return;++ if (test_result_->validation.errors.empty()) {+ ImGui::PushStyleColor(ImGuiCol_Text, BB_GREEN);+ ImGui::Text("Validation: PASSED");+ ImGui::PopStyleColor();+ } else {+ ImGui::PushStyleColor(ImGuiCol_Text, BB_RED);+ ImGui::Text("Validation: %d errors", static_cast<int>(test_result_->validation.errors.size()));+ ImGui::PopStyleColor();+ for (const auto& e : test_result_->validation.errors) {+ ImGui::PushStyleColor(ImGuiCol_Text, BB_RED);+ ImGui::Text(" [%s] %s: %s", e.rule.c_str(), e.field.c_str(), e.message.c_str());+ ImGui::PopStyleColor();+ }+ }+}++// ============================================================================+// Actions+// ============================================================================++void DataMappingScreen::load_mappings() {+ saved_mappings_ = mapping_ops::get_all_mappings();+}++void DataMappingScreen::save_current_mapping() {+ // Sync form buffers to current_mapping_+ current_mapping_.name = mapping_name_buf_;+ current_mapping_.description = mapping_desc_buf_;+ current_mapping_.api_config.name = api_name_buf_;+ current_mapping_.api_config.description = api_desc_buf_;+ current_mapping_.api_config.base_url = api_base_url_buf_;+ current_mapping_.api_config.endpoint = api_endpoint_buf_;+ current_mapping_.api_config.method = static_cast<HttpMethod>(api_method_idx_);+ current_mapping_.extraction.root_path = root_path_buf_;++ if (std::strlen(api_body_buf_) > 0) {+ current_mapping_.api_config.body = api_body_buf_;+ }++ // Auth+ switch (api_auth_type_idx_) {+ case 0: current_mapping_.api_config.authentication.type = AuthType::none; break;+ case 1: {+ current_mapping_.api_config.authentication.type = AuthType::apikey;+ current_mapping_.api_config.authentication.apikey = ApiKeyConfig{+ auth_key_location_idx_ == 1 ? ApiKeyLocation::query : ApiKeyLocation::header,+ auth_key_name_buf_, auth_key_value_buf_+ };+ break;+ }+ case 2: {+ current_mapping_.api_config.authentication.type = AuthType::bearer;+ current_mapping_.api_config.authentication.bearer = BearerConfig{auth_bearer_buf_};+ break;+ }+ case 3: {+ current_mapping_.api_config.authentication.type = AuthType::basic;+ current_mapping_.api_config.authentication.basic = BasicAuthConfig{+ auth_basic_user_buf_, auth_basic_pass_buf_};+ break;+ }+ default: break;+ }++ // Generate timestamps+ if (current_mapping_.id.empty()) {+ current_mapping_.id = db::generate_uuid();+ }+ if (current_mapping_.api_config.id.empty()) {+ current_mapping_.api_config.id = db::generate_uuid();+ }++ const auto now = std::chrono::system_clock::now();+ const auto tt = std::chrono::system_clock::to_time_t(now);+ std::tm tm_buf{};+#ifdef _WIN32+ gmtime_s(&tm_buf, &tt);+#else+ gmtime_r(&tt, &tm_buf);+#endif+ char time_str[64];+ std::strftime(time_str, sizeof(time_str), "%Y-%m-%dT%H:%M:%SZ", &tm_buf);++ if (current_mapping_.created_at.empty()) {+ current_mapping_.created_at = time_str;+ }+ current_mapping_.updated_at = time_str;++ mapping_ops::save_mapping(current_mapping_);+ load_mappings();+ view_ = MappingView::list;+}++void DataMappingScreen::delete_mapping_by_id(const std::string& id) {+ mapping_ops::delete_mapping(id);+ load_mappings();+}++void DataMappingScreen::start_test() {+ // Sync form to mapping+ current_mapping_.extraction.root_path = root_path_buf_;++ json sample_json;+ if (!sample_data_json_.empty()) {+ try {+ sample_json = json::parse(sample_data_json_);+ } catch (...) {+ test_result_ = ExecutionResult{};+ test_result_->errors.push_back("Invalid JSON in sample data");+ return;+ }+ }++ testing_ = true;+ test_future_ = std::async(std::launch::async, [this, sample_json]() {+ return engine_.test(current_mapping_, sample_json);+ });+}++void DataMappingScreen::fetch_sample_data() {+ // Sync buffers+ current_mapping_.api_config.base_url = api_base_url_buf_;+ current_mapping_.api_config.endpoint = api_endpoint_buf_;+ current_mapping_.api_config.method = static_cast<HttpMethod>(api_method_idx_);++ fetching_ = true;+ fetch_future_ = std::async(std::launch::async, [this]() {+ return engine_.fetch_api(current_mapping_.api_config);+ });+}++void DataMappingScreen::reset_create_form() {+ current_mapping_ = MappingConfig{};+ current_mapping_.id = db::generate_uuid();+ current_mapping_.api_config.id = db::generate_uuid();+ current_step_ = CreateStep::api_config;+ test_result_ = std::nullopt;+ sample_data_json_.clear();++ std::memset(api_name_buf_, 0, sizeof(api_name_buf_));+ std::memset(api_desc_buf_, 0, sizeof(api_desc_buf_));+ std::memset(api_base_url_buf_, 0, sizeof(api_base_url_buf_));+ std::memset(api_endpoint_buf_, 0, sizeof(api_endpoint_buf_));+ std::memset(api_body_buf_, 0, sizeof(api_body_buf_));+ std::memset(mapping_name_buf_, 0, sizeof(mapping_name_buf_));+ std::memset(mapping_desc_buf_, 0, sizeof(mapping_desc_buf_));+ std::memset(root_path_buf_, 0, sizeof(root_path_buf_));+ std::memset(auth_key_name_buf_, 0, sizeof(auth_key_name_buf_));+ std::memset(auth_key_value_buf_, 0, sizeof(auth_key_value_buf_));+ std::memset(auth_bearer_buf_, 0, sizeof(auth_bearer_buf_));+ std::memset(auth_basic_user_buf_, 0, sizeof(auth_basic_user_buf_));+ std::memset(auth_basic_pass_buf_, 0, sizeof(auth_basic_pass_buf_));++ api_method_idx_ = 0;+ api_auth_type_idx_ = 0;+ schema_type_idx_ = 0;+ parser_engine_idx_ = 0;+}++void DataMappingScreen::edit_mapping(const MappingConfig& config) {+ current_mapping_ = config;+ view_ = MappingView::create;+ current_step_ = CreateStep::api_config;++ std::strncpy(api_name_buf_, config.api_config.name.c_str(), sizeof(api_name_buf_) - 1);+ std::strncpy(api_desc_buf_, config.api_config.description.c_str(), sizeof(api_desc_buf_) - 1);+ std::strncpy(api_base_url_buf_, config.api_config.base_url.c_str(), sizeof(api_base_url_buf_) - 1);+ std::strncpy(api_endpoint_buf_, config.api_config.endpoint.c_str(), sizeof(api_endpoint_buf_) - 1);+ std::strncpy(mapping_name_buf_, config.name.c_str(), sizeof(mapping_name_buf_) - 1);+ std::strncpy(mapping_desc_buf_, config.description.c_str(), sizeof(mapping_desc_buf_) - 1);+ std::strncpy(root_path_buf_, config.extraction.root_path.c_str(), sizeof(root_path_buf_) - 1);++ api_method_idx_ = static_cast<int>(config.api_config.method);+ api_auth_type_idx_ = static_cast<int>(config.api_config.authentication.type);+ schema_type_idx_ = static_cast<int>(config.schema_type);++ if (config.api_config.body) {+ std::strncpy(api_body_buf_, config.api_config.body->c_str(), sizeof(api_body_buf_) - 1);+ }++ // Auth details+ if (config.api_config.authentication.apikey) {+ const auto& ak = *config.api_config.authentication.apikey;+ std::strncpy(auth_key_name_buf_, ak.key_name.c_str(), sizeof(auth_key_name_buf_) - 1);+ std::strncpy(auth_key_value_buf_, ak.value.c_str(), sizeof(auth_key_value_buf_) - 1);+ auth_key_location_idx_ = (ak.location == ApiKeyLocation::query) ? 1 : 0;+ }+ if (config.api_config.authentication.bearer) {+ std::strncpy(auth_bearer_buf_, config.api_config.authentication.bearer->token.c_str(),+ sizeof(auth_bearer_buf_) - 1);+ }+ if (config.api_config.authentication.basic) {+ std::strncpy(auth_basic_user_buf_, config.api_config.authentication.basic->username.c_str(),+ sizeof(auth_basic_user_buf_) - 1);+ std::strncpy(auth_basic_pass_buf_, config.api_config.authentication.basic->password.c_str(),+ sizeof(auth_basic_pass_buf_) - 1);+ }+}++void DataMappingScreen::load_template(const MappingTemplate& tmpl) {+ reset_create_form();+ current_mapping_ = tmpl.config;+ current_mapping_.id = db::generate_uuid();+ current_mapping_.api_config.id = db::generate_uuid();++ // Populate form buffers+ std::strncpy(mapping_name_buf_, tmpl.config.name.c_str(), sizeof(mapping_name_buf_) - 1);+ std::strncpy(mapping_desc_buf_, tmpl.config.description.c_str(), sizeof(mapping_desc_buf_) - 1);+ std::strncpy(api_name_buf_, tmpl.config.api_config.name.c_str(), sizeof(api_name_buf_) - 1);+ std::strncpy(api_base_url_buf_, tmpl.config.api_config.base_url.c_str(), sizeof(api_base_url_buf_) - 1);+ std::strncpy(api_endpoint_buf_, tmpl.config.api_config.endpoint.c_str(), sizeof(api_endpoint_buf_) - 1);+ std::strncpy(root_path_buf_, tmpl.config.extraction.root_path.c_str(), sizeof(root_path_buf_) - 1);++ api_method_idx_ = static_cast<int>(tmpl.config.api_config.method);+ schema_type_idx_ = static_cast<int>(tmpl.config.schema_type);++ view_ = MappingView::create;+ current_step_ = CreateStep::api_config;+}++// ============================================================================+// Template loader — built-in Indian broker templates+// ============================================================================++void DataMappingScreen::load_templates() {+ templates_.clear();++ // Upstox Historical OHLCV+ {+ MappingTemplate t;+ t.id = "upstox_historical_ohlcv";+ t.name = "Upstox Historical Candles -> OHLCV";+ t.description = "Map Upstox historical candle data to standard OHLCV format";+ t.category = "broker";+ t.tags = {"upstox", "historical", "ohlcv", "india"};+ t.verified = true;+ t.official = true;++ t.config.name = "Upstox Historical -> OHLCV";+ t.config.description = "Transform Upstox historical candle data";+ t.config.is_predefined_schema = true;+ t.config.schema_type = SchemaType::ohlcv;+ t.config.extraction.engine = ParserEngine::direct;+ t.config.extraction.root_path = "data.candles";+ t.config.extraction.is_array = true;+ t.config.extraction.is_array_of_arrays = true;++ t.config.field_mappings = {+ {"timestamp", FieldSourceType::path, "$[0]", "", ParserEngine::direct, {"toISODate"}, {}, true, 0.0f},+ {"open", FieldSourceType::path, "$[1]", "", ParserEngine::direct, {}, {}, true, 0.0f},+ {"high", FieldSourceType::path, "$[2]", "", ParserEngine::direct, {}, {}, true, 0.0f},+ {"low", FieldSourceType::path, "$[3]", "", ParserEngine::direct, {}, {}, true, 0.0f},+ {"close", FieldSourceType::path, "$[4]", "", ParserEngine::direct, {}, {}, true, 0.0f},+ {"volume", FieldSourceType::path, "$[5]", "", ParserEngine::direct, {}, {}, true, 0.0f},+ };+ t.config.validation.enabled = true;+ t.instructions = "Use endpoint: /historical-candle/{instrument_key}/{interval}/{to_date}/{from_date}";+ templates_.push_back(t);+ }++ // Fyers Quotes+ {+ MappingTemplate t;+ t.id = "fyers_quotes";+ t.name = "Fyers Quotes -> QUOTE";+ t.description = "Map Fyers quote data to standard QUOTE format";+ t.category = "broker";+ t.tags = {"fyers", "quote", "india"};+ t.verified = true;+ t.official = true;++ t.config.name = "Fyers Quote -> QUOTE";+ t.config.is_predefined_schema = true;+ t.config.schema_type = SchemaType::quote;+ t.config.extraction.root_path = "d";+ t.config.extraction.is_array = true;++ t.config.field_mappings = {+ {"symbol", FieldSourceType::path, "n", "", ParserEngine::direct, {}, {}, true, 0.0f},+ {"timestamp", FieldSourceType::path, "v.tt", "", ParserEngine::direct, {"toISODate"}, {}, true, 0.0f},+ {"price", FieldSourceType::path, "v.lp", "", ParserEngine::direct, {}, {}, true, 0.0f},+ {"bid", FieldSourceType::path, "v.bid", "", ParserEngine::direct, {}, {}, false, 0.0f},+ {"ask", FieldSourceType::path, "v.ask", "", ParserEngine::direct, {}, {}, false, 0.0f},+ {"volume", FieldSourceType::path, "v.volume", "", ParserEngine::direct, {}, {}, false, 0.0f},+ {"open", FieldSourceType::path, "v.open_price", "", ParserEngine::direct, {}, {}, false, 0.0f},+ {"high", FieldSourceType::path, "v.high_price", "", ParserEngine::direct, {}, {}, false, 0.0f},+ {"low", FieldSourceType::path, "v.low_price", "", ParserEngine::direct, {}, {}, false, 0.0f},+ {"previousClose", FieldSourceType::path, "v.prev_close_price", "", ParserEngine::direct, {}, {}, false, 0.0f},+ {"change", FieldSourceType::path, "v.ch", "", ParserEngine::direct, {}, {}, false, 0.0f},+ {"changePercent", FieldSourceType::path, "v.chp", "", ParserEngine::direct, {}, {}, false, 0.0f},+ };+ t.config.validation.enabled = true;+ t.instructions = "Use endpoint: /data/quotes with POST method and symbols in body";+ templates_.push_back(t);+ }++ // Fyers Positions+ {+ MappingTemplate t;+ t.id = "fyers_positions";+ t.name = "Fyers Positions -> POSITION";+ t.description = "Map Fyers position data to standard POSITION format";+ t.category = "broker";+ t.tags = {"fyers", "position", "india"};+ t.verified = true;+ t.official = true;++ t.config.name = "Fyers Position -> POSITION";+ t.config.is_predefined_schema = true;+ t.config.schema_type = SchemaType::position;+ t.config.extraction.root_path = "netPositions";+ t.config.extraction.is_array = true;++ t.config.field_mappings = {+ {"symbol", FieldSourceType::path, "symbol", "", ParserEngine::direct, {}, {}, true, 0.0f},+ {"quantity", FieldSourceType::path, "netQty", "", ParserEngine::direct, {}, {}, true, 0.0f},+ {"averagePrice", FieldSourceType::path, "avgPrice", "", ParserEngine::direct, {}, {}, true, 0.0f},+ {"currentPrice", FieldSourceType::path, "ltp", "", ParserEngine::direct, {}, {}, true, 0.0f},+ {"pnl", FieldSourceType::path, "pl", "", ParserEngine::direct, {}, {}, true, 0.0f},+ {"pnlPercent", FieldSourceType::path, "plPercent", "", ParserEngine::direct, {}, {}, true, 0.0f},+ {"productType", FieldSourceType::path, "productType", "", ParserEngine::direct, {"uppercase"}, {}, false, 0.0f},+ };+ t.config.validation.enabled = true;+ templates_.push_back(t);+ }++ // Dhan Positions+ {+ MappingTemplate t;+ t.id = "dhan_positions";+ t.name = "Dhan Positions -> POSITION";+ t.description = "Map Dhan position data to standard POSITION format";+ t.category = "broker";+ t.tags = {"dhan", "position", "india"};+ t.verified = true;+ t.official = true;++ t.config.name = "Dhan Position -> POSITION";+ t.config.is_predefined_schema = true;+ t.config.schema_type = SchemaType::position;+ t.config.extraction.root_path = "data";+ t.config.extraction.is_array = true;++ t.config.field_mappings = {+ {"symbol", FieldSourceType::path, "tradingSymbol", "", ParserEngine::direct, {}, {}, true, 0.0f},+ {"quantity", FieldSourceType::path, "netQty", "", ParserEngine::direct, {}, {}, true, 0.0f},+ {"averagePrice", FieldSourceType::path, "costPrice", "", ParserEngine::direct, {}, {}, true, 0.0f},+ {"currentPrice", FieldSourceType::path, "ltp", "", ParserEngine::direct, {}, {}, true, 0.0f},+ {"pnl", FieldSourceType::path, "realizedProfit", "", ParserEngine::direct, {}, {}, true, 0.0f},+ {"exchange", FieldSourceType::path, "exchangeSegment", "", ParserEngine::direct, {}, {}, false, 0.0f},+ };+ t.config.validation.enabled = true;+ templates_.push_back(t);+ }++ // Dhan Orders+ {+ MappingTemplate t;+ t.id = "dhan_orders";+ t.name = "Dhan Orders -> ORDER";+ t.description = "Map Dhan order data to standard ORDER format";+ t.category = "broker";+ t.tags = {"dhan", "order", "india"};+ t.verified = true;+ t.official = true;++ t.config.name = "Dhan Order -> ORDER";+ t.config.is_predefined_schema = true;+ t.config.schema_type = SchemaType::order;+ t.config.extraction.root_path = "data";+ t.config.extraction.is_array = true;++ t.config.field_mappings = {+ {"orderId", FieldSourceType::path, "orderId", "", ParserEngine::direct, {}, {}, true, 0.0f},+ {"symbol", FieldSourceType::path, "tradingSymbol", "", ParserEngine::direct, {}, {}, true, 0.0f},+ {"side", FieldSourceType::path, "transactionType", "", ParserEngine::direct, {"uppercase"}, {}, true, 0.0f},+ {"type", FieldSourceType::path, "orderType", "", ParserEngine::direct, {"uppercase"}, {}, true, 0.0f},+ {"quantity", FieldSourceType::path, "quantity", "", ParserEngine::direct, {}, {}, true, 0.0f},+ {"filledQuantity", FieldSourceType::path, "tradedQuantity", "", ParserEngine::direct, {}, {}, false, 0.0f},+ {"price", FieldSourceType::path, "price", "", ParserEngine::direct, {}, {}, false, 0.0f},+ {"averagePrice", FieldSourceType::path, "tradedPrice", "", ParserEngine::direct, {}, {}, false, 0.0f},+ {"status", FieldSourceType::path, "orderStatus", "", ParserEngine::direct, {"uppercase"}, {}, true, 0.0f},+ {"timestamp", FieldSourceType::path, "createTime", "", ParserEngine::direct, {"toISODate"}, {}, true, 0.0f},+ {"exchange", FieldSourceType::path, "exchangeSegment", "", ParserEngine::direct, {}, {}, false, 0.0f},+ };+ t.config.validation.enabled = true;+ templates_.push_back(t);+ }++ // Zerodha OHLC+ {+ MappingTemplate t;+ t.id = "zerodha_ohlc";+ t.name = "Zerodha OHLC -> OHLCV";+ t.description = "Map Zerodha/Kite OHLC data to standard OHLCV format";+ t.category = "broker";+ t.tags = {"zerodha", "kite", "ohlc", "india"};+ t.verified = true;++ t.config.name = "Zerodha OHLC -> OHLCV";+ t.config.is_predefined_schema = true;+ t.config.schema_type = SchemaType::ohlcv;+ t.config.extraction.root_path = "data";+ t.config.extraction.is_array = false;++ t.config.field_mappings = {+ {"open", FieldSourceType::path, "ohlc.open", "", ParserEngine::direct, {}, {}, true, 0.0f},+ {"high", FieldSourceType::path, "ohlc.high", "", ParserEngine::direct, {}, {}, true, 0.0f},+ {"low", FieldSourceType::path, "ohlc.low", "", ParserEngine::direct, {}, {}, true, 0.0f},+ {"close", FieldSourceType::path, "last_price", "", ParserEngine::direct, {}, {}, true, 0.0f},+ {"volume", FieldSourceType::path, "volume", "", ParserEngine::direct, {}, {}, true, 0.0f},+ };+ t.config.validation.enabled = true;+ t.instructions = "Use endpoint: /quote/ohlc with query params i=NSE:SBIN&i=NSE:RELIANCE";+ templates_.push_back(t);+ }+}++} // namespace fincept::data_mappingdiff --git a/fincept-cpp/src/screens/data_mapping/data_mapping_screen.h b/fincept-cpp/src/screens/data_mapping/data_mapping_screen.hnew file mode 100644index 000000000..b8a07c2a7--- /dev/null+++ b/fincept-cpp/src/screens/data_mapping/data_mapping_screen.h@@ -0,0 +1,132 @@+#pragma once+// Data Mapping Screen — Bloomberg Terminal-inspired API mapping configuration UI.+// 3-panel layout: left sidebar | center content | right status panel.+// Mirrors the Tauri desktop DataMappingTab with 5-step wizard.++#include "data_mapping_types.h"+#include "data_mapping_engine.h"+#include "data_mapping_db.h"+#include <string>+#include <vector>+#include <future>+#include <optional>+#include <map>++namespace fincept::data_mapping {++class DataMappingScreen {+public:+ void render();++private:+ void init();++ // Top-level panels+ void render_command_bar(float w);+ void render_sidebar(float x, float y, float w, float h);+ void render_content(float x, float y, float w, float h);+ void render_status_panel(float x, float y, float w, float h);+ void render_footer(float w, float h);++ // Views+ void render_list_view(float w, float h);+ void render_create_view(float w, float h);+ void render_templates_view(float w, float h);++ // Create wizard steps+ void render_step_api_config(float w, float h);+ void render_step_schema_select(float w, float h);+ void render_step_field_mapping(float w, float h);+ void render_step_cache_settings(float w, float h);+ void render_step_test_save(float w, float h);++ // Component renderers+ void render_auth_config();+ void render_headers_editor();+ void render_query_params_editor();+ void render_field_mapping_row(size_t index);+ void render_json_preview(const std::string& label, const std::string& json_str, float height);+ void render_validation_results();++ // Actions+ void load_mappings();+ void save_current_mapping();+ void delete_mapping_by_id(const std::string& id);+ void start_test();+ void fetch_sample_data();+ void reset_create_form();+ void edit_mapping(const MappingConfig& config);+ void load_template(const MappingTemplate& tmpl);++ // State+ bool initialized_ = false;+ MappingView view_ = MappingView::list;+ CreateStep current_step_ = CreateStep::api_config;++ // Search+ char search_buf_[128] = {};++ // Sidebar+ bool sidebar_minimized_ = false;++ // Saved mappings+ std::vector<MappingConfig> saved_mappings_;+ bool loading_mappings_ = false;++ // Current mapping being created/edited+ MappingConfig current_mapping_;++ // API config form buffers+ char api_name_buf_[128] = {};+ char api_desc_buf_[256] = {};+ char api_base_url_buf_[512] = {};+ char api_endpoint_buf_[512] = {};+ char api_body_buf_[4096] = {};+ int api_method_idx_ = 0;+ int api_auth_type_idx_ = 0;++ // Auth buffers+ char auth_key_name_buf_[128] = {};+ char auth_key_value_buf_[512] = {};+ int auth_key_location_idx_ = 0;+ char auth_bearer_buf_[512] = {};+ char auth_basic_user_buf_[128] = {};+ char auth_basic_pass_buf_[256] = {};++ // Schema selection+ int schema_type_idx_ = 0;+ bool is_custom_schema_ = false;++ // Mapping name/description+ char mapping_name_buf_[128] = {};+ char mapping_desc_buf_[256] = {};++ // Extraction+ char root_path_buf_[256] = {};+ int parser_engine_idx_ = 0;++ // Header/query param editing+ char header_key_buf_[128] = {};+ char header_val_buf_[256] = {};+ char qparam_key_buf_[128] = {};+ char qparam_val_buf_[256] = {};++ // Sample data / test results+ std::string sample_data_json_;+ std::optional<ExecutionResult> test_result_;+ bool testing_ = false;+ std::future<ExecutionResult> test_future_;++ // API fetch+ bool fetching_ = false;+ std::future<ApiResponse> fetch_future_;++ // Template data+ std::vector<MappingTemplate> templates_;+ void load_templates();++ // Engine+ MappingEngine engine_;+};++} // namespace fincept::data_mappingdiff --git a/fincept-cpp/src/screens/data_mapping/data_mapping_types.h b/fincept-cpp/src/screens/data_mapping/data_mapping_types.hnew file mode 100644index 000000000..c46c8b467--- /dev/null+++ b/fincept-cpp/src/screens/data_mapping/data_mapping_types.h@@ -0,0 +1,498 @@+#pragma once+// Data Mapping Types — Enums, structs for API mapping configuration,+// unified schemas, field mappings, and transformation pipeline.+// Mirrors the Tauri desktop DataMapping types.++#include <string>+#include <vector>+#include <map>+#include <optional>+#include <cstdint>++namespace fincept::data_mapping {++// ============================================================================+// Parser Engines — expression languages for data extraction+// ============================================================================+enum class ParserEngine {+ direct, // Simple dot-path object access+ jsonpath, // JSONPath queries: $.data.candles[*]+ regex, // Pattern matching+};++inline const char* parser_engine_label(ParserEngine e) {+ switch (e) {+ case ParserEngine::direct: return "Direct";+ case ParserEngine::jsonpath: return "JSONPath";+ case ParserEngine::regex: return "Regex";+ }+ return "?";+}++inline const char* parser_engine_id(ParserEngine e) {+ switch (e) {+ case ParserEngine::direct: return "direct";+ case ParserEngine::jsonpath: return "jsonpath";+ case ParserEngine::regex: return "regex";+ }+ return "?";+}++inline ParserEngine parser_engine_from_string(const std::string& s) {+ if (s == "jsonpath") return ParserEngine::jsonpath;+ if (s == "regex") return ParserEngine::regex;+ return ParserEngine::direct;+}++// ============================================================================+// HTTP Method+// ============================================================================+enum class HttpMethod { get, post, put, del, patch };++inline const char* http_method_label(HttpMethod m) {+ switch (m) {+ case HttpMethod::get: return "GET";+ case HttpMethod::post: return "POST";+ case HttpMethod::put: return "PUT";+ case HttpMethod::del: return "DELETE";+ case HttpMethod::patch: return "PATCH";+ }+ return "?";+}++inline HttpMethod http_method_from_string(const std::string& s) {+ if (s == "POST") return HttpMethod::post;+ if (s == "PUT") return HttpMethod::put;+ if (s == "DELETE") return HttpMethod::del;+ if (s == "PATCH") return HttpMethod::patch;+ return HttpMethod::get;+}++// ============================================================================+// Authentication type+// ============================================================================+enum class AuthType { none, apikey, bearer, basic, oauth2 };++inline const char* auth_type_label(AuthType t) {+ switch (t) {+ case AuthType::none: return "None";+ case AuthType::apikey: return "API Key";+ case AuthType::bearer: return "Bearer Token";+ case AuthType::basic: return "Basic Auth";+ case AuthType::oauth2: return "OAuth2";+ }+ return "?";+}++inline const char* auth_type_id(AuthType t) {+ switch (t) {+ case AuthType::none: return "none";+ case AuthType::apikey: return "apikey";+ case AuthType::bearer: return "bearer";+ case AuthType::basic: return "basic";+ case AuthType::oauth2: return "oauth2";+ }+ return "?";+}++inline AuthType auth_type_from_string(const std::string& s) {+ if (s == "apikey") return AuthType::apikey;+ if (s == "bearer") return AuthType::bearer;+ if (s == "basic") return AuthType::basic;+ if (s == "oauth2") return AuthType::oauth2;+ return AuthType::none;+}++// ============================================================================+// API Key location+// ============================================================================+enum class ApiKeyLocation { header, query };++inline const char* api_key_location_label(ApiKeyLocation l) {+ switch (l) {+ case ApiKeyLocation::header: return "Header";+ case ApiKeyLocation::query: return "Query Param";+ }+ return "?";+}++// ============================================================================+// Field types for unified schemas+// ============================================================================+enum class FieldType {+ string_type, number_type, boolean_type, datetime_type,+ array_type, object_type, enum_type+};++inline const char* field_type_label(FieldType t) {+ switch (t) {+ case FieldType::string_type: return "string";+ case FieldType::number_type: return "number";+ case FieldType::boolean_type: return "boolean";+ case FieldType::datetime_type: return "datetime";+ case FieldType::array_type: return "array";+ case FieldType::object_type: return "object";+ case FieldType::enum_type: return "enum";+ }+ return "?";+}++inline FieldType field_type_from_string(const std::string& s) {+ if (s == "number") return FieldType::number_type;+ if (s == "boolean") return FieldType::boolean_type;+ if (s == "datetime") return FieldType::datetime_type;+ if (s == "array") return FieldType::array_type;+ if (s == "object") return FieldType::object_type;+ if (s == "enum") return FieldType::enum_type;+ return FieldType::string_type;+}++// ============================================================================+// Unified schema types+// ============================================================================+enum class SchemaType { ohlcv, quote, tick, order, position, portfolio, instrument };++inline const char* schema_type_label(SchemaType t) {+ switch (t) {+ case SchemaType::ohlcv: return "OHLCV";+ case SchemaType::quote: return "QUOTE";+ case SchemaType::tick: return "TICK";+ case SchemaType::order: return "ORDER";+ case SchemaType::position: return "POSITION";+ case SchemaType::portfolio: return "PORTFOLIO";+ case SchemaType::instrument: return "INSTRUMENT";+ }+ return "?";+}++inline const char* schema_type_id(SchemaType t) {+ switch (t) {+ case SchemaType::ohlcv: return "OHLCV";+ case SchemaType::quote: return "QUOTE";+ case SchemaType::tick: return "TICK";+ case SchemaType::order: return "ORDER";+ case SchemaType::position: return "POSITION";+ case SchemaType::portfolio: return "PORTFOLIO";+ case SchemaType::instrument: return "INSTRUMENT";+ }+ return "?";+}++inline SchemaType schema_type_from_string(const std::string& s) {+ if (s == "QUOTE") return SchemaType::quote;+ if (s == "TICK") return SchemaType::tick;+ if (s == "ORDER") return SchemaType::order;+ if (s == "POSITION") return SchemaType::position;+ if (s == "PORTFOLIO") return SchemaType::portfolio;+ if (s == "INSTRUMENT") return SchemaType::instrument;+ return SchemaType::ohlcv;+}++// ============================================================================+// Schema category+// ============================================================================+enum class SchemaCategory { market_data, trading, portfolio_cat, reference, custom };++inline const char* schema_category_label(SchemaCategory c) {+ switch (c) {+ case SchemaCategory::market_data: return "Market Data";+ case SchemaCategory::trading: return "Trading";+ case SchemaCategory::portfolio_cat: return "Portfolio";+ case SchemaCategory::reference: return "Reference";+ case SchemaCategory::custom: return "Custom";+ }+ return "?";+}++// ============================================================================+// Transform category+// ============================================================================+enum class TransformCategory { type_conv, format, math, string_op, date, custom_xform };++inline const char* transform_category_label(TransformCategory c) {+ switch (c) {+ case TransformCategory::type_conv: return "Type";+ case TransformCategory::format: return "Format";+ case TransformCategory::math: return "Math";+ case TransformCategory::string_op: return "String";+ case TransformCategory::date: return "Date";+ case TransformCategory::custom_xform: return "Custom";+ }+ return "?";+}++// ============================================================================+// Structs — field spec for schema definition+// ============================================================================+struct FieldValidation {+ std::optional<double> min;+ std::optional<double> max;+ std::optional<std::string> pattern;+};++struct FieldSpec {+ std::string name;+ FieldType type = FieldType::string_type;+ bool required = false;+ std::string description;+ std::vector<std::string> enum_values;+ std::optional<std::string> default_value;+ FieldValidation validation;+};++struct UnifiedSchema {+ std::string name;+ SchemaCategory category = SchemaCategory::market_data;+ std::string description;+ std::vector<FieldSpec> fields;+};++// ============================================================================+// API Authentication config+// ============================================================================+struct ApiKeyConfig {+ ApiKeyLocation location = ApiKeyLocation::header;+ std::string key_name;+ std::string value;+};++struct BearerConfig {+ std::string token;+};++struct BasicAuthConfig {+ std::string username;+ std::string password;+};++struct OAuth2Config {+ std::string access_token;+ std::optional<std::string> refresh_token;+};++struct AuthConfig {+ AuthType type = AuthType::none;+ std::optional<ApiKeyConfig> apikey;+ std::optional<BearerConfig> bearer;+ std::optional<BasicAuthConfig> basic;+ std::optional<OAuth2Config> oauth2;+};++// ============================================================================+// API Configuration+// ============================================================================+struct ApiConfig {+ std::string id;+ std::string name;+ std::string description;+ std::string base_url;+ std::string endpoint;+ HttpMethod method = HttpMethod::get;+ AuthConfig authentication;+ std::map<std::string, std::string> headers;+ std::map<std::string, std::string> query_params;+ std::optional<std::string> body;+ int timeout_ms = 30000;+ bool cache_enabled = true;+ int cache_ttl_seconds = 300;+};++// ============================================================================+// Field Mapping — maps source data field to target schema field+// ============================================================================+enum class FieldSourceType { path, static_value, expression };++struct FieldMapping {+ std::string target_field;+ FieldSourceType source_type = FieldSourceType::path;+ std::string source_path;+ std::string static_value;+ ParserEngine parser = ParserEngine::direct;+ std::vector<std::string> transforms;+ std::optional<std::string> default_value;+ bool required = false;+ float confidence = 0.0f;+};++// ============================================================================+// Extraction config — how to locate the data array in the response+// ============================================================================+struct ExtractionConfig {+ ParserEngine engine = ParserEngine::direct;+ std::string root_path;+ bool is_array = true;+ bool is_array_of_arrays = false;+};++// ============================================================================+// Post-processing config+// ============================================================================+struct SortConfig {+ std::string field;+ bool descending = false;+};++struct PostProcessing {+ std::optional<std::string> filter;+ std::optional<SortConfig> sort;+ std::optional<int> limit;+ std::optional<std::string> deduplicate_field;+};++// ============================================================================+// Validation config+// ============================================================================+struct ValidationConfig {+ bool enabled = true;+ bool strict_mode = false;+};++// ============================================================================+// Full Mapping Configuration — persisted to SQLite+// ============================================================================+struct MappingConfig {+ std::string id;+ std::string name;+ std::string description;++ // Source+ bool is_api_source = true;+ ApiConfig api_config;+ std::string sample_data_json;++ // Target+ bool is_predefined_schema = true;+ SchemaType schema_type = SchemaType::ohlcv;+ std::vector<FieldSpec> custom_fields;++ // Extraction+ ExtractionConfig extraction;++ // Field mappings+ std::vector<FieldMapping> field_mappings;++ // Post-processing+ PostProcessing post_processing;++ // Validation+ ValidationConfig validation;++ // Metadata+ std::string created_at;+ std::string updated_at;+ int version = 1;+ std::string tags; // comma-separated+ bool ai_generated = false;+};++// ============================================================================+// Execution result+// ============================================================================+struct ValidationError {+ std::string field;+ std::string message;+ std::string rule;+};++struct ValidationResult {+ bool valid = true;+ std::vector<ValidationError> errors;+};++struct ExecutionResult {+ bool success = false;+ std::string data_json; // Transformed data as JSON+ std::string raw_data_json; // Raw API response+ std::vector<std::string> errors;+ std::vector<std::string> warnings;+ int64_t duration_ms = 0;+ int records_processed = 0;+ int records_returned = 0;+ ValidationResult validation;+};++// ============================================================================+// API Response+// ============================================================================+enum class ApiErrorType { none, network, auth, client, server, timeout, parse };++inline const char* api_error_type_label(ApiErrorType t) {+ switch (t) {+ case ApiErrorType::none: return "None";+ case ApiErrorType::network: return "Network";+ case ApiErrorType::auth: return "Auth";+ case ApiErrorType::client: return "Client";+ case ApiErrorType::server: return "Server";+ case ApiErrorType::timeout: return "Timeout";+ case ApiErrorType::parse: return "Parse";+ }+ return "?";+}++struct ApiResponse {+ bool success = false;+ std::string data_json;+ ApiErrorType error_type = ApiErrorType::none;+ int status_code = 0;+ std::string error_message;+ int64_t duration_ms = 0;+ std::string url;+ std::string method;+};++// ============================================================================+// Template — pre-built mapping configuration for known APIs/brokers+// ============================================================================+struct MappingTemplate {+ std::string id;+ std::string name;+ std::string description;+ std::string category; // "broker", "data-provider", "exchange", "custom"+ std::vector<std::string> tags;+ bool verified = false;+ bool official = false;+ MappingConfig config; // Pre-configured mapping+ std::string instructions;+};++// ============================================================================+// Transform definition — describes a transform for the UI+// ============================================================================+struct TransformDef {+ const char* name;+ const char* description;+ TransformCategory category;+};++// ============================================================================+// UI State+// ============================================================================+enum class MappingView { list, create, templates };++enum class CreateStep {+ api_config, schema_select, field_mapping, cache_settings, test_save+};++inline const char* create_step_label(CreateStep s) {+ switch (s) {+ case CreateStep::api_config: return "API Config";+ case CreateStep::schema_select: return "Schema";+ case CreateStep::field_mapping: return "Field Mapping";+ case CreateStep::cache_settings: return "Cache";+ case CreateStep::test_save: return "Test & Save";+ }+ return "?";+}++inline const char* create_step_short(CreateStep s) {+ switch (s) {+ case CreateStep::api_config: return "API";+ case CreateStep::schema_select: return "SCHEMA";+ case CreateStep::field_mapping: return "MAPPING";+ case CreateStep::cache_settings: return "CACHE";+ case CreateStep::test_save: return "TEST";+ }+ return "?";+}++} // namespace fincept::data_mappingdiff --git a/fincept-cpp/src/screens/dbnomics/dbnomics_screen.cpp b/fincept-cpp/src/screens/dbnomics/dbnomics_screen.cppindex c09834e90..8516b4435 100644--- a/fincept-cpp/src/screens/dbnomics/dbnomics_screen.cpp+++ b/fincept-cpp/src/screens/dbnomics/dbnomics_screen.cpp@@ -4,6 +4,7 @@#include "dbnomics_screen.h"#include "http/http_client.h"+#include "storage/cache_service.h"#include "ui/theme.h"#include "core/logger.h"#include <imgui.h>@@ -82,14 +83,29 @@ void DBnomicsScreen::load_providers() {async_task_ = std::async(std::launch::async, [this]() {try {- std::string url = std::string(DBNOMICS_API_BASE) + "/providers";- auto resp = http::HttpClient::instance().get(url);- if (!resp.success) {- error_ = "Failed to load providers: " + resp.body;- loading_ = false;- return;+ auto& cache = CacheService::instance();+ std::string cache_key = CacheService::make_key("reference", "dbnomics", "providers");++ std::string body;+ auto cached = cache.get(cache_key);+ if (cached && !cached->empty()) {+ body = *cached;+ LOG_INFO("DBnomics", "Cache HIT for providers");+ } else {+ std::string url = std::string(DBNOMICS_API_BASE) + "/providers";+ auto resp = http::HttpClient::instance().get(url);+ if (!resp.success) {+ error_ = "Failed to load providers: " + resp.body;+ loading_ = false;+ return;+ }+ body = resp.body;+ if (!body.empty()) {+ cache.set(cache_key, body, "reference", CacheTTL::ONE_DAY);+ }}- auto j = json::parse(resp.body, nullptr, false);++ auto j = json::parse(body, nullptr, false);if (j.is_discarded()) {error_ = "Invalid JSON from providers API";loading_ = false;@@ -123,17 +139,32 @@ void DBnomicsScreen::load_datasets(const std::string& provider_code, int offset,async_task_ = std::async(std::launch::async, [this, provider_code, offset, append]() {try {- std::string url = std::string(DBNOMICS_API_BASE) + "/datasets/"- + url_encode(provider_code)- + "?limit=" + std::to_string(DATASETS_PAGE_SIZE)- + "&offset=" + std::to_string(offset);- auto resp = http::HttpClient::instance().get(url);- if (!resp.success) {- error_ = "Failed to load datasets";- loading_ = false;- return;+ auto& cache = CacheService::instance();+ std::string cache_key = CacheService::make_key("reference", "dbnomics-datasets",+ provider_code + "_o" + std::to_string(offset));++ std::string body;+ auto cached = cache.get(cache_key);+ if (cached && !cached->empty()) {+ body = *cached;+ } else {+ std::string url = std::string(DBNOMICS_API_BASE) + "/datasets/"+ + url_encode(provider_code)+ + "?limit=" + std::to_string(DATASETS_PAGE_SIZE)+ + "&offset=" + std::to_string(offset);+ auto resp = http::HttpClient::instance().get(url);+ if (!resp.success) {+ error_ = "Failed to load datasets";+ loading_ = false;+ return;+ }+ body = resp.body;+ if (!body.empty()) {+ cache.set(cache_key, body, "reference", CacheTTL::ONE_HOUR);+ }}- auto j = json::parse(resp.body, nullptr, false);++ auto j = json::parse(body, nullptr, false);if (j.is_discarded()) { error_ = "Invalid JSON"; loading_ = false; return; }int total = j.value("datasets", json::object()).value("num_found", 0);@@ -174,17 +205,32 @@ void DBnomicsScreen::load_series(const std::string& provider, const std::string&async_task_ = std::async(std::launch::async, [this, provider, dataset, offset, append, query]() {try {- std::string url = std::string(DBNOMICS_API_BASE) + "/series/"- + url_encode(provider) + "/" + url_encode(dataset)- + "?limit=" + std::to_string(SERIES_PAGE_SIZE)- + "&offset=" + std::to_string(offset)- + "&observations=false";- if (!query.empty())- url += "&q=" + url_encode(query);-- auto resp = http::HttpClient::instance().get(url);- if (!resp.success) { error_ = "Failed to load series"; loading_ = false; return; }- auto j = json::parse(resp.body, nullptr, false);+ auto& cache = CacheService::instance();+ std::string cache_key = CacheService::make_key("reference", "dbnomics-series",+ provider + "_" + dataset + "_o" + std::to_string(offset) + "_q" + query);++ std::string body;+ auto cached = cache.get(cache_key);+ if (cached && !cached->empty()) {+ body = *cached;+ } else {+ std::string url = std::string(DBNOMICS_API_BASE) + "/series/"+ + url_encode(provider) + "/" + url_encode(dataset)+ + "?limit=" + std::to_string(SERIES_PAGE_SIZE)+ + "&offset=" + std::to_string(offset)+ + "&observations=false";+ if (!query.empty())+ url += "&q=" + url_encode(query);++ auto resp = http::HttpClient::instance().get(url);+ if (!resp.success) { error_ = "Failed to load series"; loading_ = false; return; }+ body = resp.body;+ if (!body.empty()) {+ cache.set(cache_key, body, "reference", CacheTTL::ONE_HOUR);+ }+ }++ auto j = json::parse(body, nullptr, false);if (j.is_discarded()) { error_ = "Invalid JSON"; loading_ = false; return; }int total = j.value("series", json::object()).value("num_found", 0);@@ -233,13 +279,28 @@ void DBnomicsScreen::load_series_data(const std::string& full_id, const std::strasync_task_ = std::async(std::launch::async, [this, prov, ds, sc, full_id, name]() {try {- std::string url = std::string(DBNOMICS_API_BASE) + "/series/"- + url_encode(prov) + "/" + url_encode(ds) + "/" + url_encode(sc)- + "?observations=1&format=json";+ auto& cache = CacheService::instance();+ std::string cache_key = CacheService::make_key("economic", "dbnomics-data",+ prov + "_" + ds + "_" + sc);++ std::string body;+ auto cached = cache.get(cache_key);+ if (cached && !cached->empty()) {+ body = *cached;+ } else {+ std::string url = std::string(DBNOMICS_API_BASE) + "/series/"+ + url_encode(prov) + "/" + url_encode(ds) + "/" + url_encode(sc)+ + "?observations=1&format=json";++ auto resp = http::HttpClient::instance().get(url);+ if (!resp.success) { error_ = "Failed to load data"; loading_ = false; return; }+ body = resp.body;+ if (!body.empty()) {+ cache.set(cache_key, body, "economic", CacheTTL::ONE_HOUR);+ }+ }- auto resp = http::HttpClient::instance().get(url);- if (!resp.success) { error_ = "Failed to load data"; loading_ = false; return; }- auto j = json::parse(resp.body, nullptr, false);+ auto j = json::parse(body, nullptr, false);if (j.is_discarded()) { error_ = "Invalid JSON"; loading_ = false; return; }auto series_docs = j.value("series", json::object()).value("docs", json::array());@@ -292,14 +353,29 @@ void DBnomicsScreen::execute_global_search(const std::string& query, int offset,async_task_ = std::async(std::launch::async, [this, query, offset, append]() {try {- std::string url = std::string(DBNOMICS_API_BASE) + "/search?q="- + url_encode(query)- + "&limit=" + std::to_string(SEARCH_PAGE_SIZE)- + "&offset=" + std::to_string(offset);-- auto resp = http::HttpClient::instance().get(url);- if (!resp.success) { error_ = "Search failed"; loading_ = false; return; }- auto j = json::parse(resp.body, nullptr, false);+ auto& cache = CacheService::instance();+ std::string cache_key = CacheService::make_key("reference", "dbnomics-search",+ query + "_o" + std::to_string(offset));++ std::string body;+ auto cached = cache.get(cache_key);+ if (cached && !cached->empty()) {+ body = *cached;+ } else {+ std::string url = std::string(DBNOMICS_API_BASE) + "/search?q="+ + url_encode(query)+ + "&limit=" + std::to_string(SEARCH_PAGE_SIZE)+ + "&offset=" + std::to_string(offset);++ auto resp = http::HttpClient::instance().get(url);+ if (!resp.success) { error_ = "Search failed"; loading_ = false; return; }+ body = resp.body;+ if (!body.empty()) {+ cache.set(cache_key, body, "reference", CacheTTL::FIFTEEN_MIN);+ }+ }++ auto j = json::parse(body, nullptr, false);if (j.is_discarded()) { error_ = "Invalid JSON"; loading_ = false; return; }int total = 0;diff --git a/fincept-cpp/src/screens/economics/economics_screen.cpp b/fincept-cpp/src/screens/economics/economics_screen.cppindex f5b5c4ac1..a78cd5559 100644--- a/fincept-cpp/src/screens/economics/economics_screen.cpp+++ b/fincept-cpp/src/screens/economics/economics_screen.cpp@@ -7,6 +7,7 @@#include "http/http_client.h"#include "auth/auth_manager.h"#include "storage/database.h"+#include "storage/cache_service.h"#include "ui/theme.h"#include "core/logger.h"#include <imgui.h>@@ -17,6 +18,7 @@#include <algorithm>#include <cstring>#include <ctime>+#include <thread>namespace fincept::economics {@@ -137,184 +139,207 @@ void EconomicsScreen::fetch_data() {const auto& cfg = get_source_config(data_source_);std::string country_code = get_country_code();- try {- // Check API key requirements- if (cfg.requires_api_key && cfg.api_key_name) {- std::string key = get_api_key(cfg.api_key_name);- if (key.empty()) {- // EIA only needs key for STEO- bool needs_key = true;- if (data_source_ == DataSource::EIA) {- std::string ind(selected_indicator_);- needs_key = ind.substr(0, 5) == "steo_";- }- if (needs_key) {- error_ = std::string(cfg.name) + " API Key required. Configure in the key panel.";- show_api_key_panel_ = true;- loading_ = false;- return;- }+ // Pre-flight check on UI thread (fast, no I/O)+ if (cfg.requires_api_key && cfg.api_key_name) {+ std::string key = get_api_key(cfg.api_key_name);+ if (key.empty()) {+ bool needs_key = true;+ if (data_source_ == DataSource::EIA) {+ std::string ind(selected_indicator_);+ needs_key = ind.substr(0, 5) == "steo_";}- }-- std::string raw_json;-- if (data_source_ == DataSource::Fincept) {- // Direct HTTP to Fincept API- const std::string BASE = "https://api.fincept.in";- std::string url;- std::string ind(selected_indicator_);-- static const char* CEIC_COUNTRIES[] = {- "china", "european-union", "france", "germany", "italy", "japan", "united-states"- };- std::string ceic_country = CEIC_COUNTRIES[fincept_ceic_country_idx_];-- if (ind == "ceic_series_countries")- url = BASE + "/macro/ceic/series/countries";- else if (ind == "ceic_series_indicators")- url = BASE + "/macro/ceic/series/indicators?country=" + ceic_country;- else if (ind == "ceic_series") {- url = BASE + "/macro/ceic/series?country=" + ceic_country;- if (!fincept_ceic_indicator_.empty())- url += "&indicator=" + fincept_ceic_indicator_;- url += "&year_from=" + std::string(start_date_).substr(0, 4);- url += "&year_to=" + std::string(end_date_).substr(0, 4);- url += "&limit=500";- } else if (ind == "economic_calendar")- url = BASE + "/macro/economic-calendar?start_date=" + std::string(start_date_) + "&end_date=" + std::string(end_date_) + "&limit=200";- else if (ind == "upcoming_events")- url = BASE + "/macro/upcoming-events?limit=200";- else if (ind == "wgb_central_bank_rates")- url = BASE + "/macro/wgb/central-bank-rates";- else if (ind == "wgb_credit_ratings")- url = BASE + "/macro/wgb/credit-ratings";- else if (ind == "wgb_sovereign_cds")- url = BASE + "/macro/wgb/sovereign-cds";- else if (ind == "wgb_bond_spreads")- url = BASE + "/macro/wgb/bond-spreads";- else if (ind == "wgb_inverted_yields")- url = BASE + "/macro/wgb/inverted-yields";- else- url = BASE + "/macro/wgb/central-bank-rates";-- auto& auth = auth::AuthManager::instance();- std::string api_key = auth.session().api_key;- http::Headers headers = {{"X-API-Key", api_key}, {"Accept", "application/json"}};- auto resp = http::HttpClient::instance().get(url, headers);- if (!resp.success) {- error_ = "HTTP error: " + std::to_string(resp.status_code);+ if (needs_key) {+ error_ = std::string(cfg.name) + " API Key required. Configure in the key panel.";+ show_api_key_panel_ = true;loading_ = false;return;}- raw_json = resp.body;- } else {- // Python script execution- std::vector<std::string> args;- std::string env_key, env_val;+ }+ }- switch (data_source_) {- case DataSource::WorldBank:- args = {"indicators", country_code, selected_indicator_};- break;- case DataSource::BIS:- args = {"fetch", selected_indicator_, country_code};- break;- case DataSource::IMF:- args = {"weo", country_code, selected_indicator_};- break;- case DataSource::FRED:- args = {"series", selected_indicator_};- break;- case DataSource::OECD:- args = {"fetch", selected_indicator_, country_code};- break;- case DataSource::WTO:- args = {"timeseries_data", "--i", selected_indicator_, "--reporters", country_code, get_api_key("wto_api_key")};- break;- case DataSource::CFTC:- args = {"cot_historical_trend", selected_indicator_, "legacy", "104"};- break;- case DataSource::EIA: {- std::string ind(selected_indicator_);- if (ind.substr(0, 5) == "steo_") {- std::string table = ind.substr(5);- args = {"get_steo", table, "", "month"};- env_key = "eia_api_key";- env_val = get_api_key("eia_api_key");- } else {- args = {"get_petroleum", selected_indicator_};+ // Capture all state needed by the background thread (avoid touching 'this' members+ // that the UI thread may read concurrently — only loading_/error_/results are shared)+ DataSource ds = data_source_;+ std::string script_name = cfg.script_name;+ std::string indicator(selected_indicator_);+ std::string start(start_date_);+ std::string end(end_date_);+ int ceic_idx = fincept_ceic_country_idx_;+ std::string ceic_indicator = fincept_ceic_indicator_;++ // Collect API keys on UI thread (they read from DB/keychain)+ std::string wto_key = get_api_key("wto_api_key");+ std::string eia_key = get_api_key("eia_api_key");+ std::string bls_key = get_api_key("bls_api_key");+ std::string bea_key = get_api_key("bea_api_key");++ std::thread([this, ds, script_name, country_code, indicator, start, end,+ ceic_idx, ceic_indicator, wto_key, eia_key, bls_key, bea_key]() {+ try {+ std::string raw_json;+ auto& cache = CacheService::instance();++ if (ds == DataSource::Fincept) {+ const std::string BASE = "https://api.fincept.in";+ std::string url;++ static const char* CEIC_COUNTRIES[] = {+ "china", "european-union", "france", "germany", "italy", "japan", "united-states"+ };+ std::string ceic_country = CEIC_COUNTRIES[ceic_idx];++ if (indicator == "ceic_series_countries")+ url = BASE + "/macro/ceic/series/countries";+ else if (indicator == "ceic_series_indicators")+ url = BASE + "/macro/ceic/series/indicators?country=" + ceic_country;+ else if (indicator == "ceic_series") {+ url = BASE + "/macro/ceic/series?country=" + ceic_country;+ if (!ceic_indicator.empty())+ url += "&indicator=" + ceic_indicator;+ url += "&year_from=" + start.substr(0, 4);+ url += "&year_to=" + end.substr(0, 4);+ url += "&limit=500";+ } else if (indicator == "economic_calendar")+ url = BASE + "/macro/economic-calendar?start_date=" + start + "&end_date=" + end + "&limit=200";+ else if (indicator == "upcoming_events")+ url = BASE + "/macro/upcoming-events?limit=200";+ else if (indicator == "wgb_central_bank_rates")+ url = BASE + "/macro/wgb/central-bank-rates";+ else if (indicator == "wgb_credit_ratings")+ url = BASE + "/macro/wgb/credit-ratings";+ else if (indicator == "wgb_sovereign_cds")+ url = BASE + "/macro/wgb/sovereign-cds";+ else if (indicator == "wgb_bond_spreads")+ url = BASE + "/macro/wgb/bond-spreads";+ else if (indicator == "wgb_inverted_yields")+ url = BASE + "/macro/wgb/inverted-yields";+ else+ url = BASE + "/macro/wgb/central-bank-rates";++ std::string fincept_cache_key = CacheService::make_key("economic", "fincept", indicator);+ auto fincept_cached = cache.get(fincept_cache_key);+ if (fincept_cached && !fincept_cached->empty()) {+ raw_json = *fincept_cached;+ } else {+ auto& auth = auth::AuthManager::instance();+ std::string api_key = auth.session().api_key;+ http::Headers headers = {{"X-API-Key", api_key}, {"Accept", "application/json"}};+ auto resp = http::HttpClient::instance().get(url, headers);+ if (!resp.success) {+ error_ = "HTTP error: " + std::to_string(resp.status_code);+ loading_ = false;+ return;+ }+ raw_json = resp.body;+ if (!raw_json.empty()) {+ cache.set(fincept_cache_key, raw_json, "economic", CacheTTL::FIFTEEN_MIN);}- break;- }- case DataSource::ADB: {- std::string ind(selected_indicator_);- std::string sy = std::string(start_date_).substr(0, 4);- std::string ey = std::string(end_date_).substr(0, 4);- if (ind.substr(0, 3) == "LP_" || ind.substr(0, 3) == "SP_" || ind.substr(0, 3) == "SM_")- args = {"get_population", country_code, selected_indicator_, sy, ey};- else- args = {"get_gdp", country_code, selected_indicator_, sy, ey};- break;- }- case DataSource::Fed: {- std::string ind(selected_indicator_);- if (ind == "market_overview")- args = {"market_overview"};- else if (ind == "yield_curve")- args = {"yield_curve", end_date_};- else if (ind == "money_measures")- args = {"money_measures", start_date_, end_date_, "false"};- else if (ind == "money_measures_adjusted")- args = {"money_measures", start_date_, end_date_, "true"};- else- args = {selected_indicator_, start_date_, end_date_};- break;}- case DataSource::BLS:- args = {"get_series", selected_indicator_, start_date_, end_date_};- env_key = "bls_api_key";- env_val = get_api_key("bls_api_key");- break;- case DataSource::UNESCO: {- std::string sy = std::string(start_date_).substr(0, 4);- std::string ey = std::string(end_date_).substr(0, 4);- args = {"fetch", selected_indicator_, country_code, sy, ey};- break;+ } else {+ // Python script execution+ std::vector<std::string> args;++ switch (ds) {+ case DataSource::WorldBank:+ args = {"indicators", country_code, indicator};+ break;+ case DataSource::BIS:+ args = {"fetch", indicator, country_code};+ break;+ case DataSource::IMF:+ args = {"weo", country_code, indicator};+ break;+ case DataSource::FRED:+ args = {"series", indicator};+ break;+ case DataSource::OECD:+ args = {"fetch", indicator, country_code};+ break;+ case DataSource::WTO:+ args = {"timeseries_data", "--i", indicator, "--reporters", country_code, wto_key};+ break;+ case DataSource::CFTC:+ args = {"cot_historical_trend", indicator, "legacy", "104"};+ break;+ case DataSource::EIA: {+ if (indicator.substr(0, 5) == "steo_") {+ std::string table = indicator.substr(5);+ args = {"get_steo", table, "", "month"};+ } else {+ args = {"get_petroleum", indicator};+ }+ break;+ }+ case DataSource::ADB: {+ std::string sy = start.substr(0, 4);+ std::string ey = end.substr(0, 4);+ if (indicator.substr(0, 3) == "LP_" || indicator.substr(0, 3) == "SP_" || indicator.substr(0, 3) == "SM_")+ args = {"get_population", country_code, indicator, sy, ey};+ else+ args = {"get_gdp", country_code, indicator, sy, ey};+ break;+ }+ case DataSource::Fed: {+ if (indicator == "market_overview")+ args = {"market_overview"};+ else if (indicator == "yield_curve")+ args = {"yield_curve", end};+ else if (indicator == "money_measures")+ args = {"money_measures", start, end, "false"};+ else if (indicator == "money_measures_adjusted")+ args = {"money_measures", start, end, "true"};+ else+ args = {indicator, start, end};+ break;+ }+ case DataSource::BLS:+ args = {"get_series", indicator, start, end};+ break;+ case DataSource::UNESCO: {+ std::string sy = start.substr(0, 4);+ std::string ey = end.substr(0, 4);+ args = {"fetch", indicator, country_code, sy, ey};+ break;+ }+ case DataSource::FiscalData:+ args = {"fetch", indicator, start, end};+ break;+ case DataSource::BEA:+ args = {"fetch", indicator, start, end};+ break;+ default:+ break;}- case DataSource::FiscalData:- args = {"fetch", selected_indicator_, start_date_, end_date_};- break;- case DataSource::BEA:- args = {"fetch", selected_indicator_, start_date_, end_date_};- env_key = "bea_api_key";- env_val = get_api_key("bea_api_key");- break;- default:- break;- }- // Build env JSON if needed- std::string stdin_data = "{}";- // For scripts that need env vars, we pass them via args or stdin- // The python_runner uses execute_with_stdin which takes script, args, stdin+ std::string stdin_data = "{}";- auto result = python::execute_with_stdin(cfg.script_name, args, stdin_data);- if (!result.success || result.output.empty()) {- error_ = result.error.empty() ? "No data returned" : result.error;- loading_ = false;- return;+ std::string py_cache_key = CacheService::make_key("economic", script_name,+ country_code + "_" + indicator);+ auto py_cached = cache.get(py_cache_key);+ if (py_cached && !py_cached->empty()) {+ raw_json = *py_cached;+ } else {+ auto result = python::execute_with_stdin(script_name, args, stdin_data);+ if (!result.success || result.output.empty()) {+ error_ = result.error.empty() ? "No data returned" : result.error;+ loading_ = false;+ return;+ }+ raw_json = result.output;+ if (!raw_json.empty()) {+ cache.set(py_cache_key, raw_json, "economic", CacheTTL::FIFTEEN_MIN);+ }+ }}- raw_json = result.output;- }- parse_response(raw_json);+ parse_response(raw_json);- } catch (const std::exception& e) {- error_ = std::string("Failed to fetch data: ") + e.what();- }+ } catch (const std::exception& e) {+ error_ = std::string("Failed to fetch data: ") + e.what();+ }- loading_ = false;+ loading_ = false;+ }).detach();}void EconomicsScreen::parse_response(const std::string& raw_json) {diff --git a/fincept-cpp/src/screens/forum/forum_screen.cpp b/fincept-cpp/src/screens/forum/forum_screen.cppindex 2ab0b385b..ac09dbe50 100644--- a/fincept-cpp/src/screens/forum/forum_screen.cpp+++ b/fincept-cpp/src/screens/forum/forum_screen.cpp@@ -4,6 +4,7 @@#include "auth/auth_manager.h"#include "auth/auth_api.h"#include "http/http_client.h"+#include "storage/cache_service.h"#include <imgui.h>#include <nlohmann/json.hpp>#include <cstdio>@@ -932,12 +933,25 @@ void ForumScreen::load_data() {try {auto headers = auth::AuthApi::instance().get_auth_headers(auth::AuthManager::instance().session().api_key);+ auto& cache = CacheService::instance();// Load categories{- std::string url = std::string(BASE_URL) + "/forum/categories";- auto resp = http::HttpClient::instance().get(url, headers);- auto j = resp.json_body();+ std::string cache_key = CacheService::make_key("api-response", "forum", "categories");+ std::string body;+ auto cached = cache.get(cache_key);+ if (cached && !cached->empty()) {+ body = *cached;+ } else {+ std::string url = std::string(BASE_URL) + "/forum/categories";+ auto resp = http::HttpClient::instance().get(url, headers);+ body = resp.body;+ if (resp.success && !body.empty()) {+ cache.set(cache_key, body, "api-response", CacheTTL::FIVE_MIN);+ }+ }+ auto j = nlohmann::json::parse(body, nullptr, false);+ if (j.is_discarded()) j = nlohmann::json::object();if (j.contains("data")) {auto& data = j["data"];@@ -958,9 +972,21 @@ void ForumScreen::load_data() {// Load stats{- std::string url = std::string(BASE_URL) + "/forum/stats";- auto resp = http::HttpClient::instance().get(url, headers);- auto j = resp.json_body();+ std::string stats_cache_key = CacheService::make_key("api-response", "forum", "stats");+ std::string stats_body;+ auto stats_cached = cache.get(stats_cache_key);+ if (stats_cached && !stats_cached->empty()) {+ stats_body = *stats_cached;+ } else {+ std::string url = std::string(BASE_URL) + "/forum/stats";+ auto resp = http::HttpClient::instance().get(url, headers);+ stats_body = resp.body;+ if (resp.success && !stats_body.empty()) {+ cache.set(stats_cache_key, stats_body, "api-response", CacheTTL::FIVE_MIN);+ }+ }+ auto j = nlohmann::json::parse(stats_body, nullptr, false);+ if (j.is_discarded()) j = nlohmann::json::object();if (j.contains("data")) {auto& d = j["data"];@@ -1013,8 +1039,25 @@ void ForumScreen::load_posts() {}}- auto resp = http::HttpClient::instance().get(url, headers);- auto j = resp.json_body();+ auto& cache = CacheService::instance();+ int cat_id = active_category_id_ > 0 ? active_category_id_ :+ (!categories_.empty() ? categories_[0].id : 0);+ std::string posts_ck = CacheService::make_key("api-response", "forum-posts",+ std::to_string(cat_id) + "_" + sort);++ std::string body;+ auto cached_posts = cache.get(posts_ck);+ if (cached_posts && !cached_posts->empty()) {+ body = *cached_posts;+ } else {+ auto resp = http::HttpClient::instance().get(url, headers);+ body = resp.body;+ if (resp.success && !body.empty())+ cache.set(posts_ck, body, "api-response", CacheTTL::FIVE_MIN);+ }++ auto j = nlohmann::json::parse(body, nullptr, false);+ if (j.is_discarded()) return;if (j.contains("data")) {auto& data = j["data"];diff --git a/fincept-cpp/src/screens/geopolitics/geopolitics_data.cpp b/fincept-cpp/src/screens/geopolitics/geopolitics_data.cppindex cf2241a1e..bfcde2e51 100644--- a/fincept-cpp/src/screens/geopolitics/geopolitics_data.cpp+++ b/fincept-cpp/src/screens/geopolitics/geopolitics_data.cpp@@ -3,6 +3,7 @@#include "geopolitics_data.h"#include "http/http_client.h"#include "auth/auth_manager.h"+#include "storage/cache_service.h"#include "core/logger.h"#include <thread>@@ -48,30 +49,53 @@ void GeopoliticsData::fetch_events(const std::string& api_key, const std::stringLOG_INFO("Geo", "GET %s", url.c_str());- auto headers = make_headers(api_key);- auto resp = http::HttpClient::instance().get(url, headers);+ auto& cache = CacheService::instance();+ std::string cache_key = CacheService::make_key("api-response", "geo-events",+ country + "_" + category + "_p" + std::to_string(page));++ // Try cache first+ auto cached_body = cache.get(cache_key);+ std::string body;+ int status_code = 200;+ bool success = false;++ if (cached_body) {+ body = *cached_body;+ success = true;+ LOG_INFO("Geo", "Cache HIT for geo-events key");+ } else {+ auto headers = make_headers(api_key);+ auto resp = http::HttpClient::instance().get(url, headers);+ body = resp.body;+ status_code = resp.status_code;+ success = resp.success;++ LOG_INFO("Geo", "Response: status=%d, success=%d, body_len=%zu, error='%s'",+ resp.status_code, (int)resp.success, resp.body.size(), resp.error.c_str());- LOG_INFO("Geo", "Response: status=%d, success=%d, body_len=%zu, error='%s'",- resp.status_code, (int)resp.success, resp.body.size(), resp.error.c_str());+ if (!resp.body.empty()) {+ std::string preview = resp.body.substr(0, std::min((size_t)500, resp.body.size()));+ LOG_DEBUG("Geo", "Body preview: %s", preview.c_str());+ }- // Log first 500 chars of body for debugging- if (!resp.body.empty()) {- std::string preview = resp.body.substr(0, std::min((size_t)500, resp.body.size()));- LOG_DEBUG("Geo", "Body preview: %s", preview.c_str());+ // Cache successful responses for 15 minutes+ if (resp.success && !resp.body.empty()) {+ cache.set(cache_key, resp.body, "api-response", CacheTTL::FIFTEEN_MIN);+ }}std::lock_guard<std::mutex> lock(mutex_);- if (!resp.success) {+ if (!success) {// Try to extract error message from API response body- if (!resp.body.empty()) {+ if (!body.empty()) {try {- auto err_json = nlohmann::json::parse(resp.body);- error_ = err_json.value("message", "API error (HTTP " + std::to_string(resp.status_code) + ")");+ auto err_json = nlohmann::json::parse(body);+ error_ = err_json.value("message", "API error (HTTP " + std::to_string(status_code) + ")");} catch (...) {- error_ = "HTTP " + std::to_string(resp.status_code);+ error_ = "HTTP " + std::to_string(status_code);}} else {- error_ = resp.error.empty() ? "Network error" : resp.error;+ error_ = "Network error";}LOG_ERROR("Geo", "Fetch events FAILED: %s", error_.c_str());loading_ = false;@@ -79,7 +103,7 @@ void GeopoliticsData::fetch_events(const std::string& api_key, const std::string}try {- auto j = resp.json_body();+ auto j = nlohmann::json::parse(body);// Log top-level keysstd::string keys;@@ -118,18 +142,18 @@ void GeopoliticsData::fetch_events(const std::string& api_key, const std::stringLOG_INFO("Geo", "events array size: %zu", events_arr.size());int with_coords = 0;- for (auto& e : events_arr) {+ for (const auto& ev_json : events_arr) {GeoEvent ev;- ev.url = e.value("url", "");- ev.domain = e.value("domain", "");- ev.event_category = e.value("event_category", "");- ev.matched_keywords = e.value("matched_keywords", "");- ev.city = e.value("city", "");- ev.country = e.value("country", "");- ev.latitude = e.value("latitude", 0.0);- ev.longitude = e.value("longitude", 0.0);- ev.extracted_date = e.value("extracted_date", "");- ev.created_at = e.value("created_at", "");+ ev.url = ev_json.value("url", "");+ ev.domain = ev_json.value("domain", "");+ ev.event_category = ev_json.value("event_category", "");+ ev.matched_keywords = ev_json.value("matched_keywords", "");+ ev.city = ev_json.value("city", "");+ ev.country = ev_json.value("country", "");+ ev.latitude = ev_json.value("latitude", 0.0);+ ev.longitude = ev_json.value("longitude", 0.0);+ ev.extracted_date = ev_json.value("extracted_date", "");+ ev.created_at = ev_json.value("created_at", "");if (ev.latitude != 0.0 || ev.longitude != 0.0) with_coords++;@@ -174,22 +198,37 @@ void GeopoliticsData::fetch_events(const std::string& api_key, const std::stringvoid GeopoliticsData::fetch_countries(const std::string& api_key) {LOG_INFO("Geo", "=== fetch_countries called, api_key_len=%zu", api_key.size());std::thread([this, api_key]() {- std::string url = std::string(API_BASE) + "/research/news-events?get_unique_countries=true";- LOG_INFO("Geo", "GET %s", url.c_str());- auto resp = http::HttpClient::instance().get(url, make_headers(api_key));-- LOG_INFO("Geo", "Countries response: status=%d, success=%d, body_len=%zu",- resp.status_code, (int)resp.success, resp.body.size());-- std::lock_guard<std::mutex> lock(mutex_);- if (!resp.success) {- LOG_ERROR("Geo", "Countries fetch FAILED: %s (body: %.200s)",- resp.error.c_str(), resp.body.c_str());- return;+ auto& cache = CacheService::instance();+ std::string cache_key = CacheService::make_key("api-response", "geo-countries", "list");++ std::string body;+ auto cached = cache.get(cache_key);+ if (cached) {+ body = *cached;+ LOG_INFO("Geo", "Cache HIT for geo-countries");+ } else {+ std::string url = std::string(API_BASE) + "/research/news-events?get_unique_countries=true";+ LOG_INFO("Geo", "GET %s", url.c_str());+ auto resp = http::HttpClient::instance().get(url, make_headers(api_key));++ LOG_INFO("Geo", "Countries response: status=%d, success=%d, body_len=%zu",+ resp.status_code, (int)resp.success, resp.body.size());++ if (!resp.success) {+ std::lock_guard<std::mutex> lock(mutex_);+ LOG_ERROR("Geo", "Countries fetch FAILED: %s (body: %.200s)",+ resp.error.c_str(), resp.body.c_str());+ return;+ }+ body = resp.body;+ if (!body.empty()) {+ cache.set(cache_key, body, "api-response", CacheTTL::ONE_HOUR);+ }}+ std::lock_guard<std::mutex> lock(mutex_);try {- auto j = resp.json_body();+ auto j = nlohmann::json::parse(body);if (!j.value("success", false)) {LOG_ERROR("Geo", "Countries API returned success=false");return;@@ -235,22 +274,37 @@ void GeopoliticsData::fetch_countries(const std::string& api_key) {void GeopoliticsData::fetch_categories(const std::string& api_key) {LOG_INFO("Geo", "=== fetch_categories called, api_key_len=%zu", api_key.size());std::thread([this, api_key]() {- std::string url = std::string(API_BASE) + "/research/news-events?get_unique_categories=true";- LOG_INFO("Geo", "GET %s", url.c_str());- auto resp = http::HttpClient::instance().get(url, make_headers(api_key));-- LOG_INFO("Geo", "Categories response: status=%d, success=%d, body_len=%zu",- resp.status_code, (int)resp.success, resp.body.size());-- std::lock_guard<std::mutex> lock(mutex_);- if (!resp.success) {- LOG_ERROR("Geo", "Categories fetch FAILED: %s (body: %.200s)",- resp.error.c_str(), resp.body.c_str());- return;+ auto& cache = CacheService::instance();+ std::string cache_key = CacheService::make_key("api-response", "geo-categories", "list");++ std::string body;+ auto cached = cache.get(cache_key);+ if (cached) {+ body = *cached;+ LOG_INFO("Geo", "Cache HIT for geo-categories");+ } else {+ std::string url = std::string(API_BASE) + "/research/news-events?get_unique_categories=true";+ LOG_INFO("Geo", "GET %s", url.c_str());+ auto resp = http::HttpClient::instance().get(url, make_headers(api_key));++ LOG_INFO("Geo", "Categories response: status=%d, success=%d, body_len=%zu",+ resp.status_code, (int)resp.success, resp.body.size());++ if (!resp.success) {+ std::lock_guard<std::mutex> lock(mutex_);+ LOG_ERROR("Geo", "Categories fetch FAILED: %s (body: %.200s)",+ resp.error.c_str(), resp.body.c_str());+ return;+ }+ body = resp.body;+ if (!body.empty()) {+ cache.set(cache_key, body, "api-response", CacheTTL::ONE_HOUR);+ }}+ std::lock_guard<std::mutex> lock(mutex_);try {- auto j = resp.json_body();+ auto j = nlohmann::json::parse(body);if (!j.value("success", false)) {LOG_ERROR("Geo", "Categories API returned success=false");return;diff --git a/fincept-cpp/src/screens/gov_data/gov_data.cpp b/fincept-cpp/src/screens/gov_data/gov_data.cppindex 07f410d60..984c795a9 100644--- a/fincept-cpp/src/screens/gov_data/gov_data.cpp+++ b/fincept-cpp/src/screens/gov_data/gov_data.cpp@@ -1,5 +1,6 @@#include "gov_data.h"#include "python/python_runner.h"+#include "storage/cache_service.h"#include "core/logger.h"#include <thread>#include <nlohmann/json.hpp>@@ -20,11 +21,28 @@ void GovData::run_script(const std::string& script,}std::thread([this, script, args]() {+ // Build cache key from script + args+ auto& cache = CacheService::instance();+ std::string args_key;+ for (const auto& a : args) args_key += a + "_";+ std::string cache_key = CacheService::make_key("reference", "gov-data", script + "_" + args_key);++ auto cached = cache.get(cache_key);+ if (cached && !cached->empty()) {+ std::lock_guard<std::mutex> lock(mutex_);+ parse_result(*cached);+ loading_.store(false);+ return;+ }+auto py_result = python::execute(script, args);{std::lock_guard<std::mutex> lock(mutex_);if (py_result.success) {parse_result(py_result.output);+ if (has_result_ && !py_result.output.empty()) {+ cache.set(cache_key, py_result.output, "reference", CacheTTL::ONE_HOUR);+ }} else {error_ = py_result.error.empty()? "Script failed (exit " + std::to_string(py_result.exit_code) + ")"diff --git a/fincept-cpp/src/screens/markets/markets_data.cpp b/fincept-cpp/src/screens/markets/markets_data.cppindex bb8c33402..c1be72004 100644--- a/fincept-cpp/src/screens/markets/markets_data.cpp+++ b/fincept-cpp/src/screens/markets/markets_data.cpp@@ -1,5 +1,6 @@#include "markets_data.h"#include "python/python_runner.h"+#include "storage/cache_service.h"#include <nlohmann/json.hpp>#include <thread>#include <sstream>@@ -53,16 +54,31 @@ void MarketsData::fetch_category(const std::string& category, const std::vector<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 cache_key = CacheService::make_key("market-quotes", "markets", cat);++ std::thread([this, cat, args, cache_key]() {+ auto& cache = CacheService::instance();++ // Try cache first+ auto cached = cache.get(cache_key);+ if (cached && !cached->empty()) {+ std::lock_guard<std::mutex> lock(mutex_);+ parse_quotes(cat, *cached);+ categories_[cat].has_data = true;+ categories_[cat].loading = false;+ return;+ }++ // Cache miss — fetch from Pythonstd::string out = run_python(args);if (!out.empty()) {std::lock_guard<std::mutex> lock(mutex_);parse_quotes(cat, out);+ cache.set(cache_key, out, "market-quotes", CacheTTL::FIVE_MIN);} else {std::lock_guard<std::mutex> lock(mutex_);categories_[cat].error = "Failed to fetch data";diff --git a/fincept-cpp/src/screens/markets/markets_screen.cpp b/fincept-cpp/src/screens/markets/markets_screen.cppindex 4b562062f..845608a7f 100644--- a/fincept-cpp/src/screens/markets/markets_screen.cpp+++ b/fincept-cpp/src/screens/markets/markets_screen.cpp@@ -177,8 +177,8 @@ void MarketsScreen::render_panels() {float avail_w = ImGui::GetContentRegionAvail().x;- // Responsive grid: auto-calculate columns based on available width- auto grid = ui::responsive_grid(avail_w, 280, 8);+ // Responsive grid: 3 cards per row — min 380px per card+ auto grid = ui::responsive_grid(avail_w, 380, 10);// --- Global Markets ---ImGui::Spacing();@@ -194,9 +194,9 @@ void MarketsScreen::render_panels() {int col = 0;for (size_t i = 0; i < global_markets_.size(); i++) {- if (col > 0) ImGui::SameLine(0, 8);+ if (col > 0) ImGui::SameLine(0, 10);ImGui::BeginChild(("##gp_" + std::to_string(i)).c_str(),- ImVec2(grid.panel_w, 280), true);+ ImVec2(grid.panel_w, 360), true);render_panel(global_markets_[i]);ImGui::EndChild();@@ -219,9 +219,9 @@ void MarketsScreen::render_panels() {col = 0;for (size_t i = 0; i < regional_markets_.size(); i++) {- if (col > 0) ImGui::SameLine(0, 8);+ if (col > 0) ImGui::SameLine(0, 10);ImGui::BeginChild(("##rp_" + std::to_string(i)).c_str(),- ImVec2(grid.panel_w, 300), true);+ ImVec2(grid.panel_w, 380), true);render_panel(regional_markets_[i]);ImGui::EndChild();diff --git a/fincept-cpp/src/screens/mna/mna_data.cpp b/fincept-cpp/src/screens/mna/mna_data.cppindex 9f654fe31..17ae653df 100644--- a/fincept-cpp/src/screens/mna/mna_data.cpp+++ b/fincept-cpp/src/screens/mna/mna_data.cpp@@ -1,5 +1,6 @@#include "mna_data.h"#include "python/python_runner.h"+#include "storage/cache_service.h"#include "core/logger.h"#include <thread>#include <nlohmann/json.hpp>@@ -23,15 +24,47 @@ void MNAData::run_analysis(const std::string& script,std::string full_script = "Analytics/corporateFinance/" + script;std::thread([this, full_script, args]() {+ auto& cache = CacheService::instance();+ std::string args_key;+ for (const auto& a : args) args_key += a + "_";+ std::string cache_key = CacheService::make_key("reference", "mna", full_script + "_" + args_key);++ auto cached = cache.get(cache_key);+ if (cached && !cached->empty()) {+ std::lock_guard<std::mutex> lock(mutex_);+ parse_result(*cached);+ loading_.store(false);+ return;+ }+auto py_result = python::execute(full_script, args);{std::lock_guard<std::mutex> lock(mutex_);if (py_result.success) {parse_result(py_result.output);+ if (has_result_ && !py_result.output.empty()) {+ cache.set(cache_key, py_result.output, "reference", CacheTTL::FIFTEEN_MIN);+ }} else {- error_ = py_result.error.empty()- ? "Python script failed (exit " + std::to_string(py_result.exit_code) + ")"- : py_result.error;+ // Try to extract a meaningful error from stderr JSON+ // Many scripts output {"success": false, "error": "..."} to stderr+ std::string err_msg;+ if (!py_result.error.empty()) {+ try {+ std::string json_str = python::extract_json(py_result.error);+ if (!json_str.empty()) {+ auto err_json = json::parse(json_str);+ if (err_json.contains("error"))+ err_msg = err_json["error"].get<std::string>();+ }+ } catch (...) {}+ }+ if (err_msg.empty()) {+ err_msg = py_result.error.empty()+ ? "Python script failed (exit " + std::to_string(py_result.exit_code) + ")"+ : py_result.error;+ }+ error_ = err_msg;has_result_ = false;LOG_ERROR("MNAData", "Script failed: %s — %s",full_script.c_str(), error_.c_str());@@ -56,15 +89,46 @@ void MNAData::run_analysis_stdin(const std::string& script,std::string full_script = "Analytics/corporateFinance/" + script;std::thread([this, full_script, args, stdin_json]() {+ auto& cache = CacheService::instance();+ std::string args_key;+ for (const auto& a : args) args_key += a + "_";+ std::string cache_key = CacheService::make_key("reference", "mna-stdin",+ full_script + "_" + args_key + stdin_json.substr(0, std::min((size_t)64, stdin_json.size())));++ auto cached = cache.get(cache_key);+ if (cached && !cached->empty()) {+ std::lock_guard<std::mutex> lock(mutex_);+ parse_result(*cached);+ loading_.store(false);+ return;+ }+auto py_result = python::execute_with_stdin(full_script, args, stdin_json);{std::lock_guard<std::mutex> lock(mutex_);if (py_result.success) {parse_result(py_result.output);+ if (has_result_ && !py_result.output.empty()) {+ cache.set(cache_key, py_result.output, "reference", CacheTTL::FIFTEEN_MIN);+ }} else {- error_ = py_result.error.empty()- ? "Python script failed (exit " + std::to_string(py_result.exit_code) + ")"- : py_result.error;+ std::string err_msg;+ if (!py_result.error.empty()) {+ try {+ std::string json_str = python::extract_json(py_result.error);+ if (!json_str.empty()) {+ auto err_json = json::parse(json_str);+ if (err_json.contains("error"))+ err_msg = err_json["error"].get<std::string>();+ }+ } catch (...) {}+ }+ if (err_msg.empty()) {+ err_msg = py_result.error.empty()+ ? "Python script failed (exit " + std::to_string(py_result.exit_code) + ")"+ : py_result.error;+ }+ error_ = err_msg;has_result_ = false;}}diff --git a/fincept-cpp/src/screens/news/news_parser.cpp b/fincept-cpp/src/screens/news/news_parser.cppindex 36e636d40..3ce60d5e0 100644--- a/fincept-cpp/src/screens/news/news_parser.cpp+++ b/fincept-cpp/src/screens/news/news_parser.cpp@@ -16,20 +16,20 @@ namespace fincept::news {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},+ {"cnbc-world", "CNBC World", "https://search.cnbc.com/rs/search/combinedcms/view.xml?partnerId=wrss01&id=100727362", "GEOPOLITICS","GLOBAL","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},+ {"ft-home", "Financial Times", "https://www.ft.com/?format=rss", "MARKETS", "GLOBAL", "FT", 2},+ {"yahoo-finance", "Yahoo Finance", "https://finance.yahoo.com/news/rssindex", "MARKETS", "US", "YAHOO FINANCE", 2},+ {"investing-com", "Investing.com", "https://www.investing.com/rss/news.rss", "MARKETS", "GLOBAL", "INVESTING.COM", 2},+ {"bbc-business", "BBC Business", "https://feeds.bbci.co.uk/news/business/rss.xml", "MARKETS", "GLOBAL", "BBC", 2},+ {"bbc-world", "BBC World", "https://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},@@ -42,11 +42,16 @@ std::vector<RSSFeed> NewsScreen::get_default_feeds() {{"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},+ {"nakedcap", "Naked Capitalism", "https://www.nakedcapitalism.com/feed", "ECONOMIC", "GLOBAL", "NAKED CAPITALISM",2},+ {"calcrisks", "Calculated Risk", "https://www.calculatedriskblog.com/feeds/posts/default?alt=rss", "ECONOMIC", "US", "CALCULATED RISK", 2},++ // Tier 2 — India / Asia+ {"et-markets", "Economic Times Markets", "https://economictimes.indiatimes.com/markets/rssfeeds/1977021501.cms", "MARKETS", "INDIA", "ECONOMIC TIMES", 2},+ {"moneycontrol", "Moneycontrol", "https://www.moneycontrol.com/rss/marketreports.xml", "MARKETS", "INDIA", "MONEYCONTROL", 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},+ {"guardian-world", "The Guardian World", "https://www.theguardian.com/world/rss", "GEOPOLITICS", "GLOBAL", "THE GUARDIAN", 2},};}diff --git a/fincept-cpp/src/screens/news/news_screen.cpp b/fincept-cpp/src/screens/news/news_screen.cppindex 75034abbe..c32948a7d 100644--- a/fincept-cpp/src/screens/news/news_screen.cpp+++ b/fincept-cpp/src/screens/news/news_screen.cpp@@ -1,8 +1,10 @@#include "news_screen.h"#include "http/http_client.h"+#include "storage/cache_service.h"#include "core/logger.h"#include "ui/yoga_helpers.h"#include <imgui.h>+#include <nlohmann/json.hpp>#include <algorithm>#include <ctime>#include <cstdio>@@ -29,22 +31,41 @@ void NewsScreen::fetch_news() {std::thread([this]() {auto feeds = get_default_feeds();- auto& http = http::HttpClient::instance();+ auto& http_client = http::HttpClient::instance();+ auto& cache = CacheService::instance();std::vector<NewsArticle> all_articles;int success_count = 0;int fail_count = 0;+ int cache_hit_count = 0;for (const auto& feed : feeds) {if (!feed.enabled) continue;- http::Headers hdrs;- hdrs["User-Agent"] = "FinceptTerminal/4.0.0";- hdrs["Accept"] = "application/rss+xml, application/xml, text/xml, */*";+ std::string cache_key = CacheService::make_key("news", "rss", feed.id);+ std::string body;- auto resp = http.get(feed.url, hdrs);- if (resp.success && !resp.body.empty()) {- auto parsed = parse_rss_xml(resp.body, feed);+ // Try cache first+ auto cached = cache.get(cache_key);+ if (cached) {+ body = *cached;+ cache_hit_count++;+ } else {+ // Fetch from network+ http::Headers hdrs;+ hdrs["User-Agent"] = "FinceptTerminal/4.0.0";+ hdrs["Accept"] = "application/rss+xml, application/xml, text/xml, */*";++ auto resp = http_client.get(feed.url, hdrs);+ if (resp.success && !resp.body.empty()) {+ body = resp.body;+ // Cache RSS response for 10 minutes+ cache.set(cache_key, body, "news", CacheTTL::TEN_MIN);+ }+ }++ if (!body.empty()) {+ auto parsed = parse_rss_xml(body, feed);all_articles.insert(all_articles.end(), parsed.begin(), parsed.end());success_count++;} else {@@ -70,7 +91,8 @@ void NewsScreen::fetch_news() {loading_ = false;last_fetch_time_ = (double)std::time(nullptr);- LOG_INFO("News", "Fetched %d articles from %d feeds", (int)articles_.size(), success_count);+ LOG_INFO("News", "Fetched %d articles from %d feeds (%d cached)",+ (int)articles_.size(), success_count, cache_hit_count);}).detach();}diff --git a/fincept-cpp/src/screens/node_editor/node_editor_screen.cpp b/fincept-cpp/src/screens/node_editor/node_editor_screen.cppindex 14b1622b9..dacc23666 100644--- a/fincept-cpp/src/screens/node_editor/node_editor_screen.cpp+++ b/fincept-cpp/src/screens/node_editor/node_editor_screen.cpp@@ -756,20 +756,30 @@ void NodeEditorScreen::render_config_panel(float /*width*/, float /*height*/) {theme::SectionHeader("ACTIONS");- // Test Node button — execute this node in isolation+ // Test Node button — execute this node in isolation (background thread)if (theme::AccentButton("Test Node", ImVec2(-1, 0))) {node->status = "running";- std::map<std::string, nlohmann::json> empty_inputs;- auto result = NodeExecutor::execute(*node, empty_inputs);- if (result.success) {- node->status = "completed";- node->result = result.display_text;- node->error.clear();- } else {- node->status = "error";- node->error = result.error;- }- execution_results_[node->id] = result;+ auto node_copy = *node; // copy for thread safety+ int nid = node->id;+ std::thread([this, node_copy, nid]() {+ std::map<std::string, nlohmann::json> empty_inputs;+ auto result = NodeExecutor::execute(node_copy, empty_inputs);+ // Find the live node and update it+ for (auto& n : state_.nodes()) {+ if (n.id == nid) {+ if (result.success) {+ n.status = "completed";+ n.result = result.display_text;+ n.error.clear();+ } else {+ n.status = "error";+ n.error = result.error;+ }+ break;+ }+ }+ execution_results_[nid] = result;+ }).detach();}ImGui::Spacing();diff --git a/fincept-cpp/src/screens/node_editor/node_executor.cpp b/fincept-cpp/src/screens/node_editor/node_executor.cppindex bb61e48a2..ad1cf0e8e 100644--- a/fincept-cpp/src/screens/node_editor/node_executor.cpp+++ b/fincept-cpp/src/screens/node_editor/node_executor.cpp@@ -5,6 +5,7 @@#include "node_executor.h"#include "http/http_client.h"#include "python/python_runner.h"+#include "storage/cache_service.h"#include "screens/agent_studio/agent_service.h"#include "core/logger.h"#include <chrono>@@ -141,18 +142,30 @@ ExecutionResult NodeExecutor::exec_data_source(const NodeInstance& node, const jsource.c_str(), symbol.c_str(), timeframe.c_str());if (source == "yahoo") {- // Use Python yfinance via PythonRunner- auto py_result = python::execute("fetch_data.py",- {symbol, start_date, end_date, timeframe});+ auto& cache = CacheService::instance();+ std::string ck = CacheService::make_key("market-quotes", "node-data",+ symbol + "_" + timeframe + "_" + start_date);++ std::string cached_out;+ auto cv = cache.get(ck);+ if (cv && !cv->empty()) { cached_out = *cv; }+ else {+ auto py_result = python::execute("fetch_data.py",+ {symbol, start_date, end_date, timeframe});+ if (py_result.success && !py_result.output.empty()) {+ cached_out = py_result.output;+ cache.set(ck, cached_out, "market-quotes", CacheTTL::FIVE_MIN);+ }+ }- if (py_result.success && !py_result.output.empty()) {+ if (!cached_out.empty()) {try {- result.data = json::parse(py_result.output);+ result.data = json::parse(cached_out);int rows = result.data.contains("rows") ? result.data["rows"].get<int>() : 0;result.display_text = "Fetched " + std::to_string(rows) + " bars for " + symbol;result.success = true;} catch (...) {- result.data = json{{"raw_output", py_result.output}, {"symbol", symbol}};+ result.data = json{{"raw_output", cached_out}, {"symbol", symbol}};result.display_text = "Fetched data for " + symbol + " (raw output)";result.success = true;}@@ -302,15 +315,28 @@ ExecutionResult NodeExecutor::exec_yfinance(const NodeInstance& node, const jsonstd::string period = get_param_str(node, "period", "1y");std::string interval = get_param_str(node, "interval", "1d");- auto py_result = python::execute("fetch_data.py", {symbol, period, interval});+ auto& yf_cache = CacheService::instance();+ std::string yf_ck = CacheService::make_key("market-quotes", "node-yfinance",+ symbol + "_" + period + "_" + interval);- if (py_result.success && !py_result.output.empty()) {+ std::string yf_out;+ auto yf_cv = yf_cache.get(yf_ck);+ if (yf_cv && !yf_cv->empty()) { yf_out = *yf_cv; }+ else {+ auto py_result = python::execute("fetch_data.py", {symbol, period, interval});+ if (py_result.success && !py_result.output.empty()) {+ yf_out = py_result.output;+ yf_cache.set(yf_ck, yf_out, "market-quotes", CacheTTL::FIVE_MIN);+ }+ }++ if (!yf_out.empty()) {try {- result.data = json::parse(py_result.output);+ result.data = json::parse(yf_out);result.success = true;result.display_text = "Fetched " + symbol + " data via yfinance";} catch (...) {- result.data = json{{"raw", py_result.output}, {"symbol", symbol}};+ result.data = json{{"raw", yf_out}, {"symbol", symbol}};result.display_text = "Fetched " + symbol + " (raw)";result.success = true;}diff --git a/fincept-cpp/src/screens/portfolio/portfolio_screen.cpp b/fincept-cpp/src/screens/portfolio/portfolio_screen.cppindex 4cfccf546..9d9b081cf 100644--- a/fincept-cpp/src/screens/portfolio/portfolio_screen.cpp+++ b/fincept-cpp/src/screens/portfolio/portfolio_screen.cpp@@ -6,6 +6,7 @@#include "trading/paper_trading.h"#include "trading/order_matcher.h"#include "python/python_runner.h"+#include "storage/cache_service.h"#include "ui/theme.h"#include "ui/yoga_helpers.h"#include "core/logger.h"@@ -16,6 +17,7 @@#include <cstdlib>#include <algorithm>#include <fstream>+#include <thread>namespace fincept::portfolio {@@ -34,7 +36,9 @@ void PortfolioScreen::render() {}if (needs_refresh_ || pt_needs_refresh_) {- if (!paper_trading_mode_) refresh_data();+ if (!paper_trading_mode_) {+ if (!data_loading_.load()) refresh_data();+ }else refresh_pt_data();}@@ -116,113 +120,167 @@ void PortfolioScreen::render() {// ============================================================================void PortfolioScreen::refresh_data() {+ needs_refresh_ = false;+try {portfolios_ = get_all_portfolios();if (selected_portfolio_idx_ < 0 && !portfolios_.empty()) {selected_portfolio_idx_ = 0;}- if (selected_portfolio_idx_ >= 0 && selected_portfolio_idx_ < (int)portfolios_.size()) {- const auto& pf = portfolios_[selected_portfolio_idx_];- assets_ = get_assets(pf.id);- transactions_ = get_transactions(pf.id, 50);+ } catch (const std::exception& e) {+ LOG_ERROR("Portfolio", "Refresh failed: %s", e.what());+ return;+ }- // Fetch live prices via yfinance Python script- std::map<std::string, std::pair<double, double>> prices;+ if (selected_portfolio_idx_ < 0 || selected_portfolio_idx_ >= (int)portfolios_.size()) {+ return;+ }- if (!assets_.empty()) {- nlohmann::json req;- std::vector<std::string> symbols;- for (const auto& a : assets_) symbols.push_back(a.symbol);- req["symbols"] = symbols;+ const auto& pf = portfolios_[selected_portfolio_idx_];+ assets_ = get_assets(pf.id);+ transactions_ = get_transactions(pf.id, 50);- auto result = python::execute_with_stdin(- "Analytics/portfolioManagement/fetch_quotes.py", {}, req.dump());+ // If no assets, skip Python calls entirely+ if (assets_.empty()) {+ std::map<std::string, std::pair<double, double>> empty_prices;+ price_cache_ = empty_prices;+ summary_ = compute_summary(pf, assets_, empty_prices);+ metrics_loaded_ = false;+ return;+ }- if (result.success && !result.output.empty()) {- auto j = nlohmann::json::parse(result.output, nullptr, false);- if (!j.is_discarded() && j.is_object() && !j.contains("error")) {- for (auto& [sym, data] : j.items()) {- double cur = data.value("price", 0.0);- double prev = data.value("prev_close", 0.0);- if (cur > 0) prices[sym] = {cur, prev > 0 ? prev : cur};- }- }- }- }+ // Build symbols list and use cached avg_buy_price as initial fallback+ std::map<std::string, std::pair<double, double>> fallback_prices;+ for (const auto& a : assets_) {+ fallback_prices[a.symbol] = {a.avg_buy_price, a.avg_buy_price};+ }- // Fallback: use avg_buy_price for symbols without live data- for (const auto& a : assets_) {- if (prices.find(a.symbol) == prices.end()) {- prices[a.symbol] = {a.avg_buy_price, a.avg_buy_price};- }- }+ // If we have no live data yet, use fallback prices to render immediately+ if (price_cache_.empty()) {+ price_cache_ = fallback_prices;+ summary_ = compute_summary(pf, assets_, fallback_prices);+ }- price_cache_ = prices;- summary_ = compute_summary(pf, assets_, prices);+ // Launch background thread for Python-based price fetching+ data_loading_ = true;- // Compute risk metrics from historical data- if (!assets_.empty()) {- compute_portfolio_metrics();- }- }- } catch (const std::exception& e) {- LOG_ERROR("Portfolio", "Refresh failed: %s", e.what());- }- needs_refresh_ = false;-}+ // Capture what the thread needs (copies, not references)+ auto assets_copy = assets_;+ auto pf_copy = pf;-void PortfolioScreen::compute_portfolio_metrics() {- try {- // Fetch 6mo historical data for all symbols + SPY+ std::thread([this, assets_copy, pf_copy, fallback_prices]() {nlohmann::json req;std::vector<std::string> symbols;- for (const auto& h : summary_.holdings) symbols.push_back(h.asset.symbol);- // Add SPY for beta calculation- if (std::find(symbols.begin(), symbols.end(), "SPY") == symbols.end())- symbols.push_back("SPY");+ for (const auto& a : assets_copy) symbols.push_back(a.symbol);req["symbols"] = symbols;- req["period"] = "6mo";- req["interval"] = "1d";- auto result = python::execute_with_stdin(- "Analytics/portfolioManagement/fetch_historical.py", {}, req.dump());+ std::string sym_key;+ for (const auto& s : symbols) sym_key += s + "_";+ auto& cache = CacheService::instance();+ std::string cache_key = CacheService::make_key("market-quotes", "portfolio-prices", sym_key);- if (!result.success || result.output.empty()) {- metrics_loaded_ = false;- return;+ std::string output;+ auto cached = cache.get(cache_key);+ if (cached && !cached->empty()) {+ output = *cached;+ } else {+ auto result = python::execute_with_stdin(+ "Analytics/portfolioManagement/fetch_quotes.py", {}, req.dump());+ if (result.success && !result.output.empty()) {+ output = result.output;+ cache.set(cache_key, output, "market-quotes", CacheTTL::FIVE_MIN);+ }}- auto j = nlohmann::json::parse(result.output, nullptr, false);- if (j.is_discarded() || !j.is_object() || j.contains("error")) {- metrics_loaded_ = false;- return;+ std::map<std::string, std::pair<double, double>> prices = fallback_prices;+ if (!output.empty()) {+ auto j = nlohmann::json::parse(output, nullptr, false);+ if (!j.is_discarded() && j.is_object() && !j.contains("error")) {+ for (auto& [sym, data] : j.items()) {+ double cur = data.value("price", 0.0);+ double prev = data.value("prev_close", 0.0);+ if (cur > 0) prices[sym] = {cur, prev > 0 ? prev : cur};+ }+ }}- // Parse into historical_cache_- historical_cache_.clear();- for (auto& [sym, data] : j.items()) {- if (!data.is_array()) continue;- std::vector<std::pair<std::string, double>> series;- for (const auto& pt : data) {- series.emplace_back(- pt.value("date", ""),- pt.value("close", 0.0));+ auto summary = compute_summary(pf_copy, assets_copy, prices);++ // Compute risk metrics in the same background thread+ ComputedMetrics metrics;+ bool metrics_ok = false;+ std::map<std::string, std::vector<std::pair<std::string, double>>> hist_cache;++ try {+ nlohmann::json hist_req;+ std::vector<std::string> hist_symbols;+ for (const auto& h : summary.holdings) hist_symbols.push_back(h.asset.symbol);+ if (std::find(hist_symbols.begin(), hist_symbols.end(), "SPY") == hist_symbols.end())+ hist_symbols.push_back("SPY");+ hist_req["symbols"] = hist_symbols;+ hist_req["period"] = "6mo";+ hist_req["interval"] = "1d";++ std::string hist_sym_key;+ for (const auto& s : hist_symbols) hist_sym_key += s + "_";+ std::string hist_cache_key = CacheService::make_key("market-quotes", "portfolio-hist", hist_sym_key);++ std::string hist_output;+ auto hist_cached = cache.get(hist_cache_key);+ if (hist_cached && !hist_cached->empty()) {+ hist_output = *hist_cached;+ } else {+ auto result = python::execute_with_stdin(+ "Analytics/portfolioManagement/fetch_historical.py", {}, hist_req.dump());+ if (result.success && !result.output.empty()) {+ hist_output = result.output;+ cache.set(hist_cache_key, hist_output, "market-quotes", CacheTTL::FIFTEEN_MIN);+ }+ }++ if (!hist_output.empty()) {+ auto j = nlohmann::json::parse(hist_output, nullptr, false);+ if (!j.is_discarded() && j.is_object() && !j.contains("error")) {+ for (auto& [sym, data] : j.items()) {+ if (!data.is_array()) continue;+ std::vector<std::pair<std::string, double>> series;+ for (const auto& pt : data) {+ series.emplace_back(pt.value("date", ""), pt.value("close", 0.0));+ }+ hist_cache[sym] = std::move(series);+ }++ std::map<std::string, double> weights;+ for (const auto& h : summary.holdings) {+ weights[h.asset.symbol] = h.weight / 100.0;+ }++ metrics = compute_metrics(hist_cache, weights);+ metrics_ok = true;+ }}- historical_cache_[sym] = std::move(series);+ } catch (const std::exception& e) {+ LOG_ERROR("Portfolio", "Metrics computation failed: %s", e.what());}- // Build weights map from summary- std::map<std::string, double> weights;- for (const auto& h : summary_.holdings) {- weights[h.asset.symbol] = h.weight / 100.0; // weight is 0-100, need 0-1+ // Update shared state atomically+ {+ std::lock_guard<std::mutex> lock(data_mutex_);+ price_cache_ = std::move(prices);+ summary_ = std::move(summary);+ historical_cache_ = std::move(hist_cache);+ if (metrics_ok) {+ metrics_ = metrics;+ metrics_loaded_ = true;+ }}+ data_loading_ = false;+ }).detach();+}- metrics_ = compute_metrics(historical_cache_, weights);- metrics_loaded_ = true;- } catch (const std::exception& e) {- LOG_ERROR("Portfolio", "Metrics computation failed: %s", e.what());- metrics_loaded_ = false;- }+void PortfolioScreen::compute_portfolio_metrics() {+ // Now handled inside refresh_data's background thread — this is a no-op.+ // Kept for API compatibility.}void PortfolioScreen::refresh_pt_data() {diff --git a/fincept-cpp/src/screens/portfolio/portfolio_screen.h b/fincept-cpp/src/screens/portfolio/portfolio_screen.hindex be84b2591..59fc03733 100644--- a/fincept-cpp/src/screens/portfolio/portfolio_screen.h+++ b/fincept-cpp/src/screens/portfolio/portfolio_screen.h@@ -17,6 +17,9 @@#include <vector>#include <string>#include <map>+#include <atomic>+#include <mutex>+#include <thread>namespace fincept::portfolio {@@ -46,6 +49,8 @@ private:PortfolioSummary summary_;bool needs_refresh_ = true;float refresh_timer_ = 0.0f;+ std::atomic<bool> data_loading_{false};+ std::mutex data_mutex_;// Live price cachestd::map<std::string, std::pair<double, double>> price_cache_; // symbol -> (current, prev_close)diff --git a/fincept-cpp/src/screens/portfolio/views/analytics_view.cpp b/fincept-cpp/src/screens/portfolio/views/analytics_view.cppindex ea1d48b16..1e476861e 100644--- a/fincept-cpp/src/screens/portfolio/views/analytics_view.cpp+++ b/fincept-cpp/src/screens/portfolio/views/analytics_view.cpp@@ -3,11 +3,16 @@#include "analytics_view.h"#include "python/python_runner.h"+#include "storage/cache_service.h"#include "ui/theme.h"#include "core/logger.h"#include <imgui.h>#include <algorithm>+#include <cmath>#include <cstdio>+#include <cstring>+#include <thread>+#include <implot.h>namespace fincept::portfolio {@@ -141,38 +146,62 @@ void AnalyticsView::fetch_analytics_data(const PortfolioSummary& summary) {if (analytics_loading_) return;analytics_loading_ = true;- try {- // Build holdings JSON for Python scripts- nlohmann::json holdings = nlohmann::json::array();- for (const auto& h : summary.holdings) {- holdings.push_back({- {"symbol", h.asset.symbol},- {"quantity", h.asset.quantity},- {"avg_price", h.asset.avg_buy_price},- {"current_price", h.current_price},- {"weight", h.weight / 100.0}- });- }-- nlohmann::json req;- req["holdings"] = holdings;- req["portfolio_name"] = summary.portfolio.name;-- auto result = python::execute_with_stdin(- "Analytics/portfolioManagement/portfolio_analytics.py",- {"calculate_portfolio_metrics"}, req.dump());+ nlohmann::json holdings = nlohmann::json::array();+ for (const auto& h : summary.holdings) {+ holdings.push_back({+ {"symbol", h.asset.symbol},+ {"quantity", h.asset.quantity},+ {"avg_price", h.asset.avg_buy_price},+ {"current_price", h.current_price},+ {"weight", h.weight / 100.0}+ });+ }+ std::string pf_name = summary.portfolio.name;+ std::string sym_key;+ for (const auto& h : summary.holdings) sym_key += h.asset.symbol + "_";++ std::thread([this, holdings, pf_name, sym_key]() {+ try {+ nlohmann::json req;+ req["holdings"] = holdings;+ req["portfolio_name"] = pf_name;++ auto& cache = CacheService::instance();+ std::string ck = CacheService::make_key("reference", "portfolio-analytics",+ sym_key.substr(0, std::min((size_t)64, sym_key.size())));++ std::string output;+ auto cached = cache.get(ck);+ if (cached && !cached->empty()) { output = *cached; }+ else {+ auto result = python::execute_with_stdin(+ "Analytics/portfolioManagement/portfolio_analytics.py",+ {"calculate_portfolio_metrics"}, req.dump());+ if (result.success && !result.output.empty()) {+ output = result.output;+ // Only cache successful results+ auto check = nlohmann::json::parse(output, nullptr, false);+ if (!check.is_discarded() && !check.contains("error"))+ cache.set(ck, output, "reference", CacheTTL::FIFTEEN_MIN);+ } else if (!result.output.empty()) {+ output = result.output; // Still show error to user+ } else if (!result.error.empty()) {+ output = nlohmann::json({{"error", result.error}}).dump();+ }+ }- if (result.success && !result.output.empty()) {- auto j = nlohmann::json::parse(result.output, nullptr, false);- if (!j.is_discarded()) {- analytics_result_ = j;- analytics_loaded_ = true;+ if (!output.empty()) {+ auto j = nlohmann::json::parse(output, nullptr, false);+ if (!j.is_discarded()) {+ analytics_result_ = j;+ analytics_loaded_ = true;+ }}+ } catch (const std::exception& e) {+ LOG_ERROR("AnalyticsView", "Failed to fetch analytics: %s", e.what());}- } catch (const std::exception& e) {- LOG_ERROR("AnalyticsView", "Failed to fetch analytics: %s", e.what());- }- analytics_loading_ = false;+ analytics_loading_ = false;+ }).detach();}void AnalyticsView::render_analytics(const PortfolioSummary& summary) {@@ -191,30 +220,81 @@ void AnalyticsView::render_analytics(const PortfolioSummary& summary) {return;}- // Render analytics results as key-value table- theme::SectionHeader("Portfolio Analytics Results");+ // Check for error+ if (analytics_result_.is_object() && analytics_result_.contains("error")) {+ ImGui::TextColored(theme::colors::MARKET_RED, "Error: %s",+ analytics_result_["error"].get<std::string>().c_str());+ ImGui::Spacing();+ if (theme::SecondaryButton("Retry")) {+ analytics_loaded_ = false;+ fetch_analytics_data(summary);+ }+ return;+ }- if (analytics_result_.is_object()) {- if (ImGui::BeginTable("##analytics_kv", 2,+ // Render analytics results — handle nested sections+ auto render_section = [](const char* label, const char* table_id,+ const nlohmann::json& obj) {+ if (!obj.is_object() || obj.empty()) return;+ theme::SectionHeader(label);+ if (ImGui::BeginTable(table_id, 2,ImGuiTableFlags_RowBg | ImGuiTableFlags_Borders)) {- ImGui::TableSetupColumn("Metric", ImGuiTableColumnFlags_WidthFixed, 250);+ ImGui::TableSetupColumn("Metric", ImGuiTableColumnFlags_WidthFixed, 280);ImGui::TableSetupColumn("Value");ImGui::TableHeadersRow();-- for (auto& [key, val] : analytics_result_.items()) {- if (val.is_object() || val.is_array()) continue; // skip nested+ for (auto& [k, v] : obj.items()) {+ if (v.is_object() || v.is_array()) continue; // skip deep nestingImGui::TableNextRow();- ImGui::TableNextColumn(); ImGui::TextColored(theme::colors::TEXT_DIM, "%s", key.c_str());ImGui::TableNextColumn();- if (val.is_number())- ImGui::Text("%.4f", val.get<double>());- else if (val.is_string())- ImGui::TextUnformatted(val.get<std::string>().c_str());+ ImGui::TextColored(theme::colors::TEXT_DIM, "%s", k.c_str());+ ImGui::TableNextColumn();+ if (v.is_number())+ ImGui::Text("%.6f", v.get<double>());+ else if (v.is_string())+ ImGui::TextUnformatted(v.get<std::string>().c_str());+ else if (v.is_null())+ ImGui::TextColored(theme::colors::TEXT_DIM, "N/A");else- ImGui::TextUnformatted(val.dump().c_str());+ ImGui::TextUnformatted(v.dump().c_str());}ImGui::EndTable();}+ ImGui::Spacing();+ };++ if (analytics_result_.is_object()) {+ // Render known sections+ if (analytics_result_.contains("portfolio_metrics"))+ render_section("Portfolio Metrics", "##pm",+ analytics_result_["portfolio_metrics"]);++ if (analytics_result_.contains("risk_metrics"))+ render_section("Risk Metrics", "##rm",+ analytics_result_["risk_metrics"]);++ if (analytics_result_.contains("capm_analysis"))+ render_section("CAPM Analysis", "##capm",+ analytics_result_["capm_analysis"]);++ if (analytics_result_.contains("systematic_risk_analysis"))+ render_section("Systematic Risk", "##sysrisk",+ analytics_result_["systematic_risk_analysis"]);++ if (analytics_result_.contains("correlation_analysis"))+ render_section("Correlation Analysis", "##corrfx",+ analytics_result_["correlation_analysis"]);++ if (analytics_result_.contains("individual_betas"))+ render_section("Individual Betas", "##betas",+ analytics_result_["individual_betas"]);++ // Render any remaining top-level scalars+ bool has_scalars = false;+ for (auto& [k, v] : analytics_result_.items()) {+ if (!v.is_object() && !v.is_array()) { has_scalars = true; break; }+ }+ if (has_scalars)+ render_section("Summary", "##a_summary", analytics_result_);}ImGui::Spacing();@@ -232,28 +312,58 @@ void AnalyticsView::fetch_correlation_data(const PortfolioSummary& summary) {if (correlation_loading_) return;correlation_loading_ = true;- try {- nlohmann::json req;- std::vector<std::string> symbols;- for (const auto& h : summary.holdings)- symbols.push_back(h.asset.symbol);- req["symbols"] = symbols;-- auto result = python::execute_with_stdin(- "Analytics/fortitudo_tech_wrapper/fortitudo_service.py",- {"covariance_analysis"}, req.dump());-- if (result.success && !result.output.empty()) {- auto j = nlohmann::json::parse(result.output, nullptr, false);- if (!j.is_discarded()) {- correlation_result_ = j;- correlation_loaded_ = true;+ std::vector<std::string> symbols;+ for (const auto& h : summary.holdings)+ symbols.push_back(h.asset.symbol);++ std::thread([this, symbols]() {+ try {+ nlohmann::json req;+ // fortitudo_service expects "returns" key — pass as comma-separated tickers+ std::string tickers_csv;+ for (size_t i = 0; i < symbols.size(); i++) {+ if (i > 0) tickers_csv += ",";+ tickers_csv += symbols[i];+ }+ req["returns"] = tickers_csv;++ auto& cache_c = CacheService::instance();+ std::string csym;+ for (const auto& s : symbols) csym += s + "_";+ std::string cck = CacheService::make_key("reference", "portfolio-correlation",+ csym.substr(0, std::min((size_t)64, csym.size())));++ std::string c_out;+ auto cached_c = cache_c.get(cck);+ if (cached_c && !cached_c->empty()) { c_out = *cached_c; }+ else {+ auto result = python::execute_with_stdin(+ "Analytics/fortitudo_tech_wrapper/fortitudo_service.py",+ {"covariance_analysis"}, req.dump());+ if (result.success && !result.output.empty()) {+ c_out = result.output;+ auto check = nlohmann::json::parse(c_out, nullptr, false);+ if (!check.is_discarded() && check.value("success", false))+ cache_c.set(cck, c_out, "reference", CacheTTL::FIFTEEN_MIN);+ } else if (!result.output.empty()) {+ c_out = result.output;+ } else if (!result.error.empty()) {+ c_out = nlohmann::json({{"success", false}, {"error", result.error}}).dump();+ }+ }++ if (!c_out.empty()) {+ auto j = nlohmann::json::parse(c_out, nullptr, false);+ if (!j.is_discarded()) {+ correlation_result_ = j;+ correlation_loaded_ = true;+ }}+ } catch (const std::exception& e) {+ LOG_ERROR("AnalyticsView", "Failed to fetch correlation: %s", e.what());}- } catch (const std::exception& e) {- LOG_ERROR("AnalyticsView", "Failed to fetch correlation: %s", e.what());- }- correlation_loading_ = false;+ correlation_loading_ = false;+ }).detach();}void AnalyticsView::render_correlation(const PortfolioSummary& summary) {@@ -272,29 +382,300 @@ void AnalyticsView::render_correlation(const PortfolioSummary& summary) {return;}- theme::SectionHeader("Correlation / Covariance Matrix");+ // Check for error+ if (correlation_result_.is_object() &&+ (correlation_result_.contains("error") ||+ (correlation_result_.contains("success") && !correlation_result_["success"].get<bool>()))) {+ std::string err = correlation_result_.contains("error")+ ? correlation_result_["error"].get<std::string>() : "Unknown error";+ ImGui::TextColored(theme::colors::MARKET_RED, "Error: %s", err.c_str());+ ImGui::Spacing();+ if (theme::SecondaryButton("Retry")) {+ correlation_loaded_ = false;+ fetch_correlation_data(summary);+ }+ return;+ }- if (correlation_result_.is_object()) {- // Render as key-value or matrix depending on shape- if (ImGui::BeginTable("##corr_kv", 2,- ImGuiTableFlags_RowBg | ImGuiTableFlags_Borders)) {- ImGui::TableSetupColumn("Key", ImGuiTableColumnFlags_WidthFixed, 250);- ImGui::TableSetupColumn("Value");+ // Build asset list from result+ std::vector<std::string> assets;+ if (correlation_result_.contains("assets") && correlation_result_["assets"].is_array()) {+ for (const auto& s : correlation_result_["assets"])+ assets.push_back(s.get<std::string>());+ }+ int n = (int)assets.size();++ // Helper: parse flat "A / B" -> value dict into NxN grid (row-major)+ auto parse_matrix = [&](const nlohmann::json& flat,+ std::vector<double>& data_flat) {+ data_flat.assign(n * n, 0.0);+ for (int r = 0; r < n; r++) {+ for (int c = 0; c < n; c++) {+ std::string key = assets[r] + " / " + assets[c];+ if (flat.contains(key) && flat[key].is_number())+ data_flat[r * n + c] = flat[key].get<double>();+ }+ }+ };++ // Helper: color for correlation value (-1 to +1)+ auto corr_color = [](double v) -> ImVec4 {+ if (v >= 0.7) return ImVec4(0.1f, 0.85f, 0.3f, 1.0f);+ if (v >= 0.3) return ImVec4(0.3f, 0.7f, 0.5f, 1.0f);+ if (v >= -0.3) return ImVec4(0.7f, 0.7f, 0.7f, 1.0f);+ if (v >= -0.7) return ImVec4(0.9f, 0.6f, 0.3f, 1.0f);+ return ImVec4(0.9f, 0.2f, 0.2f, 1.0f);+ };++ if (correlation_result_.is_object() && n > 0) {++ // ====== 1. Correlation Heatmap (DrawList-based) ======+ if (correlation_result_.contains("correlation_matrix")) {+ std::vector<double> corr_data;+ parse_matrix(correlation_result_["correlation_matrix"], corr_data);++ theme::SectionHeader("Correlation Heatmap");++ // Draw a custom heatmap using DrawList for pixel-perfect control+ float cell_size = 70.0f;+ float label_w = 60.0f; // space for row/col labels+ float total_w = label_w + cell_size * n;+ float total_h = label_w + cell_size * n;++ ImVec2 origin = ImGui::GetCursorScreenPos();+ ImDrawList* dl = ImGui::GetWindowDrawList();++ // Column headers+ for (int c = 0; c < n; c++) {+ float cx = origin.x + label_w + c * cell_size + cell_size * 0.5f;+ float cy = origin.y + label_w * 0.5f;+ ImVec2 text_size = ImGui::CalcTextSize(assets[c].c_str());+ dl->AddText(ImVec2(cx - text_size.x * 0.5f, cy - text_size.y * 0.5f),+ ImGui::ColorConvertFloat4ToU32(theme::colors::ACCENT),+ assets[c].c_str());+ }++ // Rows+ for (int r = 0; r < n; r++) {+ // Row label+ float ry = origin.y + label_w + r * cell_size + cell_size * 0.5f;+ ImVec2 text_size = ImGui::CalcTextSize(assets[r].c_str());+ dl->AddText(ImVec2(origin.x + label_w - text_size.x - 4,+ ry - text_size.y * 0.5f),+ ImGui::ColorConvertFloat4ToU32(theme::colors::ACCENT),+ assets[r].c_str());++ for (int c = 0; c < n; c++) {+ double val = corr_data[r * n + c];+ float x0 = origin.x + label_w + c * cell_size;+ float y0 = origin.y + label_w + r * cell_size;+ float x1 = x0 + cell_size;+ float y1 = y0 + cell_size;++ // Color: lerp from red (-1) -> white (0) -> green (+1)+ float t = (float)(val + 1.0) * 0.5f; // 0..1+ ImVec4 cell_col;+ if (t < 0.5f) {+ float s = t * 2.0f; // 0..1 for red→white+ cell_col = ImVec4(0.9f, 0.2f + 0.6f * s, 0.2f + 0.6f * s, 0.8f);+ } else {+ float s = (t - 0.5f) * 2.0f; // 0..1 for white→green+ cell_col = ImVec4(0.8f - 0.6f * s, 0.8f, 0.8f - 0.5f * s, 0.8f);+ }++ // Filled cell+ dl->AddRectFilled(ImVec2(x0 + 1, y0 + 1), ImVec2(x1 - 1, y1 - 1),+ ImGui::ColorConvertFloat4ToU32(cell_col), 3.0f);++ // Value text centered in cell+ char buf[16];+ std::snprintf(buf, sizeof(buf), "%+.2f", val);+ ImVec2 ts = ImGui::CalcTextSize(buf);+ // Dark text for readability+ dl->AddText(ImVec2(x0 + (cell_size - ts.x) * 0.5f,+ y0 + (cell_size - ts.y) * 0.5f),+ IM_COL32(20, 20, 20, 255), buf);+ }+ }++ // Reserve space+ ImGui::Dummy(ImVec2(total_w, total_h));+ ImGui::Spacing();++ // Correlation table with clean formatting+ theme::SectionHeader("Correlation Values");+ int cols = n + 1;+ if (ImGui::BeginTable("##corr_tbl", cols,+ ImGuiTableFlags_Borders | ImGuiTableFlags_SizingFixedFit)) {+ ImGui::TableSetupColumn("", ImGuiTableColumnFlags_WidthFixed, 80);+ for (int c = 0; c < n; c++)+ ImGui::TableSetupColumn(assets[c].c_str(), ImGuiTableColumnFlags_WidthFixed, 90);+ ImGui::TableHeadersRow();++ for (int r = 0; r < n; r++) {+ ImGui::TableNextRow();+ ImGui::TableNextColumn();+ ImGui::TextColored(theme::colors::ACCENT, "%s", assets[r].c_str());+ for (int c = 0; c < n; c++) {+ ImGui::TableNextColumn();+ double val = corr_data[r * n + c];+ ImVec4 col = corr_color(val);++ // Color bar background+ ImVec2 pos = ImGui::GetCursorScreenPos();+ float col_w = ImGui::GetColumnWidth();+ float row_h = ImGui::GetTextLineHeightWithSpacing();+ float fill = (float)std::abs(val);+ ImGui::GetWindowDrawList()->AddRectFilled(pos,+ ImVec2(pos.x + col_w * fill, pos.y + row_h),+ ImGui::ColorConvertFloat4ToU32(ImVec4(col.x, col.y, col.z, 0.2f)));++ ImGui::TextColored(col, "%+.3f", val);+ }+ }+ ImGui::EndTable();+ }+ ImGui::Spacing();+ }++ // ====== 2. Covariance Matrix (clean table, no "e" notation) ======+ if (correlation_result_.contains("covariance_matrix")) {+ std::vector<double> cov_data;+ parse_matrix(correlation_result_["covariance_matrix"], cov_data);++ theme::SectionHeader("Covariance Matrix");+ int cols = n + 1;+ if (ImGui::BeginTable("##cov_tbl", cols,+ ImGuiTableFlags_Borders | ImGuiTableFlags_SizingFixedFit)) {+ ImGui::TableSetupColumn("", ImGuiTableColumnFlags_WidthFixed, 80);+ for (int c = 0; c < n; c++)+ ImGui::TableSetupColumn(assets[c].c_str(), ImGuiTableColumnFlags_WidthFixed, 110);+ ImGui::TableHeadersRow();++ for (int r = 0; r < n; r++) {+ ImGui::TableNextRow();+ ImGui::TableNextColumn();+ ImGui::TextColored(theme::colors::ACCENT, "%s", assets[r].c_str());+ for (int c = 0; c < n; c++) {+ ImGui::TableNextColumn();+ double val = cov_data[r * n + c];+ // Always show as decimal — no scientific notation+ ImGui::Text("%.6f", val);+ }+ }+ ImGui::EndTable();+ }+ ImGui::Spacing();+ }+ }++ // ====== 3. Statistical Moments — table + volatility bar chart ======+ if (correlation_result_.contains("moments") && correlation_result_["moments"].is_object() && n > 0) {+ const auto& moments = correlation_result_["moments"];++ // Parse moments data+ std::vector<double> means, vols, skews, kurts;+ for (const auto& sym : assets) {+ auto get = [&](const char* metric) -> double {+ std::string key = sym + " " + metric;+ if (moments.contains(key) && moments[key].is_number())+ return moments[key].get<double>();+ return 0.0;+ };+ means.push_back(get("Mean"));+ vols.push_back(get("Volatility"));+ skews.push_back(get("Skewness"));+ kurts.push_back(get("Kurtosis"));+ }++ // Volatility bar chart+ theme::SectionHeader("Volatility Comparison");+ std::vector<const char*> labels;+ for (const auto& a : assets) labels.push_back(a.c_str());+ std::vector<double> positions(n);+ for (int i = 0; i < n; i++) positions[i] = i;++ ImPlot::PushStyleVar(ImPlotStyleVar_FitPadding, ImVec2(0.1f, 0.1f));+ if (ImPlot::BeginPlot("##vol_bars", ImVec2(-1, 200),+ ImPlotFlags_NoLegend | ImPlotFlags_NoMouseText)) {+ ImPlot::SetupAxes("", "Daily Volatility",+ ImPlotAxisFlags_AutoFit | ImPlotAxisFlags_NoGridLines,+ ImPlotAxisFlags_AutoFit);+ ImPlot::SetupAxisTicks(ImAxis_X1, positions.data(), n, labels.data());++ ImPlot::SetNextFillStyle(ImVec4(0.2f, 0.6f, 0.9f, 0.7f));+ ImPlot::PlotBars("Volatility", positions.data(), vols.data(), n, 0.6);++ ImPlot::EndPlot();+ }+ ImPlot::PopStyleVar();+ ImGui::Spacing();++ // Mean return bar chart+ theme::SectionHeader("Mean Daily Return");+ ImPlot::PushStyleVar(ImPlotStyleVar_FitPadding, ImVec2(0.1f, 0.1f));+ if (ImPlot::BeginPlot("##mean_bars", ImVec2(-1, 200),+ ImPlotFlags_NoLegend | ImPlotFlags_NoMouseText)) {+ ImPlot::SetupAxes("", "Daily Return",+ ImPlotAxisFlags_AutoFit | ImPlotAxisFlags_NoGridLines,+ ImPlotAxisFlags_AutoFit);+ ImPlot::SetupAxisTicks(ImAxis_X1, positions.data(), n, labels.data());++ // Color bars by sign+ for (int i = 0; i < n; i++) {+ ImVec4 bar_col = means[i] >= 0+ ? ImVec4(0.1f, 0.8f, 0.3f, 0.7f)+ : ImVec4(0.9f, 0.2f, 0.2f, 0.7f);+ ImPlot::SetNextFillStyle(bar_col);+ char lbl[64];+ std::snprintf(lbl, sizeof(lbl), "##m%d", i);+ ImPlot::PlotBars(lbl, &positions[i], &means[i], 1, 0.6);+ }+ ImPlot::EndPlot();+ }+ ImPlot::PopStyleVar();+ ImGui::Spacing();++ // Moments table+ theme::SectionHeader("Statistical Moments");+ if (ImGui::BeginTable("##moments", 5,+ ImGuiTableFlags_Borders | ImGuiTableFlags_RowBg)) {+ ImGui::TableSetupColumn("Symbol", ImGuiTableColumnFlags_WidthFixed, 80);+ ImGui::TableSetupColumn("Mean Return", ImGuiTableColumnFlags_WidthFixed, 120);+ ImGui::TableSetupColumn("Volatility", ImGuiTableColumnFlags_WidthFixed, 120);+ ImGui::TableSetupColumn("Skewness", ImGuiTableColumnFlags_WidthFixed, 100);+ ImGui::TableSetupColumn("Kurtosis", ImGuiTableColumnFlags_WidthFixed, 100);ImGui::TableHeadersRow();- for (auto& [key, val] : correlation_result_.items()) {+ for (int i = 0; i < n; i++) {ImGui::TableNextRow();- ImGui::TableNextColumn(); ImGui::TextColored(theme::colors::TEXT_DIM, "%s", key.c_str());ImGui::TableNextColumn();- if (val.is_number())- ImGui::Text("%.6f", val.get<double>());- else if (val.is_string())- ImGui::TextWrapped("%s", val.get<std::string>().c_str());- else- ImGui::TextWrapped("%s", val.dump(2).c_str());+ ImGui::TextColored(theme::colors::ACCENT, "%s", assets[i].c_str());++ ImGui::TableNextColumn();+ ImGui::TextColored(means[i] >= 0 ? theme::colors::MARKET_GREEN : theme::colors::MARKET_RED,+ "%+.6f", means[i]);++ ImGui::TableNextColumn();+ ImGui::Text("%.6f", vols[i]);++ ImGui::TableNextColumn();+ ImGui::Text("%.4f", skews[i]);++ ImGui::TableNextColumn();+ ImGui::Text("%.2f", kurts[i]);}ImGui::EndTable();}+ ImGui::Spacing();+ }++ // Summary+ if (correlation_result_.is_object()) {+ int n_obs = correlation_result_.value("n_observations", 0);+ int n_ast = correlation_result_.value("n_assets", 0);+ ImGui::TextColored(theme::colors::TEXT_DIM,+ "%d assets | %d observations | 1-year lookback", n_ast, n_obs);}ImGui::Spacing();diff --git a/fincept-cpp/src/screens/portfolio/views/economics_view.cpp b/fincept-cpp/src/screens/portfolio/views/economics_view.cppindex 4f05f5ca1..f8fbe798b 100644--- a/fincept-cpp/src/screens/portfolio/views/economics_view.cpp+++ b/fincept-cpp/src/screens/portfolio/views/economics_view.cpp@@ -3,10 +3,12 @@#include "economics_view.h"#include "python/python_runner.h"+#include "storage/cache_service.h"#include "ui/theme.h"#include "core/logger.h"#include <imgui.h>#include <cstdio>+#include <thread>namespace fincept::portfolio {@@ -34,6 +36,11 @@ void EconomicsView::render(const PortfolioSummary& /*summary*/) {ImGui::Separator();+ if (!error_.empty()) {+ ImGui::TextColored(theme::colors::MARKET_RED, "[Error] %s", error_.c_str());+ ImGui::Spacing();+ }+if (sub_tab_ == 0) {if (!cycle_loaded_) {ImGui::TextColored(theme::colors::TEXT_DIM,@@ -88,37 +95,89 @@ void EconomicsView::render(const PortfolioSummary& /*summary*/) {void EconomicsView::fetch_business_cycle() {if (loading_) return;loading_ = true;- try {- auto result = python::execute_with_stdin(- "Analytics/economics/business_cycle.py",- {"get_indicators"}, "{}");+ error_.clear();+ std::thread([this]() {+ try {+ auto& cache = CacheService::instance();+ std::string ck = CacheService::make_key("economic", "business-cycle", "indicators");- if (result.success && !result.output.empty()) {- auto j = nlohmann::json::parse(result.output, nullptr, false);- if (!j.is_discarded()) { cycle_result_ = j; cycle_loaded_ = true; }+ std::string output;+ auto cached = cache.get(ck);+ if (cached && !cached->empty()) { output = *cached; }+ else {+ auto result = python::execute_with_stdin(+ "Analytics/economics/business_cycle.py",+ {"get_indicators"}, "{}");+ if (result.success && !result.output.empty()) {+ output = result.output;+ auto check = nlohmann::json::parse(output, nullptr, false);+ if (!check.is_discarded() && !check.contains("error"))+ cache.set(ck, output, "economic", CacheTTL::FIFTEEN_MIN);+ } else if (!result.error.empty()) {+ error_ = result.error;+ }+ }++ if (!output.empty()) {+ auto j = nlohmann::json::parse(output, nullptr, false);+ if (!j.is_discarded()) {+ if (j.contains("error"))+ error_ = j["error"].get<std::string>();+ else { cycle_result_ = j; cycle_loaded_ = true; }+ }+ } else if (error_.empty()) {+ error_ = "Script returned empty output";+ }+ } catch (const std::exception& e) {+ error_ = e.what();+ LOG_ERROR("EconomicsView", "Business cycle fetch failed: %s", e.what());}- } catch (const std::exception& e) {- LOG_ERROR("EconomicsView", "Business cycle fetch failed: %s", e.what());- }- loading_ = false;+ loading_ = false;+ }).detach();}void EconomicsView::fetch_erp() {if (loading_) return;loading_ = true;- try {- auto result = python::execute_with_stdin(- "Analytics/economics/equity_risk_premium.py",- {"estimate_erp"}, "{}");+ error_.clear();+ std::thread([this]() {+ try {+ auto& cache = CacheService::instance();+ std::string ck = CacheService::make_key("economic", "equity-risk-premium", "erp");++ std::string output;+ auto cached = cache.get(ck);+ if (cached && !cached->empty()) { output = *cached; }+ else {+ auto result = python::execute_with_stdin(+ "Analytics/economics/equity_risk_premium.py",+ {"estimate_erp"}, "{}");+ if (result.success && !result.output.empty()) {+ output = result.output;+ auto check = nlohmann::json::parse(output, nullptr, false);+ if (!check.is_discarded() && !check.contains("error"))+ cache.set(ck, output, "economic", CacheTTL::FIFTEEN_MIN);+ } else if (!result.error.empty()) {+ error_ = result.error;+ }+ }- if (result.success && !result.output.empty()) {- auto j = nlohmann::json::parse(result.output, nullptr, false);- if (!j.is_discarded()) { erp_result_ = j; erp_loaded_ = true; }+ if (!output.empty()) {+ auto j = nlohmann::json::parse(output, nullptr, false);+ if (!j.is_discarded()) {+ if (j.contains("error"))+ error_ = j["error"].get<std::string>();+ else { erp_result_ = j; erp_loaded_ = true; }+ }+ } else if (error_.empty()) {+ error_ = "Script returned empty output";+ }+ } catch (const std::exception& e) {+ error_ = e.what();+ LOG_ERROR("EconomicsView", "ERP fetch failed: %s", e.what());}- } catch (const std::exception& e) {- LOG_ERROR("EconomicsView", "ERP fetch failed: %s", e.what());- }- loading_ = false;+ loading_ = false;+ }).detach();}} // namespace fincept::portfoliodiff --git a/fincept-cpp/src/screens/portfolio/views/economics_view.h b/fincept-cpp/src/screens/portfolio/views/economics_view.hindex cc412dcee..e1a32a000 100644--- a/fincept-cpp/src/screens/portfolio/views/economics_view.h+++ b/fincept-cpp/src/screens/portfolio/views/economics_view.h@@ -17,6 +17,7 @@ private:bool cycle_loaded_ = false;bool erp_loaded_ = false;bool loading_ = false;+ std::string error_;void fetch_business_cycle();void fetch_erp();diff --git a/fincept-cpp/src/screens/portfolio/views/indices_view.cpp b/fincept-cpp/src/screens/portfolio/views/indices_view.cppindex 62462de26..e70313e44 100644--- a/fincept-cpp/src/screens/portfolio/views/indices_view.cpp+++ b/fincept-cpp/src/screens/portfolio/views/indices_view.cpp@@ -4,6 +4,7 @@#include "indices_view.h"#include "storage/database.h"#include "python/python_runner.h"+#include "storage/cache_service.h"#include "ui/theme.h"#include "core/logger.h"#include <imgui.h>@@ -12,6 +13,7 @@#include <cstring>#include <cstdlib>#include <algorithm>+#include <thread>namespace fincept::portfolio {@@ -206,86 +208,110 @@ void IndicesView::remove_constituent(const std::string& id) {void IndicesView::recalculate_index(const std::string& index_id) {if (constituents_.empty()) return;- // Fetch current prices via Python- try {- nlohmann::json req;- std::vector<std::string> symbols;- for (const auto& c : constituents_)- symbols.push_back(c.symbol);- req["symbols"] = symbols;-- auto result = python::execute_with_stdin(- "Analytics/portfolioManagement/fetch_quotes.py", {}, req.dump());-- if (result.success && !result.output.empty()) {- auto j = nlohmann::json::parse(result.output, nullptr, false);- if (!j.is_discarded() && j.is_object()) {- auto& dbi = db::Database::instance();- for (auto& c : constituents_) {- if (j.contains(c.symbol) && j[c.symbol].is_object()) {- double price = j[c.symbol].value("price", c.current_price);- double prev = j[c.symbol].value("prev_close", c.prev_close);- auto ustmt = dbi.prepare("UPDATE index_constituents SET current_price = ?, prev_close = ? WHERE id = ?");- ustmt.bind_double(1, price);- ustmt.bind_double(2, prev);- ustmt.bind_text(3, c.id);- ustmt.execute();- c.current_price = price;- c.prev_close = prev;- }+ // Copy data needed for the thread+ auto constituents_copy = constituents_;+ auto indices_copy_id = index_id;++ std::thread([this, constituents_copy, indices_copy_id]() {+ auto local_constituents = constituents_copy;++ // Fetch current prices via Python+ try {+ nlohmann::json req;+ std::vector<std::string> symbols;+ for (const auto& c : local_constituents)+ symbols.push_back(c.symbol);+ req["symbols"] = symbols;++ std::string sym_key;+ for (const auto& s : symbols) sym_key += s + "_";+ auto& cache = CacheService::instance();+ std::string ck = CacheService::make_key("market-quotes", "index-prices",+ sym_key.substr(0, std::min((size_t)64, sym_key.size())));++ std::string output;+ auto cached = cache.get(ck);+ if (cached && !cached->empty()) { output = *cached; }+ else {+ auto result = python::execute_with_stdin(+ "Analytics/portfolioManagement/fetch_quotes.py", {}, req.dump());+ if (result.success && !result.output.empty()) {+ output = result.output;+ cache.set(ck, output, "market-quotes", CacheTTL::FIVE_MIN);}}- }- } catch (const std::exception& e) {- LOG_ERROR("IndicesView", "Price fetch failed: %s", e.what());- }-- // Calculate index value based on method- double index_value = 0;- auto it = std::find_if(indices_.begin(), indices_.end(),- [&](const CustomIndex& idx) { return idx.id == index_id; });- if (it == indices_.end()) return;- if (it->method == "equal_weighted") {- double sum = 0;- int count = 0;- for (const auto& c : constituents_) {- if (c.prev_close > 0) {- sum += c.current_price / c.prev_close;- count++;+ if (!output.empty()) {+ auto j = nlohmann::json::parse(output, nullptr, false);+ if (!j.is_discarded() && j.is_object()) {+ auto& dbi = db::Database::instance();+ for (auto& c : local_constituents) {+ if (j.contains(c.symbol) && j[c.symbol].is_object()) {+ double price = j[c.symbol].value("price", c.current_price);+ double prev = j[c.symbol].value("prev_close", c.prev_close);+ auto ustmt = dbi.prepare("UPDATE index_constituents SET current_price = ?, prev_close = ? WHERE id = ?");+ ustmt.bind_double(1, price);+ ustmt.bind_double(2, prev);+ ustmt.bind_text(3, c.id);+ ustmt.execute();+ c.current_price = price;+ c.prev_close = prev;+ }+ }+ }}+ } catch (const std::exception& e) {+ LOG_ERROR("IndicesView", "Price fetch failed: %s", e.what());}- index_value = count > 0 ? it->prev_close * (sum / count) : it->base_value;- } else if (it->method == "price_weighted") {- double sum = 0;- for (const auto& c : constituents_)- sum += c.current_price;- double divisor = static_cast<double>(constituents_.size());- index_value = divisor > 0 ? sum / divisor * (it->base_value / 100.0) : it->base_value;- } else {- // Market cap weighted- double total_weight = 0;- for (const auto& c : constituents_)- total_weight += c.weight;- if (total_weight <= 0) total_weight = static_cast<double>(constituents_.size());- double weighted_return = 0;- for (const auto& c : constituents_) {- double w = total_weight > 0 ? c.weight / total_weight : 1.0 / static_cast<double>(constituents_.size());- if (c.prev_close > 0)- weighted_return += w * (c.current_price / c.prev_close);+ // Calculate index value based on method+ double index_value = 0;+ auto it = std::find_if(indices_.begin(), indices_.end(),+ [&](const CustomIndex& idx) { return idx.id == indices_copy_id; });+ if (it == indices_.end()) return;++ if (it->method == "equal_weighted") {+ double sum = 0;+ int count = 0;+ for (const auto& c : local_constituents) {+ if (c.prev_close > 0) {+ sum += c.current_price / c.prev_close;+ count++;+ }+ }+ index_value = count > 0 ? it->prev_close * (sum / count) : it->base_value;+ } else if (it->method == "price_weighted") {+ double sum = 0;+ for (const auto& c : local_constituents)+ sum += c.current_price;+ double divisor = static_cast<double>(local_constituents.size());+ index_value = divisor > 0 ? sum / divisor * (it->base_value / 100.0) : it->base_value;+ } else {+ double total_weight = 0;+ for (const auto& c : local_constituents)+ total_weight += c.weight;+ if (total_weight <= 0) total_weight = static_cast<double>(local_constituents.size());++ double weighted_return = 0;+ for (const auto& c : local_constituents) {+ double w = total_weight > 0 ? c.weight / total_weight : 1.0 / static_cast<double>(local_constituents.size());+ if (c.prev_close > 0)+ weighted_return += w * (c.current_price / c.prev_close);+ }+ index_value = it->prev_close * weighted_return;}- index_value = it->prev_close * weighted_return;- }-- // Update in database- auto& dbi = db::Database::instance();- auto ustmt = dbi.prepare("UPDATE custom_indices SET current_value = ? WHERE id = ?");- ustmt.bind_double(1, index_value);- ustmt.bind_text(2, index_id);- ustmt.execute();- it->current_value = index_value;+ // Update in database+ auto& dbi = db::Database::instance();+ auto ustmt = dbi.prepare("UPDATE custom_indices SET current_value = ? WHERE id = ?");+ ustmt.bind_double(1, index_value);+ ustmt.bind_text(2, indices_copy_id);+ ustmt.execute();++ it->current_value = index_value;+ constituents_ = local_constituents;+ needs_refresh_ = true;+ }).detach();}// ============================================================================diff --git a/fincept-cpp/src/screens/portfolio/views/optimization_view.cpp b/fincept-cpp/src/screens/portfolio/views/optimization_view.cppindex 2d7874eb4..bd684d540 100644--- a/fincept-cpp/src/screens/portfolio/views/optimization_view.cpp+++ b/fincept-cpp/src/screens/portfolio/views/optimization_view.cpp@@ -3,10 +3,12 @@#include "optimization_view.h"#include "python/python_runner.h"+#include "storage/cache_service.h"#include "ui/theme.h"#include "core/logger.h"#include <imgui.h>#include <cstdio>+#include <thread>namespace fincept::portfolio {@@ -56,40 +58,66 @@ void OptimizationView::fetch_optimization(const PortfolioSummary& summary, int tloading_ = true;error_.clear();- try {- nlohmann::json req;- std::vector<std::string> symbols;- for (const auto& h : summary.holdings)- symbols.push_back(h.asset.symbol);- req["symbols"] = symbols;-- const char* strategies[] = {- "max_sharpe", "min_volatility", "efficient_risk", "efficient_return",- "max_quadratic_utility", "risk_parity", "black_litterman",- "hrp", "custom_constraints"- };- req["strategy"] = strategies[tab];-- auto result = python::execute_with_stdin(- "Analytics/portfolioManagement/portfolio_optimization.py",- {"optimize"}, req.dump());-- if (result.success && !result.output.empty()) {- auto j = nlohmann::json::parse(result.output, nullptr, false);- if (!j.is_discarded()) {- results_[tab] = j;- loaded_[tab] = true;- } else {- error_ = "Failed to parse optimization results";+ std::vector<std::string> symbols;+ for (const auto& h : summary.holdings)+ symbols.push_back(h.asset.symbol);++ std::thread([this, symbols, tab]() {+ try {+ nlohmann::json req;+ req["symbols"] = symbols;++ const char* strategies[] = {+ "max_sharpe", "min_volatility", "efficient_risk", "efficient_return",+ "max_quadratic_utility", "risk_parity", "black_litterman",+ "hrp", "custom_constraints"+ };+ req["strategy"] = strategies[tab];++ auto& cache = CacheService::instance();+ std::string sym_key;+ for (const auto& s : symbols) sym_key += s + "_";+ std::string ck = CacheService::make_key("reference", "optimization",+ sym_key.substr(0, std::min((size_t)48, sym_key.size())) + strategies[tab]);++ std::string output;+ auto cached = cache.get(ck);+ if (cached && !cached->empty()) { output = *cached; }+ else {+ auto result = python::execute_with_stdin(+ "Analytics/portfolioManagement/portfolio_optimization.py",+ {"optimize"}, req.dump());+ if (result.success && !result.output.empty()) {+ output = result.output;+ auto check = nlohmann::json::parse(output, nullptr, false);+ if (!check.is_discarded() && !check.contains("error"))+ cache.set(ck, output, "reference", CacheTTL::FIFTEEN_MIN);+ } else if (!result.error.empty()) {+ error_ = result.error;+ } else {+ error_ = "Optimization script failed";+ }+ }++ if (!output.empty()) {+ auto j = nlohmann::json::parse(output, nullptr, false);+ if (!j.is_discarded()) {+ if (j.contains("error")) {+ error_ = j["error"].get<std::string>();+ } else {+ results_[tab] = j;+ loaded_[tab] = true;+ }+ } else {+ error_ = "Failed to parse optimization results";+ }}- } else {- error_ = result.error.empty() ? "Optimization failed" : result.error;+ } catch (const std::exception& e) {+ error_ = e.what();+ LOG_ERROR("OptimizationView", "Optimization failed: %s", e.what());}- } catch (const std::exception& e) {- error_ = e.what();- LOG_ERROR("OptimizationView", "Optimization failed: %s", e.what());- }- loading_ = false;+ loading_ = false;+ }).detach();}void OptimizationView::render_result(const nlohmann::json& result) {diff --git a/fincept-cpp/src/screens/portfolio/views/performance_view.cpp b/fincept-cpp/src/screens/portfolio/views/performance_view.cppindex 1ed632742..06be14f53 100644--- a/fincept-cpp/src/screens/portfolio/views/performance_view.cpp+++ b/fincept-cpp/src/screens/portfolio/views/performance_view.cpp@@ -3,6 +3,7 @@#include "performance_view.h"#include "python/python_runner.h"+#include "storage/cache_service.h"#include "ui/theme.h"#include "core/logger.h"#include <imgui.h>@@ -12,6 +13,7 @@#include <cstdio>#include <cmath>#include <set>+#include <thread>namespace fincept::portfolio {@@ -128,112 +130,150 @@ void PerformanceView::render_period_bar(const ComputedMetrics& metrics) {void PerformanceView::fetch_historical(const PortfolioSummary& summary) {if (data_loading_) return;data_loading_ = true;+ error_msg_.clear();++ // Capture holdings data by value for the thread+ struct HoldingInfo { std::string symbol; double quantity; };+ std::vector<HoldingInfo> holdings_copy;+ std::vector<std::string> symbols;+ for (const auto& h : summary.holdings) {+ holdings_copy.push_back({h.asset.symbol, h.asset.quantity});+ symbols.push_back(h.asset.symbol);+ }+ symbols.push_back("SPY");+ int period = period_idx_;++ std::thread([this, holdings_copy, symbols, period]() {+ try {+ nlohmann::json req;+ req["symbols"] = symbols;++ const char* yf_periods[] = {"1mo", "3mo", "6mo", "1y", "5y"};+ req["period"] = yf_periods[period];+ req["interval"] = "1d";++ auto& cache = CacheService::instance();+ std::string sym_key;+ for (const auto& s : symbols) sym_key += s + "_";+ std::string cache_key = CacheService::make_key("market-quotes", "perf-hist",+ sym_key + yf_periods[period]);++ std::string output;+ auto cached = cache.get(cache_key);+ if (cached && !cached->empty()) {+ output = *cached;+ } else {+ auto result = python::execute_with_stdin(+ "Analytics/portfolioManagement/fetch_historical.py",+ {}, req.dump());+ if (result.success && !result.output.empty()) {+ output = result.output;+ // Only cache if valid JSON and no error+ auto check = nlohmann::json::parse(output, nullptr, false);+ if (!check.is_discarded() && !check.contains("error"))+ cache.set(cache_key, output, "market-quotes", CacheTTL::FIFTEEN_MIN);+ } else if (!result.error.empty()) {+ error_msg_ = result.error;+ data_loading_ = false;+ return;+ }+ }- try {- nlohmann::json req;- std::vector<std::string> symbols;- for (const auto& h : summary.holdings)- symbols.push_back(h.asset.symbol);-- // Also fetch SPY as benchmark- symbols.push_back("SPY");- req["symbols"] = symbols;-- // Map period to yfinance period strings- const char* yf_periods[] = {"1mo", "3mo", "6mo", "1y", "5y"};- req["period"] = yf_periods[period_idx_];- req["interval"] = "1d";-- auto result = python::execute_with_stdin(- "Analytics/portfolioManagement/fetch_historical.py",- {}, req.dump());-- if (result.success && !result.output.empty()) {- auto j = nlohmann::json::parse(result.output, nullptr, false);- if (!j.is_discarded() && j.is_object()) {- // Build portfolio NAV from weighted holdings- // First, collect all unique dates across all symbols- std::map<std::string, std::map<std::string, double>> sym_data; // symbol -> {date -> close}-- for (const auto& sym : symbols) {- if (!j.contains(sym)) continue;- auto& sd = j[sym];- if (!sd.contains("dates") || !sd.contains("closes")) continue;- auto& dates = sd["dates"];- auto& closes = sd["closes"];- for (size_t i = 0; i < dates.size() && i < closes.size(); i++) {- sym_data[sym][dates[i].get<std::string>()] = closes[i].get<double>();+ if (!output.empty()) {+ auto j = nlohmann::json::parse(output, nullptr, false);+ if (!j.is_discarded() && j.is_object()) {+ if (j.contains("error")) {+ error_msg_ = j["error"].get<std::string>();+ data_loading_ = false;+ return;+ }+ std::map<std::string, std::map<std::string, double>> sym_data;++ for (const auto& sym : symbols) {+ if (!j.contains(sym)) continue;+ auto& sd = j[sym];+ if (sd.is_array()) {+ // Format: [{"date": "2024-01-01", "close": 150.0}, ...]+ for (const auto& rec : sd) {+ if (rec.contains("date") && rec.contains("close")) {+ sym_data[sym][rec["date"].get<std::string>()] = rec["close"].get<double>();+ }+ }+ } else if (sd.is_object() && sd.contains("dates") && sd.contains("closes")) {+ // Legacy format: {"dates": [...], "closes": [...]}+ auto& dates = sd["dates"];+ auto& closes = sd["closes"];+ for (size_t i = 0; i < dates.size() && i < closes.size(); i++) {+ sym_data[sym][dates[i].get<std::string>()] = closes[i].get<double>();+ }+ }}- }- // Collect all dates- std::set<std::string> all_dates;- for (const auto& [sym, dmap] : sym_data) {- if (sym == "SPY") continue;- for (const auto& [d, _] : dmap) all_dates.insert(d);- }+ std::set<std::string> all_dates;+ for (const auto& [sym, dmap] : sym_data) {+ if (sym == "SPY") continue;+ for (const auto& [d, _] : dmap) all_dates.insert(d);+ }- std::vector<std::string> sorted_dates(all_dates.begin(), all_dates.end());- std::sort(sorted_dates.begin(), sorted_dates.end());-- // Build NAV: sum(quantity * close) for each date- nav_values_.clear();- nav_times_.clear();- nav_dates_.clear();-- for (size_t di = 0; di < sorted_dates.size(); di++) {- const auto& date = sorted_dates[di];- double nav = 0;- bool has_any = false;-- for (const auto& h : summary.holdings) {- auto sit = sym_data.find(h.asset.symbol);- if (sit == sym_data.end()) continue;- auto dit = sit->second.find(date);- if (dit != sit->second.end()) {- nav += h.asset.quantity * dit->second;- has_any = true;+ std::vector<std::string> sorted_dates(all_dates.begin(), all_dates.end());+ std::sort(sorted_dates.begin(), sorted_dates.end());++ nav_values_.clear();+ nav_times_.clear();+ nav_dates_.clear();++ for (size_t di = 0; di < sorted_dates.size(); di++) {+ const auto& date = sorted_dates[di];+ double nav = 0;+ bool has_any = false;++ for (const auto& h : holdings_copy) {+ auto sit = sym_data.find(h.symbol);+ if (sit == sym_data.end()) continue;+ auto dit = sit->second.find(date);+ if (dit != sit->second.end()) {+ nav += h.quantity * dit->second;+ has_any = true;+ }}- }- if (has_any) {- nav_values_.push_back(nav);- nav_times_.push_back(static_cast<double>(di));- nav_dates_.push_back(date);+ if (has_any) {+ nav_values_.push_back(nav);+ nav_times_.push_back(static_cast<double>(di));+ nav_dates_.push_back(date);+ }}- }- // Build benchmark returns- bench_returns_.clear();- auto spy_it = sym_data.find("SPY");- if (spy_it != sym_data.end()) {- std::vector<double> spy_closes;- for (const auto& date : sorted_dates) {- auto dit = spy_it->second.find(date);- if (dit != spy_it->second.end())- spy_closes.push_back(dit->second);+ bench_returns_.clear();+ auto spy_it = sym_data.find("SPY");+ if (spy_it != sym_data.end()) {+ std::vector<double> spy_closes;+ for (const auto& date : sorted_dates) {+ auto dit = spy_it->second.find(date);+ if (dit != spy_it->second.end())+ spy_closes.push_back(dit->second);+ }+ for (size_t i = 1; i < spy_closes.size(); i++) {+ if (spy_closes[i - 1] > 0)+ bench_returns_.push_back((spy_closes[i] - spy_closes[i - 1]) / spy_closes[i - 1]);+ }}- for (size_t i = 1; i < spy_closes.size(); i++) {- if (spy_closes[i - 1] > 0)- bench_returns_.push_back((spy_closes[i] - spy_closes[i - 1]) / spy_closes[i - 1]);++ if (nav_values_.size() >= 2) {+ start_nav_ = nav_values_.front();+ current_nav_ = nav_values_.back();+ period_return_ = start_nav_ > 0 ? ((current_nav_ - start_nav_) / start_nav_) * 100.0 : 0.0;+ trading_days_ = static_cast<int>(nav_values_.size());}- }- // Compute period return- if (nav_values_.size() >= 2) {- start_nav_ = nav_values_.front();- current_nav_ = nav_values_.back();- period_return_ = start_nav_ > 0 ? ((current_nav_ - start_nav_) / start_nav_) * 100.0 : 0.0;- trading_days_ = static_cast<int>(nav_values_.size());+ data_loaded_ = true;}-- data_loaded_ = true;}+ } catch (const std::exception& e) {+ LOG_ERROR("PerformanceView", "Failed to fetch historical: %s", e.what());}- } catch (const std::exception& e) {- LOG_ERROR("PerformanceView", "Failed to fetch historical: %s", e.what());- }- data_loading_ = false;+ data_loading_ = false;+ }).detach();}// ============================================================================@@ -246,6 +286,8 @@ void PerformanceView::render_nav_chart() {if (!data_loaded_ || nav_values_.size() < 2) {if (data_loading_) {theme::LoadingSpinner("Loading historical data...");+ } else if (!error_msg_.empty()) {+ ImGui::TextColored(theme::colors::MARKET_RED, "Error: %s", error_msg_.c_str());} else {ImGui::TextColored(theme::colors::TEXT_DIM, "No historical data available.");}diff --git a/fincept-cpp/src/screens/portfolio/views/performance_view.h b/fincept-cpp/src/screens/portfolio/views/performance_view.hindex 8812adb93..cc542a18f 100644--- a/fincept-cpp/src/screens/portfolio/views/performance_view.h+++ b/fincept-cpp/src/screens/portfolio/views/performance_view.h@@ -25,6 +25,7 @@ private:bool data_loading_ = false;std::string loaded_for_portfolio_;int loaded_for_period_ = -1;+ std::string error_msg_;// Benchmark datastd::vector<double> bench_returns_;diff --git a/fincept-cpp/src/screens/portfolio/views/planning_view.cpp b/fincept-cpp/src/screens/portfolio/views/planning_view.cppindex 51b44e2c9..bb82d2f5e 100644--- a/fincept-cpp/src/screens/portfolio/views/planning_view.cpp+++ b/fincept-cpp/src/screens/portfolio/views/planning_view.cpp@@ -3,12 +3,14 @@#include "planning_view.h"#include "python/python_runner.h"+#include "storage/cache_service.h"#include "ui/theme.h"#include "core/logger.h"#include <imgui.h>#include <cstdio>#include <cstdlib>#include <cmath>+#include <thread>namespace fincept::portfolio {@@ -30,6 +32,11 @@ void PlanningView::render(const PortfolioSummary& summary) {ImGui::PopStyleVar();ImGui::Separator();+ if (!error_.empty()) {+ ImGui::TextColored(theme::colors::MARKET_RED, "[Error] %s", error_.c_str());+ ImGui::Spacing();+ }+if (sub_tab_ == 0) {// Asset allocation from current holdingsif (!allocation_loaded_ && !loading_) {@@ -174,32 +181,64 @@ void PlanningView::render(const PortfolioSummary& summary) {void PlanningView::fetch_allocation(const PortfolioSummary& summary) {if (loading_) return;loading_ = true;- try {- nlohmann::json req;- auto holdings = nlohmann::json::array();- for (const auto& h : summary.holdings) {- holdings.push_back({- {"symbol", h.asset.symbol},- {"weight", h.weight / 100.0},- {"value", h.market_value}- });- }- req["holdings"] = holdings;-- auto result = python::execute_with_stdin(- "Analytics/portfolioManagement/portfolio_analytics.py",- {"allocation_analysis"}, req.dump());+ error_.clear();++ nlohmann::json holdings = nlohmann::json::array();+ for (const auto& h : summary.holdings) {+ holdings.push_back({+ {"symbol", h.asset.symbol},+ {"weight", h.weight / 100.0},+ {"value", h.market_value}+ });+ }+ std::string sym_key;+ for (const auto& h : summary.holdings) sym_key += h.asset.symbol + "_";++ std::thread([this, holdings, sym_key]() {+ try {+ nlohmann::json req;+ req["holdings"] = holdings;++ auto& cache = CacheService::instance();+ std::string ck = CacheService::make_key("reference", "allocation-analysis",+ sym_key.substr(0, std::min((size_t)64, sym_key.size())));++ std::string output;+ auto cached = cache.get(ck);+ if (cached && !cached->empty()) { output = *cached; }+ else {+ auto result = python::execute_with_stdin(+ "Analytics/portfolioManagement/portfolio_analytics.py",+ {"allocation_analysis"}, req.dump());+ if (result.success && !result.output.empty()) {+ output = result.output;+ auto check = nlohmann::json::parse(output, nullptr, false);+ if (!check.is_discarded() && !check.contains("error"))+ cache.set(ck, output, "reference", CacheTTL::FIFTEEN_MIN);+ } else if (!result.error.empty()) {+ error_ = result.error;+ }+ }- if (result.success && !result.output.empty()) {- auto j = nlohmann::json::parse(result.output, nullptr, false);- if (!j.is_discarded()) { allocation_result_ = j; }+ if (!output.empty()) {+ auto j = nlohmann::json::parse(output, nullptr, false);+ if (!j.is_discarded()) {+ if (j.contains("error"))+ error_ = j["error"].get<std::string>();+ else+ allocation_result_ = j;+ }+ } else if (error_.empty()) {+ error_ = "Script returned empty output";+ }+ allocation_loaded_ = true;+ } catch (const std::exception& e) {+ error_ = e.what();+ LOG_ERROR("PlanningView", "Allocation analysis failed: %s", e.what());+ allocation_loaded_ = true;}- allocation_loaded_ = true;- } catch (const std::exception& e) {- LOG_ERROR("PlanningView", "Allocation analysis failed: %s", e.what());- allocation_loaded_ = true; // show table anyway- }- loading_ = false;+ loading_ = false;+ }).detach();}void PlanningView::fetch_retirement() {diff --git a/fincept-cpp/src/screens/portfolio/views/planning_view.h b/fincept-cpp/src/screens/portfolio/views/planning_view.hindex f6ed8c686..61703ff41 100644--- a/fincept-cpp/src/screens/portfolio/views/planning_view.h+++ b/fincept-cpp/src/screens/portfolio/views/planning_view.h@@ -18,6 +18,7 @@ private:bool retirement_loaded_ = false;bool loading_ = false;std::string loaded_for_portfolio_;+ std::string error_;// Retirement planner inputschar current_age_[8] = "30";diff --git a/fincept-cpp/src/screens/portfolio/views/quantstats_view.cpp b/fincept-cpp/src/screens/portfolio/views/quantstats_view.cppindex 08216884a..f98c84d1d 100644--- a/fincept-cpp/src/screens/portfolio/views/quantstats_view.cpp+++ b/fincept-cpp/src/screens/portfolio/views/quantstats_view.cpp@@ -3,10 +3,12 @@#include "quantstats_view.h"#include "python/python_runner.h"+#include "storage/cache_service.h"#include "ui/theme.h"#include "core/logger.h"#include <imgui.h>#include <cstdio>+#include <thread>namespace fincept::portfolio {@@ -39,6 +41,11 @@ void QuantStatsView::render(const PortfolioSummary& summary) {ImGui::Separator();+ if (!error_.empty()) {+ ImGui::TextColored(theme::colors::MARKET_RED, "[Error] %s", error_.c_str());+ ImGui::Spacing();+ }+if (sub_tab_ == 0) {if (!qs_loaded_) {ImGui::TextColored(theme::colors::TEXT_DIM,@@ -130,53 +137,115 @@ void QuantStatsView::render_stats_table(const nlohmann::json& data) {void QuantStatsView::fetch_quantstats(const PortfolioSummary& summary) {if (loading_) return;loading_ = true;- try {- nlohmann::json req;- std::vector<std::string> symbols;- std::vector<double> weights;- for (const auto& h : summary.holdings) {- symbols.push_back(h.asset.symbol);- weights.push_back(h.weight / 100.0);- }- req["symbols"] = symbols;- req["weights"] = weights;+ error_.clear();- auto result = python::execute_with_stdin(- "Analytics/portfolioManagement/quantstats_analysis.py",- {"portfolio_stats"}, req.dump());+ std::vector<std::string> symbols;+ std::vector<double> weights;+ for (const auto& h : summary.holdings) {+ symbols.push_back(h.asset.symbol);+ weights.push_back(h.weight / 100.0);+ }- if (result.success && !result.output.empty()) {- auto j = nlohmann::json::parse(result.output, nullptr, false);- if (!j.is_discarded()) { qs_result_ = j; qs_loaded_ = true; }+ std::thread([this, symbols, weights]() {+ try {+ nlohmann::json req;+ req["symbols"] = symbols;+ req["weights"] = weights;++ auto& cache = CacheService::instance();+ std::string sym_key;+ for (const auto& s : symbols) sym_key += s + "_";+ std::string cache_key = CacheService::make_key("reference", "quantstats", sym_key);++ std::string output;+ auto cached_qs = cache.get(cache_key);+ if (cached_qs && !cached_qs->empty()) {+ output = *cached_qs;+ } else {+ auto result = python::execute_with_stdin(+ "Analytics/portfolioManagement/quantstats_analysis.py",+ {"portfolio_stats"}, req.dump());+ if (result.success && !result.output.empty()) {+ output = result.output;+ auto check = nlohmann::json::parse(output, nullptr, false);+ if (!check.is_discarded() && !check.contains("error"))+ cache.set(cache_key, output, "reference", CacheTTL::FIFTEEN_MIN);+ } else if (!result.error.empty()) {+ error_ = result.error;+ }+ }++ if (!output.empty()) {+ auto j = nlohmann::json::parse(output, nullptr, false);+ if (!j.is_discarded()) {+ if (j.contains("error"))+ error_ = j["error"].get<std::string>();+ else { qs_result_ = j; qs_loaded_ = true; }+ }+ } else if (error_.empty()) {+ error_ = "Script returned empty output";+ }+ } catch (const std::exception& e) {+ error_ = e.what();+ LOG_ERROR("QuantStatsView", "QuantStats failed: %s", e.what());}- } catch (const std::exception& e) {- LOG_ERROR("QuantStatsView", "QuantStats failed: %s", e.what());- }- loading_ = false;+ loading_ = false;+ }).detach();}void QuantStatsView::fetch_ffn(const PortfolioSummary& summary) {if (loading_) return;loading_ = true;- try {- nlohmann::json req;- std::vector<std::string> symbols;- for (const auto& h : summary.holdings)- symbols.push_back(h.asset.symbol);- req["symbols"] = symbols;-- auto result = python::execute_with_stdin(- "Analytics/portfolioManagement/ffn_analysis.py",- {"run_ffn"}, req.dump());-- if (result.success && !result.output.empty()) {- auto j = nlohmann::json::parse(result.output, nullptr, false);- if (!j.is_discarded()) { ffn_result_ = j; ffn_loaded_ = true; }+ error_.clear();++ std::vector<std::string> symbols;+ for (const auto& h : summary.holdings)+ symbols.push_back(h.asset.symbol);++ std::thread([this, symbols]() {+ try {+ nlohmann::json req;+ req["symbols"] = symbols;++ auto& cache_svc = CacheService::instance();+ std::string ffn_sym_key;+ for (const auto& s : symbols) ffn_sym_key += s + "_";+ std::string ffn_cache_key = CacheService::make_key("reference", "ffn", ffn_sym_key);++ std::string ffn_output;+ auto cached_ffn = cache_svc.get(ffn_cache_key);+ if (cached_ffn && !cached_ffn->empty()) {+ ffn_output = *cached_ffn;+ } else {+ auto result = python::execute_with_stdin(+ "Analytics/portfolioManagement/ffn_analysis.py",+ {"run_ffn"}, req.dump());+ if (result.success && !result.output.empty()) {+ ffn_output = result.output;+ auto check = nlohmann::json::parse(ffn_output, nullptr, false);+ if (!check.is_discarded() && !check.contains("error"))+ cache_svc.set(ffn_cache_key, ffn_output, "reference", CacheTTL::FIFTEEN_MIN);+ } else if (!result.error.empty()) {+ error_ = result.error;+ }+ }++ if (!ffn_output.empty()) {+ auto j = nlohmann::json::parse(ffn_output, nullptr, false);+ if (!j.is_discarded()) {+ if (j.contains("error"))+ error_ = j["error"].get<std::string>();+ else { ffn_result_ = j; ffn_loaded_ = true; }+ }+ } else if (error_.empty()) {+ error_ = "Script returned empty output";+ }+ } catch (const std::exception& e) {+ error_ = e.what();+ LOG_ERROR("QuantStatsView", "FFN failed: %s", e.what());}- } catch (const std::exception& e) {- LOG_ERROR("QuantStatsView", "FFN failed: %s", e.what());- }- loading_ = false;+ loading_ = false;+ }).detach();}} // namespace fincept::portfoliodiff --git a/fincept-cpp/src/screens/portfolio/views/quantstats_view.h b/fincept-cpp/src/screens/portfolio/views/quantstats_view.hindex 259e35609..47911b33c 100644--- a/fincept-cpp/src/screens/portfolio/views/quantstats_view.h+++ b/fincept-cpp/src/screens/portfolio/views/quantstats_view.h@@ -18,6 +18,7 @@ private:bool ffn_loaded_ = false;bool loading_ = false;std::string loaded_for_portfolio_;+ std::string error_;void fetch_quantstats(const PortfolioSummary& summary);void fetch_ffn(const PortfolioSummary& summary);diff --git a/fincept-cpp/src/screens/portfolio/views/reports_view.cpp b/fincept-cpp/src/screens/portfolio/views/reports_view.cppindex 47f309fa5..83826610b 100644--- a/fincept-cpp/src/screens/portfolio/views/reports_view.cpp+++ b/fincept-cpp/src/screens/portfolio/views/reports_view.cpp@@ -3,10 +3,12 @@#include "reports_view.h"#include "python/python_runner.h"+#include "storage/cache_service.h"#include "ui/theme.h"#include "core/logger.h"#include <imgui.h>#include <cstdio>+#include <thread>namespace fincept::portfolio {@@ -39,6 +41,11 @@ void ReportsView::render(const PortfolioSummary& summary) {ImGui::Separator();+ if (!error_.empty()) {+ ImGui::TextColored(theme::colors::MARKET_RED, "[Error] %s", error_.c_str());+ ImGui::Spacing();+ }+if (sub_tab_ == 0) {if (!tax_loaded_) {ImGui::TextColored(theme::colors::TEXT_DIM,@@ -93,57 +100,121 @@ void ReportsView::render(const PortfolioSummary& summary) {void ReportsView::fetch_tax_report(const PortfolioSummary& summary) {if (loading_) return;loading_ = true;- try {- nlohmann::json req;- auto txns = nlohmann::json::array();- for (const auto& h : summary.holdings) {- txns.push_back({- {"symbol", h.asset.symbol},- {"quantity", h.asset.quantity},- {"avg_price", h.asset.avg_buy_price},- {"current_price", h.current_price}- });- }- req["holdings"] = txns;- req["portfolio_name"] = summary.portfolio.name;+ error_.clear();++ nlohmann::json txns = nlohmann::json::array();+ for (const auto& h : summary.holdings) {+ txns.push_back({+ {"symbol", h.asset.symbol},+ {"quantity", h.asset.quantity},+ {"avg_price", h.asset.avg_buy_price},+ {"current_price", h.current_price}+ });+ }+ std::string pf_name = summary.portfolio.name;+ std::string sym_key;+ for (const auto& h : summary.holdings) sym_key += h.asset.symbol + "_";++ std::thread([this, txns, pf_name, sym_key]() {+ try {+ nlohmann::json req;+ req["holdings"] = txns;+ req["portfolio_name"] = pf_name;- auto result = python::execute_with_stdin(- "Analytics/portfolioManagement/portfolio_analytics.py",- {"tax_report"}, req.dump());+ auto& cache = CacheService::instance();+ std::string ck = CacheService::make_key("reference", "tax-report",+ sym_key.substr(0, std::min((size_t)64, sym_key.size())));- if (result.success && !result.output.empty()) {- auto j = nlohmann::json::parse(result.output, nullptr, false);- if (!j.is_discarded()) { tax_result_ = j; tax_loaded_ = true; }+ std::string output;+ auto cached = cache.get(ck);+ if (cached && !cached->empty()) { output = *cached; }+ else {+ auto result = python::execute_with_stdin(+ "Analytics/portfolioManagement/portfolio_analytics.py",+ {"tax_report"}, req.dump());+ if (result.success && !result.output.empty()) {+ output = result.output;+ auto check = nlohmann::json::parse(output, nullptr, false);+ if (!check.is_discarded() && !check.contains("error"))+ cache.set(ck, output, "reference", CacheTTL::FIFTEEN_MIN);+ } else if (!result.error.empty()) {+ error_ = result.error;+ }+ }++ if (!output.empty()) {+ auto j = nlohmann::json::parse(output, nullptr, false);+ if (!j.is_discarded()) {+ if (j.contains("error"))+ error_ = j["error"].get<std::string>();+ else { tax_result_ = j; tax_loaded_ = true; }+ }+ } else if (error_.empty()) {+ error_ = "Script returned empty output";+ }+ } catch (const std::exception& e) {+ error_ = e.what();+ LOG_ERROR("ReportsView", "Tax report failed: %s", e.what());}- } catch (const std::exception& e) {- LOG_ERROR("ReportsView", "Tax report failed: %s", e.what());- }- loading_ = false;+ loading_ = false;+ }).detach();}void ReportsView::fetch_pme(const PortfolioSummary& summary) {if (loading_) return;loading_ = true;- try {- nlohmann::json req;- std::vector<std::string> symbols;- for (const auto& h : summary.holdings)- symbols.push_back(h.asset.symbol);- req["symbols"] = symbols;- req["portfolio_name"] = summary.portfolio.name;-- auto result = python::execute_with_stdin(- "Analytics/portfolioManagement/portfolio_analytics.py",- {"pme_analysis"}, req.dump());-- if (result.success && !result.output.empty()) {- auto j = nlohmann::json::parse(result.output, nullptr, false);- if (!j.is_discarded()) { pme_result_ = j; pme_loaded_ = true; }+ error_.clear();++ std::vector<std::string> symbols;+ for (const auto& h : summary.holdings)+ symbols.push_back(h.asset.symbol);+ std::string pf_name = summary.portfolio.name;++ std::thread([this, symbols, pf_name]() {+ try {+ nlohmann::json req;+ req["symbols"] = symbols;+ req["portfolio_name"] = pf_name;++ auto& cache_p = CacheService::instance();+ std::string psym;+ for (const auto& s : symbols) psym += s + "_";+ std::string pck = CacheService::make_key("reference", "pme-analysis",+ psym.substr(0, std::min((size_t)64, psym.size())));++ std::string p_out;+ auto cached_p = cache_p.get(pck);+ if (cached_p && !cached_p->empty()) { p_out = *cached_p; }+ else {+ auto result = python::execute_with_stdin(+ "Analytics/portfolioManagement/portfolio_analytics.py",+ {"pme_analysis"}, req.dump());+ if (result.success && !result.output.empty()) {+ p_out = result.output;+ auto check = nlohmann::json::parse(p_out, nullptr, false);+ if (!check.is_discarded() && !check.contains("error"))+ cache_p.set(pck, p_out, "reference", CacheTTL::FIFTEEN_MIN);+ } else if (!result.error.empty()) {+ error_ = result.error;+ }+ }++ if (!p_out.empty()) {+ auto j = nlohmann::json::parse(p_out, nullptr, false);+ if (!j.is_discarded()) {+ if (j.contains("error"))+ error_ = j["error"].get<std::string>();+ else { pme_result_ = j; pme_loaded_ = true; }+ }+ } else if (error_.empty()) {+ error_ = "Script returned empty output";+ }+ } catch (const std::exception& e) {+ error_ = e.what();+ LOG_ERROR("ReportsView", "PME analysis failed: %s", e.what());}- } catch (const std::exception& e) {- LOG_ERROR("ReportsView", "PME analysis failed: %s", e.what());- }- loading_ = false;+ loading_ = false;+ }).detach();}} // namespace fincept::portfoliodiff --git a/fincept-cpp/src/screens/portfolio/views/reports_view.h b/fincept-cpp/src/screens/portfolio/views/reports_view.hindex d960bfae1..d964a6838 100644--- a/fincept-cpp/src/screens/portfolio/views/reports_view.h+++ b/fincept-cpp/src/screens/portfolio/views/reports_view.h@@ -18,6 +18,7 @@ private:bool pme_loaded_ = false;bool loading_ = false;std::string loaded_for_portfolio_;+ std::string error_;void fetch_tax_report(const PortfolioSummary& summary);void fetch_pme(const PortfolioSummary& summary);diff --git a/fincept-cpp/src/screens/portfolio/views/risk_view.cpp b/fincept-cpp/src/screens/portfolio/views/risk_view.cppindex c6e85123c..62ce908cc 100644--- a/fincept-cpp/src/screens/portfolio/views/risk_view.cpp+++ b/fincept-cpp/src/screens/portfolio/views/risk_view.cpp@@ -3,11 +3,13 @@#include "risk_view.h"#include "python/python_runner.h"+#include "storage/cache_service.h"#include "ui/theme.h"#include "core/logger.h"#include <imgui.h>#include <algorithm>#include <cstdio>+#include <thread>namespace fincept::portfolio {@@ -121,33 +123,57 @@ void RiskView::fetch_overview(const PortfolioSummary& summary) {loading_ = true;error_.clear();- try {- nlohmann::json req;- req["symbols"] = build_symbols_csv(summary);- req["weights"] = build_weights_array(summary);- req["portfolio_value"] = summary.total_market_value;- req["function"] = "comprehensive_risk_analysis";-- auto result = python::execute_with_stdin(- "Analytics/fortitudo_tech_wrapper/fortitudo_service.py",- {"comprehensive_risk_analysis"}, req.dump());-- if (result.success && !result.output.empty()) {- auto j = nlohmann::json::parse(result.output, nullptr, false);- if (!j.is_discarded()) {- overview_result_ = j;- overview_loaded_ = true;- } else {- error_ = "Failed to parse analysis results";+ auto sym_csv = build_symbols_csv(summary);+ auto weights = build_weights_array(summary);+ double mv = summary.total_market_value;+ std::thread([this, sym_csv, weights, mv]() {+ try {+ nlohmann::json req;+ req["symbols"] = sym_csv;+ req["weights"] = weights;+ req["portfolio_value"] = mv;+ req["function"] = "full_analysis";++ auto& cache = CacheService::instance();+ std::string ck = CacheService::make_key("reference", "risk-overview", sym_csv.substr(0, std::min((size_t)64, sym_csv.size())));+ std::string output;+ auto cached_r = cache.get(ck);+ if (cached_r && !cached_r->empty()) { output = *cached_r; }+ else {+ auto result = python::execute_with_stdin(+ "Analytics/fortitudo_tech_wrapper/fortitudo_service.py",+ {"full_analysis"}, req.dump());+ if (result.success && !result.output.empty()) {+ output = result.output;+ auto check = nlohmann::json::parse(output, nullptr, false);+ if (!check.is_discarded() && !check.contains("error"))+ cache.set(ck, output, "reference", CacheTTL::FIFTEEN_MIN);+ } else if (!result.error.empty()) {+ error_ = result.error;+ }+ }++ if (!output.empty()) {+ auto j = nlohmann::json::parse(output, nullptr, false);+ if (!j.is_discarded()) {+ if (j.contains("error")) {+ error_ = j["error"].get<std::string>();+ } else {+ overview_result_ = j;+ overview_loaded_ = true;+ }+ } else {+ error_ = "Failed to parse analysis results";+ }+ } else if (error_.empty()) {+ error_ = "Python script returned empty output";}- } else {- error_ = result.error.empty() ? "Python script failed" : result.error;+ } catch (const std::exception& e) {+ error_ = e.what();+ LOG_ERROR("RiskView", "Overview fetch failed: %s", e.what());}- } catch (const std::exception& e) {- error_ = e.what();- LOG_ERROR("RiskView", "Overview fetch failed: %s", e.what());- }- loading_ = false;+ loading_ = false;+ }).detach();}void RiskView::fetch_stress(const PortfolioSummary& summary) {@@ -155,29 +181,51 @@ void RiskView::fetch_stress(const PortfolioSummary& summary) {loading_ = true;error_.clear();- try {- nlohmann::json req;- req["symbols"] = build_symbols_csv(summary);- req["half_life"] = 252;-- auto result = python::execute_with_stdin(- "Analytics/fortitudo_tech_wrapper/fortitudo_service.py",- {"exp_decay_and_covariance"}, req.dump());+ auto sym_csv = build_symbols_csv(summary);+ std::thread([this, sym_csv]() {+ try {+ nlohmann::json req;+ req["returns"] = sym_csv;+ req["half_life"] = 252;++ auto& cache_s = CacheService::instance();+ std::string sc = CacheService::make_key("reference", "risk-stress", sym_csv.substr(0, std::min((size_t)64, sym_csv.size())));+ std::string s_out;+ auto cs = cache_s.get(sc);+ if (cs && !cs->empty()) { s_out = *cs; }+ else {+ auto result = python::execute_with_stdin(+ "Analytics/fortitudo_tech_wrapper/fortitudo_service.py",+ {"exp_decay_weighting"}, req.dump());+ if (result.success && !result.output.empty()) {+ s_out = result.output;+ auto check = nlohmann::json::parse(s_out, nullptr, false);+ if (!check.is_discarded() && !check.contains("error"))+ cache_s.set(sc, s_out, "reference", CacheTTL::FIFTEEN_MIN);+ } else if (!result.error.empty()) {+ error_ = result.error;+ }+ }- if (result.success && !result.output.empty()) {- auto j = nlohmann::json::parse(result.output, nullptr, false);- if (!j.is_discarded()) {- stress_result_ = j;- stress_loaded_ = true;+ if (!s_out.empty()) {+ auto j = nlohmann::json::parse(s_out, nullptr, false);+ if (!j.is_discarded()) {+ if (j.contains("error")) {+ error_ = j["error"].get<std::string>();+ } else {+ stress_result_ = j;+ stress_loaded_ = true;+ }+ }+ } else if (error_.empty()) {+ error_ = "Python script returned empty output";}- } else {- error_ = result.error.empty() ? "Python script failed" : result.error;+ } catch (const std::exception& e) {+ error_ = e.what();+ LOG_ERROR("RiskView", "Stress fetch failed: %s", e.what());}- } catch (const std::exception& e) {- error_ = e.what();- LOG_ERROR("RiskView", "Stress fetch failed: %s", e.what());- }- loading_ = false;+ loading_ = false;+ }).detach();}void RiskView::fetch_fortitudo(const PortfolioSummary& summary) {@@ -185,29 +233,50 @@ void RiskView::fetch_fortitudo(const PortfolioSummary& summary) {loading_ = true;error_.clear();- try {- nlohmann::json req;- req["weights"] = build_weights_array(summary);- req["n_scenarios"] = 1000;-- auto result = python::execute_with_stdin(- "Analytics/fortitudo_tech_wrapper/fortitudo_service.py",- {"entropy_pooling_and_stacking"}, req.dump());+ auto weights = build_weights_array(summary);+ std::thread([this, weights]() {+ try {+ nlohmann::json req;+ req["weights"] = weights;++ auto& cache_f = CacheService::instance();+ std::string fc = CacheService::make_key("reference", "risk-fortitudo", weights.dump().substr(0, 64));+ std::string f_out;+ auto cf = cache_f.get(fc);+ if (cf && !cf->empty()) { f_out = *cf; }+ else {+ auto result = python::execute_with_stdin(+ "Analytics/fortitudo_tech_wrapper/fortitudo_service.py",+ {"entropy_pooling"}, req.dump());+ if (result.success && !result.output.empty()) {+ f_out = result.output;+ auto check = nlohmann::json::parse(f_out, nullptr, false);+ if (!check.is_discarded() && !check.contains("error"))+ cache_f.set(fc, f_out, "reference", CacheTTL::FIFTEEN_MIN);+ } else if (!result.error.empty()) {+ error_ = result.error;+ }+ }- if (result.success && !result.output.empty()) {- auto j = nlohmann::json::parse(result.output, nullptr, false);- if (!j.is_discarded()) {- fortitudo_result_ = j;- fortitudo_loaded_ = true;+ if (!f_out.empty()) {+ auto j = nlohmann::json::parse(f_out, nullptr, false);+ if (!j.is_discarded()) {+ if (j.contains("error")) {+ error_ = j["error"].get<std::string>();+ } else {+ fortitudo_result_ = j;+ fortitudo_loaded_ = true;+ }+ }+ } else if (error_.empty()) {+ error_ = "Python script returned empty output";}- } else {- error_ = result.error.empty() ? "Python script failed" : result.error;+ } catch (const std::exception& e) {+ error_ = e.what();+ LOG_ERROR("RiskView", "Fortitudo fetch failed: %s", e.what());}- } catch (const std::exception& e) {- error_ = e.what();- LOG_ERROR("RiskView", "Fortitudo fetch failed: %s", e.what());- }- loading_ = false;+ loading_ = false;+ }).detach();}void RiskView::fetch_frontiers(const PortfolioSummary& summary) {@@ -215,30 +284,52 @@ void RiskView::fetch_frontiers(const PortfolioSummary& summary) {loading_ = true;error_.clear();- try {- nlohmann::json req;- req["symbols"] = build_symbols_csv(summary);- req["n_points"] = 20;- req["alpha"] = 0.05;-- auto result = python::execute_with_stdin(- "Analytics/fortitudo_tech_wrapper/fortitudo_service.py",- {"efficient_frontiers"}, req.dump());-- if (result.success && !result.output.empty()) {- auto j = nlohmann::json::parse(result.output, nullptr, false);- if (!j.is_discarded()) {- frontier_result_ = j;- frontier_loaded_ = true;+ auto sym_csv = build_symbols_csv(summary);+ std::thread([this, sym_csv]() {+ try {+ nlohmann::json req;+ req["returns"] = sym_csv;+ req["n_points"] = 20;+ req["alpha"] = 0.05;++ auto& cache_fr = CacheService::instance();+ std::string frc = CacheService::make_key("reference", "risk-frontier", sym_csv.substr(0, std::min((size_t)64, sym_csv.size())));+ std::string fr_out;+ auto cfr = cache_fr.get(frc);+ if (cfr && !cfr->empty()) { fr_out = *cfr; }+ else {+ auto result = python::execute_with_stdin(+ "Analytics/fortitudo_tech_wrapper/fortitudo_service.py",+ {"efficient_frontier_mv"}, req.dump());+ if (result.success && !result.output.empty()) {+ fr_out = result.output;+ auto check = nlohmann::json::parse(fr_out, nullptr, false);+ if (!check.is_discarded() && !check.contains("error"))+ cache_fr.set(frc, fr_out, "reference", CacheTTL::FIFTEEN_MIN);+ } else if (!result.error.empty()) {+ error_ = result.error;+ }}- } else {- error_ = result.error.empty() ? "Python script failed" : result.error;++ if (!fr_out.empty()) {+ auto j = nlohmann::json::parse(fr_out, nullptr, false);+ if (!j.is_discarded()) {+ if (j.contains("error")) {+ error_ = j["error"].get<std::string>();+ } else {+ frontier_result_ = j;+ frontier_loaded_ = true;+ }+ }+ } else if (error_.empty()) {+ error_ = "Python script returned empty output";+ }+ } catch (const std::exception& e) {+ error_ = e.what();+ LOG_ERROR("RiskView", "Frontier fetch failed: %s", e.what());}- } catch (const std::exception& e) {- error_ = e.what();- LOG_ERROR("RiskView", "Frontier fetch failed: %s", e.what());- }- loading_ = false;+ loading_ = false;+ }).detach();}// ============================================================================diff --git a/fincept-cpp/src/screens/quantlib/quantlib_api.cpp b/fincept-cpp/src/screens/quantlib/quantlib_api.cppindex 2820dddc6..c7fb1e1eb 100644--- a/fincept-cpp/src/screens/quantlib/quantlib_api.cpp+++ b/fincept-cpp/src/screens/quantlib/quantlib_api.cpp@@ -1,6 +1,7 @@#include "quantlib_api.h"#include "http/http_client.h"#include "auth/auth_manager.h"+#include "storage/cache_service.h"#include "core/logger.h"#include <chrono>@@ -70,6 +71,24 @@ std::future<ApiResult> QuantLibApi::get(const std::string& path,}}+ // Check cache for GET requests+ auto& cache = CacheService::instance();+ std::string params_key;+ for (auto& [k, v] : params) params_key += k + "=" + v + "&";+ std::string cache_key = CacheService::make_key("api-response", "quantlib", path + "_" + params_key);++ auto cached = cache.get(cache_key);+ if (cached && !cached->empty()) {+ auto end = std::chrono::high_resolution_clock::now();+ result.elapsed_ms = std::chrono::duration<double, std::milli>(end - start).count();+ result.data = nlohmann::json::parse(*cached, nullptr, false);+ if (!result.data.is_discarded()) {+ result.success = true;+ result.status_code = 200;+ return result;+ }+ }+std::string api_key = get_api_key();std::map<std::string, std::string> headers;if (!api_key.empty()) {@@ -86,6 +105,9 @@ std::future<ApiResult> QuantLibApi::get(const std::string& path,if (resp.success) {result.data = resp.json_body();result.success = true;+ if (!resp.body.empty()) {+ cache.set(cache_key, resp.body, "api-response", CacheTTL::FIFTEEN_MIN);+ }} else {result.error = resp.error.empty()? ("HTTP " + std::to_string(resp.status_code))diff --git a/fincept-cpp/src/screens/research/research_data.cpp b/fincept-cpp/src/screens/research/research_data.cppindex a5254d58f..b87de6cd5 100644--- a/fincept-cpp/src/screens/research/research_data.cpp+++ b/fincept-cpp/src/screens/research/research_data.cpp@@ -1,5 +1,6 @@#include "research_data.h"#include "python/python_runner.h"+#include "storage/cache_service.h"#include <nlohmann/json.hpp>#include <thread>#include <cmath>@@ -69,9 +70,22 @@ void ResearchData::fetch(const std::string& symbol, ChartPeriod period) {std::string per = chart_period_yf(period);std::thread([this, sym, per]() {+ auto& cache = CacheService::instance();++ // Helper: try cache, fallback to Python, cache on success+ auto cached_python = [&](const std::string& args, const std::string& cache_cat,+ const std::string& cache_sub, int64_t ttl) -> std::string {+ std::string key = CacheService::make_key(cache_cat, cache_sub, sym);+ auto cached = cache.get(key);+ if (cached && !cached->empty()) return *cached;+ std::string out = run_python(args);+ if (!out.empty()) cache.set(key, out, cache_cat, ttl);+ return out;+ };+// 1. Fetch quote{- std::string out = run_python("quote " + sym);+ std::string out = cached_python("quote " + sym, "market-quotes", "research-quote", CacheTTL::FIVE_MIN);if (!out.empty()) {std::lock_guard<std::mutex> lock(mutex_);parse_quote(out);@@ -80,7 +94,7 @@ void ResearchData::fetch(const std::string& symbol, ChartPeriod period) {// 2. Fetch stock info{- std::string out = run_python("info " + sym);+ std::string out = cached_python("info " + sym, "reference", "research-info", CacheTTL::ONE_HOUR);if (!out.empty()) {std::lock_guard<std::mutex> lock(mutex_);parse_stock_info(out);@@ -89,7 +103,15 @@ void ResearchData::fetch(const std::string& symbol, ChartPeriod period) {// 3. Fetch historical data{- std::string out = run_python("historical_period " + sym + " " + per + " 1d");+ std::string hist_key = CacheService::make_key("market-quotes", "research-hist", sym + "_" + per);+ std::string out;+ auto cached_hist = cache.get(hist_key);+ if (cached_hist && !cached_hist->empty()) {+ out = *cached_hist;+ } else {+ out = run_python("historical_period " + sym + " " + per + " 1d");+ if (!out.empty()) cache.set(hist_key, out, "market-quotes", CacheTTL::FIVE_MIN);+ }if (!out.empty()) {std::lock_guard<std::mutex> lock(mutex_);parse_historical(out);@@ -98,7 +120,7 @@ void ResearchData::fetch(const std::string& symbol, ChartPeriod period) {// 4. Fetch financials{- std::string out = run_python("financials " + sym);+ std::string out = cached_python("financials " + sym, "reference", "research-financials", CacheTTL::ONE_HOUR);if (!out.empty()) {std::lock_guard<std::mutex> lock(mutex_);parse_financials(out);@@ -123,7 +145,16 @@ void ResearchData::fetch_news(const std::string& symbol) {std::string sym = symbol;std::thread([this, sym]() {- std::string out = run_python("news " + sym + " 20");+ auto& cache = CacheService::instance();+ std::string cache_key = CacheService::make_key("news", "research-news", sym);+ std::string out;+ auto cached = cache.get(cache_key);+ if (cached && !cached->empty()) {+ out = *cached;+ } else {+ out = run_python("news " + sym + " 20");+ if (!out.empty()) cache.set(cache_key, out, "news", CacheTTL::TEN_MIN);+ }if (!out.empty()) {std::lock_guard<std::mutex> lock(mutex_);parse_news(out);diff --git a/fincept-cpp/src/screens/settings/sections/llm_config_section.cpp b/fincept-cpp/src/screens/settings/sections/llm_config_section.cppindex 393ac6ea2..6cbb6a100 100644--- a/fincept-cpp/src/screens/settings/sections/llm_config_section.cpp+++ b/fincept-cpp/src/screens/settings/sections/llm_config_section.cpp@@ -11,9 +11,30 @@ void LLMConfigSection::init() {if (initialized_) return;load_configs();load_global_settings();+ ensure_fincept_config();initialized_ = true;}+void LLMConfigSection::ensure_fincept_config() {+ // Auto-create Fincept LLM config if user has a fincept_api_key (set on login)+ auto api_key = db::ops::get_setting("fincept_api_key");+ if (!api_key || api_key->empty()) return;++ // Check if Fincept config already exists+ for (auto& cfg : configs_) {+ if (cfg.provider == "Fincept") return; // already exists+ }++ // Auto-create it+ db::LLMConfig cfg;+ cfg.provider = "Fincept";+ cfg.api_key = *api_key;+ cfg.model = "fincept-llm";+ cfg.is_active = false;+ db::ops::save_llm_config(cfg);+ load_configs();+}+void LLMConfigSection::load_configs() {configs_ = db::ops::get_llm_configs();}@@ -172,52 +193,133 @@ void LLMConfigSection::render_providers() {ImGui::BeginChild("##prov_config", ImVec2(config_w, 0), ImGuiChildFlags_Borders);if (selected_provider_ >= 0 && selected_provider_ < (int)providers.size()) {- char header[128];- std::snprintf(header, sizeof(header), "CONFIGURE: %s", providers[selected_provider_]);- ImGui::TextColored(ACCENT, "%s", header);- ImGui::Separator();+ const char* prov_name = providers[selected_provider_];+ bool is_fincept = (std::string(prov_name) == "Fincept");++ if (is_fincept) {+ // ── Special Fincept auto-configured panel ──+ render_fincept_panel();+ } else {+ // ── Standard provider config form ──+ char header[128];+ std::snprintf(header, sizeof(header), "CONFIGURE: %s", prov_name);+ ImGui::TextColored(ACCENT, "%s", header);+ ImGui::Separator();+ ImGui::Spacing();++ float label_w = 100.0f;+ float input_w = ImGui::GetContentRegionAvail().x - label_w - 8;++ // API Key+ ImGui::TextColored(TEXT_SECONDARY, "API Key");+ ImGui::SameLine(label_w);+ ImGui::SetNextItemWidth(input_w);+ ImGui::InputText("##llm_api_key", edit_api_key_, sizeof(edit_api_key_),+ ImGuiInputTextFlags_Password);++ // Base URL+ ImGui::TextColored(TEXT_SECONDARY, "Base URL");+ ImGui::SameLine(label_w);+ ImGui::SetNextItemWidth(input_w);+ ImGui::InputTextWithHint("##llm_base_url", "https://api.openai.com/v1",+ edit_base_url_, sizeof(edit_base_url_));++ // Model+ ImGui::TextColored(TEXT_SECONDARY, "Model");+ ImGui::SameLine(label_w);+ ImGui::SetNextItemWidth(input_w);+ ImGui::InputTextWithHint("##llm_model", "gpt-4o",+ edit_model_, sizeof(edit_model_));++ ImGui::Spacing();++ // Save & Set Active buttons+ if (theme::AccentButton("Save Config")) {+ save_provider_config();+ }+ ImGui::SameLine();+ if (theme::SecondaryButton("Set as Active")) {+ db::ops::set_active_llm_provider(prov_name);+ load_configs();+ status_ = std::string(prov_name) + " set as active";+ status_time_ = ImGui::GetTime();+ }+ }+ }++ ImGui::EndChild();+}++// ============================================================================+// Fincept auto-configured panel (mirrors FinceptConfigPanel.tsx)+// ============================================================================+void LLMConfigSection::render_fincept_panel() {+ using namespace theme::colors;++ ImGui::TextColored(ACCENT, "FINCEPT LLM");+ ImGui::Separator();+ ImGui::Spacing();++ auto api_key = db::ops::get_setting("fincept_api_key");+ bool has_key = api_key && !api_key->empty();++ if (has_key) {+ // Auto-configured status+ ImGui::TextColored(SUCCESS, "AUTO CONFIGURED");ImGui::Spacing();- float label_w = 100.0f;- float input_w = ImGui::GetContentRegionAvail().x - label_w - 8;-- // API Key- ImGui::TextColored(TEXT_SECONDARY, "API Key");- ImGui::SameLine(label_w);- ImGui::SetNextItemWidth(input_w);- ImGui::InputText("##llm_api_key", edit_api_key_, sizeof(edit_api_key_),- ImGuiInputTextFlags_Password);-- // Base URL- ImGui::TextColored(TEXT_SECONDARY, "Base URL");- ImGui::SameLine(label_w);- ImGui::SetNextItemWidth(input_w);- ImGui::InputTextWithHint("##llm_base_url", "https://api.openai.com/v1",- edit_base_url_, sizeof(edit_base_url_));-- // Model- ImGui::TextColored(TEXT_SECONDARY, "Model");- ImGui::SameLine(label_w);- ImGui::SetNextItemWidth(input_w);- ImGui::InputTextWithHint("##llm_model", "gpt-4o",- edit_model_, sizeof(edit_model_));+ // Show masked API key+ std::string masked = api_key->substr(0, 8) + "..." ++ api_key->substr(api_key->size() > 8 ? api_key->size() - 4 : 0);+ ImGui::TextColored(TEXT_SECONDARY, "API Key:");+ ImGui::SameLine();+ ImGui::TextColored(TEXT_DIM, "%s", masked.c_str());++ ImGui::TextColored(TEXT_SECONDARY, "Model:");+ ImGui::SameLine();+ ImGui::TextColored(TEXT_PRIMARY, "fincept-llm");++ ImGui::TextColored(TEXT_SECONDARY, "Cost:");+ ImGui::SameLine();+ ImGui::TextColored(TEXT_PRIMARY, "5 credits / response");++ ImGui::TextColored(TEXT_SECONDARY, "Endpoint:");+ ImGui::SameLine();+ ImGui::TextColored(TEXT_DIM, "api.fincept.in/research/llm");++ ImGui::Spacing();+ ImGui::TextColored(TEXT_DIM,+ "Fincept LLM is automatically configured when you log in.");+ ImGui::TextColored(TEXT_DIM,+ "No manual setup required. API key is linked to your account.");ImGui::Spacing();- // Save & Set Active buttons- if (theme::AccentButton("Save Config")) {- save_provider_config();+ // Set as Active button+ bool is_active = false;+ for (auto& cfg : configs_) {+ if (cfg.provider == "Fincept") {+ is_active = cfg.is_active;+ break;+ }}- ImGui::SameLine();- if (theme::SecondaryButton("Set as Active")) {- db::ops::set_active_llm_provider(providers[selected_provider_]);- load_configs();- status_ = std::string(providers[selected_provider_]) + " set as active";- status_time_ = ImGui::GetTime();++ if (is_active) {+ ImGui::TextColored(SUCCESS, "Currently Active");+ } else {+ if (theme::AccentButton("Set as Active")) {+ db::ops::set_active_llm_provider("Fincept");+ load_configs();+ status_ = "Fincept set as active";+ status_time_ = ImGui::GetTime();+ }}+ } else {+ ImGui::TextColored(TEXT_DIM,+ "Fincept LLM requires a Fincept account.");+ ImGui::TextColored(TEXT_DIM,+ "Log in to your Fincept account to auto-configure.");}-- ImGui::EndChild();}// ============================================================================diff --git a/fincept-cpp/src/screens/settings/sections/llm_config_section.h b/fincept-cpp/src/screens/settings/sections/llm_config_section.hindex e8b0ee6b6..e3999cee7 100644--- a/fincept-cpp/src/screens/settings/sections/llm_config_section.h+++ b/fincept-cpp/src/screens/settings/sections/llm_config_section.h@@ -43,11 +43,13 @@ private:void render_sub_tabs();void render_providers();+ void render_fincept_panel();void render_global_settings();void render_model_library();void save_provider_config();void save_global_settings();+ void ensure_fincept_config();};} // namespace fincept::settingsdiff --git a/fincept-cpp/src/screens/watchlist/watchlist_data.cpp b/fincept-cpp/src/screens/watchlist/watchlist_data.cppindex 855d333c1..b7ccccd32 100644--- a/fincept-cpp/src/screens/watchlist/watchlist_data.cpp+++ b/fincept-cpp/src/screens/watchlist/watchlist_data.cpp@@ -1,5 +1,6 @@#include "watchlist_data.h"#include "python/python_runner.h"+#include "storage/cache_service.h"#include <nlohmann/json.hpp>#include <thread>#include <sstream>@@ -36,8 +37,29 @@ void WatchlistData::fetch_quotes(const std::vector<std::string>& symbols) {std::string args = "batch_quotes";for (auto& s : symbols) args += " " + s;- std::thread([this, args]() {- std::string out = run_python(args);+ std::thread([this, args, symbols]() {+ auto& cache = CacheService::instance();++ // Build a cache key that includes the actual symbols+ std::string sym_key;+ for (auto& s : symbols) {+ if (!sym_key.empty()) sym_key += ",";+ sym_key += s;+ }+ std::string cache_key = CacheService::make_key("market-quotes", "watchlist", sym_key);++ std::string out;+ auto cached = cache.get(cache_key);+ if (cached && !cached->empty() && *cached != "[]") {+ out = *cached;+ } else {+ out = run_python(args);+ // Only cache non-empty, non-trivial results+ if (!out.empty() && out != "[]") {+ cache.set(cache_key, out, "market-quotes", CacheTTL::FIVE_MIN);+ }+ }+{std::lock_guard<std::mutex> lock(mutex_);if (!out.empty()) {diff --git a/fincept-cpp/src/screens/watchlist/watchlist_screen.cpp b/fincept-cpp/src/screens/watchlist/watchlist_screen.cppindex 42f4f91ee..feba7a820 100644--- a/fincept-cpp/src/screens/watchlist/watchlist_screen.cpp+++ b/fincept-cpp/src/screens/watchlist/watchlist_screen.cpp@@ -5,12 +5,74 @@#include <cstring>#include <cstdio>#include <ctime>+#include <cmath>#include <algorithm>namespace fincept::watchlist {+// Bloomberg amber/orange palette overlaid on Fincept theme+namespace bb {+ constexpr ImVec4 AMBER = {1.00f, 0.53f, 0.00f, 1.0f}; // #FF8800 — Bloomberg signature amber+ constexpr ImVec4 AMBER_DIM = {0.80f, 0.42f, 0.00f, 1.0f}; // dimmed amber for labels+ constexpr ImVec4 AMBER_BG = {1.00f, 0.53f, 0.00f, 0.06f}; // amber tint background+ constexpr ImVec4 WHITE = {0.95f, 0.95f, 0.97f, 1.0f}; // bright data text+ constexpr ImVec4 WHITE_DIM = {0.65f, 0.65f, 0.70f, 1.0f}; // secondary text+ constexpr ImVec4 GREEN = {0.00f, 0.85f, 0.35f, 1.0f}; // positive change+ constexpr ImVec4 RED = {0.95f, 0.22f, 0.22f, 1.0f}; // negative change+ constexpr ImVec4 YELLOW = {1.00f, 0.85f, 0.00f, 1.0f}; // highlights/warnings+ constexpr ImVec4 CYAN = {0.00f, 0.80f, 0.90f, 1.0f}; // info accent+ constexpr ImVec4 BG_BLACK = {0.04f, 0.04f, 0.05f, 1.0f}; // near-black background+ constexpr ImVec4 BG_PANEL = {0.07f, 0.07f, 0.08f, 1.0f}; // panel background+ constexpr ImVec4 BG_ROW_ALT = {0.06f, 0.06f, 0.07f, 1.0f}; // alternating row+ constexpr ImVec4 BG_SELECTED = {0.15f, 0.10f, 0.00f, 1.0f}; // selected row (amber tint)+ constexpr ImVec4 BG_HEADER = {0.10f, 0.10f, 0.12f, 1.0f}; // header bar bg+ constexpr ImVec4 BORDER = {0.18f, 0.18f, 0.20f, 1.0f}; // thin grid lines+ constexpr ImVec4 BORDER_DIM = {0.12f, 0.12f, 0.14f, 1.0f}; // subtle borders+ constexpr ImVec4 FUNC_KEY_BG = {0.12f, 0.12f, 0.15f, 1.0f}; // function key background+ constexpr ImVec4 FUNC_KEY_AC = {0.20f, 0.14f, 0.00f, 1.0f}; // active function key+}+// ============================================================================-// Init & data loading+// Bloomberg drawing helpers+// ============================================================================+void WatchlistScreen::bb_label(const char* label, const char* value, ImVec4 val_color) {+ ImGui::TextColored(bb::AMBER_DIM, "%-12s", label);+ ImGui::SameLine(100);+ ImGui::TextColored(val_color, "%s", value);+}++void WatchlistScreen::bb_separator_line(float width) {+ ImVec2 p = ImGui::GetCursorScreenPos();+ ImGui::GetWindowDrawList()->AddLine(+ p, ImVec2(p.x + width, p.y),+ ImGui::ColorConvertFloat4ToU32(bb::BORDER), 1.0f);+ ImGui::Dummy(ImVec2(width, 1));+}++bool WatchlistScreen::bb_func_key(const char* label, bool active, float width) {+ if (width <= 0) width = ImGui::CalcTextSize(label).x + 16;++ ImGui::PushStyleVar(ImGuiStyleVar_FrameRounding, 0);+ ImGui::PushStyleVar(ImGuiStyleVar_FramePadding, ImVec2(6, 3));++ if (active) {+ ImGui::PushStyleColor(ImGuiCol_Button, bb::FUNC_KEY_AC);+ ImGui::PushStyleColor(ImGuiCol_ButtonHovered, bb::AMBER_DIM);+ ImGui::PushStyleColor(ImGuiCol_Text, bb::AMBER);+ } else {+ ImGui::PushStyleColor(ImGuiCol_Button, bb::FUNC_KEY_BG);+ ImGui::PushStyleColor(ImGuiCol_ButtonHovered, bb::BORDER);+ ImGui::PushStyleColor(ImGuiCol_Text, bb::WHITE_DIM);+ }++ bool clicked = ImGui::Button(label, ImVec2(width, 0));+ ImGui::PopStyleColor(3);+ ImGui::PopStyleVar(2);+ return clicked;+}++// ============================================================================+// Init & data loading (unchanged logic, reused from original)// ============================================================================void WatchlistScreen::init() {if (initialized_) return;@@ -29,18 +91,14 @@ void WatchlistScreen::load_watchlists() {wc.color = wl.color;wc.created_at = wl.created_at;wc.updated_at = wl.updated_at;- // Count stocksauto stocks = db::ops::get_watchlist_stocks(wl.id);wc.stock_count = static_cast<int>(stocks.size());watchlists_.push_back(std::move(wc));}-- // Auto-select first if nothing selectedif (selected_watchlist_ < 0 && !watchlists_.empty()) {selected_watchlist_ = 0;load_stocks();}- // Validate selectionif (selected_watchlist_ >= static_cast<int>(watchlists_.size())) {selected_watchlist_ = watchlists_.empty() ? -1 : 0;if (selected_watchlist_ >= 0) load_stocks();@@ -50,13 +108,10 @@ void WatchlistScreen::load_watchlists() {void WatchlistScreen::load_stocks() {stocks_.clear();selected_stock_ = -1;-if (selected_watchlist_ < 0 || selected_watchlist_ >= static_cast<int>(watchlists_.size()))return;-auto& wl = watchlists_[selected_watchlist_];auto db_stocks = db::ops::get_watchlist_stocks(wl.id);-for (auto& s : db_stocks) {WatchlistStockEntry entry;entry.id = s.id;@@ -66,18 +121,14 @@ void WatchlistScreen::load_stocks() {entry.notes = s.notes.value_or("");stocks_.push_back(std::move(entry));}-- // Fetch quotes for loaded stocksrefresh_quotes();}void WatchlistScreen::refresh_quotes() {if (stocks_.empty()) return;-std::vector<std::string> symbols;symbols.reserve(stocks_.size());for (auto& s : stocks_) symbols.push_back(s.symbol);-data_.fetch_quotes(symbols);refresh_timer_ = 0;}@@ -86,288 +137,254 @@ void WatchlistScreen::sort_stocks() {std::sort(stocks_.begin(), stocks_.end(),[this](const WatchlistStockEntry& a, const WatchlistStockEntry& b) {switch (sort_by_) {- case SortCriteria::Ticker:- return a.symbol < b.symbol;- case SortCriteria::Change:- return b.quote.change_percent < a.quote.change_percent;- case SortCriteria::Volume:- return b.quote.volume < a.quote.volume;- case SortCriteria::Price:- return b.quote.price < a.quote.price;+ case SortCriteria::Ticker: return a.symbol < b.symbol;+ case SortCriteria::Change: return b.quote.change_percent < a.quote.change_percent;+ case SortCriteria::Volume: return b.quote.volume < a.quote.volume;+ case SortCriteria::Price: return b.quote.price < a.quote.price;}return false;});}// ============================================================================-// Actions+// Actions (unchanged logic)// ============================================================================void WatchlistScreen::create_watchlist() {std::string name(create_name_);if (name.empty()) return;-std::string desc(create_desc_);const auto& colors = watchlist_colors();std::string color = colors[create_color_idx_ % colors.size()];-db::ops::create_watchlist(name, color, desc);load_watchlists();-- // Select the new one (last added)if (!watchlists_.empty()) {selected_watchlist_ = static_cast<int>(watchlists_.size()) - 1;load_stocks();}-std::memset(create_name_, 0, sizeof(create_name_));std::memset(create_desc_, 0, sizeof(create_desc_));create_color_idx_ = 0;show_create_modal_ = false;-- status_ = "Watchlist created: " + name;+ status_ = "CREATED: " + name;status_time_ = ImGui::GetTime();}void WatchlistScreen::delete_watchlist(const std::string& id) {db::ops::delete_watchlist(id);load_watchlists();-- status_ = "Watchlist deleted";+ status_ = "WATCHLIST DELETED";status_time_ = ImGui::GetTime();}void WatchlistScreen::add_stock() {if (selected_watchlist_ < 0 || selected_watchlist_ >= static_cast<int>(watchlists_.size()))return;-std::string symbol(add_symbol_);if (symbol.empty()) return;-- // Uppercasefor (auto& c : symbol) c = static_cast<char>(std::toupper(c));-- // Check duplicatefor (auto& s : stocks_) {if (s.symbol == symbol) {- status_ = symbol + " already in this watchlist";+ status_ = symbol + " DUPLICATE";status_time_ = ImGui::GetTime();return;}}-auto& wl = watchlists_[selected_watchlist_];std::string notes(add_notes_);db::ops::add_watchlist_stock(wl.id, symbol, notes);-load_stocks();- load_watchlists(); // Update count-+ load_watchlists();std::memset(add_symbol_, 0, sizeof(add_symbol_));std::memset(add_notes_, 0, sizeof(add_notes_));show_add_stock_ = false;-- status_ = "Added " + symbol;+ status_ = "ADDED " + symbol;status_time_ = ImGui::GetTime();}void WatchlistScreen::remove_stock(const std::string& symbol) {if (selected_watchlist_ < 0 || selected_watchlist_ >= static_cast<int>(watchlists_.size()))return;-auto& wl = watchlists_[selected_watchlist_];db::ops::remove_watchlist_stock(wl.id, symbol);-if (selected_stock_ >= 0 && selected_stock_ < static_cast<int>(stocks_.size()) &&stocks_[selected_stock_].symbol == symbol) {selected_stock_ = -1;}-load_stocks();load_watchlists();-- status_ = "Removed " + symbol;+ status_ = "REMOVED " + symbol;status_time_ = ImGui::GetTime();}// ============================================================================-// Header bar — top navigation with status and action buttons+// COMMAND BAR — Bloomberg top bar with WLIST<GO> branding// ============================================================================-void WatchlistScreen::render_header_bar() {- using namespace theme::colors;+void WatchlistScreen::render_command_bar(float width) {+ ImGui::PushStyleColor(ImGuiCol_ChildBg, bb::BG_HEADER);+ ImGui::BeginChild("##bb_cmdbar", ImVec2(width, 28), ImGuiChildFlags_Borders);- ImGui::PushStyleColor(ImGuiCol_ChildBg, BG_PANEL);- ImGui::BeginChild("##wl_header", ImVec2(0, 36), ImGuiChildFlags_Borders);+ // WLIST<GO> branding+ ImGui::TextColored(bb::AMBER, "WLIST");+ ImGui::SameLine(0, 0);+ ImGui::TextColored(bb::YELLOW, "<GO>");- // Left: title + status- ImGui::TextColored(ACCENT, "WATCHLIST MONITOR");- ImGui::SameLine(0, 12);- ImGui::TextColored(BORDER_BRIGHT, "|");- ImGui::SameLine(0, 12);+ ImGui::SameLine(0, 16);+ ImGui::TextColored(bb::BORDER, "|");+ ImGui::SameLine(0, 8);++ // Title+ ImGui::TextColored(bb::WHITE, "WATCHLIST MONITOR");- // Status dot+ ImGui::SameLine(0, 16);+ ImGui::TextColored(bb::BORDER, "|");+ ImGui::SameLine(0, 8);++ // Live status with blinkbool loading = data_.is_loading();- ImVec4 dot_color = loading ? WARNING : MARKET_GREEN;- ImGui::TextColored(dot_color, "[*]");+ if (loading) {+ ImGui::TextColored(bb::YELLOW, "[*]");+ ImGui::SameLine(0, 4);+ ImGui::TextColored(bb::YELLOW, "UPDATING");+ } else {+ ImVec4 dot_color = blink_on_ ? bb::GREEN : ImVec4(0, 0, 0, 0);+ // Draw blinking dot+ ImVec2 p = ImGui::GetCursorScreenPos();+ float cy = p.y + ImGui::GetTextLineHeight() * 0.5f;+ ImGui::GetWindowDrawList()->AddCircleFilled(+ ImVec2(p.x + 4, cy), 3.0f,+ ImGui::ColorConvertFloat4ToU32(dot_color));+ ImGui::Dummy(ImVec2(12, 0));+ ImGui::SameLine(0, 4);+ ImGui::TextColored(bb::GREEN, "LIVE");+ }++ ImGui::SameLine(0, 16);+ ImGui::TextColored(bb::BORDER, "|");+ ImGui::SameLine(0, 8);++ // Security count+ ImGui::TextColored(bb::AMBER_DIM, "SEC:");ImGui::SameLine(0, 4);- ImGui::TextColored(dot_color, "%s", loading ? "UPDATING" : "LIVE");+ ImGui::TextColored(bb::WHITE, "%d", static_cast<int>(stocks_.size()));- ImGui::SameLine(0, 12);- ImGui::TextColored(BORDER_BRIGHT, "|");- ImGui::SameLine(0, 12);+ // Right side: timestamp + action buttons+ float right_x = width - 420;+ if (right_x > 300) {+ ImGui::SameLine(right_x);- // Timestamp- 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);- ImGui::TextColored(INFO, "%s", datetime);+ // Timestamp+ 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);+ ImGui::TextColored(bb::CYAN, "%s", datetime);- // Right: action buttons- float right_x = ImGui::GetWindowWidth() - 340;- ImGui::SameLine(right_x);+ ImGui::SameLine(0, 16);+ } else {+ ImGui::SameLine(width - 200);+ }+ // Action buttonsbool has_wl = selected_watchlist_ >= 0 && selected_watchlist_ < static_cast<int>(watchlists_.size());-if (has_wl) {- if (theme::SecondaryButton("+ ADD STOCK")) {- show_add_stock_ = true;- }- ImGui::SameLine();+ if (bb_func_key("+SEC", false, 50)) show_add_stock_ = true;+ ImGui::SameLine(0, 2);}-- if (theme::SecondaryButton("REFRESH")) {+ if (bb_func_key("RFSH", false, 50)) {if (has_wl) refresh_quotes();}-- ImGui::SameLine();- if (theme::AccentButton("+ NEW LIST")) {- show_create_modal_ = true;- }-- ImGui::EndChild();- ImGui::PopStyleColor();-}--// ============================================================================-// Info bar — active watchlist summary-// ============================================================================-void WatchlistScreen::render_info_bar() {- using namespace theme::colors;-- if (selected_watchlist_ < 0 || selected_watchlist_ >= static_cast<int>(watchlists_.size()))- return;-- auto& wl = watchlists_[selected_watchlist_];-- ImGui::PushStyleColor(ImGuiCol_ChildBg, BG_PANEL);- ImGui::BeginChild("##wl_info", ImVec2(0, 22), ImGuiChildFlags_Borders);-- ImGui::TextColored(TEXT_DIM, "ACTIVE LIST");- ImGui::SameLine(0, 8);- ImGui::TextColored(WARNING, "%s", wl.name.c_str());- ImGui::SameLine(0, 16);- ImGui::TextColored(BORDER_BRIGHT, "|");- ImGui::SameLine(0, 16);- ImGui::TextColored(TEXT_DIM, "SYMBOLS");- ImGui::SameLine(0, 8);- ImGui::TextColored(INFO, "%d", static_cast<int>(stocks_.size()));- ImGui::SameLine(0, 16);- ImGui::TextColored(BORDER_BRIGHT, "|");- ImGui::SameLine(0, 16);- ImGui::TextColored(TEXT_DIM, "SORT");- ImGui::SameLine(0, 8);- ImGui::TextColored(INFO, "%s", sort_label(sort_by_));+ ImGui::SameLine(0, 2);+ if (bb_func_key("+NEW", false, 50)) show_create_modal_ = true;ImGui::EndChild();ImGui::PopStyleColor();}// ============================================================================-// Sidebar — watchlist list + market stats+// SIDEBAR — Watchlist navigation + market movers// ============================================================================void WatchlistScreen::render_sidebar(float width, float height) {- using namespace theme::colors;-- ImGui::PushStyleColor(ImGuiCol_ChildBg, BG_PANEL);- ImGui::BeginChild("##wl_sidebar", ImVec2(width, height), ImGuiChildFlags_Borders);+ ImGui::PushStyleColor(ImGuiCol_ChildBg, bb::BG_PANEL);+ ImGui::BeginChild("##bb_sidebar", ImVec2(width, height), ImGuiChildFlags_Borders);// Header- ImGui::PushStyleColor(ImGuiCol_ChildBg, BG_DARK);- ImGui::BeginChild("##wl_sidebar_hdr", ImVec2(0, 32), ImGuiChildFlags_Borders);- char hdr[64];- std::snprintf(hdr, sizeof(hdr), "WATCHLISTS (%d)", static_cast<int>(watchlists_.size()));- ImGui::TextColored(TEXT_DIM, "%s", hdr);- ImGui::SameLine(width - 60);- ImGui::PushStyleColor(ImGuiCol_Button, ACCENT);- ImGui::PushStyleColor(ImGuiCol_ButtonHovered, ACCENT_HOVER);- ImGui::PushStyleColor(ImGuiCol_Text, BG_DARKEST);- if (ImGui::SmallButton("+ NEW")) {- show_create_modal_ = true;- }- ImGui::PopStyleColor(3);+ ImGui::PushStyleColor(ImGuiCol_ChildBg, bb::BG_HEADER);+ ImGui::BeginChild("##sb_hdr", ImVec2(0, 22), ImGuiChildFlags_Borders);+ ImGui::TextColored(bb::AMBER, "LISTS");+ ImGui::SameLine(width - 50);+ ImGui::TextColored(bb::WHITE_DIM, "(%d)", static_cast<int>(watchlists_.size()));ImGui::EndChild();ImGui::PopStyleColor();// Watchlist itemsif (watchlists_.empty()) {ImGui::Spacing();- ImGui::TextColored(TEXT_DIM, " No watchlists yet.");- ImGui::TextColored(TEXT_DIM, " Click + NEW to create one.");+ ImGui::TextColored(bb::WHITE_DIM, " No watchlists.");+ ImGui::TextColored(bb::AMBER_DIM, " Press +NEW");} else {for (int i = 0; i < static_cast<int>(watchlists_.size()); i++) {auto& wl = watchlists_[i];- bool is_selected = (i == selected_watchlist_);+ bool is_sel = (i == selected_watchlist_);ImGui::PushID(i);- // Highlight selected- if (is_selected) {- ImGui::PushStyleColor(ImGuiCol_Button, ACCENT_BG);- ImGui::PushStyleColor(ImGuiCol_ButtonHovered, ACCENT_BG);- ImGui::PushStyleColor(ImGuiCol_Text, TEXT_PRIMARY);- } else {- ImGui::PushStyleColor(ImGuiCol_Button, ImVec4(0, 0, 0, 0));- ImGui::PushStyleColor(ImGuiCol_ButtonHovered, BG_HOVER);- ImGui::PushStyleColor(ImGuiCol_Text, TEXT_SECONDARY);+ // Row background+ ImVec2 row_start = ImGui::GetCursorScreenPos();+ float row_h = ImGui::GetTextLineHeightWithSpacing() + 4;++ if (is_sel) {+ ImGui::GetWindowDrawList()->AddRectFilled(+ row_start,+ ImVec2(row_start.x + width - 2, row_start.y + row_h),+ ImGui::ColorConvertFloat4ToU32(bb::BG_SELECTED));}- // Color dot + name+ // Color indicator bar (3px left edge)ImVec4 wl_color = hex_to_color(wl.color);- ImGui::PushStyleVar(ImGuiStyleVar_FramePadding, ImVec2(6, 6));+ ImGui::GetWindowDrawList()->AddRectFilled(+ row_start,+ ImVec2(row_start.x + 3, row_start.y + row_h),+ ImGui::ColorConvertFloat4ToU32(wl_color));++ // Clickable row+ ImGui::PushStyleColor(ImGuiCol_Button, ImVec4(0, 0, 0, 0));+ ImGui::PushStyleColor(ImGuiCol_ButtonHovered, bb::BORDER_DIM);+ ImGui::PushStyleVar(ImGuiStyleVar_FramePadding, ImVec2(8, 2));+ ImGui::PushStyleVar(ImGuiStyleVar_FrameRounding, 0);char label[128];- std::snprintf(label, sizeof(label), "%s (%d)##wl_%d",- wl.name.c_str(), wl.stock_count, i);+ std::snprintf(label, sizeof(label), " %s%s##wl_%d",+ is_sel ? "> " : " ", wl.name.c_str(), i);- if (ImGui::Button(label, ImVec2(width - 44, 0))) {+ ImGui::PushStyleColor(ImGuiCol_Text, is_sel ? bb::AMBER : bb::WHITE);+ if (ImGui::Button(label, ImVec2(width - 38, 0))) {if (selected_watchlist_ != i) {selected_watchlist_ = i;load_stocks();}}+ ImGui::PopStyleColor();+ ImGui::PopStyleVar(2);+ ImGui::PopStyleColor(2);- ImGui::PopStyleVar();- ImGui::PopStyleColor(3);+ // Stock count badge+ ImGui::SameLine(width - 50);+ ImGui::TextColored(bb::WHITE_DIM, "%d", wl.stock_count);- // Color indicator (drawn after button)- ImVec2 btn_min = ImGui::GetItemRectMin();- ImGui::GetWindowDrawList()->AddRectFilled(- ImVec2(btn_min.x, btn_min.y),- ImVec2(btn_min.x + 3, ImGui::GetItemRectMax().y),- ImGui::ColorConvertFloat4ToU32(wl_color));-- // Delete button- ImGui::SameLine();+ // Delete+ ImGui::SameLine(width - 30);ImGui::PushStyleColor(ImGuiCol_Button, ImVec4(0, 0, 0, 0));- ImGui::PushStyleColor(ImGuiCol_ButtonHovered, BG_HOVER);- ImGui::PushStyleColor(ImGuiCol_Text, TEXT_DIM);- if (ImGui::SmallButton("X")) {+ ImGui::PushStyleColor(ImGuiCol_ButtonHovered, ImVec4(bb::RED.x, bb::RED.y, bb::RED.z, 0.3f));+ ImGui::PushStyleColor(ImGuiCol_Text, bb::BORDER);+ ImGui::PushStyleVar(ImGuiStyleVar_FrameRounding, 0);+ if (ImGui::SmallButton("x")) {delete_watchlist(wl.id);}+ ImGui::PopStyleVar();ImGui::PopStyleColor(3);if (ImGui::IsItemHovered()) {- ImGui::PushStyleColor(ImGuiCol_Text, ERROR_RED);- ImGui::SetTooltip("Delete %s", wl.name.c_str());+ ImGui::PushStyleColor(ImGuiCol_PopupBg, bb::BG_HEADER);+ ImGui::SetTooltip("DEL %s", wl.name.c_str());ImGui::PopStyleColor();}@@ -375,39 +392,37 @@ void WatchlistScreen::render_sidebar(float width, float height) {}}- // Market movers section (bottom of sidebar)- // Show top gainers/losers from current watchlist stocks+ // ── MARKET MOVERS ──if (!stocks_.empty() && data_.has_data()) {ImGui::Spacing();- ImGui::Separator();- ImGui::PushStyleColor(ImGuiCol_ChildBg, BG_DARK);- ImGui::BeginChild("##mkt_movers", ImVec2(0, 0), ImGuiChildFlags_Borders);- ImGui::TextColored(TEXT_DIM, "MARKET MOVERS");- ImGui::Separator();+ // Divider line+ bb_separator_line(width - 16);+ ImGui::Spacing();- // Collect stocks with valid quotes, sort by change- std::vector<const WatchlistStockEntry*> sorted;- for (auto& s : stocks_) {- std::lock_guard<std::mutex> lock(data_.mutex());- auto* q = data_.quote(s.symbol);- if (q && q->valid) sorted.push_back(&s);- }+ ImGui::PushStyleColor(ImGuiCol_ChildBg, bb::BG_BLACK);+ ImGui::BeginChild("##bb_movers", ImVec2(0, 0), ImGuiChildFlags_Borders);- // Sort by change_percent+ ImGui::TextColored(bb::AMBER, "MOVERS");+ ImGui::Spacing();++ // Collect and sort by change+ std::vector<const WatchlistStockEntry*> sorted;{std::lock_guard<std::mutex> lock(data_.mutex());+ for (auto& s : stocks_) {+ auto* q = data_.quote(s.symbol);+ if (q && q->valid) sorted.push_back(&s);+ }std::sort(sorted.begin(), sorted.end(),[this](const WatchlistStockEntry* a, const WatchlistStockEntry* b) {auto* qa = data_.quote(a->symbol);auto* qb = data_.quote(b->symbol);- double ca = qa ? qa->change_percent : 0;- double cb = qb ? qb->change_percent : 0;- return cb < ca;+ return (qb ? qb->change_percent : 0) < (qa ? qa->change_percent : 0);});}- // Top 3 gainers+ // Top gainersint shown = 0;{std::lock_guard<std::mutex> lock(data_.mutex());@@ -415,27 +430,30 @@ void WatchlistScreen::render_sidebar(float width, float height) {if (shown >= 3) break;auto* q = data_.quote(s->symbol);if (!q || q->change_percent <= 0) break;- ImGui::TextColored(MARKET_GREEN, " + ");- ImGui::SameLine();- ImGui::TextColored(INFO, "%-6s", s->symbol.c_str());- ImGui::SameLine(width - 80);- ImGui::TextColored(MARKET_GREEN, "+%.2f%%", q->change_percent);++ // Green up arrow + symbol + change+ ImGui::TextColored(bb::GREEN, " %s", "\xe2\x96\xb2"); // ▲+ ImGui::SameLine(0, 4);+ ImGui::TextColored(bb::WHITE, "%-6s", s->symbol.c_str());+ ImGui::SameLine(width - 70);+ ImGui::TextColored(bb::GREEN, "+%.2f%%", q->change_percent);shown++;}}- // Bottom 2 losers+ // Bottom losersshown = 0;{std::lock_guard<std::mutex> lock(data_.mutex());for (int i = static_cast<int>(sorted.size()) - 1; i >= 0 && shown < 2; i--) {auto* q = data_.quote(sorted[i]->symbol);if (!q || q->change_percent >= 0) break;- ImGui::TextColored(MARKET_RED, " - ");- ImGui::SameLine();- ImGui::TextColored(INFO, "%-6s", sorted[i]->symbol.c_str());- ImGui::SameLine(width - 80);- ImGui::TextColored(MARKET_RED, "%.2f%%", q->change_percent);++ ImGui::TextColored(bb::RED, " %s", "\xe2\x96\xbc"); // ▼+ ImGui::SameLine(0, 4);+ ImGui::TextColored(bb::WHITE, "%-6s", sorted[i]->symbol.c_str());+ ImGui::SameLine(width - 70);+ ImGui::TextColored(bb::RED, "%.2f%%", q->change_percent);shown++;}}@@ -449,22 +467,20 @@ void WatchlistScreen::render_sidebar(float width, float height) {}// ============================================================================-// Stock list — table with sort buttons+// STOCK TABLE — Dense Bloomberg-style data grid// ============================================================================-void WatchlistScreen::render_stock_list(float width, float height) {- using namespace theme::colors;-- ImGui::PushStyleColor(ImGuiCol_ChildBg, BG_DARK);- ImGui::BeginChild("##wl_stocks", ImVec2(width, height), ImGuiChildFlags_Borders);+void WatchlistScreen::render_stock_table(float width, float height) {+ ImGui::PushStyleColor(ImGuiCol_ChildBg, bb::BG_BLACK);+ ImGui::BeginChild("##bb_table", ImVec2(width, height), ImGuiChildFlags_Borders);bool has_wl = selected_watchlist_ >= 0 && selected_watchlist_ < static_cast<int>(watchlists_.size());if (!has_wl) {float cy = height * 0.4f;ImGui::SetCursorPosY(cy);- float tw = ImGui::CalcTextSize("SELECT A WATCHLIST TO VIEW").x;+ float tw = ImGui::CalcTextSize("SELECT A WATCHLIST").x;ImGui::SetCursorPosX((width - tw) * 0.5f);- ImGui::TextColored(TEXT_DIM, "SELECT A WATCHLIST TO VIEW");+ ImGui::TextColored(bb::WHITE_DIM, "SELECT A WATCHLIST");ImGui::EndChild();ImGui::PopStyleColor();return;@@ -472,41 +488,30 @@ void WatchlistScreen::render_stock_list(float width, float height) {auto& wl = watchlists_[selected_watchlist_];- // Header with sort buttons- ImGui::PushStyleColor(ImGuiCol_ChildBg, BG_PANEL);- ImGui::BeginChild("##stock_hdr", ImVec2(0, 28), ImGuiChildFlags_Borders);-- char title[64];- std::snprintf(title, sizeof(title), "%s (%d)", wl.name.c_str(), static_cast<int>(stocks_.size()));- ImGui::TextColored(TEXT_DIM, "%s", title);-- // Sort buttons (right side)- static const SortCriteria sort_opts[] = {- SortCriteria::Ticker, SortCriteria::Change,- SortCriteria::Volume, SortCriteria::Price- };-- float btn_start = width - 240;- ImGui::SameLine(btn_start);-- for (int i = 0; i < 4; i++) {- bool active = (sort_by_ == sort_opts[i]);- 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);- }+ // Table header bar with sort function keys+ ImGui::PushStyleColor(ImGuiCol_ChildBg, bb::BG_HEADER);+ ImGui::BeginChild("##tbl_hdr", ImVec2(0, 24), ImGuiChildFlags_Borders);- if (ImGui::SmallButton(sort_label(sort_opts[i]))) {- sort_by_ = sort_opts[i];- sort_stocks();+ ImGui::TextColored(bb::AMBER, "%s", wl.name.c_str());+ ImGui::SameLine(0, 8);+ ImGui::TextColored(bb::WHITE_DIM, "(%d)", static_cast<int>(stocks_.size()));++ // Sort function keys (right side)+ float btn_start = width - 260;+ if (btn_start > 150) {+ ImGui::SameLine(btn_start);+ static const SortCriteria opts[] = {+ SortCriteria::Ticker, SortCriteria::Change,+ SortCriteria::Volume, SortCriteria::Price+ };+ static const char* labels[] = {"F1 SYM", "F2 CHG", "F3 VOL", "F4 PX"};+ for (int i = 0; i < 4; i++) {+ if (bb_func_key(labels[i], sort_by_ == opts[i], 58)) {+ sort_by_ = opts[i];+ sort_stocks();+ }+ if (i < 3) ImGui::SameLine(0, 2);}- ImGui::PopStyleColor(3);- if (i < 3) ImGui::SameLine(0, 2);}ImGui::EndChild();@@ -522,93 +527,176 @@ void WatchlistScreen::render_stock_list(float width, float height) {sort_stocks();}- // Stock table+ // Data tableif (stocks_.empty()) {ImGui::Spacing();- float tw = ImGui::CalcTextSize("NO STOCKS IN THIS WATCHLIST").x;+ float tw = ImGui::CalcTextSize("NO SECURITIES").x;ImGui::SetCursorPosX((width - tw) * 0.5f);- ImGui::TextColored(TEXT_DIM, "NO STOCKS IN THIS WATCHLIST");- ImGui::SetCursorPosX((width - ImGui::CalcTextSize("Click ADD STOCK to get started").x) * 0.5f);- ImGui::TextColored(TEXT_DIM, "Click ADD STOCK to get started");+ ImGui::TextColored(bb::WHITE_DIM, "NO SECURITIES");+ ImGui::Spacing();+ float tw2 = ImGui::CalcTextSize("Press +SEC to add").x;+ ImGui::SetCursorPosX((width - tw2) * 0.5f);+ ImGui::TextColored(bb::AMBER_DIM, "Press +SEC to add");} else {- if (ImGui::BeginTable("##stock_table", 5,+ // Bloomberg-style dense table+ ImGui::PushStyleVar(ImGuiStyleVar_CellPadding, ImVec2(4, 1));+ ImGui::PushStyleColor(ImGuiCol_TableHeaderBg, bb::BG_HEADER);+ ImGui::PushStyleColor(ImGuiCol_TableBorderStrong, bb::BORDER);+ ImGui::PushStyleColor(ImGuiCol_TableBorderLight, bb::BORDER_DIM);+ ImGui::PushStyleColor(ImGuiCol_TableRowBg, bb::BG_BLACK);+ ImGui::PushStyleColor(ImGuiCol_TableRowBgAlt, bb::BG_ROW_ALT);++ if (ImGui::BeginTable("##bb_stock_tbl", 7,ImGuiTableFlags_Borders | ImGuiTableFlags_RowBg |- ImGuiTableFlags_ScrollY | ImGuiTableFlags_Resizable)) {-- ImGui::TableSetupColumn("SYMBOL", ImGuiTableColumnFlags_WidthFixed, 90);- ImGui::TableSetupColumn("PRICE", ImGuiTableColumnFlags_WidthFixed, 80);- ImGui::TableSetupColumn("CHANGE", ImGuiTableColumnFlags_WidthStretch);- ImGui::TableSetupColumn("VOLUME", ImGuiTableColumnFlags_WidthFixed, 80);- ImGui::TableSetupColumn("##act", ImGuiTableColumnFlags_WidthFixed, 30);- ImGui::TableHeadersRow();+ ImGuiTableFlags_ScrollY | ImGuiTableFlags_Resizable |+ ImGuiTableFlags_SizingFixedFit)) {++ ImGui::TableSetupColumn("SYMBOL", ImGuiTableColumnFlags_WidthFixed, 80);+ ImGui::TableSetupColumn("LAST", ImGuiTableColumnFlags_WidthFixed, 72);+ ImGui::TableSetupColumn("CHG", ImGuiTableColumnFlags_WidthFixed, 64);+ ImGui::TableSetupColumn("CHG%", ImGuiTableColumnFlags_WidthFixed, 60);+ ImGui::TableSetupColumn("VOLUME", ImGuiTableColumnFlags_WidthFixed, 68);+ ImGui::TableSetupColumn("RANGE", ImGuiTableColumnFlags_WidthStretch);+ ImGui::TableSetupColumn("##del", ImGuiTableColumnFlags_WidthFixed, 20);++ // Custom header row styling+ ImGui::TableNextRow(ImGuiTableRowFlags_Headers);+ const char* hdrs[] = {"SYMBOL", "LAST", "CHG", "CHG%", "VOLUME", "RANGE", ""};+ for (int col = 0; col < 7; col++) {+ ImGui::TableSetColumnIndex(col);+ ImGui::TextColored(bb::AMBER_DIM, "%s", hdrs[col]);+ }for (int i = 0; i < static_cast<int>(stocks_.size()); i++) {auto& stock = stocks_[i];- bool is_selected = (i == selected_stock_);+ bool is_sel = (i == selected_stock_);ImGui::TableNextRow();ImGui::PushID(i);- // Row click highlight- if (is_selected) {+ // Selected row highlight+ if (is_sel) {ImGui::TableSetBgColor(ImGuiTableBgTarget_RowBg0,- ImGui::ColorConvertFloat4ToU32(ACCENT_BG));+ ImGui::ColorConvertFloat4ToU32(bb::BG_SELECTED));+ ImGui::TableSetBgColor(ImGuiTableBgTarget_RowBg1,+ ImGui::ColorConvertFloat4ToU32(bb::BG_SELECTED));}- // Symbol+ // SYMBOLImGui::TableNextColumn();- if (ImGui::Selectable(stock.symbol.c_str(), is_selected,+ ImGui::PushStyleColor(ImGuiCol_Header, bb::BG_SELECTED);+ ImGui::PushStyleColor(ImGuiCol_HeaderHovered, bb::BG_SELECTED);+ if (ImGui::Selectable(stock.symbol.c_str(), is_sel,ImGuiSelectableFlags_SpanAllColumns)) {selected_stock_ = i;}+ ImGui::PopStyleColor(2);- // Price+ // LASTImGui::TableNextColumn();if (stock.quote.valid) {- ImGui::TextColored(TEXT_PRIMARY, "$%.2f", stock.quote.price);+ ImGui::TextColored(bb::WHITE, "%.2f", stock.quote.price);} else {- ImGui::TextColored(TEXT_DIM, "--");+ ImGui::TextColored(bb::WHITE_DIM, "--");}- // Change+ // CHGImGui::TableNextColumn();if (stock.quote.valid) {- ImVec4 chg_color = stock.quote.change_percent >= 0 ? MARKET_GREEN : MARKET_RED;- ImGui::TextColored(chg_color, "%s%.2f%%",- stock.quote.change_percent >= 0 ? "+" : "",- stock.quote.change_percent);- ImGui::SameLine(0, 8);- ImGui::TextColored(chg_color, "($%.2f)", stock.quote.change);+ ImVec4 cc = stock.quote.change >= 0 ? bb::GREEN : bb::RED;+ ImGui::TextColored(cc, "%+.2f", stock.quote.change);} else {- ImGui::TextColored(TEXT_DIM, "--");+ ImGui::TextColored(bb::WHITE_DIM, "--");}- // Volume+ // CHG%+ ImGui::TableNextColumn();+ if (stock.quote.valid) {+ ImVec4 cc = stock.quote.change_percent >= 0 ? bb::GREEN : bb::RED;+ // Change percent with background color bar+ ImVec2 p = ImGui::GetCursorScreenPos();+ float bar_w = std::min(std::abs((float)stock.quote.change_percent) * 8.0f, 55.0f);+ ImGui::GetWindowDrawList()->AddRectFilled(+ p, ImVec2(p.x + bar_w, p.y + ImGui::GetTextLineHeight()),+ ImGui::ColorConvertFloat4ToU32(ImVec4(cc.x, cc.y, cc.z, 0.12f)));+ ImGui::TextColored(cc, "%+.2f%%", stock.quote.change_percent);+ } else {+ ImGui::TextColored(bb::WHITE_DIM, "--");+ }++ // VOLUMEImGui::TableNextColumn();if (stock.quote.valid && stock.quote.volume > 0) {- ImGui::TextColored(WARNING, "%s", format_volume(stock.quote.volume).c_str());+ ImGui::TextColored(bb::YELLOW, "%s", format_volume(stock.quote.volume).c_str());} else {- ImGui::TextColored(TEXT_DIM, "--");+ ImGui::TextColored(bb::WHITE_DIM, "--");}- // Remove button+ // RANGE (mini inline bar)+ ImGui::TableNextColumn();+ if (stock.quote.valid && stock.quote.high > stock.quote.low && stock.quote.high > 0) {+ ImVec2 p = ImGui::GetCursorScreenPos();+ float cell_w = ImGui::GetContentRegionAvail().x;+ float bar_h = 3.0f;+ float bar_y = p.y + ImGui::GetTextLineHeight() * 0.5f - bar_h * 0.5f;++ // Track background+ ImGui::GetWindowDrawList()->AddRectFilled(+ ImVec2(p.x, bar_y),+ ImVec2(p.x + cell_w, bar_y + bar_h),+ ImGui::ColorConvertFloat4ToU32(bb::BORDER_DIM));++ // Gradient: red → green+ float half = cell_w * 0.5f;+ ImGui::GetWindowDrawList()->AddRectFilledMultiColor(+ ImVec2(p.x, bar_y),+ ImVec2(p.x + half, bar_y + bar_h),+ ImGui::ColorConvertFloat4ToU32(ImVec4(bb::RED.x, bb::RED.y, bb::RED.z, 0.4f)),+ ImGui::ColorConvertFloat4ToU32(ImVec4(bb::YELLOW.x, bb::YELLOW.y, bb::YELLOW.z, 0.3f)),+ ImGui::ColorConvertFloat4ToU32(ImVec4(bb::YELLOW.x, bb::YELLOW.y, bb::YELLOW.z, 0.3f)),+ ImGui::ColorConvertFloat4ToU32(ImVec4(bb::RED.x, bb::RED.y, bb::RED.z, 0.4f)));+ ImGui::GetWindowDrawList()->AddRectFilledMultiColor(+ ImVec2(p.x + half, bar_y),+ ImVec2(p.x + cell_w, bar_y + bar_h),+ ImGui::ColorConvertFloat4ToU32(ImVec4(bb::YELLOW.x, bb::YELLOW.y, bb::YELLOW.z, 0.3f)),+ ImGui::ColorConvertFloat4ToU32(ImVec4(bb::GREEN.x, bb::GREEN.y, bb::GREEN.z, 0.4f)),+ ImGui::ColorConvertFloat4ToU32(ImVec4(bb::GREEN.x, bb::GREEN.y, bb::GREEN.z, 0.4f)),+ ImGui::ColorConvertFloat4ToU32(ImVec4(bb::YELLOW.x, bb::YELLOW.y, bb::YELLOW.z, 0.3f)));++ // Price position dot+ float range = (float)(stock.quote.high - stock.quote.low);+ float pct = (float)((stock.quote.price - stock.quote.low) / range);+ pct = std::max(0.0f, std::min(1.0f, pct));+ float dot_x = p.x + pct * cell_w;+ ImGui::GetWindowDrawList()->AddCircleFilled(+ ImVec2(dot_x, bar_y + bar_h * 0.5f), 4.0f,+ ImGui::ColorConvertFloat4ToU32(bb::AMBER));+ ImGui::GetWindowDrawList()->AddCircle(+ ImVec2(dot_x, bar_y + bar_h * 0.5f), 4.0f,+ ImGui::ColorConvertFloat4ToU32(bb::WHITE), 0, 1.0f);++ ImGui::Dummy(ImVec2(cell_w, ImGui::GetTextLineHeight()));+ } else {+ ImGui::TextColored(bb::WHITE_DIM, "--");+ }++ // DELETEImGui::TableNextColumn();ImGui::PushStyleColor(ImGuiCol_Button, ImVec4(0, 0, 0, 0));- ImGui::PushStyleColor(ImGuiCol_ButtonHovered, BG_HOVER);- ImGui::PushStyleColor(ImGuiCol_Text, TEXT_DIM);- if (ImGui::SmallButton("X")) {+ ImGui::PushStyleColor(ImGuiCol_ButtonHovered, ImVec4(bb::RED.x, bb::RED.y, bb::RED.z, 0.2f));+ ImGui::PushStyleColor(ImGuiCol_Text, bb::BORDER);+ if (ImGui::SmallButton("x")) {remove_stock(stock.symbol);}ImGui::PopStyleColor(3);- if (ImGui::IsItemHovered()) {- ImGui::SetTooltip("Remove %s", stock.symbol.c_str());- }ImGui::PopID();}-ImGui::EndTable();}++ ImGui::PopStyleColor(5);+ ImGui::PopStyleVar();}ImGui::EndChild();@@ -616,20 +704,18 @@ void WatchlistScreen::render_stock_list(float width, float height) {}// ============================================================================-// Stock detail — right panel showing selected stock info+// DETAIL PANEL — Bloomberg security detail view// ============================================================================-void WatchlistScreen::render_stock_detail(float width, float height) {- using namespace theme::colors;-- ImGui::PushStyleColor(ImGuiCol_ChildBg, BG_PANEL);- ImGui::BeginChild("##wl_detail", ImVec2(width, height), ImGuiChildFlags_Borders);+void WatchlistScreen::render_detail_panel(float width, float height) {+ ImGui::PushStyleColor(ImGuiCol_ChildBg, bb::BG_PANEL);+ ImGui::BeginChild("##bb_detail", ImVec2(width, height), ImGuiChildFlags_Borders);if (selected_stock_ < 0 || selected_stock_ >= static_cast<int>(stocks_.size())) {- float cy = height * 0.4f;+ float cy = height * 0.35f;ImGui::SetCursorPosY(cy);- float tw = ImGui::CalcTextSize("SELECT A STOCK TO VIEW DETAILS").x;+ float tw = ImGui::CalcTextSize("SELECT SECURITY").x;ImGui::SetCursorPosX((width - tw) * 0.5f);- ImGui::TextColored(TEXT_DIM, "SELECT A STOCK TO VIEW DETAILS");+ ImGui::TextColored(bb::WHITE_DIM, "SELECT SECURITY");ImGui::EndChild();ImGui::PopStyleColor();return;@@ -637,156 +723,228 @@ void WatchlistScreen::render_stock_detail(float width, float height) {auto& stock = stocks_[selected_stock_];- // Header- ImGui::PushStyleColor(ImGuiCol_ChildBg, BG_DARK);- ImGui::BeginChild("##detail_hdr", ImVec2(0, 24), ImGuiChildFlags_Borders);- ImGui::TextColored(TEXT_DIM, "STOCK DETAIL");+ // Security header+ ImGui::PushStyleColor(ImGuiCol_ChildBg, bb::BG_HEADER);+ ImGui::BeginChild("##det_hdr", ImVec2(0, 22), ImGuiChildFlags_Borders);+ ImGui::TextColored(bb::AMBER, "DES");+ ImGui::SameLine(0, 8);+ ImGui::TextColored(bb::WHITE, "%s", stock.symbol.c_str());+ ImGui::SameLine(0, 4);+ ImGui::TextColored(bb::WHITE_DIM, "US Equity");ImGui::EndChild();ImGui::PopStyleColor();ImGui::Spacing();- // Symbol hero- ImGui::TextColored(INFO, "%s", stock.symbol.c_str());-if (!stock.quote.valid) {+ // Error state+ ImVec2 p = ImGui::GetCursorScreenPos();+ ImGui::GetWindowDrawList()->AddRectFilled(+ p, ImVec2(p.x + width - 16, p.y + 20),+ ImGui::ColorConvertFloat4ToU32(ImVec4(bb::RED.x, bb::RED.y, bb::RED.z, 0.1f)));+ ImGui::TextColored(bb::RED, " NO MARKET DATA");ImGui::Spacing();- ImGui::PushStyleColor(ImGuiCol_ChildBg, ImVec4(ERROR_RED.x, ERROR_RED.y, ERROR_RED.z, 0.1f));- ImGui::BeginChild("##no_data", ImVec2(0, 28), ImGuiChildFlags_Borders);- ImGui::TextColored(ERROR_RED, " FAILED TO LOAD MARKET DATA");- ImGui::EndChild();- ImGui::PopStyleColor();} else {auto& q = stock.quote;+ ImVec4 chg_color = q.change_percent >= 0 ? bb::GREEN : bb::RED;- // Price + change- ImGui::SetWindowFontScale(1.5f);- ImGui::TextColored(TEXT_PRIMARY, "$%.2f", q.price);+ // Big price display+ ImGui::SetWindowFontScale(1.8f);+ ImGui::TextColored(bb::WHITE, " %.2f", q.price);ImGui::SetWindowFontScale(1.0f);- ImVec4 chg_color = q.change_percent >= 0 ? MARKET_GREEN : MARKET_RED;+ // Change badge with colored background+ ImGui::SameLine(0, 12);+ ImVec2 badge_pos = ImGui::GetCursorScreenPos();+ char chg_text[32];+ std::snprintf(chg_text, sizeof(chg_text), " %+.2f (%+.2f%%) ",+ q.change, q.change_percent);+ ImVec2 badge_sz = ImGui::CalcTextSize(chg_text);- // Change badge- ImVec2 p = ImGui::GetCursorScreenPos();+ // Badge backgroundImGui::GetWindowDrawList()->AddRectFilled(- p, ImVec2(p.x + 80, p.y + 18),- ImGui::ColorConvertFloat4ToU32(ImVec4(chg_color.x, chg_color.y, chg_color.z, 0.15f)),- 2.0f);- char chg_buf[32];- std::snprintf(chg_buf, sizeof(chg_buf), " %s%.2f%%",- q.change_percent >= 0 ? "+" : "", q.change_percent);- ImGui::TextColored(chg_color, "%s", chg_buf);- ImGui::SameLine(0, 8);- ImGui::TextColored(chg_color, "($%.2f)", q.change);+ badge_pos,+ ImVec2(badge_pos.x + badge_sz.x + 4, badge_pos.y + badge_sz.y + 2),+ ImGui::ColorConvertFloat4ToU32(ImVec4(chg_color.x, chg_color.y, chg_color.z, 0.2f)));+ ImGui::TextColored(chg_color, "%s", chg_text);- ImGui::Spacing();- ImGui::Separator();ImGui::Spacing();- // Stats rows- auto stat_row = [&](const char* label, const char* val, ImVec4 color) {- ImGui::TextColored(TEXT_DIM, "%-12s", label);- ImGui::SameLine(120);- ImGui::TextColored(color, "%s", val);- };+ // Horizontal divider+ bb_separator_line(width - 16);+ ImGui::Spacing();+ // Stats grid — Bloomberg style label:value pairschar buf[32];- std::snprintf(buf, sizeof(buf), "$%.2f", q.open);- stat_row("OPEN", buf, TEXT_PRIMARY);- std::snprintf(buf, sizeof(buf), "$%.2f", q.previous_close);- stat_row("PREV CLOSE", buf, TEXT_PRIMARY);- std::snprintf(buf, sizeof(buf), "$%.2f", q.high);- stat_row("DAY HIGH", buf, MARKET_GREEN);- std::snprintf(buf, sizeof(buf), "$%.2f", q.low);- stat_row("DAY LOW", buf, MARKET_RED);- stat_row("VOLUME", format_volume(q.volume).c_str(), WARNING);-- // Day range visual bar++ std::snprintf(buf, sizeof(buf), "%.2f", q.open);+ bb_label("OPEN", buf, bb::WHITE);++ std::snprintf(buf, sizeof(buf), "%.2f", q.previous_close);+ bb_label("PREV CLOSE", buf, bb::WHITE);++ std::snprintf(buf, sizeof(buf), "%.2f", q.high);+ bb_label("DAY HIGH", buf, bb::GREEN);++ std::snprintf(buf, sizeof(buf), "%.2f", q.low);+ bb_label("DAY LOW", buf, bb::RED);++ bb_label("VOLUME", format_volume(q.volume).c_str(), bb::YELLOW);++ // Day range calculationif (q.high > q.low && q.high > 0) {ImGui::Spacing();- ImGui::TextColored(TEXT_DIM, "DAY RANGE");+ bb_separator_line(width - 16);+ ImGui::Spacing();- float bar_w = width - 24;+ ImGui::TextColored(bb::AMBER_DIM, "DAY RANGE");+ ImGui::Spacing();++ // Low label+ ImGui::TextColored(bb::RED, "%.2f", q.low);+ ImGui::SameLine(0, 8);++ // Range bar+ float bar_w = width - 120;+ if (bar_w < 60) bar_w = 60;ImVec2 bar_pos = ImGui::GetCursorScreenPos();- float bar_h = 4.0f;+ float bar_h = 8.0f;- // Background bar+ // TrackImGui::GetWindowDrawList()->AddRectFilled(bar_pos,ImVec2(bar_pos.x + bar_w, bar_pos.y + bar_h),- ImGui::ColorConvertFloat4ToU32(BORDER_DIM), 2.0f);-- // Gradient overlay- float range = static_cast<float>(q.high - q.low);- float pos_pct = static_cast<float>((q.price - q.low) / range);- pos_pct = std::max(0.0f, std::min(1.0f, pos_pct));+ ImGui::ColorConvertFloat4ToU32(bb::BORDER_DIM));- // Current price indicator- float dot_x = bar_pos.x + pos_pct * bar_w;- ImGui::GetWindowDrawList()->AddCircleFilled(- ImVec2(dot_x, bar_pos.y + bar_h * 0.5f), 5.0f,- ImGui::ColorConvertFloat4ToU32(ACCENT));-- ImGui::Dummy(ImVec2(bar_w, bar_h + 4));+ // Gradient fill (red -> amber -> green)+ float third = bar_w / 3.0f;+ ImGui::GetWindowDrawList()->AddRectFilledMultiColor(+ bar_pos,+ ImVec2(bar_pos.x + third, bar_pos.y + bar_h),+ ImGui::ColorConvertFloat4ToU32(ImVec4(bb::RED.x, bb::RED.y, bb::RED.z, 0.6f)),+ ImGui::ColorConvertFloat4ToU32(ImVec4(bb::AMBER.x, bb::AMBER.y, bb::AMBER.z, 0.5f)),+ ImGui::ColorConvertFloat4ToU32(ImVec4(bb::AMBER.x, bb::AMBER.y, bb::AMBER.z, 0.5f)),+ ImGui::ColorConvertFloat4ToU32(ImVec4(bb::RED.x, bb::RED.y, bb::RED.z, 0.6f)));+ ImGui::GetWindowDrawList()->AddRectFilledMultiColor(+ ImVec2(bar_pos.x + third, bar_pos.y),+ ImVec2(bar_pos.x + third * 2, bar_pos.y + bar_h),+ ImGui::ColorConvertFloat4ToU32(ImVec4(bb::AMBER.x, bb::AMBER.y, bb::AMBER.z, 0.5f)),+ ImGui::ColorConvertFloat4ToU32(ImVec4(bb::YELLOW.x, bb::YELLOW.y, bb::YELLOW.z, 0.5f)),+ ImGui::ColorConvertFloat4ToU32(ImVec4(bb::YELLOW.x, bb::YELLOW.y, bb::YELLOW.z, 0.5f)),+ ImGui::ColorConvertFloat4ToU32(ImVec4(bb::AMBER.x, bb::AMBER.y, bb::AMBER.z, 0.5f)));+ ImGui::GetWindowDrawList()->AddRectFilledMultiColor(+ ImVec2(bar_pos.x + third * 2, bar_pos.y),+ ImVec2(bar_pos.x + bar_w, bar_pos.y + bar_h),+ ImGui::ColorConvertFloat4ToU32(ImVec4(bb::YELLOW.x, bb::YELLOW.y, bb::YELLOW.z, 0.5f)),+ ImGui::ColorConvertFloat4ToU32(ImVec4(bb::GREEN.x, bb::GREEN.y, bb::GREEN.z, 0.6f)),+ ImGui::ColorConvertFloat4ToU32(ImVec4(bb::GREEN.x, bb::GREEN.y, bb::GREEN.z, 0.6f)),+ ImGui::ColorConvertFloat4ToU32(ImVec4(bb::YELLOW.x, bb::YELLOW.y, bb::YELLOW.z, 0.5f)));++ // Current price marker (diamond shape)+ float range = (float)(q.high - q.low);+ float pct = (float)((q.price - q.low) / range);+ pct = std::max(0.0f, std::min(1.0f, pct));+ float marker_x = bar_pos.x + pct * bar_w;+ float marker_y = bar_pos.y + bar_h * 0.5f;++ // Diamond marker+ ImVec2 diamond[4] = {+ {marker_x, marker_y - 6},+ {marker_x + 5, marker_y},+ {marker_x, marker_y + 6},+ {marker_x - 5, marker_y}+ };+ ImGui::GetWindowDrawList()->AddConvexPolyFilled(diamond, 4,+ ImGui::ColorConvertFloat4ToU32(bb::AMBER));+ ImGui::GetWindowDrawList()->AddPolyline(diamond, 4,+ ImGui::ColorConvertFloat4ToU32(bb::WHITE), ImDrawFlags_Closed, 1.0f);++ ImGui::Dummy(ImVec2(bar_w, bar_h + 8));++ // High label+ ImGui::SameLine(0, 8);+ ImGui::TextColored(bb::GREEN, "%.2f", q.high);+ }- // Low / High labels- ImGui::TextColored(MARKET_RED, "$%.2f", q.low);- ImGui::SameLine(width - 80);- ImGui::TextColored(MARKET_GREEN, "$%.2f", q.high);+ // Price position percentage+ if (q.high > q.low) {+ float range = (float)(q.high - q.low);+ float pct = (float)((q.price - q.low) / range) * 100.0f;+ char pos_buf[32];+ std::snprintf(pos_buf, sizeof(pos_buf), "%.0f%%", pct);+ bb_label("POSITION", pos_buf, bb::CYAN);}}// Notes sectionif (!stock.notes.empty()) {ImGui::Spacing();- ImGui::Separator();+ bb_separator_line(width - 16);ImGui::Spacing();- ImGui::TextColored(WARNING, "NOTES");- ImGui::PushStyleColor(ImGuiCol_ChildBg, BG_DARKEST);- ImGui::BeginChild("##stock_notes", ImVec2(0, 60), ImGuiChildFlags_Borders);- ImGui::TextWrapped("%s", stock.notes.c_str());++ ImGui::TextColored(bb::AMBER, "NOTES");++ ImGui::PushStyleColor(ImGuiCol_ChildBg, bb::BG_BLACK);+ ImGui::BeginChild("##bb_notes", ImVec2(0, 60), ImGuiChildFlags_Borders);+ ImGui::TextColored(bb::WHITE_DIM, "%s", stock.notes.c_str());ImGui::EndChild();ImGui::PopStyleColor();}+ // Added date+ ImGui::Spacing();+ ImGui::TextColored(bb::BORDER, "ADDED %s", stock.added_at.c_str());+ImGui::EndChild();ImGui::PopStyleColor();}// ============================================================================-// Status bar+// FOOTER BAR — Bloomberg status line// ============================================================================-void WatchlistScreen::render_status_bar() {- using namespace theme::colors;-- ImGui::PushStyleColor(ImGuiCol_ChildBg, BG_DARKEST);- ImGui::BeginChild("##wl_status", ImVec2(0, ImGui::GetFrameHeight()), ImGuiChildFlags_Borders);+void WatchlistScreen::render_footer_bar(float width) {+ ImGui::PushStyleColor(ImGuiCol_ChildBg, bb::BG_HEADER);+ ImGui::BeginChild("##bb_footer", ImVec2(width, ImGui::GetFrameHeight()), ImGuiChildFlags_Borders);- ImGui::TextColored(TEXT_DIM, "FINCEPT WATCHLIST");- ImGui::SameLine(0, 16);- ImGui::TextColored(BORDER_BRIGHT, "|");- ImGui::SameLine(0, 16);+ // Left: branding+ ImGui::TextColored(bb::AMBER, "WLIST");+ ImGui::SameLine(0, 8);+ ImGui::TextColored(bb::BORDER, "|");+ ImGui::SameLine(0, 8);- ImGui::TextColored(TEXT_DIM, "LISTS:");+ // Stats+ ImGui::TextColored(bb::AMBER_DIM, "LISTS");ImGui::SameLine(0, 4);- ImGui::TextColored(INFO, "%d", static_cast<int>(watchlists_.size()));- ImGui::SameLine(0, 16);- ImGui::TextColored(TEXT_DIM, "STOCKS:");+ ImGui::TextColored(bb::WHITE, "%d", static_cast<int>(watchlists_.size()));+ ImGui::SameLine(0, 12);++ ImGui::TextColored(bb::AMBER_DIM, "SEC");ImGui::SameLine(0, 4);- ImGui::TextColored(INFO, "%d", static_cast<int>(stocks_.size()));- ImGui::SameLine(0, 16);- ImGui::TextColored(TEXT_DIM, "STATUS:");+ ImGui::TextColored(bb::WHITE, "%d", static_cast<int>(stocks_.size()));+ ImGui::SameLine(0, 12);++ ImGui::TextColored(bb::AMBER_DIM, "STATUS");ImGui::SameLine(0, 4);- ImGui::TextColored(data_.is_loading() ? WARNING : MARKET_GREEN,- "%s", data_.is_loading() ? "LOADING" : "CONNECTED");+ if (data_.is_loading()) {+ ImGui::TextColored(bb::YELLOW, "LOADING");+ } else {+ ImGui::TextColored(bb::GREEN, "CONNECTED");+ }- // Status message on right+ // Right: status message (fades after 5s)if (!status_.empty()) {double elapsed = ImGui::GetTime() - status_time_;if (elapsed < 5.0) {- float msg_w = ImGui::CalcTextSize(status_.c_str()).x + 16;- ImGui::SameLine(ImGui::GetWindowWidth() - msg_w);- ImGui::TextColored(SUCCESS, "%s", status_.c_str());+ // Flash effect for first second+ bool show = true;+ if (elapsed < 1.0) {+ show = (int)(elapsed * 6) % 2 == 0;+ }+ if (show) {+ float msg_w = ImGui::CalcTextSize(status_.c_str()).x + 24;+ ImGui::SameLine(width - msg_w);+ ImGui::TextColored(bb::YELLOW, "%s", status_.c_str());+ }} else {status_.clear();}@@ -797,44 +955,49 @@ void WatchlistScreen::render_status_bar() {}// ============================================================================-// Create watchlist modal+// CREATE WATCHLIST MODAL — Bloomberg-styled dark modal// ============================================================================void WatchlistScreen::render_create_modal() {- using namespace theme::colors;-if (!show_create_modal_) return;- // Center the modalImVec2 center = ImGui::GetMainViewport()->GetCenter();ImGui::SetNextWindowPos(center, ImGuiCond_Appearing, ImVec2(0.5f, 0.5f));- ImGui::SetNextWindowSize(ImVec2(420, 320));+ ImGui::SetNextWindowSize(ImVec2(400, 300));- ImGui::PushStyleColor(ImGuiCol_WindowBg, BG_PANEL);- ImGui::PushStyleColor(ImGuiCol_TitleBg, BG_DARK);- ImGui::PushStyleColor(ImGuiCol_TitleBgActive, BG_DARK);+ ImGui::PushStyleColor(ImGuiCol_WindowBg, bb::BG_PANEL);+ ImGui::PushStyleColor(ImGuiCol_TitleBg, bb::BG_HEADER);+ ImGui::PushStyleColor(ImGuiCol_TitleBgActive, bb::BG_HEADER);+ ImGui::PushStyleColor(ImGuiCol_Border, bb::AMBER_DIM);+ ImGui::PushStyleVar(ImGuiStyleVar_WindowRounding, 0);- if (ImGui::Begin("CREATE NEW WATCHLIST##modal", &show_create_modal_,+ if (ImGui::Begin("NEW WATCHLIST##bb_modal", &show_create_modal_,ImGuiWindowFlags_NoResize | ImGuiWindowFlags_NoCollapse |ImGuiWindowFlags_NoDocking)) {// Name- ImGui::TextColored(TEXT_DIM, "WATCHLIST NAME *");+ ImGui::TextColored(bb::AMBER, "NAME *");+ ImGui::PushStyleColor(ImGuiCol_FrameBg, bb::BG_BLACK);+ ImGui::PushStyleColor(ImGuiCol_Text, bb::WHITE);ImGui::SetNextItemWidth(-1);- ImGui::InputTextWithHint("##wl_name", "My Watchlist",+ ImGui::InputTextWithHint("##wl_name", "WATCHLIST NAME",create_name_, sizeof(create_name_));+ ImGui::PopStyleColor(2);ImGui::Spacing();// Description- ImGui::TextColored(TEXT_DIM, "DESCRIPTION");+ ImGui::TextColored(bb::AMBER, "DESCRIPTION");+ ImGui::PushStyleColor(ImGuiCol_FrameBg, bb::BG_BLACK);+ ImGui::PushStyleColor(ImGuiCol_Text, bb::WHITE);ImGui::SetNextItemWidth(-1);ImGui::InputTextMultiline("##wl_desc", create_desc_, sizeof(create_desc_),- ImVec2(-1, 60));+ ImVec2(-1, 50));+ ImGui::PopStyleColor(2);ImGui::Spacing();- // Color picker- ImGui::TextColored(TEXT_DIM, "COLOR");+ // Color picker (horizontal swatches)+ ImGui::TextColored(bb::AMBER, "COLOR");const auto& colors = watchlist_colors();for (int i = 0; i < static_cast<int>(colors.size()); i++) {ImVec4 c = hex_to_color(colors[i]);@@ -843,153 +1006,188 @@ void WatchlistScreen::render_create_modal() {ImGui::PushID(i);ImGui::PushStyleColor(ImGuiCol_Button, c);ImGui::PushStyleColor(ImGuiCol_ButtonHovered,- ImVec4(c.x * 0.8f, c.y * 0.8f, c.z * 0.8f, 1.0f));+ ImVec4(c.x * 0.7f, c.y * 0.7f, c.z * 0.7f, 1.0f));+ ImGui::PushStyleVar(ImGuiStyleVar_FrameRounding, 0);- float size = selected ? 32.0f : 28.0f;- if (ImGui::Button("##color", ImVec2(size, size))) {+ float sz = selected ? 28.0f : 24.0f;+ if (ImGui::Button("##clr", ImVec2(sz, sz))) {create_color_idx_ = i;}+ ImGui::PopStyleVar();ImGui::PopStyleColor(2);if (selected) {ImVec2 mn = ImGui::GetItemRectMin();ImVec2 mx = ImGui::GetItemRectMax();ImGui::GetWindowDrawList()->AddRect(mn, mx,- ImGui::ColorConvertFloat4ToU32(TEXT_PRIMARY), 0, 0, 2.0f);+ ImGui::ColorConvertFloat4ToU32(bb::WHITE), 0, 0, 2.0f);}ImGui::PopID();- if (i < static_cast<int>(colors.size()) - 1) ImGui::SameLine(0, 6);+ if (i < static_cast<int>(colors.size()) - 1) ImGui::SameLine(0, 4);}ImGui::Spacing();- ImGui::Separator();+ bb_separator_line(380);ImGui::Spacing();// Buttons- float btn_w = 100;- ImGui::SetCursorPosX(ImGui::GetWindowWidth() - btn_w * 2 - 24);+ ImGui::SetCursorPosX(ImGui::GetWindowWidth() - 180);- if (theme::SecondaryButton("Cancel")) {+ if (bb_func_key("CANCEL", false, 70)) {show_create_modal_ = false;}- ImGui::SameLine();+ ImGui::SameLine(0, 8);+bool can_create = create_name_[0] != '\0';if (!can_create) ImGui::BeginDisabled();- if (theme::AccentButton("Create")) {++ ImGui::PushStyleColor(ImGuiCol_Button, bb::AMBER_DIM);+ ImGui::PushStyleColor(ImGuiCol_ButtonHovered, bb::AMBER);+ ImGui::PushStyleColor(ImGuiCol_Text, bb::BG_BLACK);+ ImGui::PushStyleVar(ImGuiStyleVar_FrameRounding, 0);+ if (ImGui::Button("CREATE", ImVec2(70, 0))) {create_watchlist();}+ ImGui::PopStyleVar();+ ImGui::PopStyleColor(3);+if (!can_create) ImGui::EndDisabled();}ImGui::End();- ImGui::PopStyleColor(3);+ ImGui::PopStyleVar();+ ImGui::PopStyleColor(4);}// ============================================================================-// Add stock modal+// ADD STOCK MODAL// ============================================================================void WatchlistScreen::render_add_stock_modal() {- using namespace theme::colors;-if (!show_add_stock_) return;ImVec2 center = ImGui::GetMainViewport()->GetCenter();ImGui::SetNextWindowPos(center, ImGuiCond_Appearing, ImVec2(0.5f, 0.5f));- ImGui::SetNextWindowSize(ImVec2(400, 260));+ ImGui::SetNextWindowSize(ImVec2(380, 240));- ImGui::PushStyleColor(ImGuiCol_WindowBg, BG_PANEL);- ImGui::PushStyleColor(ImGuiCol_TitleBg, BG_DARK);- ImGui::PushStyleColor(ImGuiCol_TitleBgActive, BG_DARK);+ ImGui::PushStyleColor(ImGuiCol_WindowBg, bb::BG_PANEL);+ ImGui::PushStyleColor(ImGuiCol_TitleBg, bb::BG_HEADER);+ ImGui::PushStyleColor(ImGuiCol_TitleBgActive, bb::BG_HEADER);+ ImGui::PushStyleColor(ImGuiCol_Border, bb::AMBER_DIM);+ ImGui::PushStyleVar(ImGuiStyleVar_WindowRounding, 0);- if (ImGui::Begin("ADD STOCK TO WATCHLIST##add_modal", &show_add_stock_,+ if (ImGui::Begin("ADD SECURITY##bb_add", &show_add_stock_,ImGuiWindowFlags_NoResize | ImGuiWindowFlags_NoCollapse |ImGuiWindowFlags_NoDocking)) {- // Symbol- ImGui::TextColored(TEXT_DIM, "SYMBOL *");+ // Symbol input+ ImGui::TextColored(bb::AMBER, "TICKER *");+ ImGui::PushStyleColor(ImGuiCol_FrameBg, bb::BG_BLACK);+ ImGui::PushStyleColor(ImGuiCol_Text, bb::WHITE);ImGui::SetNextItemWidth(-1);- if (ImGui::InputTextWithHint("##add_sym", "AAPL",- add_symbol_, sizeof(add_symbol_),- ImGuiInputTextFlags_CharsUppercase)) {- }- ImGui::TextColored(TEXT_DIM, "Enter stock ticker (e.g., AAPL, MSFT, GOOGL)");+ ImGui::InputTextWithHint("##add_sym", "AAPL",+ add_symbol_, sizeof(add_symbol_),+ ImGuiInputTextFlags_CharsUppercase);+ ImGui::PopStyleColor(2);++ ImGui::TextColored(bb::WHITE_DIM, "Enter ticker symbol (AAPL, MSFT, GOOGL)");ImGui::Spacing();// Notes- ImGui::TextColored(TEXT_DIM, "NOTES (OPTIONAL)");+ ImGui::TextColored(bb::AMBER, "NOTES");+ ImGui::PushStyleColor(ImGuiCol_FrameBg, bb::BG_BLACK);+ ImGui::PushStyleColor(ImGuiCol_Text, bb::WHITE);ImGui::SetNextItemWidth(-1);ImGui::InputTextMultiline("##add_notes", add_notes_, sizeof(add_notes_),- ImVec2(-1, 60));+ ImVec2(-1, 50));+ ImGui::PopStyleColor(2);ImGui::Spacing();- ImGui::Separator();+ bb_separator_line(360);ImGui::Spacing();// Buttons- ImGui::SetCursorPosX(ImGui::GetWindowWidth() - 220);- if (theme::SecondaryButton("Cancel")) {+ ImGui::SetCursorPosX(ImGui::GetWindowWidth() - 180);++ if (bb_func_key("CANCEL", false, 70)) {show_add_stock_ = false;}- ImGui::SameLine();+ ImGui::SameLine(0, 8);bool can_add = add_symbol_[0] != '\0';if (!can_add) ImGui::BeginDisabled();- ImGui::PushStyleColor(ImGuiCol_Button, MARKET_GREEN);++ ImGui::PushStyleColor(ImGuiCol_Button, bb::GREEN);ImGui::PushStyleColor(ImGuiCol_ButtonHovered,- ImVec4(MARKET_GREEN.x * 0.8f, MARKET_GREEN.y * 0.8f, MARKET_GREEN.z * 0.8f, 1));- ImGui::PushStyleColor(ImGuiCol_Text, BG_DARKEST);- if (ImGui::Button("Add Stock")) {+ ImVec4(bb::GREEN.x * 0.8f, bb::GREEN.y * 0.8f, bb::GREEN.z * 0.8f, 1));+ ImGui::PushStyleColor(ImGuiCol_Text, bb::BG_BLACK);+ ImGui::PushStyleVar(ImGuiStyleVar_FrameRounding, 0);+ if (ImGui::Button("ADD", ImVec2(70, 0))) {add_stock();}+ ImGui::PopStyleVar();ImGui::PopStyleColor(3);+if (!can_add) ImGui::EndDisabled();}ImGui::End();- ImGui::PopStyleColor(3);+ ImGui::PopStyleVar();+ ImGui::PopStyleColor(4);}// ============================================================================-// Main render+// MAIN RENDER — Bloomberg 4-zone layout// ============================================================================void WatchlistScreen::render() {init();- using namespace theme::colors;-- // Auto-refresh timer+ // Blink timer (1Hz pulse for live indicator)float dt = ImGui::GetIO().DeltaTime;+ blink_timer_ += dt;+ if (blink_timer_ >= 0.8f) {+ blink_on_ = !blink_on_;+ blink_timer_ = 0;+ }++ // Auto-refreshrefresh_timer_ += dt;if (refresh_timer_ >= REFRESH_INTERVAL && !data_.is_loading()) {refresh_quotes();}- ui::ScreenFrame frame("##watchlist", ImVec2(4, 4), BG_DARKEST);+ // Full-screen Bloomberg frame+ ui::ScreenFrame frame("##watchlist", ImVec2(0, 0), bb::BG_BLACK);if (!frame.begin()) { frame.end(); return; }- // Header bar- render_header_bar();-- // Info bar- render_info_bar();-- // Three-panel layout- float sidebar_w = 240.0f;- float detail_w = 280.0f;- float status_h = ImGui::GetFrameHeight() + 4;- float header_h = 36 + 22 + 8; // header + info + spacing- float content_h = frame.height() - header_h - status_h;- float stock_list_w = frame.width() - sidebar_w - detail_w - 8;- if (stock_list_w < 200) stock_list_w = 200;-- render_sidebar(sidebar_w, content_h);- ImGui::SameLine(0, 4);- render_stock_list(stock_list_w, content_h);- ImGui::SameLine(0, 4);- render_stock_detail(detail_w, content_h);+ float total_w = frame.width();+ float total_h = frame.height();++ // ── ZONE 1: Command bar (top) ──+ float cmd_h = 28;+ render_command_bar(total_w);++ // ── ZONE 2: Three-panel content area ──+ float footer_h = ImGui::GetFrameHeight() + 2;+ float content_h = total_h - cmd_h - footer_h - 4;++ // Use yoga for responsive three-panel layout+ auto panels = ui::three_panel_layout(+ total_w, content_h,+ 16, 22, // left%, right%+ 180, 240, 300, // min widths+ 2 // gap+ );++ render_sidebar(panels.left_w, panels.left_h);+ ImGui::SameLine(0, panels.gap);+ render_stock_table(panels.center_w, panels.center_h);+ if (panels.right_w > 0) {+ ImGui::SameLine(0, panels.gap);+ render_detail_panel(panels.right_w, panels.right_h);+ }- // Status bar- render_status_bar();+ // ── ZONE 3: Footer status bar ──+ render_footer_bar(total_w);frame.end();diff --git a/fincept-cpp/src/screens/watchlist/watchlist_screen.h b/fincept-cpp/src/screens/watchlist/watchlist_screen.hindex 73b9c937c..0904cad89 100644--- a/fincept-cpp/src/screens/watchlist/watchlist_screen.h+++ b/fincept-cpp/src/screens/watchlist/watchlist_screen.h@@ -1,6 +1,6 @@#pragma once-// Watchlist Screen — three-panel layout: sidebar | stock list | stock detail-// Mirrors WatchlistTab.tsx from the Tauri project+// Watchlist Screen — Bloomberg Terminal style+// Dense 4-zone layout: command bar | sidebar+table+detail | status bar#include "watchlist_types.h"#include "watchlist_data.h"@@ -30,7 +30,7 @@ private:// Data fetcherWatchlistData data_;float refresh_timer_ = 0;- static constexpr float REFRESH_INTERVAL = 600.0f; // 10 min+ static constexpr float REFRESH_INTERVAL = 600.0f;// Create watchlist modalbool show_create_modal_ = false;@@ -47,6 +47,10 @@ private:std::string status_;double status_time_ = 0;+ // Bloomberg blink state+ float blink_timer_ = 0;+ bool blink_on_ = true;+// Init & datavoid init();void load_watchlists();@@ -54,13 +58,12 @@ private:void refresh_quotes();void sort_stocks();- // Rendering panels- void render_header_bar();- void render_info_bar();+ // Bloomberg-style rendering+ void render_command_bar(float width);void render_sidebar(float width, float height);- void render_stock_list(float width, float height);- void render_stock_detail(float width, float height);- void render_status_bar();+ void render_stock_table(float width, float height);+ void render_detail_panel(float width, float height);+ void render_footer_bar(float width);// Modalsvoid render_create_modal();@@ -71,6 +74,11 @@ private:void delete_watchlist(const std::string& id);void add_stock();void remove_stock(const std::string& symbol);++ // Bloomberg drawing helpers+ void bb_label(const char* label, const char* value, ImVec4 val_color = {1,1,1,1});+ void bb_separator_line(float width);+ bool bb_func_key(const char* label, bool active, float width = 0);};} // namespace fincept::watchlistdiff --git a/fincept-cpp/src/storage/database.cpp b/fincept-cpp/src/storage/database.cppindex 23b16d903..a735aee09 100644--- a/fincept-cpp/src/storage/database.cpp+++ b/fincept-cpp/src/storage/database.cpp@@ -619,7 +619,9 @@ void Database::create_schema() {FOREIGN KEY (deployment_id) REFERENCES algo_deployments(id) ON DELETE CASCADE);CREATE INDEX IF NOT EXISTS idx_algo_signals_status ON algo_order_signals(status);+ )");+ exec(R"(-- Algo Trading: Candle CacheCREATE TABLE IF NOT EXISTS candle_cache (id INTEGER PRIMARY KEY AUTOINCREMENT,@@ -1086,9 +1088,36 @@ std::vector<ChatMessage> get_chat_messages(const std::string& session_uuid) {void delete_chat_session(const std::string& session_uuid) {auto& db = Database::instance();std::lock_guard<std::recursive_mutex> lock(db.mutex());- auto stmt = db.prepare("DELETE FROM chat_sessions WHERE session_uuid = ?1");+ // Delete messages first, then session+ auto stmt1 = db.prepare("DELETE FROM chat_messages WHERE session_uuid = ?1");+ stmt1.bind_text(1, session_uuid);+ stmt1.execute();+ auto stmt2 = db.prepare("DELETE FROM chat_sessions WHERE session_uuid = ?1");+ stmt2.bind_text(1, session_uuid);+ stmt2.execute();+}++void update_chat_session_title(const std::string& session_uuid, const std::string& title) {+ auto& db = Database::instance();+ std::lock_guard<std::recursive_mutex> lock(db.mutex());+ auto stmt = db.prepare(+ "UPDATE chat_sessions SET title = ?1, updated_at = datetime('now') WHERE session_uuid = ?2");+ stmt.bind_text(1, title);+ stmt.bind_text(2, session_uuid);+ stmt.execute();+}++void clear_chat_session_messages(const std::string& session_uuid) {+ auto& db = Database::instance();+ std::lock_guard<std::recursive_mutex> lock(db.mutex());+ auto stmt = db.prepare("DELETE FROM chat_messages WHERE session_uuid = ?1");stmt.bind_text(1, session_uuid);stmt.execute();+ // Reset message count+ auto stmt2 = db.prepare(+ "UPDATE chat_sessions SET message_count = 0, updated_at = datetime('now') WHERE session_uuid = ?1");+ stmt2.bind_text(1, session_uuid);+ stmt2.execute();}// ============================================================================diff --git a/fincept-cpp/src/storage/database.h b/fincept-cpp/src/storage/database.hindex 84b9d1125..312989a9b 100644--- a/fincept-cpp/src/storage/database.h+++ b/fincept-cpp/src/storage/database.h@@ -388,6 +388,8 @@ std::vector<ChatSession> get_chat_sessions(int limit = -1);ChatMessage add_chat_message(const ChatMessage& msg);std::vector<ChatMessage> get_chat_messages(const std::string& session_uuid);void delete_chat_session(const std::string& session_uuid);+void update_chat_session_title(const std::string& session_uuid, const std::string& title);+void clear_chat_session_messages(const std::string& session_uuid);// --- Watchlist ---Watchlist create_watchlist(const std::string& name, const std::string& color,diff --git a/fincept-cpp/src/ui/tile_map.cpp b/fincept-cpp/src/ui/tile_map.cppindex bdb4191e4..3418ee4cc 100644--- a/fincept-cpp/src/ui/tile_map.cpp+++ b/fincept-cpp/src/ui/tile_map.cpp@@ -45,8 +45,8 @@ static std::string fetch_tile_data(const std::string& url) {curl_easy_setopt(curl, CURLOPT_URL, url.c_str());curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, write_binary);curl_easy_setopt(curl, CURLOPT_WRITEDATA, &data);- curl_easy_setopt(curl, CURLOPT_TIMEOUT, 10L);- curl_easy_setopt(curl, CURLOPT_CONNECTTIMEOUT, 5L);+ curl_easy_setopt(curl, CURLOPT_TIMEOUT, 5L);+ curl_easy_setopt(curl, CURLOPT_CONNECTTIMEOUT, 3L);curl_easy_setopt(curl, CURLOPT_FOLLOWLOCATION, 1L);curl_easy_setopt(curl, CURLOPT_SSL_VERIFYPEER, 1L);curl_easy_setopt(curl, CURLOPT_USERAGENT, "FinceptTerminal/4.0.0");@@ -184,6 +184,11 @@ void TileMap::ensure_tile(const TileKey& key) {return;}+ // Throttle concurrent loads to avoid spawning dozens of threads+ if (pending_loads_.load() >= MAX_CONCURRENT_LOADS) {+ return; // Will retry next frame+ }+tile_cache_[key].state = TileState::Loading;load_tile_async(key);}@@ -406,11 +411,8 @@ void TileMap::render_tiles(ImDrawList* dl, ImVec2 pos, ImVec2 size) {}}- for (auto& info : visible_tiles) {- ensure_tile(info.key);- }-- // Second pass: render+ // Second pass: render existing tiles and collect missing ones+ std::vector<TileKey> missing_keys;{std::lock_guard<std::mutex> lock(tile_mutex_);for (auto& info : visible_tiles) {@@ -422,10 +424,18 @@ void TileMap::render_tiles(ImDrawList* dl, ImVec2 pos, ImVec2 size) {} else {dl->AddRectFilled(info.tile_min, info.tile_max, IM_COL32(24, 24, 26, 255));dl->AddRect(info.tile_min, info.tile_max, IM_COL32(40, 40, 44, 100));+ if (it == tile_cache_.end()) {+ missing_keys.push_back(info.key);+ }}}}+ // Third pass: request missing tiles (outside render lock)+ for (auto& key : missing_keys) {+ ensure_tile(key);+ }+dl->PopClipRect();}diff --git a/fincept-cpp/src/ui/tile_map.h b/fincept-cpp/src/ui/tile_map.hindex 848b5b477..5da552779 100644--- a/fincept-cpp/src/ui/tile_map.h+++ b/fincept-cpp/src/ui/tile_map.h@@ -86,6 +86,7 @@ private:std::mutex tile_mutex_;std::unordered_map<TileKey, TileEntry, TileKeyHash> tile_cache_;std::atomic<int> pending_loads_{0};+ static constexpr int MAX_CONCURRENT_LOADS = 6;// Pending texture uploads (background thread -> main GL thread)struct PendingUpload {diff --git a/fincept-cpp/tmp/01_basic_layout.cpp b/fincept-cpp/tmp/01_basic_layout.cppdeleted file mode 100644index 59413a27f..000000000--- a/fincept-cpp/tmp/01_basic_layout.cpp+++ /dev/null@@ -1,63 +0,0 @@-// Example 1: Basic Yoga layout — two columns-// This shows the raw flow: create nodes → set styles → calculate → read results-//-// You don't need to compile this file. It's a reference showing-// exactly what happens under the hood.--#include "ui/yoga_layout.h"-#include <imgui.h>-#include <cstdio>--using namespace fincept::ui;--void example_basic_two_columns() {- // Available space (imagine this comes from ImGui viewport)- float avail_w = 1200;- float avail_h = 800;-- // Step 1: Create the layout and build the tree- YogaLayout layout;-- auto root = layout.node()- .row() // children laid out horizontally- .width(avail_w) // root fills available width- .height(avail_h) // root fills available height- .padding(8) // 8px inner padding on all sides- .gap(4); // 4px gap between children-- auto sidebar = root.child()- .width_percent(25) // 25% of parent width- .min_width(200); // but never less than 200px-- auto main_area = root.child()- .flex_grow(1); // takes all remaining space-- // Step 2: Run the layout algorithm- layout.calculate(avail_w, avail_h);-- // Step 3: Read computed values- printf("=== Two Column Layout (%.0f x %.0f) ===\n", avail_w, avail_h);- printf("Sidebar: x=%.0f y=%.0f w=%.0f h=%.0f\n",- sidebar.rect().x, sidebar.rect().y,- sidebar.rect().w, sidebar.rect().h);- printf("Main: x=%.0f y=%.0f w=%.0f h=%.0f\n",- main_area.rect().x, main_area.rect().y,- main_area.rect().w, main_area.rect().h);-- // Expected output (approximately):- // Sidebar: x=8 y=8 w=296 h=784 (25% of 1200 = 300, minus padding/gap)- // Main: x=308 y=8 w=884 h=784 (remaining space)-- // Step 4: Use with ImGui (in your render function)- // ImGui::SetCursorPos(sidebar.pos());- // ImGui::BeginChild("sidebar", sidebar.size());- // ImGui::Text("Sidebar content here");- // ImGui::EndChild();- //- // ImGui::SetCursorPos(main_area.pos());- // ImGui::BeginChild("main", main_area.size());- // ImGui::Text("Main content here");- // ImGui::EndChild();-- // Layout is automatically freed when `layout` goes out of scope (RAII)-}diff --git a/fincept-cpp/tmp/02_three_panel.cpp b/fincept-cpp/tmp/02_three_panel.cppdeleted file mode 100644index b81f2b1ab..000000000--- a/fincept-cpp/tmp/02_three_panel.cpp+++ /dev/null@@ -1,61 +0,0 @@-// Example 2: Three-panel layout (sidebar | content | detail)-// This is the most common pattern in the terminal for research/analysis screens.--#include "ui/yoga_layout.h"-#include <imgui.h>-#include <cstdio>--using namespace fincept::ui;--void example_three_panel() {- float w = 1400, h = 800;-- YogaLayout layout;- auto root = layout.node()- .row() // horizontal layout- .width(w).height(h)- .padding(4)- .gap(4);-- // Left sidebar: 18% width, minimum 160px- auto left = root.child()- .width_percent(18)- .min_width(160);-- // Center: flexible, takes remaining space- auto center = root.child()- .flex_grow(1)- .min_width(200);-- // Right detail panel: 24% width, minimum 200px- auto right = root.child()- .width_percent(24)- .min_width(200);-- layout.calculate(w, h);-- printf("=== Three Panel (%.0f x %.0f) ===\n", w, h);- printf("Left: w=%.0f h=%.0f\n", left.computed_width(), left.computed_height());- printf("Center: w=%.0f h=%.0f\n", center.computed_width(), center.computed_height());- printf("Right: w=%.0f h=%.0f\n", right.computed_width(), right.computed_height());-- // With ImGui — the pattern every screen follows:- //- // ImGui::SetCursorPos(left.pos());- // if (ImGui::BeginChild("##left", left.size())) {- // // watchlist, navigation, etc.- // }- // ImGui::EndChild();- //- // ImGui::SetCursorPos(center.pos());- // if (ImGui::BeginChild("##center", center.size())) {- // // main content: charts, tables, etc.- // }- // ImGui::EndChild();- //- // ImGui::SetCursorPos(right.pos());- // if (ImGui::BeginChild("##right", right.size())) {- // // detail panel: stock info, news feed, etc.- // }- // ImGui::EndChild();-}diff --git a/fincept-cpp/tmp/03_nested_layout.cpp b/fincept-cpp/tmp/03_nested_layout.cppdeleted file mode 100644index 65fda0b91..000000000--- a/fincept-cpp/tmp/03_nested_layout.cpp+++ /dev/null@@ -1,90 +0,0 @@-// Example 3: Nested layouts — header + toolbar + content area with inner columns-// Shows how to compose vertical and horizontal layouts together.--#include "ui/yoga_layout.h"-#include <imgui.h>-#include <cstdio>--using namespace fincept::ui;--void example_nested() {- float w = 1200, h = 800;-- YogaLayout layout;-- // Outer container: vertical stack- auto root = layout.node()- .column() // vertical: children stack top-to-bottom- .width(w).height(h);-- // Fixed-height header (40px)- auto header = root.child()- .width_percent(100)- .height(40);-- // Fixed-height toolbar (32px)- auto toolbar = root.child()- .width_percent(100)- .height(32);-- // Content area: fills remaining vertical space- auto content = root.child()- .width_percent(100)- .flex_grow(1); // KEY: takes all remaining height-- layout.calculate(w, h);-- printf("=== Nested Layout (%.0f x %.0f) ===\n", w, h);- printf("Header: h=%.0f (fixed 40)\n", header.computed_height());- printf("Toolbar: h=%.0f (fixed 32)\n", toolbar.computed_height());- printf("Content: h=%.0f (fills remaining = %.0f - 40 - 32 = %.0f)\n",- content.computed_height(), h, h - 40 - 32);-- // Now you can create a SECOND YogaLayout for the content area's inner layout:- float content_w = content.computed_width();- float content_h = content.computed_height();-- YogaLayout inner;- auto inner_root = inner.node()- .row() // horizontal split inside content- .width(content_w).height(content_h)- .gap(4);-- auto list_panel = inner_root.child()- .width_percent(30)- .min_width(200);-- auto detail_panel = inner_root.child()- .flex_grow(1);-- inner.calculate(content_w, content_h);-- printf("\nInner content area (%.0f x %.0f):\n", content_w, content_h);- printf(" List: w=%.0f\n", list_panel.computed_width());- printf(" Detail: w=%.0f\n", detail_panel.computed_width());-- // With ImGui, you'd set cursor positions relative to each section's origin:- //- // ImGui::SetCursorPos(header.pos());- // ImGui::BeginChild("header", header.size());- // ImGui::Text("FINCEPT TERMINAL");- // ImGui::EndChild();- //- // ImGui::SetCursorPos(toolbar.pos());- // ImGui::BeginChild("toolbar", toolbar.size());- // if (ImGui::Button("Refresh")) { ... }- // ImGui::EndChild();- //- // ImGui::SetCursorPos(content.pos());- // ImGui::BeginChild("content", content.size());- // // Now use inner layout positions RELATIVE to this child window:- // ImGui::SetCursorPos(list_panel.pos());- // ImGui::BeginChild("list", list_panel.size());- // ...- // ImGui::EndChild();- // ImGui::SetCursorPos(detail_panel.pos());- // ImGui::BeginChild("detail", detail_panel.size());- // ...- // ImGui::EndChild();- // ImGui::EndChild();-}diff --git a/fincept-cpp/tmp/04_responsive.cpp b/fincept-cpp/tmp/04_responsive.cppdeleted file mode 100644index d03ff9090..000000000--- a/fincept-cpp/tmp/04_responsive.cpp+++ /dev/null@@ -1,59 +0,0 @@-// Example 4: Responsive layout — adapts to window size-// Shows how breakpoints + Yoga work together for responsive UIs.--#include "ui/yoga_helpers.h"-#include <imgui.h>-#include <cstdio>--using namespace fincept::ui;--void example_responsive() {- // Simulate different screen widths- float test_widths[] = { 500, 700, 1000, 1400 };-- for (float w : test_widths) {- float h = 800;- Breakpoint bp = get_breakpoint(w);-- const char* bp_name = "?";- switch (bp) {- case Breakpoint::Compact: bp_name = "Compact (<600)"; break;- case Breakpoint::Medium: bp_name = "Medium (600-840)"; break;- case Breakpoint::Expanded: bp_name = "Expanded (840-1200)"; break;- case Breakpoint::Large: bp_name = "Large (>1200)"; break;- }-- printf("\n=== Width: %.0f → %s ===\n", w, bp_name);-- // The three_panel_layout function handles responsiveness automatically:- // - Compact: stacks all panels vertically- // - Medium: two panels (collapses right)- // - Expanded/Large: full three panels- auto panels = three_panel_layout(w, h);-- printf("Left: w=%.0f h=%.0f\n", panels.left_w, panels.left_h);- printf("Center: w=%.0f h=%.0f\n", panels.center_w, panels.center_h);- printf("Right: w=%.0f h=%.0f\n", panels.right_w, panels.right_h);-- // Grid also adapts:- auto grid = responsive_grid(w, 280);- printf("Grid: %d columns, %.0fpx each\n", grid.columns, grid.panel_w);- }-}--// When using in a real screen, you'd do:-//-// void MyScreen::render() {-// ScreenFrame frame("##my_screen");-// if (frame.begin()) {-// if (frame.is_compact()) {-// // Single column, simplified UI-// render_compact(frame.width(), frame.height());-// } else {-// // Multi-column layout-// auto panels = three_panel_layout(frame.width(), frame.height());-// render_panels(panels);-// }-// }-// frame.end();-// }diff --git a/fincept-cpp/tmp/05_common_mistakes.cpp b/fincept-cpp/tmp/05_common_mistakes.cppdeleted file mode 100644index d71ee07ab..000000000--- a/fincept-cpp/tmp/05_common_mistakes.cpp+++ /dev/null@@ -1,120 +0,0 @@-// Example 5: Common mistakes and how to fix them-// Read through these — they're the gotchas you'll hit.--#include "ui/yoga_layout.h"-#include <imgui.h>--using namespace fincept::ui;--// ❌ MISTAKE 1: Forgetting to set root size-void mistake_no_root_size() {- YogaLayout layout;- auto root = layout.node().row(); // no width/height!- auto child = root.child().flex_grow(1);- layout.calculate(800, 600); // passes w/h here but root has no constraint-- // Fix: always set root width/height- // auto root = layout.node().row().width(800).height(600);-}--// ❌ MISTAKE 2: Reading layout BEFORE calculate()-void mistake_read_before_calculate() {- YogaLayout layout;- auto root = layout.node().row().width(800).height(600);- auto child = root.child().flex_grow(1);-- // BAD: reading before calculate — all values will be 0!- float w = child.computed_width(); // 0 !!-- layout.calculate(800, 600);- w = child.computed_width(); // NOW it's correct-}--// ❌ MISTAKE 3: Using absolute positions without SetCursorPos-void mistake_no_cursor_pos() {- // If you just do:- // ImGui::BeginChild("panel", node.size());- // without SetCursorPos first, ImGui places it at the current cursor- // position, which is NOT where Yoga computed it should be.-- // Fix: ALWAYS pair them:- // ImGui::SetCursorPos(node.pos());- // ImGui::BeginChild("panel", node.size());-}--// ❌ MISTAKE 4: Mixing Yoga layout with ImGui::SameLine-void mistake_mixing_sameline() {- // Don't do this:- // ImGui::SetCursorPos(left.pos());- // ImGui::BeginChild("left", left.size());- // ImGui::EndChild();- // ImGui::SameLine(); // ❌ Yoga already computed the position!- // ImGui::BeginChild("right", right.size());-- // Fix: use SetCursorPos for EACH child:- // ImGui::SetCursorPos(left.pos());- // ImGui::BeginChild("left", left.size());- // ImGui::EndChild();- // ImGui::SetCursorPos(right.pos()); // ✅ Let Yoga handle positioning- // ImGui::BeginChild("right", right.size());- // ImGui::EndChild();-}--// ❌ MISTAKE 5: Using width_percent without parent having a defined width-void mistake_percent_no_parent() {- YogaLayout layout;- auto root = layout.node().row(); // root has NO width set- auto child = root.child().width_percent(50); // 50% of what?? → 0-- // Fix: root must have a defined width for percent children to work- // auto root = layout.node().row().width(800).height(600);-}--// ❌ MISTAKE 6: Forgetting EndChild() — causes ImGui stack corruption-void mistake_unmatched_begin_end() {- // EVERY BeginChild MUST have a matching EndChild, even if Begin returns false:- //- // ImGui::SetCursorPos(node.pos());- // if (ImGui::BeginChild("panel", node.size())) {- // // draw stuff- // }- // ImGui::EndChild(); // ✅ ALWAYS called, even if BeginChild returned false-}--// ✅ CORRECT: Complete pattern for a Yoga-powered screen-void correct_pattern() {- // This is the pattern to follow for every screen:-- // 1. ScreenFrame handles viewport math- ScreenFrame frame("##example");- if (frame.begin()) {-- // 2. Create Yoga layout- YogaLayout layout;- auto root = layout.node()- .row()- .width(frame.width())- .height(frame.height())- .padding(8).gap(4);-- auto left = root.child().width_percent(25).min_width(200);- auto right = root.child().flex_grow(1);-- // 3. Calculate- layout.calculate(frame.width(), frame.height());-- // 4. Render with computed positions- ImGui::SetCursorPos(left.pos());- if (ImGui::BeginChild("##left", left.size())) {- // sidebar content- }- ImGui::EndChild();-- ImGui::SetCursorPos(right.pos());- if (ImGui::BeginChild("##right", right.size())) {- // main content- }- ImGui::EndChild();- }- frame.end(); // 5. Always end the frame-}diff --git a/fincept-cpp/tmp/CMakeLists.txt b/fincept-cpp/tmp/CMakeLists.txtdeleted file mode 100644index 6918a3503..000000000--- a/fincept-cpp/tmp/CMakeLists.txt+++ /dev/null@@ -1,34 +0,0 @@-cmake_minimum_required(VERSION 3.20)-project(YogaPlayground LANGUAGES CXX)--set(CMAKE_CXX_STANDARD 20)-set(CMAKE_CXX_STANDARD_REQUIRED ON)--# Dependencies (same as parent project via vcpkg)-find_package(yoga CONFIG REQUIRED)-find_package(glfw3 CONFIG REQUIRED)-find_package(imgui CONFIG REQUIRED)-find_package(OpenGL REQUIRED)--# Console-only playground-add_executable(yoga_playground yoga_playground.cpp)-target_link_libraries(yoga_playground PRIVATE yoga::yogacore)--# GUI playground-add_executable(yoga_gui yoga_gui.cpp)-target_link_libraries(yoga_gui PRIVATE- yoga::yogacore- imgui::imgui- glfw- OpenGL::GL-)--if(MSVC)- target_compile_definitions(yoga_playground PRIVATE _CRT_SECURE_NO_WARNINGS)- target_compile_definitions(yoga_gui PRIVATE _CRT_SECURE_NO_WARNINGS)-endif()--if(WIN32)- target_link_libraries(yoga_gui PRIVATE ws2_32)- target_compile_definitions(yoga_gui PRIVATE NOMINMAX WIN32_LEAN_AND_MEAN)-endif()diff --git a/fincept-cpp/tmp/yoga_gui.cpp b/fincept-cpp/tmp/yoga_gui.cppdeleted file mode 100644index 98eea6e52..000000000--- a/fincept-cpp/tmp/yoga_gui.cpp+++ /dev/null@@ -1,806 +0,0 @@-// Bloomberg Terminal Layout Demo — Yoga + ImGui-// Complex multi-panel layout with real-time data simulation--#include <yoga/YGNode.h>-#include <yoga/YGNodeStyle.h>-#include <yoga/YGNodeLayout.h>-#include <yoga/YGEnums.h>--#include <imgui.h>-#include <imgui_impl_glfw.h>-#include <imgui_impl_opengl3.h>-#include <GLFW/glfw3.h>--#include <cstdio>-#include <cmath>-#include <cstring>-#include <string>-#include <vector>--// ============================================================================-// Bloomberg color palette-// ============================================================================-namespace colors {- constexpr ImVec4 BG_DARKEST = {0.047f, 0.047f, 0.051f, 1.0f};- constexpr ImVec4 BG_DARK = {0.075f, 0.075f, 0.082f, 1.0f};- constexpr ImVec4 BG_PANEL = {0.098f, 0.098f, 0.106f, 1.0f};- constexpr ImVec4 BG_HEADER = {0.067f, 0.067f, 0.075f, 1.0f};- constexpr ImVec4 ORANGE = {1.00f, 0.45f, 0.05f, 1.0f};- constexpr ImVec4 GREEN = {0.00f, 0.85f, 0.45f, 1.0f};- constexpr ImVec4 RED = {0.95f, 0.25f, 0.20f, 1.0f};- constexpr ImVec4 CYAN = {0.00f, 0.75f, 0.95f, 1.0f};- constexpr ImVec4 YELLOW = {0.95f, 0.85f, 0.15f, 1.0f};- constexpr ImVec4 PURPLE = {0.60f, 0.40f, 0.95f, 1.0f};- constexpr ImVec4 WHITE = {0.90f, 0.90f, 0.92f, 1.0f};- constexpr ImVec4 DIM = {0.40f, 0.40f, 0.43f, 1.0f};- constexpr ImVec4 DIMMER = {0.28f, 0.28f, 0.30f, 1.0f};- constexpr ImVec4 BORDER = {0.18f, 0.18f, 0.20f, 1.0f};-}--static ImU32 col32(ImVec4 c, float a = -1.0f) {- if (a < 0) a = c.w;- return IM_COL32((int)(c.x*255),(int)(c.y*255),(int)(c.z*255),(int)(a*255));-}--// ============================================================================-// Fake market data-// ============================================================================-struct Ticker {- const char* symbol;- const char* name;- float price;- float change_pct;- float volume_m; // millions-};--static Ticker indices[] = {- {"SPX", "S&P 500", 5842.31f, 0.47f, 3821.4f},- {"INDU", "Dow Jones", 43274.56f, 0.31f, 892.1f},- {"CCMP", "Nasdaq", 18512.73f, 0.68f, 5234.7f},- {"RTY", "Russell 2000", 2287.14f, -0.23f, 1456.2f},- {"UKX", "FTSE 100", 8412.30f, 0.15f, 723.8f},- {"DAX", "DAX", 19876.45f, 0.52f, 612.3f},- {"NKY", "Nikkei 225", 38742.18f, -0.34f, 1893.5f},- {"HSI", "Hang Seng", 20134.67f, 1.12f, 2145.6f},-};--static Ticker currencies[] = {- {"EUR/USD", "Euro", 1.0847f, 0.12f, 0},- {"GBP/USD", "British Pound",1.2734f, -0.08f, 0},- {"USD/JPY", "Japanese Yen", 153.42f, 0.23f, 0},- {"USD/CHF", "Swiss Franc", 0.8812f, -0.15f, 0},- {"AUD/USD", "Aussie Dollar",0.6523f, 0.31f, 0},- {"USD/CAD", "Canadian Dollar",1.3678f, 0.07f, 0},-};--static Ticker commodities[] = {- {"GC1", "Gold", 2687.40f, 0.82f, 234.5f},- {"SI1", "Silver", 31.24f, 1.23f, 89.2f},- {"CL1", "Crude Oil", 71.83f, -0.45f, 567.8f},- {"NG1", "Natural Gas", 2.87f, 2.14f, 345.1f},- {"HG1", "Copper", 4.12f, 0.67f, 123.4f},- {"W 1", "Wheat", 587.25f, -0.92f, 78.3f},-};--struct OrderEntry {- const char* time;- const char* symbol;- const char* side;- int qty;- float price;- const char* status;-};--static OrderEntry orders[] = {- {"14:32:18", "AAPL", "BUY", 500, 198.45f, "FILLED"},- {"14:31:05", "MSFT", "SELL", 200, 425.12f, "FILLED"},- {"14:30:42", "GOOGL", "BUY", 100, 176.83f, "PARTIAL"},- {"14:29:15", "AMZN", "BUY", 300, 195.67f, "FILLED"},- {"14:28:03", "NVDA", "SELL", 150, 875.23f, "WORKING"},- {"14:27:51", "META", "BUY", 400, 542.18f, "FILLED"},- {"14:26:30", "TSLA", "SELL", 250, 245.90f, "FILLED"},- {"14:25:12", "JPM", "BUY", 600, 198.34f, "WORKING"},-};--struct NewsItem {- const char* time;- const char* source;- const char* headline;- ImVec4 tag_color;-};--static NewsItem news[] = {- {"14:32", "BBG", "Fed Minutes Show Officials Divided on Rate Path", colors::ORANGE},- {"14:28", "RTRS", "China PMI Beats Expectations, Manufacturing Expands", colors::GREEN},- {"14:25", "BBG", "Treasury Yields Rise as Inflation Data Comes in Hot", colors::RED},- {"14:22", "CNBC", "NVIDIA Announces Next-Gen AI Chip Architecture", colors::CYAN},- {"14:18", "FT", "European Banks Face New Capital Requirements", colors::YELLOW},- {"14:15", "BBG", "Oil Prices Dip on Surprise Inventory Build", colors::RED},- {"14:12", "WSJ", "Apple Vision Pro Sales Exceed Analyst Forecasts", colors::GREEN},- {"14:08", "RTRS", "BOJ Governor Signals Potential Policy Shift in Q2", colors::PURPLE},- {"14:05", "BBG", "Gold Hits Record as Central Banks Accelerate Buying", colors::YELLOW},- {"14:02", "FT", "UK GDP Growth Surprises to the Upside at 0.6%", colors::GREEN},-};--// Simulated price chart data-static float chart_data[120];-static bool chart_initialized = false;--static void init_chart() {- if (chart_initialized) return;- float base = 5800.0f;- for (int i = 0; i < 120; i++) {- base += sinf(i * 0.15f) * 8.0f + cosf(i * 0.07f) * 12.0f- + sinf(i * 0.3f) * 3.0f + (float)(i % 7 - 3) * 1.5f;- chart_data[i] = base;- }- chart_initialized = true;-}--// ============================================================================-// Panel rendering functions-// ============================================================================--static void panel_header(const char* title, ImVec4 accent = colors::ORANGE) {- ImDrawList* dl = ImGui::GetWindowDrawList();- ImVec2 p = ImGui::GetCursorScreenPos();- float w = ImGui::GetContentRegionAvail().x;-- // Header background- dl->AddRectFilled(p, ImVec2(p.x + w, p.y + 22), col32(colors::BG_HEADER));- // Accent left bar- dl->AddRectFilled(p, ImVec2(p.x + 3, p.y + 22), col32(accent));- // Title- dl->AddText(ImVec2(p.x + 10, p.y + 3), col32(accent), title);-- ImGui::SetCursorPosY(ImGui::GetCursorPosY() + 26);-}--static void render_ticker_table(Ticker* tickers, int count) {- // Header row- ImGui::TextColored(colors::DIM, "%-8s %12s %8s %10s", "SYMBOL", "PRICE", "CHG%", "VOL(M)");- ImGui::Separator();-- for (int i = 0; i < count; i++) {- Ticker& t = tickers[i];- float anim_t = (float)ImGui::GetTime();- // Subtle price animation- float jitter = sinf(anim_t * (1.5f + i * 0.3f) + i * 2.0f) * t.price * 0.0002f;- float display_price = t.price + jitter;- float display_chg = t.change_pct + sinf(anim_t * 0.7f + i) * 0.02f;-- ImVec4 chg_col = display_chg >= 0 ? colors::GREEN : colors::RED;- const char* arrow = display_chg >= 0 ? "+" : "";-- ImGui::TextColored(colors::WHITE, "%-8s", t.symbol);- ImGui::SameLine(100);- ImGui::TextColored(colors::WHITE, "%12.2f", display_price);- ImGui::SameLine(210);- ImGui::TextColored(chg_col, "%s%.2f%%", arrow, display_chg);- if (t.volume_m > 0) {- ImGui::SameLine(300);- ImGui::TextColored(colors::DIM, "%8.1f", t.volume_m);- }- }-}--static void render_chart(float w, float h) {- init_chart();- ImDrawList* dl = ImGui::GetWindowDrawList();- ImVec2 origin = ImGui::GetCursorScreenPos();- float anim_t = (float)ImGui::GetTime();-- // Chart area background- dl->AddRectFilled(origin, ImVec2(origin.x + w, origin.y + h),- col32(colors::BG_DARK));-- // Find min/max for scaling- float min_v = 99999, max_v = -99999;- for (int i = 0; i < 120; i++) {- float v = chart_data[i] + sinf(anim_t * 0.5f + i * 0.1f) * 3.0f;- if (v < min_v) min_v = v;- if (v > max_v) max_v = v;- }- float range = max_v - min_v;- if (range < 1) range = 1;-- float pad_x = 4, pad_y = 8;- float chart_w = w - pad_x * 2;- float chart_h = h - pad_y * 2;-- // Horizontal grid lines- for (int g = 0; g <= 4; g++) {- float gy = origin.y + pad_y + chart_h * (1.0f - g / 4.0f);- dl->AddLine(ImVec2(origin.x + pad_x, gy),- ImVec2(origin.x + w - pad_x, gy),- col32(colors::DIMMER, 0.3f), 1.0f);- float val = min_v + range * (g / 4.0f);- char buf[32];- snprintf(buf, sizeof(buf), "%.0f", val);- dl->AddText(ImVec2(origin.x + pad_x + 2, gy - 12), col32(colors::DIMMER), buf);- }-- // Price line- ImVec2 prev;- for (int i = 0; i < 120; i++) {- float v = chart_data[i] + sinf(anim_t * 0.5f + i * 0.1f) * 3.0f;- float nx = origin.x + pad_x + (i / 119.0f) * chart_w;- float ny = origin.y + pad_y + chart_h * (1.0f - (v - min_v) / range);- ImVec2 cur(nx, ny);- if (i > 0) {- dl->AddLine(prev, cur, col32(colors::CYAN), 1.5f);- }- prev = cur;- }-- // Fill under the line- for (int i = 1; i < 120; i++) {- float v0 = chart_data[i-1] + sinf(anim_t * 0.5f + (i-1) * 0.1f) * 3.0f;- float v1 = chart_data[i] + sinf(anim_t * 0.5f + i * 0.1f) * 3.0f;- float x0 = origin.x + pad_x + ((i-1) / 119.0f) * chart_w;- float x1 = origin.x + pad_x + (i / 119.0f) * chart_w;- float y0 = origin.y + pad_y + chart_h * (1.0f - (v0 - min_v) / range);- float y1 = origin.y + pad_y + chart_h * (1.0f - (v1 - min_v) / range);- float bottom = origin.y + h - pad_y;- dl->AddQuadFilled(ImVec2(x0, y0), ImVec2(x1, y1),- ImVec2(x1, bottom), ImVec2(x0, bottom),- col32(colors::CYAN, 0.06f));- }-- // Current price label- float last_price = chart_data[119] + sinf(anim_t * 0.5f + 119 * 0.1f) * 3.0f;- char price_buf[32];- snprintf(price_buf, sizeof(price_buf), "%.2f", last_price);- float last_y = origin.y + pad_y + chart_h * (1.0f - (last_price - min_v) / range);- dl->AddRectFilled(ImVec2(origin.x + w - 58, last_y - 8),- ImVec2(origin.x + w - 2, last_y + 8),- col32(colors::CYAN, 0.9f), 2.0f);- dl->AddText(ImVec2(origin.x + w - 55, last_y - 6), col32(colors::BG_DARKEST), price_buf);-- ImGui::Dummy(ImVec2(w, h));-}--static void render_orders() {- ImGui::TextColored(colors::DIM, "%-8s %-6s %-5s %5s %10s %-8s",- "TIME", "SYM", "SIDE", "QTY", "PRICE", "STATUS");- ImGui::Separator();-- for (auto& o : orders) {- ImVec4 side_col = (strcmp(o.side, "BUY") == 0) ? colors::GREEN : colors::RED;- ImVec4 status_col = colors::DIM;- if (strcmp(o.status, "FILLED") == 0) status_col = colors::GREEN;- else if (strcmp(o.status, "WORKING") == 0) status_col = colors::YELLOW;- else if (strcmp(o.status, "PARTIAL") == 0) status_col = colors::ORANGE;-- ImGui::TextColored(colors::DIMMER, "%s", o.time);- ImGui::SameLine(80);- ImGui::TextColored(colors::WHITE, "%-6s", o.symbol);- ImGui::SameLine(140);- ImGui::TextColored(side_col, "%-5s", o.side);- ImGui::SameLine(190);- ImGui::TextColored(colors::WHITE, "%5d", o.qty);- ImGui::SameLine(240);- ImGui::TextColored(colors::WHITE, "%10.2f", o.price);- ImGui::SameLine(340);- ImGui::TextColored(status_col, "%s", o.status);- }-}--static void render_news() {- for (auto& n : news) {- ImGui::TextColored(colors::DIMMER, "%s", n.time);- ImGui::SameLine(50);- ImGui::TextColored(n.tag_color, "[%s]", n.source);- ImGui::SameLine(100);- ImGui::TextColored(colors::WHITE, "%s", n.headline);- }-}--static void render_portfolio() {- struct Position {- const char* symbol;- int shares;- float avg_cost;- float current;- };- Position positions[] = {- {"AAPL", 1500, 178.23f, 198.45f},- {"MSFT", 800, 398.50f, 425.12f},- {"GOOGL", 1200, 165.40f, 176.83f},- {"AMZN", 600, 182.75f, 195.67f},- {"NVDA", 400, 812.00f, 875.23f},- {"META", 900, 495.30f, 542.18f},- {"TSLA", 350, 238.60f, 245.90f},- };-- ImGui::TextColored(colors::DIM, "%-6s %6s %10s %10s %10s %8s",- "SYM", "SHARES", "AVG COST", "CURRENT", "P/L", "P/L%");- ImGui::Separator();-- float total_pl = 0;- for (auto& p : positions) {- float pl = (p.current - p.avg_cost) * p.shares;- float pl_pct = ((p.current / p.avg_cost) - 1.0f) * 100.0f;- total_pl += pl;- ImVec4 pl_col = pl >= 0 ? colors::GREEN : colors::RED;-- ImGui::TextColored(colors::WHITE, "%-6s", p.symbol);- ImGui::SameLine(65);- ImGui::TextColored(colors::WHITE, "%6d", p.shares);- ImGui::SameLine(120);- ImGui::TextColored(colors::DIM, "%10.2f", p.avg_cost);- ImGui::SameLine(200);- ImGui::TextColored(colors::WHITE, "%10.2f", p.current);- ImGui::SameLine(280);- ImGui::TextColored(pl_col, "%+10.0f", pl);- ImGui::SameLine(360);- ImGui::TextColored(pl_col, "%+7.2f%%", pl_pct);- }-- ImGui::Separator();- ImVec4 total_col = total_pl >= 0 ? colors::GREEN : colors::RED;- ImGui::TextColored(colors::ORANGE, "TOTAL");- ImGui::SameLine(280);- ImGui::TextColored(total_col, "%+10.0f", total_pl);-}--static void render_heatmap(float w, float h) {- ImDrawList* dl = ImGui::GetWindowDrawList();- ImVec2 origin = ImGui::GetCursorScreenPos();- float anim_t = (float)ImGui::GetTime();-- struct Sector {- const char* name;- float weight; // relative area- float change;- };- Sector sectors[] = {- {"Tech", 0.28f, 0.72f},- {"Health", 0.14f, -0.31f},- {"Finance", 0.13f, 0.45f},- {"Consumer", 0.11f, 0.18f},- {"Industrial", 0.10f, -0.12f},- {"Energy", 0.08f, -0.67f},- {"Materials", 0.06f, 0.33f},- {"Utilities", 0.05f, 0.08f},- {"Real Est", 0.05f, -0.45f},- };- int n = sizeof(sectors) / sizeof(sectors[0]);-- // Simple treemap: lay out in rows- float x = origin.x + 2, y = origin.y + 2;- float usable_w = w - 4, usable_h = h - 4;- float remaining_w = usable_w;- float row_h = usable_h / 3.0f;- int row = 0;- float row_weight = 0;-- // Pre-compute row weights- float row_weights[3] = {0};- int row_assign[9];- float cum = 0;- for (int i = 0; i < n; i++) {- cum += sectors[i].weight;- if (cum <= 0.38f) { row_assign[i] = 0; row_weights[0] += sectors[i].weight; }- else if (cum <= 0.70f) { row_assign[i] = 1; row_weights[1] += sectors[i].weight; }- else { row_assign[i] = 2; row_weights[2] += sectors[i].weight; }- }-- float row_x[3] = {origin.x + 2, origin.x + 2, origin.x + 2};- for (int i = 0; i < n; i++) {- int r = row_assign[i];- float ry = origin.y + 2 + r * row_h;- float cell_w = (sectors[i].weight / row_weights[r]) * usable_w;- float cx = row_x[r];-- // Color based on change- float chg = sectors[i].change + sinf(anim_t * 0.8f + i * 1.5f) * 0.05f;- ImVec4 bg;- if (chg >= 0) {- float intensity = fminf(chg / 1.0f, 1.0f);- bg = ImVec4(0.0f, 0.15f + intensity * 0.25f, 0.05f + intensity * 0.1f, 1.0f);- } else {- float intensity = fminf(-chg / 1.0f, 1.0f);- bg = ImVec4(0.15f + intensity * 0.25f, 0.03f, 0.03f, 1.0f);- }-- dl->AddRectFilled(ImVec2(cx, ry), ImVec2(cx + cell_w - 2, ry + row_h - 2),- col32(bg), 2.0f);- dl->AddRect(ImVec2(cx, ry), ImVec2(cx + cell_w - 2, ry + row_h - 2),- col32(colors::BORDER), 2.0f);-- // Label- if (cell_w > 40) {- ImVec4 text_col = chg >= 0 ? colors::GREEN : colors::RED;- float tx = cx + 5;- float ty = ry + 4;- dl->AddText(ImVec2(tx, ty), col32(colors::WHITE), sectors[i].name);- char buf[16];- snprintf(buf, sizeof(buf), "%+.2f%%", chg);- dl->AddText(ImVec2(tx, ty + 16), col32(text_col), buf);- }-- row_x[r] += cell_w;- }-- ImGui::Dummy(ImVec2(w, h));-}--// ============================================================================-// Status bar ticker animation-// ============================================================================-static void render_status_bar(float w, float h) {- ImDrawList* dl = ImGui::GetWindowDrawList();- ImVec2 origin = ImGui::GetCursorScreenPos();- float anim_t = (float)ImGui::GetTime();-- dl->AddRectFilled(origin, ImVec2(origin.x + w, origin.y + h),- col32(colors::BG_HEADER));-- // Scrolling ticker- float scroll_speed = 40.0f;- float ticker_x = origin.x + 8 - fmodf(anim_t * scroll_speed, 1800.0f);- float ty = origin.y + 3;-- for (auto& t : indices) {- if (ticker_x > origin.x + w + 200) { ticker_x += 180; continue; }- if (ticker_x > origin.x - 200) {- float jitter = sinf(anim_t * 2.0f + ticker_x * 0.01f) * 0.03f;- float chg = t.change_pct + jitter;- ImVec4 chg_col = chg >= 0 ? colors::GREEN : colors::RED;-- dl->AddText(ImVec2(ticker_x, ty), col32(colors::ORANGE), t.symbol);- char buf[32];- snprintf(buf, sizeof(buf), "%.2f", t.price);- dl->AddText(ImVec2(ticker_x + 45, ty), col32(colors::WHITE), buf);- snprintf(buf, sizeof(buf), "%+.2f%%", chg);- dl->AddText(ImVec2(ticker_x + 115, ty), col32(chg_col), buf);- }- ticker_x += 180;- }- // Repeat for seamless scroll- for (auto& t : indices) {- if (ticker_x > origin.x + w + 200) break;- if (ticker_x > origin.x - 200) {- float chg = t.change_pct;- ImVec4 chg_col = chg >= 0 ? colors::GREEN : colors::RED;- dl->AddText(ImVec2(ticker_x, ty), col32(colors::ORANGE), t.symbol);- char buf[32];- snprintf(buf, sizeof(buf), "%.2f", t.price);- dl->AddText(ImVec2(ticker_x + 45, ty), col32(colors::WHITE), buf);- snprintf(buf, sizeof(buf), "%+.2f%%", chg);- dl->AddText(ImVec2(ticker_x + 115, ty), col32(chg_col), buf);- }- ticker_x += 180;- }-- // Right side: clock- float time_val = fmodf(anim_t, 86400.0f) + 52200.0f; // start at ~14:30- int hh = ((int)(time_val / 3600)) % 24;- int mm = ((int)(time_val / 60)) % 60;- int ss = ((int)time_val) % 60;- char clock[32];- snprintf(clock, sizeof(clock), "NYC %02d:%02d:%02d", hh, mm, ss);- float clock_w = ImGui::CalcTextSize(clock).x;- dl->AddText(ImVec2(origin.x + w - clock_w - 12, ty), col32(colors::ORANGE), clock);-- ImGui::Dummy(ImVec2(w, h));-}--// ============================================================================-// Main-// ============================================================================-int main() {- if (!glfwInit()) return 1;-- glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3);- glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3);- glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);-- GLFWwindow* window = glfwCreateWindow(1600, 950,- "Bloomberg Terminal — Yoga Layout Demo", nullptr, nullptr);- if (!window) { glfwTerminate(); return 1; }-- glfwMakeContextCurrent(window);- glfwSwapInterval(1);-- IMGUI_CHECKVERSION();- ImGui::CreateContext();- ImGui::GetIO().ConfigFlags |= ImGuiConfigFlags_NavEnableKeyboard;-- ImGui::StyleColorsDark();- ImGuiStyle& style = ImGui::GetStyle();- style.WindowRounding = 0;- style.ChildRounding = 2.0f;- style.FrameRounding = 2.0f;- style.WindowBorderSize = 0;- style.ChildBorderSize = 1.0f;- style.WindowPadding = ImVec2(0, 0);- style.Colors[ImGuiCol_WindowBg] = colors::BG_DARKEST;- style.Colors[ImGuiCol_ChildBg] = colors::BG_PANEL;- style.Colors[ImGuiCol_Border] = colors::BORDER;- style.Colors[ImGuiCol_Separator] = colors::BORDER;-- ImGui_ImplGlfw_InitForOpenGL(window, true);- ImGui_ImplOpenGL3_Init("#version 330 core");-- while (!glfwWindowShouldClose(window)) {- glfwPollEvents();- ImGui_ImplOpenGL3_NewFrame();- ImGui_ImplGlfw_NewFrame();- ImGui::NewFrame();-- ImGuiViewport* vp = ImGui::GetMainViewport();- float screen_w = vp->WorkSize.x;- float screen_h = vp->WorkSize.y;-- // ==================================================================- // YOGA LAYOUT — Full Bloomberg terminal structure- // ==================================================================- // Outer: column [ticker_bar | main_body | status_bar]- // main_body: row [left_col | center_col | right_col]- // left_col: column [indices | currencies | commodities]- // center_col: column [chart | order_book]- // right_col: column [portfolio | heatmap | news]- // ==================================================================-- YGNodeRef root = YGNodeNew();- YGNodeStyleSetFlexDirection(root, YGFlexDirectionColumn);- YGNodeStyleSetWidth(root, screen_w);- YGNodeStyleSetHeight(root, screen_h);-- // Ticker bar (top)- YGNodeRef ticker_bar = YGNodeNew();- YGNodeStyleSetHeight(ticker_bar, 22);- YGNodeInsertChild(root, ticker_bar, 0);-- // Main body (fills remaining)- YGNodeRef body = YGNodeNew();- YGNodeStyleSetFlexGrow(body, 1);- YGNodeStyleSetFlexDirection(body, YGFlexDirectionRow);- YGNodeStyleSetPadding(body, YGEdgeAll, 2);- YGNodeStyleSetGap(body, YGGutterAll, 2);- YGNodeInsertChild(root, body, 1);-- // Status bar (bottom)- YGNodeRef status_bar = YGNodeNew();- YGNodeStyleSetHeight(status_bar, 22);- YGNodeInsertChild(root, status_bar, 2);-- // --- Left column: 20%, min 280 ---- YGNodeRef left_col = YGNodeNew();- YGNodeStyleSetWidthPercent(left_col, 20);- YGNodeStyleSetMinWidth(left_col, 280);- YGNodeStyleSetFlexDirection(left_col, YGFlexDirectionColumn);- YGNodeStyleSetGap(left_col, YGGutterAll, 2);- YGNodeInsertChild(body, left_col, 0);-- YGNodeRef indices_panel = YGNodeNew();- YGNodeStyleSetFlexGrow(indices_panel, 1);- YGNodeInsertChild(left_col, indices_panel, 0);-- YGNodeRef fx_panel = YGNodeNew();- YGNodeStyleSetFlexGrow(fx_panel, 0.8f);- YGNodeInsertChild(left_col, fx_panel, 1);-- YGNodeRef comm_panel = YGNodeNew();- YGNodeStyleSetFlexGrow(comm_panel, 0.8f);- YGNodeInsertChild(left_col, comm_panel, 2);-- // --- Center column: flex grow ---- YGNodeRef center_col = YGNodeNew();- YGNodeStyleSetFlexGrow(center_col, 1);- YGNodeStyleSetMinWidth(center_col, 300);- YGNodeStyleSetFlexDirection(center_col, YGFlexDirectionColumn);- YGNodeStyleSetGap(center_col, YGGutterAll, 2);- YGNodeInsertChild(body, center_col, 1);-- YGNodeRef chart_panel = YGNodeNew();- YGNodeStyleSetFlexGrow(chart_panel, 1.2f);- YGNodeInsertChild(center_col, chart_panel, 0);-- YGNodeRef orders_panel = YGNodeNew();- YGNodeStyleSetFlexGrow(orders_panel, 1);- YGNodeInsertChild(center_col, orders_panel, 1);-- // --- Right column: 28%, min 320 ---- YGNodeRef right_col = YGNodeNew();- YGNodeStyleSetWidthPercent(right_col, 28);- YGNodeStyleSetMinWidth(right_col, 320);- YGNodeStyleSetFlexDirection(right_col, YGFlexDirectionColumn);- YGNodeStyleSetGap(right_col, YGGutterAll, 2);- YGNodeInsertChild(body, right_col, 2);-- YGNodeRef portfolio_panel = YGNodeNew();- YGNodeStyleSetFlexGrow(portfolio_panel, 1);- YGNodeInsertChild(right_col, portfolio_panel, 0);-- YGNodeRef heatmap_panel = YGNodeNew();- YGNodeStyleSetHeightPercent(heatmap_panel, 30);- YGNodeStyleSetMinHeight(heatmap_panel, 120);- YGNodeInsertChild(right_col, heatmap_panel, 1);-- YGNodeRef news_panel = YGNodeNew();- YGNodeStyleSetFlexGrow(news_panel, 1);- YGNodeInsertChild(right_col, news_panel, 2);-- // --- CALCULATE ---- YGNodeCalculateLayout(root, screen_w, screen_h, YGDirectionLTR);-- // ==================================================================- // Read computed positions- // ==================================================================- auto get_rect = [&](YGNodeRef node, YGNodeRef parent, YGNodeRef grandparent = nullptr) {- float x = YGNodeLayoutGetLeft(node);- float y = YGNodeLayoutGetTop(node);- if (parent) {- x += YGNodeLayoutGetLeft(parent);- y += YGNodeLayoutGetTop(parent);- }- if (grandparent) {- x += YGNodeLayoutGetLeft(grandparent);- y += YGNodeLayoutGetTop(grandparent);- }- float w = YGNodeLayoutGetWidth(node);- float h = YGNodeLayoutGetHeight(node);- return ImVec4(vp->WorkPos.x + x, vp->WorkPos.y + y, w, h);- };-- // Ticker bar rect- ImVec4 r_ticker = get_rect(ticker_bar, nullptr);- // Status bar rect- ImVec4 r_status = get_rect(status_bar, nullptr);- // Left panels- ImVec4 r_indices = get_rect(indices_panel, left_col, body);- ImVec4 r_fx = get_rect(fx_panel, left_col, body);- ImVec4 r_comm = get_rect(comm_panel, left_col, body);- // Center panels- ImVec4 r_chart = get_rect(chart_panel, center_col, body);- ImVec4 r_orders = get_rect(orders_panel, center_col, body);- // Right panels- ImVec4 r_port = get_rect(portfolio_panel, right_col, body);- ImVec4 r_heat = get_rect(heatmap_panel, right_col, body);- ImVec4 r_news = get_rect(news_panel, right_col, body);-- YGNodeFreeRecursive(root);-- // ==================================================================- // RENDER — fullscreen host window- // ==================================================================- ImGui::SetNextWindowPos(vp->WorkPos);- ImGui::SetNextWindowSize(vp->WorkSize);- ImGui::Begin("##bloomberg", nullptr,- ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_NoResize |- ImGuiWindowFlags_NoMove | ImGuiWindowFlags_NoCollapse |- ImGuiWindowFlags_NoBringToFrontOnFocus | ImGuiWindowFlags_NoDocking);-- // --- Scrolling ticker bar ---- ImGui::SetCursorScreenPos(ImVec2(r_ticker.x, r_ticker.y));- render_status_bar(r_ticker.z, r_ticker.w);-- // --- Left: Indices ---- ImGui::SetCursorScreenPos(ImVec2(r_indices.x, r_indices.y));- if (ImGui::BeginChild("##indices", ImVec2(r_indices.z, r_indices.w), ImGuiChildFlags_Borders)) {- panel_header("GLOBAL INDICES", colors::CYAN);- ImGui::PushStyleVar(ImGuiStyleVar_ItemSpacing, ImVec2(4, 2));- render_ticker_table(indices, 8);- ImGui::PopStyleVar();- }- ImGui::EndChild();-- // --- Left: FX ---- ImGui::SetCursorScreenPos(ImVec2(r_fx.x, r_fx.y));- if (ImGui::BeginChild("##fx", ImVec2(r_fx.z, r_fx.w), ImGuiChildFlags_Borders)) {- panel_header("CURRENCIES", colors::YELLOW);- ImGui::PushStyleVar(ImGuiStyleVar_ItemSpacing, ImVec2(4, 2));- render_ticker_table(currencies, 6);- ImGui::PopStyleVar();- }- ImGui::EndChild();-- // --- Left: Commodities ---- ImGui::SetCursorScreenPos(ImVec2(r_comm.x, r_comm.y));- if (ImGui::BeginChild("##comm", ImVec2(r_comm.z, r_comm.w), ImGuiChildFlags_Borders)) {- panel_header("COMMODITIES", colors::ORANGE);- ImGui::PushStyleVar(ImGuiStyleVar_ItemSpacing, ImVec2(4, 2));- render_ticker_table(commodities, 6);- ImGui::PopStyleVar();- }- ImGui::EndChild();-- // --- Center: Chart ---- ImGui::SetCursorScreenPos(ImVec2(r_chart.x, r_chart.y));- if (ImGui::BeginChild("##chart", ImVec2(r_chart.z, r_chart.w), ImGuiChildFlags_Borders)) {- panel_header("S&P 500 — INTRADAY", colors::CYAN);- float cw = ImGui::GetContentRegionAvail().x;- float ch = ImGui::GetContentRegionAvail().y;- render_chart(cw, ch);- }- ImGui::EndChild();-- // --- Center: Orders ---- ImGui::SetCursorScreenPos(ImVec2(r_orders.x, r_orders.y));- if (ImGui::BeginChild("##orders", ImVec2(r_orders.z, r_orders.w), ImGuiChildFlags_Borders)) {- panel_header("ORDER BOOK", colors::GREEN);- ImGui::PushStyleVar(ImGuiStyleVar_ItemSpacing, ImVec2(4, 2));- render_orders();- ImGui::PopStyleVar();- }- ImGui::EndChild();-- // --- Right: Portfolio ---- ImGui::SetCursorScreenPos(ImVec2(r_port.x, r_port.y));- if (ImGui::BeginChild("##portfolio", ImVec2(r_port.z, r_port.w), ImGuiChildFlags_Borders)) {- panel_header("PORTFOLIO", colors::GREEN);- ImGui::PushStyleVar(ImGuiStyleVar_ItemSpacing, ImVec2(4, 2));- render_portfolio();- ImGui::PopStyleVar();- }- ImGui::EndChild();-- // --- Right: Heatmap ---- ImGui::SetCursorScreenPos(ImVec2(r_heat.x, r_heat.y));- if (ImGui::BeginChild("##heatmap", ImVec2(r_heat.z, r_heat.w), ImGuiChildFlags_Borders)) {- panel_header("SECTOR HEATMAP", colors::PURPLE);- float hw = ImGui::GetContentRegionAvail().x;- float hh = ImGui::GetContentRegionAvail().y;- render_heatmap(hw, hh);- }- ImGui::EndChild();-- // --- Right: News ---- ImGui::SetCursorScreenPos(ImVec2(r_news.x, r_news.y));- if (ImGui::BeginChild("##news", ImVec2(r_news.z, r_news.w), ImGuiChildFlags_Borders)) {- panel_header("NEWS WIRE", colors::ORANGE);- ImGui::PushStyleVar(ImGuiStyleVar_ItemSpacing, ImVec2(4, 3));- render_news();- ImGui::PopStyleVar();- }- ImGui::EndChild();-- // --- Bottom status bar ---- ImGui::SetCursorScreenPos(ImVec2(r_status.x, r_status.y));- {- ImDrawList* dl = ImGui::GetWindowDrawList();- dl->AddRectFilled(ImVec2(r_status.x, r_status.y),- ImVec2(r_status.x + r_status.z, r_status.y + r_status.w),- col32(colors::BG_HEADER));- // Accent top border- dl->AddRectFilled(ImVec2(r_status.x, r_status.y),- ImVec2(r_status.x + r_status.z, r_status.y + 1),- col32(colors::ORANGE, 0.3f));-- dl->AddText(ImVec2(r_status.x + 8, r_status.y + 4),- col32(colors::ORANGE), "FINCEPT TERMINAL");- dl->AddText(ImVec2(r_status.x + 160, r_status.y + 4),- col32(colors::DIM), "YOGA LAYOUT DEMO");- dl->AddText(ImVec2(r_status.x + 320, r_status.y + 4),- col32(colors::DIMMER), "All data simulated | Resize window to test responsive layout");-- char fps[32];- snprintf(fps, sizeof(fps), "%.0f FPS", ImGui::GetIO().Framerate);- float fps_w = ImGui::CalcTextSize(fps).x;- dl->AddText(ImVec2(r_status.x + r_status.z - fps_w - 12, r_status.y + 4),- col32(colors::DIM), fps);- }-- ImGui::End();-- // Render- ImGui::Render();- int dw, dh;- glfwGetFramebufferSize(window, &dw, &dh);- glViewport(0, 0, dw, dh);- glClearColor(colors::BG_DARKEST.x, colors::BG_DARKEST.y, colors::BG_DARKEST.z, 1.0f);- glClear(GL_COLOR_BUFFER_BIT);- ImGui_ImplOpenGL3_RenderDrawData(ImGui::GetDrawData());- glfwSwapBuffers(window);- }-- ImGui_ImplOpenGL3_Shutdown();- ImGui_ImplGlfw_Shutdown();- ImGui::DestroyContext();- glfwDestroyWindow(window);- glfwTerminate();- return 0;-}diff --git a/fincept-cpp/tmp/yoga_playground.cpp b/fincept-cpp/tmp/yoga_playground.cppdeleted file mode 100644index ade3232a8..000000000--- a/fincept-cpp/tmp/yoga_playground.cpp+++ /dev/null@@ -1,407 +0,0 @@-// Yoga Playground — standalone console app to learn Yoga layout-// Prints computed layout values so you can see exactly how flexbox works.--#include <yoga/YGNode.h>-#include <yoga/YGNodeStyle.h>-#include <yoga/YGNodeLayout.h>-#include <yoga/YGEnums.h>-#include <cstdio>-#include <vector>--// Helper to print a node's computed rect-void print_node(const char* name, YGNodeRef node) {- printf(" %-20s x=%6.1f y=%6.1f w=%6.1f h=%6.1f\n",- name,- YGNodeLayoutGetLeft(node),- YGNodeLayoutGetTop(node),- YGNodeLayoutGetWidth(node),- YGNodeLayoutGetHeight(node));-}--void separator(const char* title) {- printf("\n========================================\n");- printf(" %s\n", title);- printf("========================================\n\n");-}--// ============================================================================-// Example 1: Two columns — fixed + flexible-// ============================================================================-void example_two_columns() {- separator("1. TWO COLUMNS (fixed sidebar + flexible main)");-- printf(" Concept: flex_grow(1) means 'take all remaining space'\n");- printf(" Container: 800 x 600, Row direction\n\n");-- YGNodeRef root = YGNodeNew();- YGNodeStyleSetFlexDirection(root, YGFlexDirectionRow);- YGNodeStyleSetWidth(root, 800);- YGNodeStyleSetHeight(root, 600);-- YGNodeRef sidebar = YGNodeNew();- YGNodeStyleSetWidth(sidebar, 200); // fixed 200px-- YGNodeRef main_area = YGNodeNew();- YGNodeStyleSetFlexGrow(main_area, 1); // takes remaining 600px-- YGNodeInsertChild(root, sidebar, 0);- YGNodeInsertChild(root, main_area, 1);-- YGNodeCalculateLayout(root, 800, 600, YGDirectionLTR);-- print_node("sidebar (w=200)", sidebar);- print_node("main (grow=1)", main_area);-- printf("\n -> Sidebar is fixed at 200px\n");- printf(" -> Main fills remaining: 800 - 200 = 600px\n");-- YGNodeFreeRecursive(root);-}--// ============================================================================-// Example 2: Three columns with percentages-// ============================================================================-void example_three_columns() {- separator("2. THREE COLUMNS (percentage widths)");-- printf(" Concept: width_percent distributes space proportionally\n");- printf(" Container: 1200 x 800, Row direction\n\n");-- YGNodeRef root = YGNodeNew();- YGNodeStyleSetFlexDirection(root, YGFlexDirectionRow);- YGNodeStyleSetWidth(root, 1200);- YGNodeStyleSetHeight(root, 800);- YGNodeStyleSetGap(root, YGGutterAll, 4); // 4px gap between children-- YGNodeRef left = YGNodeNew();- YGNodeStyleSetWidthPercent(left, 20); // 20%-- YGNodeRef center = YGNodeNew();- YGNodeStyleSetFlexGrow(center, 1); // fills remaining-- YGNodeRef right = YGNodeNew();- YGNodeStyleSetWidthPercent(right, 25); // 25%-- YGNodeInsertChild(root, left, 0);- YGNodeInsertChild(root, center, 1);- YGNodeInsertChild(root, right, 2);-- YGNodeCalculateLayout(root, 1200, 800, YGDirectionLTR);-- print_node("left (20%)", left);- print_node("center (grow=1)", center);- print_node("right (25%)", right);-- printf("\n -> Left: 20%% of 1200 = ~240px\n");- printf(" -> Right: 25%% of 1200 = ~300px\n");- printf(" -> Center: remaining space (minus gaps)\n");-- YGNodeFreeRecursive(root);-}--// ============================================================================-// Example 3: Vertical stack (column direction)-// ============================================================================-void example_vertical_stack() {- separator("3. VERTICAL STACK (header + content + footer)");-- printf(" Concept: Column direction stacks top-to-bottom\n");- printf(" flex_grow on content = fill remaining vertical space\n");- printf(" Container: 800 x 600\n\n");-- YGNodeRef root = YGNodeNew();- YGNodeStyleSetFlexDirection(root, YGFlexDirectionColumn);- YGNodeStyleSetWidth(root, 800);- YGNodeStyleSetHeight(root, 600);-- YGNodeRef header = YGNodeNew();- YGNodeStyleSetHeight(header, 40); // fixed 40px-- YGNodeRef content = YGNodeNew();- YGNodeStyleSetFlexGrow(content, 1); // fills remaining-- YGNodeRef footer = YGNodeNew();- YGNodeStyleSetHeight(footer, 30); // fixed 30px-- YGNodeInsertChild(root, header, 0);- YGNodeInsertChild(root, content, 1);- YGNodeInsertChild(root, footer, 2);-- YGNodeCalculateLayout(root, 800, 600, YGDirectionLTR);-- print_node("header (h=40)", header);- print_node("content (grow=1)", content);- print_node("footer (h=30)", footer);-- printf("\n -> Header: fixed 40px at top\n");- printf(" -> Content: 600 - 40 - 30 = 530px\n");- printf(" -> Footer: fixed 30px at bottom\n");-- YGNodeFreeRecursive(root);-}--// ============================================================================-// Example 4: Padding and gaps-// ============================================================================-void example_padding_and_gaps() {- separator("4. PADDING AND GAPS");-- printf(" Concept: Padding = inner space, Gap = space between children\n");- printf(" Container: 800 x 600, padding=16, gap=8\n\n");-- YGNodeRef root = YGNodeNew();- YGNodeStyleSetFlexDirection(root, YGFlexDirectionRow);- YGNodeStyleSetWidth(root, 800);- YGNodeStyleSetHeight(root, 600);- YGNodeStyleSetPadding(root, YGEdgeAll, 16); // 16px inner padding- YGNodeStyleSetGap(root, YGGutterAll, 8); // 8px between children-- YGNodeRef a = YGNodeNew();- YGNodeStyleSetFlexGrow(a, 1);-- YGNodeRef b = YGNodeNew();- YGNodeStyleSetFlexGrow(b, 1);-- YGNodeRef c = YGNodeNew();- YGNodeStyleSetFlexGrow(c, 1);-- YGNodeInsertChild(root, a, 0);- YGNodeInsertChild(root, b, 1);- YGNodeInsertChild(root, c, 2);-- YGNodeCalculateLayout(root, 800, 600, YGDirectionLTR);-- print_node("child A", a);- print_node("child B", b);- print_node("child C", c);-- float usable = 800 - 16*2 - 8*2; // total - padding*2 - gap*2- printf("\n -> Usable width: 800 - 32 (padding) - 16 (gaps) = %.0f\n", usable);- printf(" -> Each child: %.0f / 3 = %.1f\n", usable, usable / 3);- printf(" -> Notice x positions offset by padding (16) and gaps (8)\n");-- YGNodeFreeRecursive(root);-}--// ============================================================================-// Example 5: min/max constraints-// ============================================================================-void example_min_max() {- separator("5. MIN/MAX WIDTH CONSTRAINTS");-- printf(" Concept: min_width/max_width set bounds on computed size\n\n");-- // Test with wide container- printf(" --- Wide container (1400px) ---\n");- {- YGNodeRef root = YGNodeNew();- YGNodeStyleSetFlexDirection(root, YGFlexDirectionRow);- YGNodeStyleSetWidth(root, 1400);- YGNodeStyleSetHeight(root, 600);-- YGNodeRef sidebar = YGNodeNew();- YGNodeStyleSetWidthPercent(sidebar, 30);- YGNodeStyleSetMinWidth(sidebar, 150);- YGNodeStyleSetMaxWidth(sidebar, 300);-- YGNodeRef main_area = YGNodeNew();- YGNodeStyleSetFlexGrow(main_area, 1);-- YGNodeInsertChild(root, sidebar, 0);- YGNodeInsertChild(root, main_area, 1);-- YGNodeCalculateLayout(root, 1400, 600, YGDirectionLTR);-- print_node("sidebar (30%, max=300)", sidebar);- print_node("main", main_area);- printf(" -> 30%% of 1400 = 420, but max=300, so clamped to 300\n");-- YGNodeFreeRecursive(root);- }-- // Test with narrow container- printf("\n --- Narrow container (400px) ---\n");- {- YGNodeRef root = YGNodeNew();- YGNodeStyleSetFlexDirection(root, YGFlexDirectionRow);- YGNodeStyleSetWidth(root, 400);- YGNodeStyleSetHeight(root, 600);-- YGNodeRef sidebar = YGNodeNew();- YGNodeStyleSetWidthPercent(sidebar, 30);- YGNodeStyleSetMinWidth(sidebar, 150);- YGNodeStyleSetMaxWidth(sidebar, 300);-- YGNodeRef main_area = YGNodeNew();- YGNodeStyleSetFlexGrow(main_area, 1);-- YGNodeInsertChild(root, sidebar, 0);- YGNodeInsertChild(root, main_area, 1);-- YGNodeCalculateLayout(root, 400, 600, YGDirectionLTR);-- print_node("sidebar (30%, min=150)", sidebar);- print_node("main", main_area);- printf(" -> 30%% of 400 = 120, but min=150, so bumped to 150\n");-- YGNodeFreeRecursive(root);- }-}--// ============================================================================-// Example 6: Nested layouts (vertical outer, horizontal inner)-// ============================================================================-void example_nested() {- separator("6. NESTED LAYOUT (vertical outer, horizontal inner)");-- printf(" Concept: Children can have their own flex direction\n");- printf(" Outer: column (header + body), Inner body: row (list + detail)\n\n");-- YGNodeRef root = YGNodeNew();- YGNodeStyleSetFlexDirection(root, YGFlexDirectionColumn);- YGNodeStyleSetWidth(root, 1000);- YGNodeStyleSetHeight(root, 700);-- // Header: fixed 50px- YGNodeRef header = YGNodeNew();- YGNodeStyleSetHeight(header, 50);-- // Body: fills remaining, has its own row children- YGNodeRef body = YGNodeNew();- YGNodeStyleSetFlexGrow(body, 1);- YGNodeStyleSetFlexDirection(body, YGFlexDirectionRow); // inner row!- YGNodeStyleSetGap(body, YGGutterAll, 4);-- // Body's children- YGNodeRef list = YGNodeNew();- YGNodeStyleSetWidthPercent(list, 30);-- YGNodeRef detail = YGNodeNew();- YGNodeStyleSetFlexGrow(detail, 1);-- YGNodeInsertChild(body, list, 0);- YGNodeInsertChild(body, detail, 1);-- YGNodeInsertChild(root, header, 0);- YGNodeInsertChild(root, body, 1);-- YGNodeCalculateLayout(root, 1000, 700, YGDirectionLTR);-- printf(" Outer (column):\n");- print_node("header (h=50)", header);- print_node("body (grow=1)", body);- printf("\n Inner body (row):\n");- print_node("list (30%%)", list);- print_node("detail (grow=1)", detail);-- printf("\n -> Header: 50px tall, full width\n");- printf(" -> Body: 700-50 = 650px tall\n");- printf(" -> List: 30%% of 1000 = 300px wide, 650px tall\n");- printf(" -> Detail: remaining width, 650px tall\n");- printf("\n NOTE: list and detail y=0 because they're relative to body,\n");- printf(" not to root. In ImGui you'd nest BeginChild calls.\n");-- YGNodeFreeRecursive(root);-}--// ============================================================================-// Example 7: flex_grow ratios-// ============================================================================-void example_flex_grow_ratios() {- separator("7. FLEX GROW RATIOS");-- printf(" Concept: flex_grow values are RATIOS, not absolute sizes\n");- printf(" Container: 900px wide\n\n");-- YGNodeRef root = YGNodeNew();- YGNodeStyleSetFlexDirection(root, YGFlexDirectionRow);- YGNodeStyleSetWidth(root, 900);- YGNodeStyleSetHeight(root, 100);-- YGNodeRef a = YGNodeNew();- YGNodeStyleSetFlexGrow(a, 1); // 1 part-- YGNodeRef b = YGNodeNew();- YGNodeStyleSetFlexGrow(b, 2); // 2 parts-- YGNodeRef c = YGNodeNew();- YGNodeStyleSetFlexGrow(c, 3); // 3 parts-- YGNodeInsertChild(root, a, 0);- YGNodeInsertChild(root, b, 1);- YGNodeInsertChild(root, c, 2);-- YGNodeCalculateLayout(root, 900, 100, YGDirectionLTR);-- print_node("A (grow=1)", a);- print_node("B (grow=2)", b);- print_node("C (grow=3)", c);-- printf("\n -> Total grow = 1+2+3 = 6\n");- printf(" -> A = 900 * 1/6 = 150px\n");- printf(" -> B = 900 * 2/6 = 300px\n");- printf(" -> C = 900 * 3/6 = 450px\n");-- YGNodeFreeRecursive(root);-}--// ============================================================================-// Example 8: Alignment-// ============================================================================-void example_alignment() {- separator("8. ALIGNMENT (justify + align_items)");-- printf(" justify_content = main axis (horizontal in row)\n");- printf(" align_items = cross axis (vertical in row)\n\n");-- // Center both axes- YGNodeRef root = YGNodeNew();- YGNodeStyleSetFlexDirection(root, YGFlexDirectionRow);- YGNodeStyleSetWidth(root, 400);- YGNodeStyleSetHeight(root, 400);- YGNodeStyleSetJustifyContent(root, YGJustifyCenter);- YGNodeStyleSetAlignItems(root, YGAlignCenter);-- YGNodeRef box = YGNodeNew();- YGNodeStyleSetWidth(box, 100);- YGNodeStyleSetHeight(box, 100);-- YGNodeInsertChild(root, box, 0);-- YGNodeCalculateLayout(root, 400, 400, YGDirectionLTR);-- print_node("box (centered)", box);-- printf("\n -> Box should be at (150, 150) — dead center of 400x400\n");- printf(" -> justify:center → x = (400-100)/2 = 150\n");- printf(" -> align:center → y = (400-100)/2 = 150\n");-- YGNodeFreeRecursive(root);-}--// ============================================================================-// Main-// ============================================================================-int main() {- printf("╔══════════════════════════════════════════╗\n");- printf("║ YOGA LAYOUT PLAYGROUND ║\n");- printf("║ Learn flexbox by seeing the numbers ║\n");- printf("╚══════════════════════════════════════════╝\n");-- example_two_columns();- example_three_columns();- example_vertical_stack();- example_padding_and_gaps();- example_min_max();- example_nested();- example_flex_grow_ratios();- example_alignment();-- printf("\n========================================\n");- printf(" Done! All layouts computed successfully.\n");- printf(" These are the same computations that\n");- printf(" happen every frame in the terminal app.\n");- printf("========================================\n\n");-- return 0;-}