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
cpp migration
tilakpatel22481c2c4da888
diff --git a/fincept-cpp/CMakeLists.txt b/fincept-cpp/CMakeLists.txtindex f766687f3..d8e4cc905 100644--- a/fincept-cpp/CMakeLists.txt+++ b/fincept-cpp/CMakeLists.txt@@ -36,6 +36,7 @@ set(SOURCESsrc/http/http_client.cppsrc/storage/database.cppsrc/storage/crypto.cpp+ src/storage/cache_service.cpp# Authsrc/auth/auth_api.cpp@@ -130,6 +131,8 @@ set(SOURCESsrc/trading/paper_trading.cppsrc/trading/order_matcher.cppsrc/trading/exchange_service.cpp+ src/trading/broker_registry.cpp+ src/trading/brokers/fyers_broker.cppsrc/screens/portfolio/portfolio_screen.cppsrc/screens/portfolio/views/analytics_view.cppsrc/screens/portfolio/views/performance_view.cpp@@ -192,6 +195,17 @@ set(SOURCESsrc/screens/gov_data/providers/universal_ckan.cppsrc/screens/gov_data/providers/data_gov_hk.cpp+ # Screens — Backtesting+ src/screens/backtesting/backtesting_data.cpp+ src/screens/backtesting/backtesting_screen.cpp++ # Screens — Algo Trading+ src/screens/algo_trading/algo_trading_screen.cpp+ src/screens/algo_trading/algo_service.cpp++ # Trading — Unified Trading+ src/trading/unified_trading.cpp+# Screens — Code Editorsrc/screens/code_editor/notebook_io.cppsrc/screens/code_editor/code_editor_screen.cpp@@ -221,12 +235,18 @@ target_include_directories(${PROJECT_NAME} PRIVATE# Compiler warnings (enable for code quality, CI enforcement)# =============================================================================if(MSVC)- target_compile_options(${PROJECT_NAME} PRIVATE /W3)+ target_compile_options(${PROJECT_NAME} PRIVATE /W3 /FS)target_compile_definitions(${PROJECT_NAME} PRIVATE _CRT_SECURE_NO_WARNINGS)else()target_compile_options(${PROJECT_NAME} PRIVATE -Wall -Wextra -Wpedantic)endif()+# Enable 32-bit Unicode (emoji support) and FreeType color glyphs+target_compile_definitions(${PROJECT_NAME} PRIVATE+ IMGUI_USE_WCHAR32+ IMGUI_ENABLE_FREETYPE+)+target_link_libraries(${PROJECT_NAME} PRIVATEglfwOpenGL::GLdiff --git a/fincept-cpp/scripts/exchange/fetch_funding_rate.py b/fincept-cpp/scripts/exchange/fetch_funding_rate.pynew file mode 100644index 000000000..1bc0d5246--- /dev/null+++ b/fincept-cpp/scripts/exchange/fetch_funding_rate.py@@ -0,0 +1,34 @@+"""+Fetch current funding rate for a perpetual futures symbol.+Usage: python fetch_funding_rate.py <exchange_id> <symbol>+"""+import sys+from exchange_client import make_exchange, output_success, output_error, run_with_error_handling++@run_with_error_handling+def main():+ if len(sys.argv) < 3:+ output_error("Usage: fetch_funding_rate.py <exchange_id> <symbol>", "INVALID_ARGS")++ exchange_id = sys.argv[1]+ symbol = sys.argv[2]++ exchange = make_exchange(exchange_id)+ exchange.options["defaultType"] = "swap"++ try:+ rate = exchange.fetch_funding_rate(symbol)+ output_success({+ "symbol": symbol,+ "funding_rate": rate.get("fundingRate"),+ "funding_timestamp": rate.get("fundingTimestamp"),+ "next_funding_timestamp": rate.get("nextFundingTimestamp"),+ "mark_price": rate.get("markPrice"),+ "index_price": rate.get("indexPrice"),+ "interest_rate": rate.get("interestRate"),+ })+ except Exception as e:+ output_error(f"Funding rate not available: {e}", "NOT_SUPPORTED")++if __name__ == "__main__":+ main()diff --git a/fincept-cpp/scripts/exchange/fetch_mark_price.py b/fincept-cpp/scripts/exchange/fetch_mark_price.pynew file mode 100644index 000000000..009772bee--- /dev/null+++ b/fincept-cpp/scripts/exchange/fetch_mark_price.py@@ -0,0 +1,31 @@+"""+Fetch mark price and index price for liquidation calculations.+Usage: python fetch_mark_price.py <exchange_id> <symbol>+"""+import sys+from exchange_client import make_exchange, output_success, output_error, run_with_error_handling++@run_with_error_handling+def main():+ if len(sys.argv) < 3:+ output_error("Usage: fetch_mark_price.py <exchange_id> <symbol>", "INVALID_ARGS")++ exchange_id = sys.argv[1]+ symbol = sys.argv[2]++ exchange = make_exchange(exchange_id)+ exchange.options["defaultType"] = "swap"++ try:+ rate = exchange.fetch_funding_rate(symbol)+ output_success({+ "symbol": symbol,+ "mark_price": rate.get("markPrice"),+ "index_price": rate.get("indexPrice"),+ "timestamp": rate.get("timestamp"),+ })+ except Exception as e:+ output_error(f"Mark price not available: {e}", "NOT_SUPPORTED")++if __name__ == "__main__":+ main()diff --git a/fincept-cpp/scripts/exchange/fetch_my_trades.py b/fincept-cpp/scripts/exchange/fetch_my_trades.pynew file mode 100644index 000000000..f326ff864--- /dev/null+++ b/fincept-cpp/scripts/exchange/fetch_my_trades.py@@ -0,0 +1,42 @@+"""+Fetch user's trade history.+Usage: python fetch_my_trades.py <exchange_id> <symbol> [limit]+Credentials via stdin JSON.+"""+import sys+from exchange_client import make_exchange, output_success, output_error, run_with_error_handling, parse_credentials_from_stdin++@run_with_error_handling+def main():+ if len(sys.argv) < 3:+ output_error("Usage: fetch_my_trades.py <exchange_id> <symbol> [limit]", "INVALID_ARGS")++ exchange_id = sys.argv[1]+ symbol = sys.argv[2]+ limit = int(sys.argv[3]) if len(sys.argv) > 3 else 50++ creds = parse_credentials_from_stdin()+ exchange = make_exchange(exchange_id, credentials=creds)++ trades = exchange.fetch_my_trades(symbol, limit=limit)+ output_success({+ "trades": [+ {+ "id": t.get("id"),+ "order": t.get("order"),+ "symbol": t.get("symbol"),+ "side": t.get("side"),+ "price": t.get("price"),+ "amount": t.get("amount"),+ "cost": t.get("cost"),+ "fee": t.get("fee", {}).get("cost", 0),+ "fee_currency": t.get("fee", {}).get("currency", ""),+ "timestamp": t.get("timestamp"),+ }+ for t in trades+ ],+ "count": len(trades),+ })++if __name__ == "__main__":+ main()diff --git a/fincept-cpp/scripts/exchange/fetch_open_interest.py b/fincept-cpp/scripts/exchange/fetch_open_interest.pynew file mode 100644index 000000000..922663e0d--- /dev/null+++ b/fincept-cpp/scripts/exchange/fetch_open_interest.py@@ -0,0 +1,31 @@+"""+Fetch open interest for a perpetual futures symbol.+Usage: python fetch_open_interest.py <exchange_id> <symbol>+"""+import sys+from exchange_client import make_exchange, output_success, output_error, run_with_error_handling++@run_with_error_handling+def main():+ if len(sys.argv) < 3:+ output_error("Usage: fetch_open_interest.py <exchange_id> <symbol>", "INVALID_ARGS")++ exchange_id = sys.argv[1]+ symbol = sys.argv[2]++ exchange = make_exchange(exchange_id)+ exchange.options["defaultType"] = "swap"++ try:+ oi = exchange.fetch_open_interest(symbol)+ output_success({+ "symbol": symbol,+ "open_interest": oi.get("openInterestAmount"),+ "open_interest_value": oi.get("openInterestValue"),+ "timestamp": oi.get("timestamp"),+ })+ except Exception as e:+ output_error(f"Open interest not available: {e}", "NOT_SUPPORTED")++if __name__ == "__main__":+ main()diff --git a/fincept-cpp/scripts/exchange/fetch_open_orders.py b/fincept-cpp/scripts/exchange/fetch_open_orders.pynew file mode 100644index 000000000..b7c5638be--- /dev/null+++ b/fincept-cpp/scripts/exchange/fetch_open_orders.py@@ -0,0 +1,44 @@+"""+Fetch open orders.+Usage: python fetch_open_orders.py <exchange_id> [symbol]+Credentials via stdin JSON.+"""+import sys+from exchange_client import make_exchange, output_success, output_error, run_with_error_handling, parse_credentials_from_stdin++@run_with_error_handling+def main():+ if len(sys.argv) < 2:+ output_error("Usage: fetch_open_orders.py <exchange_id> [symbol]", "INVALID_ARGS")++ exchange_id = sys.argv[1]+ symbol = sys.argv[2] if len(sys.argv) > 2 else None++ creds = parse_credentials_from_stdin()+ exchange = make_exchange(exchange_id, credentials=creds)++ orders = exchange.fetch_open_orders(symbol)+ output_success({+ "orders": [+ {+ "id": o.get("id"),+ "symbol": o.get("symbol"),+ "type": o.get("type"),+ "side": o.get("side"),+ "price": o.get("price"),+ "amount": o.get("amount"),+ "filled": o.get("filled"),+ "remaining": o.get("remaining"),+ "status": o.get("status"),+ "timestamp": o.get("timestamp"),+ "stopPrice": o.get("stopPrice"),+ "takeProfitPrice": o.get("takeProfitPrice"),+ "stopLossPrice": o.get("stopLossPrice"),+ }+ for o in orders+ ],+ "count": len(orders),+ })++if __name__ == "__main__":+ main()diff --git a/fincept-cpp/scripts/exchange/fetch_positions.py b/fincept-cpp/scripts/exchange/fetch_positions.pynew file mode 100644index 000000000..5d4f7d1bb--- /dev/null+++ b/fincept-cpp/scripts/exchange/fetch_positions.py@@ -0,0 +1,47 @@+"""+Fetch open positions (futures/margin).+Usage: python fetch_positions.py <exchange_id> [symbol]+Credentials via stdin JSON.+"""+import sys+from exchange_client import make_exchange, output_success, output_error, run_with_error_handling, parse_credentials_from_stdin++@run_with_error_handling+def main():+ if len(sys.argv) < 2:+ output_error("Usage: fetch_positions.py <exchange_id> [symbol]", "INVALID_ARGS")++ exchange_id = sys.argv[1]+ symbols = [sys.argv[2]] if len(sys.argv) > 2 else None++ creds = parse_credentials_from_stdin()+ exchange = make_exchange(exchange_id, credentials=creds)+ exchange.options["defaultType"] = "swap"++ positions = exchange.fetch_positions(symbols)+ output_success({+ "positions": [+ {+ "symbol": p.get("symbol"),+ "side": p.get("side"),+ "contracts": p.get("contracts"),+ "contractSize": p.get("contractSize"),+ "notional": p.get("notional"),+ "leverage": p.get("leverage"),+ "unrealizedPnl": p.get("unrealizedPnl"),+ "realizedPnl": p.get("realizedPnl", 0),+ "entryPrice": p.get("entryPrice"),+ "markPrice": p.get("markPrice"),+ "liquidationPrice": p.get("liquidationPrice"),+ "marginMode": p.get("marginMode"),+ "marginRatio": p.get("marginRatio"),+ "collateral": p.get("collateral"),+ "timestamp": p.get("timestamp"),+ }+ for p in positions if p.get("contracts") and float(p["contracts"]) != 0+ ],+ "count": len(positions),+ })++if __name__ == "__main__":+ main()diff --git a/fincept-cpp/scripts/exchange/fetch_trading_fees.py b/fincept-cpp/scripts/exchange/fetch_trading_fees.pynew file mode 100644index 000000000..63ff22e9a--- /dev/null+++ b/fincept-cpp/scripts/exchange/fetch_trading_fees.py@@ -0,0 +1,39 @@+"""+Fetch trading fee rates.+Usage: python fetch_trading_fees.py <exchange_id> [symbol]+"""+import sys+from exchange_client import make_exchange, output_success, output_error, run_with_error_handling++@run_with_error_handling+def main():+ if len(sys.argv) < 2:+ output_error("Usage: fetch_trading_fees.py <exchange_id> [symbol]", "INVALID_ARGS")++ exchange_id = sys.argv[1]++ exchange = make_exchange(exchange_id)++ if len(sys.argv) > 2:+ symbol = sys.argv[2]+ fee = exchange.fetch_trading_fee(symbol)+ output_success({+ "symbol": symbol,+ "maker": fee.get("maker"),+ "taker": fee.get("taker"),+ "percentage": fee.get("percentage", True),+ })+ else:+ fees = exchange.fetch_trading_fees()+ result = []+ for symbol, fee in list(fees.items())[:50]:+ if isinstance(fee, dict) and "maker" in fee:+ result.append({+ "symbol": symbol,+ "maker": fee.get("maker"),+ "taker": fee.get("taker"),+ })+ output_success({"fees": result, "count": len(result)})++if __name__ == "__main__":+ main()diff --git a/fincept-cpp/scripts/exchange/set_leverage.py b/fincept-cpp/scripts/exchange/set_leverage.pynew file mode 100644index 000000000..9566b9bde--- /dev/null+++ b/fincept-cpp/scripts/exchange/set_leverage.py@@ -0,0 +1,26 @@+"""+Set leverage for a symbol on futures exchanges.+Usage: python set_leverage.py <exchange_id> <symbol> <leverage>+Credentials via stdin JSON.+"""+import sys+from exchange_client import make_exchange, output_success, output_error, run_with_error_handling, parse_credentials_from_stdin++@run_with_error_handling+def main():+ if len(sys.argv) < 4:+ output_error("Usage: set_leverage.py <exchange_id> <symbol> <leverage>", "INVALID_ARGS")++ exchange_id = sys.argv[1]+ symbol = sys.argv[2]+ leverage = int(sys.argv[3])++ creds = parse_credentials_from_stdin()+ exchange = make_exchange(exchange_id, credentials=creds)+ exchange.options["defaultType"] = "swap"++ result = exchange.set_leverage(leverage, symbol)+ output_success({"symbol": symbol, "leverage": leverage, "result": result})++if __name__ == "__main__":+ main()diff --git a/fincept-cpp/scripts/exchange/set_margin_mode.py b/fincept-cpp/scripts/exchange/set_margin_mode.pynew file mode 100644index 000000000..ead1d660b--- /dev/null+++ b/fincept-cpp/scripts/exchange/set_margin_mode.py@@ -0,0 +1,26 @@+"""+Set margin mode (cross/isolated) for a symbol.+Usage: python set_margin_mode.py <exchange_id> <symbol> <mode>+Credentials via stdin JSON.+"""+import sys+from exchange_client import make_exchange, output_success, output_error, run_with_error_handling, parse_credentials_from_stdin++@run_with_error_handling+def main():+ if len(sys.argv) < 4:+ output_error("Usage: set_margin_mode.py <exchange_id> <symbol> <mode>", "INVALID_ARGS")++ exchange_id = sys.argv[1]+ symbol = sys.argv[2]+ mode = sys.argv[3] # "cross" or "isolated"++ creds = parse_credentials_from_stdin()+ exchange = make_exchange(exchange_id, credentials=creds)+ exchange.options["defaultType"] = "swap"++ result = exchange.set_margin_mode(mode, symbol)+ output_success({"symbol": symbol, "margin_mode": mode, "result": result})++if __name__ == "__main__":+ main()diff --git a/fincept-cpp/scripts/exchange/ws_stream.py b/fincept-cpp/scripts/exchange/ws_stream.pyindex df02e901c..70363301f 100644--- a/fincept-cpp/scripts/exchange/ws_stream.py+++ b/fincept-cpp/scripts/exchange/ws_stream.py@@ -131,6 +131,35 @@ async def watch_ohlcv(exchange, symbol, timeframe="1m"):await asyncio.sleep(min(errors * 2, 30))+async def watch_trades_stream(exchange, symbol):+ """Stream real-time public trades (Time & Sales)."""+ errors = 0+ while True:+ try:+ trades = await exchange.watch_trades(symbol)+ errors = 0+ for t in trades:+ emit({+ "type": "trade",+ "symbol": symbol,+ "id": t.get("id"),+ "timestamp": t.get("timestamp"),+ "side": t.get("side"),+ "price": t.get("price"),+ "amount": t.get("amount"),+ "cost": t.get("cost"),+ })+ except Exception as e:+ errors += 1+ if errors <= 3:+ emit({"type": "error", "source": "trades", "symbol": symbol, "message": str(e)})+ if errors >= MAX_CONSECUTIVE_ERRORS:+ emit({"type": "error", "source": "trades", "symbol": symbol,+ "message": f"Too many errors ({errors}), stopping trades watcher"})+ return+ await asyncio.sleep(min(errors * 2, 30))++async def watch_tickers(exchange, symbols):"""Stream ticker updates for multiple symbols (batch)."""errors = 0@@ -193,21 +222,33 @@ async def main():"options": {"defaultType": "spot"},})- # Try to load markets first — if this fails, WS won't work- try:- emit({"type": "status", "connected": False, "exchange": exchange_id,- "symbols": all_symbols, "message": "Loading markets..."})- await exchange.load_markets()- emit({- "type": "status",- "connected": True,- "exchange": exchange_id,- "symbols": all_symbols,- })- except Exception as e:- emit({"type": "error", "message": f"Failed to load markets: {e}"})+ # Try to load markets with retry — some exchanges may be temporarily unreachable+ MAX_RETRIES = 5+ markets_loaded = False+ for attempt in range(1, MAX_RETRIES + 1):+ try:+ emit({"type": "status", "connected": False, "exchange": exchange_id,+ "symbols": all_symbols, "message": f"Loading markets (attempt {attempt}/{MAX_RETRIES})..."})+ await exchange.load_markets()+ emit({+ "type": "status",+ "connected": True,+ "exchange": exchange_id,+ "symbols": all_symbols,+ })+ markets_loaded = True+ break+ except Exception as e:+ emit({"type": "error", "message": f"Failed to load markets (attempt {attempt}): {e}"})+ if attempt < MAX_RETRIES:+ delay = min(attempt * 5, 30)+ emit({"type": "status", "connected": False, "exchange": exchange_id,+ "symbols": all_symbols, "message": f"Retrying in {delay}s..."})+ await asyncio.sleep(delay)++ if not markets_loaded:emit({"type": "status", "connected": False, "exchange": exchange_id,- "symbols": all_symbols, "message": "load_markets failed"})+ "symbols": all_symbols, "message": "load_markets failed after all retries"})await exchange.close()sys.exit(1)@@ -217,6 +258,7 @@ async def main():asyncio.create_task(watch_ticker(exchange, primary_symbol)),asyncio.create_task(watch_orderbook(exchange, primary_symbol, 15)),asyncio.create_task(watch_ohlcv(exchange, primary_symbol, "1m")),+ asyncio.create_task(watch_trades_stream(exchange, primary_symbol)),]# All symbols get batch ticker updatesdiff --git a/fincept-cpp/src/app.cpp b/fincept-cpp/src/app.cppindex 66ca4298d..365ef09c8 100644--- a/fincept-cpp/src/app.cpp+++ b/fincept-cpp/src/app.cpp@@ -1,6 +1,7 @@#include "app.h"#include "auth/auth_manager.h"#include "storage/database.h"+#include "storage/cache_service.h"#include "core/config.h"#include "core/logger.h"#include "ui/theme.h"@@ -14,6 +15,7 @@ void App::initialize() {// Initialize databases before anything elsedb::Database::instance().initialize();db::CacheDatabase::instance().initialize();+ CacheService::instance().initialize();auth::AuthManager::instance().initialize();initialized_ = true;@@ -28,6 +30,7 @@ void App::initialize() {void App::shutdown() {LOG_INFO("App", "Shutting down");+ CacheService::instance().shutdown();db::CacheDatabase::instance().close();db::Database::instance().close();}@@ -522,6 +525,7 @@ void App::render() {case AppScreen::Pricing: pricing_screen_.render(next_screen_); break;case AppScreen::Dashboard:if (active_tab_ == 26) gov_data_screen_.render();+ else if (active_tab_ == 6) backtesting_screen_.render();else if (active_tab_ == 25) about_screen_.render();else if (active_tab_ == 24) support_screen_.render();else if (active_tab_ == 23) docs_screen_.render();@@ -544,6 +548,7 @@ void App::render() {else if (active_tab_ == 2) crypto_trading_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 dashboard_screen_.render();break;default:diff --git a/fincept-cpp/src/app.h b/fincept-cpp/src/app.hindex 16607f959..87a8c1b8c 100644--- a/fincept-cpp/src/app.h+++ b/fincept-cpp/src/app.h@@ -33,6 +33,8 @@#include "screens/about/about_screen.h"#include "screens/code_editor/code_editor_screen.h"#include "screens/gov_data/gov_data_screen.h"+#include "screens/backtesting/backtesting_screen.h"+#include "screens/algo_trading/algo_trading_screen.h"// Fullscreen toggle (implemented in main.cpp, delegates to Window)void toggle_fullscreen();@@ -87,6 +89,8 @@ private:about::AboutScreen about_screen_;code_editor::CodeEditorScreen code_editor_screen_;gov_data::GovDataScreen gov_data_screen_;+ backtesting::BacktestingScreen backtesting_screen_;+ algo::AlgoTradingScreen algo_trading_screen_;// Rendering sectionsvoid render_top_bar();diff --git a/fincept-cpp/src/core/font_loader.cpp b/fincept-cpp/src/core/font_loader.cppindex 4f9a63e43..bbdf471ba 100644--- a/fincept-cpp/src/core/font_loader.cpp+++ b/fincept-cpp/src/core/font_loader.cpp@@ -1,8 +1,10 @@-// Font loading implementation+// Font loading implementation — primary font + color emoji merge+// Requires IMGUI_USE_WCHAR32 and IMGUI_ENABLE_FREETYPE#include "core/font_loader.h"#include "core/logger.h"#include <filesystem>+#include <imgui_freetype.h>namespace fincept::core {@@ -57,6 +59,61 @@ void load_fonts(float dpi_scale) {LOG_WARN("Font", "Using ImGui default font at %.0fpx", font_size);}+ // ── Merge color emoji font ──+ // With IMGUI_USE_WCHAR32, ImWchar is 32-bit so we can address emoji codepoints.+ // With IMGUI_ENABLE_FREETYPE, we can use LoadColor for COLR/CBLC color fonts.+ // Segoe UI Emoji (seguiemj.ttf) on Windows has excellent color emoji coverage.+ const char* emoji_font_candidates[] = {+#ifdef _WIN32+ "C:/Windows/Fonts/seguiemj.ttf", // Segoe UI Emoji — color emoji+#elif defined(__APPLE__)+ "/System/Library/Fonts/Apple Color Emoji.ttc",+#else+ "/usr/share/fonts/truetype/noto/NotoColorEmoji.ttf",+ "/usr/share/fonts/noto-cjk/NotoColorEmoji.ttf",+#endif+ };++ // Emoji ranges we need (32-bit codepoints):+ // Misc Symbols: U+2600–U+26FF (☀ ☁ ⚡ etc.)+ // Dingbats: U+2700–U+27BF (❄ etc.)+ // Misc Symbols & Arrows: U+2B00–U+2BFF+ // Supplemental Symbols: U+1F300–U+1F5FF (🌍 🌊 🐘 🐬 🍃 📄 📊 etc.)+ // Emoticons: U+1F600–U+1F64F+ // Transport/Map: U+1F680–U+1F6FF (🔌 🔒 etc.)+ // Supplemental: U+1F900–U+1F9FF (🦂 🦎 🧠 🧱 🧼 🥑 🥬 etc.)+ // Symbols Extended-A: U+1FA00–U+1FA6F+ // Symbols Extended-B: U+1FA70–U+1FAFF (🪙 🪟 🪳 🪶 etc.)+ // Currency Symbols: U+20A0–U+20CF (₿ etc.)+ static const ImWchar emoji_ranges[] = {+ 0x2000, 0x2BFF, // General Punctuation through Misc Symbols & Arrows+ 0x20A0, 0x20CF, // Currency Symbols (₿)+ 0x1F300, 0x1F9FF, // Misc Symbols & Pictographs, Emoticons, Transport, Supplemental+ 0x1FA00, 0x1FAFF, // Symbols Extended-A & B (🪙 🪟 🪳 🪶 etc.)+ 0,+ };++ for (const char* emoji_path : emoji_font_candidates) {+ if (std::filesystem::exists(emoji_path)) {+ ImFontConfig merge_cfg;+ merge_cfg.MergeMode = true;+ merge_cfg.OversampleH = 1;+ merge_cfg.OversampleV = 1;+ merge_cfg.PixelSnapH = true;+ merge_cfg.RasterizerDensity = dpi_scale;+ merge_cfg.FontBuilderFlags |= ImGuiFreeTypeBuilderFlags_LoadColor;++ ImFont* emoji = io.Fonts->AddFontFromFileTTF(+ emoji_path, font_size, &merge_cfg, emoji_ranges);+ if (emoji) {+ LOG_INFO("Font", "Merged emoji font: %s (color)", emoji_path);+ } else {+ LOG_WARN("Font", "Failed to merge emoji font: %s", emoji_path);+ }+ break;+ }+ }+io.Fonts->Build();}diff --git a/fincept-cpp/src/screens/algo_trading/algo_constants.h b/fincept-cpp/src/screens/algo_trading/algo_constants.hnew file mode 100644index 000000000..4c95feab3--- /dev/null+++ b/fincept-cpp/src/screens/algo_trading/algo_constants.h@@ -0,0 +1,213 @@+#pragma once+// Algo Trading Constants — indicator definitions, operators, timeframes+// Mirrors: fincept-terminal-desktop/src/components/tabs/algo-trading/constants/indicators.ts++#include <string>+#include <vector>+#include <utility>++namespace fincept::algo {++// ============================================================================+// Indicator definition+// ============================================================================++struct IndicatorDef {+ const char* id;+ const char* name;+ const char* category;+ bool has_period;+ int default_period;+ const char* description;+};++// ============================================================================+// Operator definition+// ============================================================================++struct OperatorDef {+ const char* id;+ const char* label;+ const char* description;+ bool needs_value2; // "between" needs two values+};++// ============================================================================+// Timeframe definition+// ============================================================================++struct TimeframeDef {+ const char* id;+ const char* label;+ int seconds; // duration in seconds (0 = live/tick)+};++// ============================================================================+// All indicators (6 categories, 60 total)+// ============================================================================++inline const std::vector<IndicatorDef>& get_indicators() {+ static const std::vector<IndicatorDef> indicators = {+ // --- Stock Attributes (16) ---+ {"close", "Close Price", "stock_attributes", false, 0, "Closing price"},+ {"open", "Open Price", "stock_attributes", false, 0, "Opening price"},+ {"high", "High Price", "stock_attributes", false, 0, "High price"},+ {"low", "Low Price", "stock_attributes", false, 0, "Low price"},+ {"volume", "Volume", "stock_attributes", false, 0, "Trading volume"},+ {"vwap", "VWAP", "stock_attributes", false, 0, "Volume-weighted average price"},+ {"typical", "Typical Price", "stock_attributes", false, 0, "(H+L+C)/3"},+ {"median", "Median Price", "stock_attributes", false, 0, "(H+L)/2"},+ {"weighted", "Weighted Close", "stock_attributes", false, 0, "(H+L+2C)/4"},+ {"tr", "True Range", "stock_attributes", false, 0, "True range"},+ {"atr", "ATR", "stock_attributes", true, 14, "Average true range"},+ {"gap", "Gap", "stock_attributes", false, 0, "Open vs prev close"},+ {"gap_pct", "Gap %", "stock_attributes", false, 0, "Gap as percentage"},+ {"range", "Range", "stock_attributes", false, 0, "High - Low"},+ {"range_pct", "Range %", "stock_attributes", false, 0, "Range as pct of close"},+ {"body_pct", "Body %", "stock_attributes", false, 0, "|Open-Close|/Range"},++ // --- Moving Averages (10) ---+ {"sma", "SMA", "moving_averages", true, 20, "Simple moving average"},+ {"ema", "EMA", "moving_averages", true, 20, "Exponential moving average"},+ {"wma", "WMA", "moving_averages", true, 20, "Weighted moving average"},+ {"dema", "DEMA", "moving_averages", true, 20, "Double EMA"},+ {"tema", "TEMA", "moving_averages", true, 20, "Triple EMA"},+ {"kama", "KAMA", "moving_averages", true, 20, "Kaufman adaptive MA"},+ {"hma", "HMA", "moving_averages", true, 20, "Hull moving average"},+ {"vwma", "VWMA", "moving_averages", true, 20, "Volume-weighted MA"},+ {"zlema", "ZLEMA", "moving_averages", true, 20, "Zero-lag EMA"},+ {"alma", "ALMA", "moving_averages", true, 20, "Arnaud Legoux MA"},++ // --- Momentum (10) ---+ {"rsi", "RSI", "momentum", true, 14, "Relative strength index"},+ {"stoch_k", "Stochastic %K", "momentum", true, 14, "Stochastic oscillator %K"},+ {"stoch_d", "Stochastic %D", "momentum", true, 3, "Stochastic oscillator %D"},+ {"cci", "CCI", "momentum", true, 20, "Commodity channel index"},+ {"williams_r", "Williams %R", "momentum", true, 14, "Williams percent range"},+ {"roc", "ROC", "momentum", true, 12, "Rate of change"},+ {"momentum", "Momentum", "momentum", true, 10, "Price momentum"},+ {"tsi", "TSI", "momentum", true, 25, "True strength index"},+ {"uo", "Ultimate Oscillator", "momentum", false, 0, "Ultimate oscillator"},+ {"ao", "Awesome Oscillator", "momentum", false, 0, "Awesome oscillator"},++ // --- Trend (12) ---+ {"macd", "MACD Line", "trend", true, 12, "MACD line (12,26)"},+ {"macd_signal", "MACD Signal", "trend", true, 9, "MACD signal line"},+ {"macd_hist", "MACD Histogram", "trend", false, 0, "MACD histogram"},+ {"adx", "ADX", "trend", true, 14, "Average directional index"},+ {"plus_di", "+DI", "trend", true, 14, "Positive directional indicator"},+ {"minus_di", "-DI", "trend", true, 14, "Negative directional indicator"},+ {"aroon_up", "Aroon Up", "trend", true, 25, "Aroon up"},+ {"aroon_down", "Aroon Down", "trend", true, 25, "Aroon down"},+ {"psar", "Parabolic SAR", "trend", false, 0, "Parabolic SAR"},+ {"supertrend", "Supertrend", "trend", true, 10, "Supertrend"},+ {"ichimoku_a", "Ichimoku Span A", "trend", false, 0, "Ichimoku cloud span A"},+ {"ichimoku_b", "Ichimoku Span B", "trend", false, 0, "Ichimoku cloud span B"},++ // --- Volatility (4) ---+ {"bb_upper", "Bollinger Upper", "volatility", true, 20, "Upper Bollinger band"},+ {"bb_middle", "Bollinger Middle", "volatility", true, 20, "Middle Bollinger band"},+ {"bb_lower", "Bollinger Lower", "volatility", true, 20, "Lower Bollinger band"},+ {"kc_upper", "Keltner Upper", "volatility", true, 20, "Upper Keltner channel"},++ // --- Volume (8) ---+ {"obv", "OBV", "volume", false, 0, "On-balance volume"},+ {"ad", "A/D Line", "volume", false, 0, "Accumulation/distribution"},+ {"cmf", "CMF", "volume", true, 20, "Chaikin money flow"},+ {"mfi", "MFI", "volume", true, 14, "Money flow index"},+ {"vpt", "VPT", "volume", false, 0, "Volume price trend"},+ {"eom", "EOM", "volume", true, 14, "Ease of movement"},+ {"fi", "Force Index", "volume", true, 13, "Force index"},+ {"nvi", "NVI", "volume", false, 0, "Negative volume index"},+ };+ return indicators;+}++// ============================================================================+// All operators (12)+// ============================================================================++inline const std::vector<OperatorDef>& get_operators() {+ static const std::vector<OperatorDef> operators = {+ {">", ">", "Greater than", false},+ {"<", "<", "Less than", false},+ {">=", ">=", "Greater than or equal", false},+ {"<=", "<=", "Less than or equal", false},+ {"==", "==", "Equal to", false},+ {"crosses_above", "Crosses Above", "Crosses above value/indicator", false},+ {"crosses_below", "Crosses Below", "Crosses below value/indicator", false},+ {"between", "Between", "Between two values", true},+ {"crossed_above_within", "Crossed Above Within", "Crossed above within N bars", false},+ {"crossed_below_within", "Crossed Below Within", "Crossed below within N bars", false},+ {"rising", "Rising", "Value is rising over N bars", false},+ {"falling", "Falling", "Value is falling over N bars", false},+ };+ return operators;+}++// ============================================================================+// Timeframes (10)+// ============================================================================++inline const std::vector<TimeframeDef>& get_timeframes() {+ static const std::vector<TimeframeDef> timeframes = {+ {"live", "Live/Tick", 0},+ {"1m", "1 Minute", 60},+ {"3m", "3 Minutes", 180},+ {"5m", "5 Minutes", 300},+ {"10m", "10 Minutes", 600},+ {"15m", "15 Minutes", 900},+ {"30m", "30 Minutes", 1800},+ {"1h", "1 Hour", 3600},+ {"4h", "4 Hours", 14400},+ {"1d", "1 Day", 86400},+ };+ return timeframes;+}++// ============================================================================+// Indicator categories (for UI grouping)+// ============================================================================++inline const std::vector<std::pair<const char*, const char*>>& get_indicator_categories() {+ static const std::vector<std::pair<const char*, const char*>> categories = {+ {"stock_attributes", "Stock Attributes"},+ {"moving_averages", "Moving Averages"},+ {"momentum", "Momentum"},+ {"trend", "Trend"},+ {"volatility", "Volatility"},+ {"volume", "Volume"},+ };+ return categories;+}++// ============================================================================+// Broker providers (for strategy config)+// ============================================================================++inline const std::vector<std::pair<const char*, const char*>>& get_broker_providers() {+ static const std::vector<std::pair<const char*, const char*>> providers = {+ // Indian+ {"fyers", "Fyers"},+ {"zerodha", "Zerodha"},+ {"upstox", "Upstox"},+ {"dhan", "Dhan"},+ {"kotak", "Kotak"},+ {"groww", "Groww"},+ {"aliceblue", "AliceBlue"},+ {"angelone", "AngelOne"},+ {"fivepaisa", "5Paisa"},+ {"iifl", "IIFL"},+ {"motilal", "Motilal Oswal"},+ {"shoonya", "Shoonya"},+ // US+ {"alpaca", "Alpaca"},+ {"ibkr", "Interactive Brokers"},+ {"tradier", "Tradier"},+ // EU+ {"saxobank", "Saxo Bank"},+ };+ return providers;+}++} // namespace fincept::algodiff --git a/fincept-cpp/src/screens/algo_trading/algo_service.cpp b/fincept-cpp/src/screens/algo_trading/algo_service.cppnew file mode 100644index 000000000..726e25e52--- /dev/null+++ b/fincept-cpp/src/screens/algo_trading/algo_service.cpp@@ -0,0 +1,749 @@+#include "algo_service.h"+#include "storage/database.h"+#include "python/python_runner.h"+#include "trading/unified_trading.h"+#include "core/logger.h"+#include <nlohmann/json.hpp>+#include <filesystem>+#include <fstream>+#include <sstream>+#include <thread>+#include <chrono>+#include <algorithm>++#ifdef _WIN32+#include <windows.h>+#include <tlhelp32.h>+#else+#include <signal.h>+#endif++namespace fincept::algo {++using json = nlohmann::json;++AlgoService& AlgoService::instance() {+ static AlgoService svc;+ return svc;+}++// ============================================================================+// Path Helpers+// ============================================================================++std::string AlgoService::get_scripts_dir() const {+ auto exe_dir = python::get_exe_dir();+ // Check: exe_dir/scripts/algo_trading/+ auto path = exe_dir / "scripts" / "algo_trading";+ if (std::filesystem::exists(path)) return path.string();++ // Fallback: CWD/scripts/algo_trading/+ path = std::filesystem::current_path() / "scripts" / "algo_trading";+ if (std::filesystem::exists(path)) return path.string();++ return "";+}++std::string AlgoService::get_db_path() const {+ auto dir = python::get_install_dir();+ return (dir / "fincept.db").string();+}++// ============================================================================+// Process Management (cross-platform)+// ============================================================================++bool AlgoService::is_pid_alive(int pid) const {+ if (pid <= 0) return false;+#ifdef _WIN32+ HANDLE proc = OpenProcess(PROCESS_QUERY_LIMITED_INFORMATION, FALSE, (DWORD)pid);+ if (!proc) return false;+ DWORD exit_code = 0;+ GetExitCodeProcess(proc, &exit_code);+ CloseHandle(proc);+ return exit_code == STILL_ACTIVE;+#else+ return kill(pid, 0) == 0;+#endif+}++bool AlgoService::verify_pid_is_algo_runner(int pid) const {+ if (pid <= 0) return false;+#ifdef _WIN32+ HANDLE snap = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);+ if (snap == INVALID_HANDLE_VALUE) return false;+ PROCESSENTRY32 pe;+ pe.dwSize = sizeof(pe);+ bool found = false;+ if (Process32First(snap, &pe)) {+ do {+ if ((int)pe.th32ProcessID == pid) {+ std::string name = pe.szExeFile;+ // Check if it's a python process+ found = (name.find("python") != std::string::npos ||+ name.find("Python") != std::string::npos);+ break;+ }+ } while (Process32Next(snap, &pe));+ }+ CloseHandle(snap);+ return found;+#else+ std::string cmdline_path = "/proc/" + std::to_string(pid) + "/cmdline";+ std::ifstream f(cmdline_path);+ if (!f.is_open()) return false;+ std::string content((std::istreambuf_iterator<char>(f)), {});+ return content.find("algo_live_runner") != std::string::npos;+#endif+}++bool AlgoService::safe_kill_process(int pid) const {+ if (!verify_pid_is_algo_runner(pid)) {+ LOG_WARN("AlgoService", "PID %d is not an algo runner, skipping kill", pid);+ return false;+ }+#ifdef _WIN32+ HANDLE proc = OpenProcess(PROCESS_TERMINATE, FALSE, (DWORD)pid);+ if (!proc) return false;+ bool ok = TerminateProcess(proc, 1) != 0;+ CloseHandle(proc);+ return ok;+#else+ return kill(pid, SIGTERM) == 0;+#endif+}++// ============================================================================+// Deploy Strategy+// ============================================================================++std::string AlgoService::deploy_strategy(const std::string& strategy_id,+ const std::string& symbol,+ const std::string& mode,+ const std::string& provider,+ const std::string& timeframe,+ double quantity,+ const std::string& params_json) {+ std::lock_guard lock(mutex_);++ // Validate quantity+ if (quantity <= 0) {+ return json({{"success", false}, {"error", "Quantity must be > 0"}}).dump();+ }++ // Rate limit+ if (running_deployment_count() >= MAX_CONCURRENT) {+ return json({{"success", false},+ {"error", "Max " + std::to_string(MAX_CONCURRENT) + " concurrent deployments"}}).dump();+ }++ // Get strategy+ auto strategy = db::ops::get_algo_strategy(strategy_id);+ if (!strategy) {+ return json({{"success", false}, {"error", "Strategy not found"}}).dump();+ }++ // Create deployment record+ std::string deploy_id = "algo-" + db::generate_uuid();+ AlgoDeployment dep;+ dep.id = deploy_id;+ dep.strategy_id = strategy_id;+ dep.strategy_name = strategy->name;+ dep.mode = mode;+ dep.status = DeploymentStatus::Starting;+ dep.config = params_json;+ db::ops::save_algo_deployment(dep);++ // Create initial metrics row+ AlgoMetrics metrics;+ metrics.deployment_id = deploy_id;+ db::ops::save_algo_metrics(metrics);++ // Find the runner script+ std::string scripts_dir = get_scripts_dir();+ std::string runner_path = scripts_dir + "/algo_live_runner.py";+ if (scripts_dir.empty() || !std::filesystem::exists(runner_path)) {+ db::ops::update_algo_deployment_status(deploy_id, "error", "Runner script not found");+ return json({{"success", false}, {"error", "algo_live_runner.py not found"}}).dump();+ }++ std::string db_path = get_db_path();+ std::string prov = provider.empty() ? "fyers" : provider;++ // Spawn the Python runner process+ LOG_INFO("AlgoService", "Deploying %s: %s mode=%s tf=%s qty=%.2f",+ deploy_id.c_str(), symbol.c_str(), mode.c_str(), timeframe.c_str(), quantity);++ auto python_path = python::resolve_python_path("algo_live_runner");++#ifdef _WIN32+ // Build command line+ std::string cmdline = "\"" + python_path.string() + "\" "+ "\"" + runner_path + "\" "+ "--deploy-id " + deploy_id + " "+ "--strategy-id " + strategy_id + " "+ "--symbol " + symbol + " "+ "--provider " + prov + " "+ "--mode " + mode + " "+ "--timeframe " + timeframe + " "+ "--quantity " + std::to_string(quantity) + " "+ "--db \"" + db_path + "\"";++ STARTUPINFOA si = {};+ si.cb = sizeof(si);+ PROCESS_INFORMATION pi = {};++ BOOL ok = CreateProcessA(+ nullptr, const_cast<char*>(cmdline.c_str()),+ nullptr, nullptr, FALSE,+ CREATE_NO_WINDOW | DETACHED_PROCESS,+ nullptr, nullptr, &si, &pi+ );++ if (!ok) {+ db::ops::update_algo_deployment_status(deploy_id, "error", "Failed to spawn Python runner");+ return json({{"success", false}, {"error", "CreateProcess failed"}}).dump();+ }++ int pid = (int)pi.dwProcessId;+ CloseHandle(pi.hThread);+ CloseHandle(pi.hProcess);+#else+ // Unix: fork+exec+ std::vector<std::string> args = {+ runner_path,+ "--deploy-id", deploy_id,+ "--strategy-id", strategy_id,+ "--symbol", symbol,+ "--provider", prov,+ "--mode", mode,+ "--timeframe", timeframe,+ "--quantity", std::to_string(quantity),+ "--db", db_path+ };++ pid_t child = fork();+ if (child < 0) {+ db::ops::update_algo_deployment_status(deploy_id, "error", "Fork failed");+ return json({{"success", false}, {"error", "fork() failed"}}).dump();+ }+ if (child == 0) {+ // Child process+ std::vector<const char*> argv;+ argv.push_back(python_path.c_str());+ for (auto& a : args) argv.push_back(a.c_str());+ argv.push_back(nullptr);+ execvp(python_path.c_str(), const_cast<char* const*>(argv.data()));+ _exit(1);+ }+ int pid = (int)child;+#endif++ LOG_INFO("AlgoService", "Python runner spawned PID=%d for %s", pid, deploy_id.c_str());++ // Update deployment with PID and running status+ dep.pid = pid;+ dep.status = DeploymentStatus::Running;+ db::ops::update_algo_deployment_status(deploy_id, "running");+ // Update PID separately+ {+ auto& db = db::Database::instance();+ std::lock_guard db_lock(db.mutex());+ auto stmt = db.prepare("UPDATE algo_deployments SET pid = ?1 WHERE id = ?2");+ stmt.bind_int(1, pid);+ stmt.bind_text(2, deploy_id);+ stmt.execute();+ }++ // Spawn background reaper thread to detect when the runner exits+ std::string reaper_id = deploy_id;+ int reaper_pid = pid;+ std::thread([reaper_id, reaper_pid]() {+ // Poll every 2 seconds to check if PID is still alive+ while (true) {+ std::this_thread::sleep_for(std::chrono::seconds(2));+#ifdef _WIN32+ HANDLE proc = OpenProcess(PROCESS_QUERY_LIMITED_INFORMATION, FALSE, (DWORD)reaper_pid);+ if (!proc) break;+ DWORD code = 0;+ GetExitCodeProcess(proc, &code);+ CloseHandle(proc);+ if (code != STILL_ACTIVE) break;+#else+ if (kill(reaper_pid, 0) != 0) break;+#endif+ }+ // Process exited — update DB if still marked as running+ auto dep = db::ops::get_algo_deployment(reaper_id);+ if (dep && dep->status == DeploymentStatus::Running) {+ db::ops::update_algo_deployment_status(reaper_id, "stopped", "Runner process exited");+ LOG_INFO("AlgoReaper", "Deployment %s runner exited", reaper_id.c_str());+ }+ }).detach();++ // Auto-start order bridge for live mode+ if (mode == "live") {+ trading::UnifiedTrading::instance().start_order_bridge();+ }++ return json({{"success", true}, {"deployment_id", deploy_id}, {"pid", pid}}).dump();+}++// ============================================================================+// Stop Deployment+// ============================================================================++bool AlgoService::stop_deployment(const std::string& deployment_id) {+ auto dep = db::ops::get_algo_deployment(deployment_id);+ if (!dep) return false;++ // Kill the process+ if (dep->pid > 0) {+ safe_kill_process(dep->pid);+ }++ db::ops::update_algo_deployment_status(deployment_id, "stopped");+ LOG_INFO("AlgoService", "Stopped deployment %s", deployment_id.c_str());+ return true;+}++int AlgoService::stop_all_deployments() {+ auto deployments = db::ops::list_algo_deployments();+ int count = 0;+ for (auto& d : deployments) {+ if (d.status == DeploymentStatus::Running || d.status == DeploymentStatus::Starting) {+ if (stop_deployment(d.id)) count++;+ }+ }+ // Stop order bridge too+ trading::UnifiedTrading::instance().stop_order_bridge();+ return count;+}++void AlgoService::delete_deployment(const std::string& deployment_id) {+ // Stop first if running+ auto dep = db::ops::get_algo_deployment(deployment_id);+ if (dep && (dep->status == DeploymentStatus::Running || dep->status == DeploymentStatus::Starting)) {+ stop_deployment(deployment_id);+ }+ db::ops::delete_algo_deployment(deployment_id);+}++// ============================================================================+// Backtest+// ============================================================================++BacktestResult AlgoService::run_backtest(const std::string& strategy_id,+ const std::string& symbol,+ const std::string& start_date,+ const std::string& end_date,+ double capital,+ const std::string& provider) {+ BacktestResult result;++ auto strategy = db::ops::get_algo_strategy(strategy_id);+ if (!strategy) {+ result.error = "Strategy not found";+ return result;+ }++ std::vector<std::string> args = {+ "--strategy-id", strategy_id,+ "--symbol", symbol,+ "--start", start_date,+ "--end", end_date,+ "--capital", std::to_string(capital),+ "--provider", provider,+ "--entry-conditions", strategy->entry_conditions,+ "--exit-conditions", strategy->exit_conditions,+ "--timeframe", strategy->timeframe,+ "--stop-loss", std::to_string(strategy->stop_loss),+ "--take-profit", std::to_string(strategy->take_profit),+ "--db", get_db_path()+ };++ auto py_result = python::execute("algo_trading/backtest_engine.py", args);+ if (!py_result.success) {+ result.error = py_result.error;+ return result;+ }++ // Parse JSON result+ try {+ auto j = json::parse(py_result.output);+ result.success = j.value("success", false);+ if (!result.success) {+ result.error = j.value("error", "Backtest failed");+ return result;+ }++ auto m = j.value("metrics", json::object());+ result.metrics.total_return = m.value("total_return", 0.0);+ result.metrics.total_return_pct = m.value("total_return_pct", 0.0);+ result.metrics.max_drawdown = m.value("max_drawdown", 0.0);+ result.metrics.sharpe_ratio = m.value("sharpe_ratio", 0.0);+ result.metrics.win_rate = m.value("win_rate", 0.0);+ result.metrics.total_trades = m.value("total_trades", 0);+ result.metrics.winning_trades = m.value("winning_trades", 0);+ result.metrics.losing_trades = m.value("losing_trades", 0);+ result.metrics.avg_win = m.value("avg_win", 0.0);+ result.metrics.avg_loss = m.value("avg_loss", 0.0);+ result.metrics.profit_factor = m.value("profit_factor", 0.0);++ for (auto& t : j.value("trades", json::array())) {+ BacktestTrade bt;+ bt.symbol = t.value("symbol", "");+ bt.side = t.value("side", "");+ bt.entry_price = t.value("entry_price", 0.0);+ bt.exit_price = t.value("exit_price", 0.0);+ bt.quantity = t.value("quantity", 0.0);+ bt.pnl = t.value("pnl", 0.0);+ bt.pnl_pct = t.value("pnl_pct", 0.0);+ bt.entry_time = t.value("entry_time", "");+ bt.exit_time = t.value("exit_time", "");+ result.trades.push_back(bt);+ }++ for (auto& e : j.value("equity_curve", json::array())) {+ EquityPoint ep;+ ep.date = e.value("date", "");+ ep.equity = e.value("equity", 0.0);+ ep.drawdown = e.value("drawdown", 0.0);+ result.equity_curve.push_back(ep);+ }+ } catch (const std::exception& e) {+ result.error = std::string("Failed to parse backtest result: ") + e.what();+ }++ return result;+}++BacktestResult AlgoService::run_python_backtest(const std::string& code,+ const std::string& symbol,+ const std::string& start_date,+ const std::string& end_date,+ double capital) {+ BacktestResult result;++ std::vector<std::string> args = {+ "--symbol", symbol,+ "--start", start_date,+ "--end", end_date,+ "--capital", std::to_string(capital),+ "--db", get_db_path()+ };++ auto py_result = python::execute_with_stdin("algo_trading/python_backtest_engine.py", args, code);+ if (!py_result.success) {+ result.error = py_result.error;+ return result;+ }++ try {+ auto j = json::parse(py_result.output);+ result.success = j.value("success", false);+ result.error = j.value("error", "");+ // Parse metrics same as above (reuse pattern)+ auto m = j.value("metrics", json::object());+ result.metrics.total_return = m.value("total_return", 0.0);+ result.metrics.total_return_pct = m.value("total_return_pct", 0.0);+ result.metrics.max_drawdown = m.value("max_drawdown", 0.0);+ result.metrics.sharpe_ratio = m.value("sharpe_ratio", 0.0);+ result.metrics.win_rate = m.value("win_rate", 0.0);+ result.metrics.total_trades = m.value("total_trades", 0);+ } catch (const std::exception& e) {+ result.error = std::string("Parse error: ") + e.what();+ }++ return result;+}++// ============================================================================+// Scanner+// ============================================================================++std::vector<ScanResult> AlgoService::run_scan(const std::string& conditions_json,+ const std::vector<std::string>& symbols,+ const std::string& timeframe,+ const std::string& provider) {+ std::vector<ScanResult> results;++ // Build symbols CSV+ std::string syms;+ for (size_t i = 0; i < symbols.size(); i++) {+ if (i > 0) syms += ",";+ syms += symbols[i];+ }++ std::vector<std::string> args = {+ "--conditions", conditions_json,+ "--symbols", syms,+ "--timeframe", timeframe,+ "--provider", provider,+ "--db", get_db_path()+ };++ auto py_result = python::execute("algo_trading/scanner_engine.py", args);+ if (!py_result.success) return results;++ try {+ auto j = json::parse(py_result.output);+ for (auto& r : j.value("results", json::array())) {+ ScanResult sr;+ sr.symbol = r.value("symbol", "");+ sr.entry_match = r.value("entry_match", false);+ sr.exit_match = r.value("exit_match", false);+ sr.last_price = r.value("last_price", 0.0);+ sr.volume = r.value("volume", 0.0);+ sr.details = r.value("details", json::object()).dump();+ results.push_back(sr);+ }+ } catch (...) {}++ return results;+}++// ============================================================================+// Condition Evaluation+// ============================================================================++std::string AlgoService::evaluate_conditions(const std::string& conditions_json,+ const std::string& symbol,+ const std::string& timeframe) {+ std::vector<std::string> args = {+ "--conditions", conditions_json,+ "--symbol", symbol,+ "--timeframe", timeframe,+ "--db", get_db_path()+ };++ auto py_result = python::execute("algo_trading/condition_evaluator.py", args);+ return py_result.success ? py_result.output : json({{"error", py_result.error}}).dump();+}++// ============================================================================+// Deployment Count+// ============================================================================++int AlgoService::running_deployment_count() const {+ auto deployments = db::ops::list_algo_deployments();+ int count = 0;+ for (auto& d : deployments) {+ if (d.status == DeploymentStatus::Running || d.status == DeploymentStatus::Starting)+ count++;+ }+ return count;+}++// ============================================================================+// Python Strategy Library+// ============================================================================++std::string AlgoService::get_strategies_dir() const {+ // strategies/ sits next to algo_trading/ under scripts/+ auto base = std::filesystem::path(get_scripts_dir()).parent_path() / "strategies";+ return base.string();+}++std::vector<PythonStrategy> AlgoService::list_python_strategies() const {+ std::vector<PythonStrategy> result;+ auto dir = get_strategies_dir();+ auto registry_path = dir + "/_registry.py";++ std::ifstream f(registry_path);+ if (!f.is_open()) return result;++ std::string content((std::istreambuf_iterator<char>(f)),+ std::istreambuf_iterator<char>());+ f.close();++ // Parse STRATEGY_REGISTRY entries: "FCT-XXXXX": {"name": "...", "category": "...", "path": "..."}+ std::string marker = "STRATEGY_REGISTRY = {";+ auto start = content.find(marker);+ if (start == std::string::npos) return result;++ std::string dict = content.substr(start + marker.size());++ size_t pos = 0;+ while (pos < dict.size()) {+ // Find "FCT-+ auto id_start = dict.find("\"FCT-", pos);+ if (id_start == std::string::npos) break;+ id_start += 1; // skip opening quote++ auto id_end = dict.find("\"", id_start);+ if (id_end == std::string::npos) break;+ std::string id = dict.substr(id_start, id_end - id_start);++ // Find the { ... } for this entry+ auto brace_start = dict.find("{", id_end);+ if (brace_start == std::string::npos) break;+ auto brace_end = dict.find("}", brace_start);+ if (brace_end == std::string::npos) break;++ std::string entry = dict.substr(brace_start, brace_end - brace_start + 1);++ // Extract fields with simple parsing+ auto extract = [&](const char* field) -> std::string {+ std::string key = std::string("\"") + field + "\"";+ auto kpos = entry.find(key);+ if (kpos == std::string::npos) {+ // Try single quotes+ key = std::string("'") + field + "'";+ kpos = entry.find(key);+ if (kpos == std::string::npos) return "";+ }+ auto colon = entry.find(":", kpos + key.size());+ if (colon == std::string::npos) return "";+ // Find the value (quoted string)+ auto val_start = entry.find_first_of("\"'", colon + 1);+ if (val_start == std::string::npos) return "";+ char quote = entry[val_start];+ auto val_end = entry.find(quote, val_start + 1);+ if (val_end == std::string::npos) return "";+ return entry.substr(val_start + 1, val_end - val_start - 1);+ };++ PythonStrategy ps;+ ps.id = id;+ ps.name = extract("name");+ ps.category = extract("category");+ ps.filename = extract("path");+ result.push_back(ps);++ pos = brace_end + 1;+ }++ return result;+}++std::vector<std::string> AlgoService::get_strategy_categories() const {+ auto strategies = list_python_strategies();+ std::vector<std::string> cats;+ for (auto& s : strategies) {+ bool found = false;+ for (auto& c : cats) {+ if (c == s.category) { found = true; break; }+ }+ if (!found && !s.category.empty()) cats.push_back(s.category);+ }+ std::sort(cats.begin(), cats.end());+ return cats;+}++std::string AlgoService::get_strategy_code(const std::string& strategy_id) const {+ auto strategies = list_python_strategies();+ std::string filename;+ for (auto& s : strategies) {+ if (s.id == strategy_id) { filename = s.filename; break; }+ }+ if (filename.empty()) return "# Strategy not found: " + strategy_id;++ auto path = get_strategies_dir() + "/" + filename;+ std::ifstream f(path);+ if (!f.is_open()) return "# File not found: " + path;++ std::string code((std::istreambuf_iterator<char>(f)),+ std::istreambuf_iterator<char>());+ return code;+}++bool AlgoService::validate_python_syntax(const std::string& code, std::string& error_out) const {+ // Write code to temp file, then validate with python -c "import ast; ast.parse(open(...).read())"+ auto tmp = std::filesystem::temp_directory_path() / "fct_validate.py";+ {+ std::ofstream f(tmp);+ f << code;+ }++ std::string cmd = "python -c \"import ast; ast.parse(open('" ++ tmp.string() + "').read())\" 2>&1";++ // Use popen to capture stderr+#ifdef _WIN32+ FILE* pipe = _popen(cmd.c_str(), "r");+#else+ FILE* pipe = popen(cmd.c_str(), "r");+#endif+ if (!pipe) {+ error_out = "Failed to run Python";+ return false;+ }++ char buf[256];+ std::string output;+ while (fgets(buf, sizeof(buf), pipe)) output += buf;+#ifdef _WIN32+ int ret = _pclose(pipe);+#else+ int ret = pclose(pipe);+#endif++ std::filesystem::remove(tmp);++ if (ret == 0) return true;+ error_out = output;+ return false;+}++std::vector<StrategyParameter> AlgoService::extract_strategy_parameters(const std::string& code) const {+ std::vector<StrategyParameter> params;++ // Look for patterns: UPPER_CASE_NAME = number+ // Simple line-by-line scan+ std::istringstream stream(code);+ std::string line;+ while (std::getline(stream, line)) {+ // Skip comments and empty lines+ auto trimmed = line;+ while (!trimmed.empty() && (trimmed[0] == ' ' || trimmed[0] == '\t'))+ trimmed.erase(0, 1);+ if (trimmed.empty() || trimmed[0] == '#') continue;++ // Match: UPPER_NAME = 123 or UPPER_NAME = 12.5+ size_t eq = trimmed.find('=');+ if (eq == std::string::npos || eq == 0) continue;+ // Make sure it's not ==+ if (eq + 1 < trimmed.size() && trimmed[eq + 1] == '=') continue;++ std::string name = trimmed.substr(0, eq);+ // trim trailing spaces+ while (!name.empty() && name.back() == ' ') name.pop_back();+ // Check if it's all uppercase + underscore+ bool all_upper = true;+ for (char c : name) {+ if (!((c >= 'A' && c <= 'Z') || c == '_' || (c >= '0' && c <= '9'))) {+ all_upper = false;+ break;+ }+ }+ if (!all_upper || name.empty()) continue;++ std::string val = trimmed.substr(eq + 1);+ while (!val.empty() && val[0] == ' ') val.erase(0, 1);+ // Strip trailing comment+ auto hash = val.find('#');+ if (hash != std::string::npos) val = val.substr(0, hash);+ while (!val.empty() && val.back() == ' ') val.pop_back();++ // Check if value is numeric+ bool is_float = false;+ bool is_numeric = !val.empty();+ for (char c : val) {+ if (c == '.') { is_float = true; continue; }+ if (c == '-' && &c == &val[0]) continue;+ if (c < '0' || c > '9') { is_numeric = false; break; }+ }+ if (!is_numeric) continue;++ StrategyParameter p;+ p.name = name;+ p.type = is_float ? "float" : "int";+ p.default_value = val;+ params.push_back(p);+ }++ return params;+}++} // namespace fincept::algodiff --git a/fincept-cpp/src/screens/algo_trading/algo_service.h b/fincept-cpp/src/screens/algo_trading/algo_service.hnew file mode 100644index 000000000..887e7bf91--- /dev/null+++ b/fincept-cpp/src/screens/algo_trading/algo_service.h@@ -0,0 +1,108 @@+#pragma once+// Algo Service — deployment lifecycle, backtesting, scanning, process management+// Bridges between the UI screen and the backend (DB, Python scripts, unified trading)++#include "algo_types.h"+#include <string>+#include <vector>+#include <mutex>+#include <atomic>++namespace fincept::algo {++class AlgoService {+public:+ static AlgoService& instance();++ // --- Deployment lifecycle ---+ // Deploy a strategy: spawn algo_live_runner.py, track PID, prefetch candles+ std::string deploy_strategy(const std::string& strategy_id,+ const std::string& symbol,+ const std::string& mode,+ const std::string& provider,+ const std::string& timeframe,+ double quantity,+ const std::string& params_json = "{}");++ // Stop a running deployment (kill process, update DB)+ bool stop_deployment(const std::string& deployment_id);++ // Stop all running deployments (emergency stop)+ int stop_all_deployments();++ // Delete a deployment and its cascaded data+ void delete_deployment(const std::string& deployment_id);++ // --- Backtesting ---+ // Run condition-based backtest via backtest_engine.py+ BacktestResult run_backtest(const std::string& strategy_id,+ const std::string& symbol,+ const std::string& start_date,+ const std::string& end_date,+ double capital,+ const std::string& provider = "fyers");++ // Run Python strategy backtest via python_backtest_engine.py+ BacktestResult run_python_backtest(const std::string& code,+ const std::string& symbol,+ const std::string& start_date,+ const std::string& end_date,+ double capital);++ // --- Scanner ---+ // Run condition-based scan across symbols via scanner_engine.py+ std::vector<ScanResult> run_scan(const std::string& conditions_json,+ const std::vector<std::string>& symbols,+ const std::string& timeframe,+ const std::string& provider = "fyers");++ // --- Condition evaluation ---+ // One-shot condition evaluation via condition_evaluator.py+ std::string evaluate_conditions(const std::string& conditions_json,+ const std::string& symbol,+ const std::string& timeframe);++ // --- Python Strategy Library ---+ // Parse _registry.py and return all built-in strategies+ std::vector<PythonStrategy> list_python_strategies() const;++ // Get categories from the registry+ std::vector<std::string> get_strategy_categories() const;++ // Read strategy source code from file+ std::string get_strategy_code(const std::string& strategy_id) const;++ // Validate Python syntax via `python -c "import ast; ast.parse(...)"`+ bool validate_python_syntax(const std::string& code, std::string& error_out) const;++ // Extract parameters from Python code (UPPER_CASE = number patterns)+ std::vector<StrategyParameter> extract_strategy_parameters(const std::string& code) const;++ // --- Process management ---+ bool is_pid_alive(int pid) const;+ bool verify_pid_is_algo_runner(int pid) const;+ bool safe_kill_process(int pid) const;++ // --- Deployment count ---+ int running_deployment_count() const;++ AlgoService(const AlgoService&) = delete;+ AlgoService& operator=(const AlgoService&) = delete;++private:+ AlgoService() = default;++ // Max concurrent deployments+ static constexpr int MAX_CONCURRENT = 10;++ // Get the path to algo_trading scripts directory+ std::string get_scripts_dir() const;+ // Get the path to strategies library directory+ std::string get_strategies_dir() const;+ // Get the main DB path for passing to Python scripts+ std::string get_db_path() const;++ mutable std::mutex mutex_;+};++} // namespace fincept::algodiff --git a/fincept-cpp/src/screens/algo_trading/algo_trading_screen.cpp b/fincept-cpp/src/screens/algo_trading/algo_trading_screen.cppnew file mode 100644index 000000000..9dd8d65c8--- /dev/null+++ b/fincept-cpp/src/screens/algo_trading/algo_trading_screen.cpp@@ -0,0 +1,1362 @@+#include "algo_trading_screen.h"+#include "algo_service.h"+#include "storage/database.h"+#include <thread>++namespace fincept::algo {++void AlgoTradingScreen::init() {+ load_strategies();+ load_deployments();+ refresh_running_count();+ initialized_ = true;+}++void AlgoTradingScreen::render() {+ if (!initialized_) init();++ ImVec2 avail = ImGui::GetContentRegionAvail();+ float w = avail.x;+ float h = avail.y;++ // Top navigation bar (sub-view tabs)+ float nav_h = 40.0f;+ render_top_nav(w);++ // Status bar at bottom+ float status_h = 28.0f;+ float content_h = h - nav_h - status_h;++ // Content area+ ImGui::BeginChild("##algo_content", ImVec2(w, content_h), false);+ switch (active_view_) {+ case SubView::Builder: render_builder(w, content_h); break;+ case SubView::Strategies: render_strategies(w, content_h); break;+ case SubView::Library: render_library(w, content_h); break;+ case SubView::Scanner: render_scanner(w, content_h); break;+ case SubView::Dashboard: render_dashboard(w, content_h); break;+ }+ ImGui::EndChild();++ render_status_bar(w);+}++void AlgoTradingScreen::render_top_nav(float w) {+ ImGui::PushStyleColor(ImGuiCol_ChildBg, ImVec4(0.08f, 0.08f, 0.12f, 1.0f));+ ImGui::BeginChild("##algo_nav", ImVec2(w, 40.0f), false);++ struct NavItem { const char* label; SubView view; };+ static const NavItem items[] = {+ {"Strategy Builder", SubView::Builder},+ {"My Strategies", SubView::Strategies},+ {"Strategy Library", SubView::Library},+ {"Scanner", SubView::Scanner},+ {"Dashboard", SubView::Dashboard},+ };++ ImGui::SetCursorPosY(6.0f);+ ImGui::SetCursorPosX(10.0f);++ for (const auto& item : items) {+ bool selected = (active_view_ == item.view);+ if (selected) {+ ImGui::PushStyleColor(ImGuiCol_Button, ImVec4(0.20f, 0.40f, 0.80f, 1.0f));+ } else {+ ImGui::PushStyleColor(ImGuiCol_Button, ImVec4(0.15f, 0.15f, 0.20f, 1.0f));+ }+ if (ImGui::Button(item.label, ImVec2(0, 28))) {+ active_view_ = item.view;+ }+ ImGui::PopStyleColor();+ ImGui::SameLine();+ }++ // Running deployments indicator + emergency stop+ if (running_count_ > 0) {+ ImGui::SameLine(w - 250.0f);+ ImGui::PushStyleColor(ImGuiCol_Text, ImVec4(0.2f, 1.0f, 0.2f, 1.0f));+ ImGui::Text("%d Running", running_count_);+ ImGui::PopStyleColor();+ ImGui::SameLine();+ ImGui::PushStyleColor(ImGuiCol_Button, ImVec4(0.8f, 0.1f, 0.1f, 1.0f));+ if (ImGui::SmallButton("STOP ALL")) stop_all_deployments();+ ImGui::PopStyleColor();+ }++ // Backtest indicator+ if (backtest_running_) {+ ImGui::SameLine(running_count_ > 0 ? 0 : w - 180.0f);+ ImGui::TextColored(ImVec4(0.4f, 0.7f, 1, 1), "Backtesting...");+ }++ ImGui::EndChild();+ ImGui::PopStyleColor();+}++void AlgoTradingScreen::render_status_bar(float w) {+ ImGui::PushStyleColor(ImGuiCol_ChildBg, ImVec4(0.06f, 0.06f, 0.10f, 1.0f));+ ImGui::BeginChild("##algo_status", ImVec2(w, 28.0f), false);+ ImGui::SetCursorPos(ImVec2(10.0f, 6.0f));+ ImGui::TextColored(ImVec4(0.5f, 0.5f, 0.5f, 1.0f),+ "Algo Trading | Strategies: %d | Deployments: %d | Running: %d",+ (int)strategies_.size(), (int)deployments_.size(), running_count_);+ if (!status_msg_.empty()) {+ ImGui::SameLine(w - 400.0f);+ ImGui::TextColored(ImVec4(0.4f, 0.7f, 1.0f, 1.0f), "%s", status_msg_.c_str());+ }+ ImGui::EndChild();+ ImGui::PopStyleColor();+}++// ============================================================================+// Builder sub-view+// ============================================================================++void AlgoTradingScreen::render_builder(float w, float h) {+ ImGui::Columns(2, "##builder_cols", true);+ ImGui::SetColumnWidth(0, w * 0.55f);++ // Left: Condition editor+ ImGui::BeginChild("##builder_left", ImVec2(0, h), false);++ ImGui::Text("Strategy Name");+ ImGui::SetNextItemWidth(-1);+ ImGui::InputText("##strat_name", strategy_name_, sizeof(strategy_name_));++ ImGui::Text("Symbols (comma-separated)");+ ImGui::SetNextItemWidth(-1);+ ImGui::InputText("##strat_symbols", symbols_buf_, sizeof(symbols_buf_));++ ImGui::Spacing();+ ImGui::Separator();+ ImGui::Text("Entry Conditions");+ render_condition_editor("entry", entry_conditions_, entry_logic_idx_);++ ImGui::Spacing();+ ImGui::Separator();+ ImGui::Text("Exit Conditions");+ render_condition_editor("exit", exit_conditions_, exit_logic_idx_);++ ImGui::EndChild();++ // Right: Parameters+ ImGui::NextColumn();+ ImGui::BeginChild("##builder_right", ImVec2(0, h), false);++ ImGui::Text("Parameters");+ ImGui::Separator();++ ImGui::Text("Timeframe");+ auto& tfs = get_timeframes();+ if (ImGui::BeginCombo("##timeframe", tfs[timeframe_idx_].label)) {+ for (int i = 0; i < (int)tfs.size(); i++) {+ if (ImGui::Selectable(tfs[i].label, i == timeframe_idx_))+ timeframe_idx_ = i;+ }+ ImGui::EndCombo();+ }++ ImGui::Text("Provider");+ auto& provs = get_broker_providers();+ if (ImGui::BeginCombo("##provider", provs[provider_idx_].second)) {+ for (int i = 0; i < (int)provs.size(); i++) {+ if (ImGui::Selectable(provs[i].second, i == provider_idx_))+ provider_idx_ = i;+ }+ ImGui::EndCombo();+ }++ ImGui::Text("Stop Loss (%%)");+ ImGui::SliderFloat("##sl", &stop_loss_, 0, 20, "%.1f%%");+ ImGui::Text("Take Profit (%%)");+ ImGui::SliderFloat("##tp", &take_profit_, 0, 50, "%.1f%%");+ ImGui::Text("Trailing Stop (%%)");+ ImGui::SliderFloat("##ts", &trailing_stop_, 0, 20, "%.1f%%");+ ImGui::Text("Position Size");+ ImGui::InputFloat("##possize", &position_size_, 0.1f, 1.0f, "%.1f");+ ImGui::Text("Max Positions");+ ImGui::InputInt("##maxpos", &max_positions_);++ ImGui::Spacing();+ ImGui::Separator();+ ImGui::Text("Description");+ ImGui::InputTextMultiline("##strat_desc", strategy_desc_, sizeof(strategy_desc_),+ ImVec2(-1, 80));++ ImGui::Spacing();+ if (ImGui::Button("Save Strategy", ImVec2(-1, 36))) {+ save_strategy();+ }+ if (!editing_strategy_id_.empty()) {+ if (ImGui::Button("Cancel Edit", ImVec2(-1, 28))) {+ editing_strategy_id_.clear();+ strategy_name_[0] = '\0';+ strategy_desc_[0] = '\0';+ symbols_buf_[0] = '\0';+ entry_conditions_.clear();+ exit_conditions_.clear();+ }+ }++ ImGui::EndChild();+ ImGui::Columns(1);+}++void AlgoTradingScreen::render_condition_editor(const char* label,+ std::vector<ConditionItem>& conditions,+ int& logic_idx) {+ ImGui::PushID(label);++ // Logic selector+ const char* logic_options[] = {"AND", "OR"};+ ImGui::Text("Logic:");+ ImGui::SameLine();+ ImGui::SetNextItemWidth(80);+ ImGui::Combo("##logic", &logic_idx, logic_options, 2);++ ImGui::SameLine();+ if (ImGui::Button("+ Add Condition")) {+ ConditionItem c;+ c.indicator = "close";+ c.operator_type = ">";+ c.field = "value";+ conditions.push_back(c);+ }++ // Render each condition+ int remove_idx = -1;+ for (int i = 0; i < (int)conditions.size(); i++) {+ ImGui::PushID(i);+ bool remove = false;+ render_condition_row(conditions[i], i, remove);+ if (remove) remove_idx = i;+ ImGui::PopID();+ }++ if (remove_idx >= 0) {+ conditions.erase(conditions.begin() + remove_idx);+ }++ ImGui::PopID();+}++void AlgoTradingScreen::render_condition_row(ConditionItem& cond, int /*idx*/, bool& remove) {+ auto& indicators = get_indicators();+ auto& operators = get_operators();++ ImGui::BeginGroup();++ // Indicator selector+ ImGui::SetNextItemWidth(140);+ if (ImGui::BeginCombo("##ind", cond.indicator.c_str())) {+ for (auto& cat : get_indicator_categories()) {+ ImGui::TextDisabled("%s", cat.second);+ for (auto& ind : indicators) {+ if (std::string(ind.category) == cat.first) {+ if (ImGui::Selectable(ind.name, cond.indicator == ind.id)) {+ cond.indicator = ind.id;+ if (ind.has_period) cond.period = ind.default_period;+ }+ }+ }+ ImGui::Separator();+ }+ ImGui::EndCombo();+ }++ ImGui::SameLine();++ // Period input (if applicable)+ bool has_period = false;+ for (auto& ind : indicators) {+ if (ind.id == cond.indicator) { has_period = ind.has_period; break; }+ }+ if (has_period) {+ ImGui::SetNextItemWidth(60);+ ImGui::InputInt("##period", &cond.period, 0, 0);+ ImGui::SameLine();+ }++ // Operator selector+ ImGui::SetNextItemWidth(120);+ if (ImGui::BeginCombo("##op", cond.operator_type.c_str())) {+ for (auto& op : operators) {+ if (ImGui::Selectable(op.label, cond.operator_type == op.id))+ cond.operator_type = op.id;+ }+ ImGui::EndCombo();+ }++ ImGui::SameLine();++ // Value input+ ImGui::SetNextItemWidth(100);+ char vbuf[64];+ snprintf(vbuf, sizeof(vbuf), "%s", cond.value.c_str());+ if (ImGui::InputText("##val", vbuf, sizeof(vbuf))) {+ cond.value = vbuf;+ }++ // Second value for "between"+ for (auto& op : operators) {+ if (op.id == cond.operator_type && op.needs_value2) {+ ImGui::SameLine();+ ImGui::Text("and");+ ImGui::SameLine();+ ImGui::SetNextItemWidth(100);+ char v2buf[64];+ snprintf(v2buf, sizeof(v2buf), "%s", cond.value2.c_str());+ if (ImGui::InputText("##val2", v2buf, sizeof(v2buf))) {+ cond.value2 = v2buf;+ }+ break;+ }+ }++ ImGui::SameLine();+ ImGui::PushStyleColor(ImGuiCol_Button, ImVec4(0.6f, 0.1f, 0.1f, 1.0f));+ if (ImGui::Button("X")) remove = true;+ ImGui::PopStyleColor();++ ImGui::EndGroup();+}++// ============================================================================+// Strategies sub-view+// ============================================================================++void AlgoTradingScreen::render_strategies(float w, float h) {+ ImGui::BeginChild("##strategies_view", ImVec2(w, h), false);++ if (ImGui::Button("Refresh")) load_strategies();+ ImGui::SameLine();+ ImGui::Text("(%d strategies)", (int)strategies_.size());++ ImGui::Separator();++ // Table of strategies+ if (ImGui::BeginTable("##strat_table", 7,+ ImGuiTableFlags_Borders | ImGuiTableFlags_RowBg |+ ImGuiTableFlags_Resizable | ImGuiTableFlags_ScrollY)) {+ ImGui::TableSetupColumn("Name");+ ImGui::TableSetupColumn("Symbols");+ ImGui::TableSetupColumn("Timeframe");+ ImGui::TableSetupColumn("Provider");+ ImGui::TableSetupColumn("SL/TP");+ ImGui::TableSetupColumn("Status");+ ImGui::TableSetupColumn("Actions");+ ImGui::TableHeadersRow();++ std::lock_guard lock(data_mutex_);+ for (auto& s : strategies_) {+ ImGui::TableNextRow();+ ImGui::TableNextColumn(); ImGui::Text("%s", s.name.c_str());+ ImGui::TableNextColumn(); ImGui::TextWrapped("%s", s.symbols.c_str());+ ImGui::TableNextColumn(); ImGui::Text("%s", s.timeframe.c_str());+ ImGui::TableNextColumn(); ImGui::Text("%s", s.provider.c_str());+ ImGui::TableNextColumn(); ImGui::Text("%.1f/%.1f", s.stop_loss, s.take_profit);+ ImGui::TableNextColumn();+ ImGui::TextColored(s.is_active ? ImVec4(0.2f,1,0.2f,1) : ImVec4(0.5f,0.5f,0.5f,1),+ s.is_active ? "Active" : "Inactive");+ ImGui::TableNextColumn();+ ImGui::PushID(s.id.c_str());+ if (ImGui::SmallButton("Edit")) edit_strategy(s);+ ImGui::SameLine();+ if (ImGui::SmallButton("Paper")) deploy_strategy(s.id, "paper");+ ImGui::SameLine();+ if (ImGui::SmallButton("Live")) deploy_strategy(s.id, "live");+ ImGui::SameLine();+ if (ImGui::SmallButton("Backtest")) run_backtest(s.id);+ ImGui::SameLine();+ ImGui::PushStyleColor(ImGuiCol_Button, ImVec4(0.6f,0.1f,0.1f,1));+ if (ImGui::SmallButton("Del")) delete_strategy(s.id);+ ImGui::PopStyleColor();+ ImGui::PopID();+ }++ ImGui::EndTable();+ }++ // Deployments section+ ImGui::Spacing();+ ImGui::Text("Active Deployments");+ ImGui::Separator();++ if (ImGui::BeginTable("##deploy_table", 6,+ ImGuiTableFlags_Borders | ImGuiTableFlags_RowBg |+ ImGuiTableFlags_ScrollY, ImVec2(0, 200))) {+ ImGui::TableSetupColumn("Strategy");+ ImGui::TableSetupColumn("Mode");+ ImGui::TableSetupColumn("Status");+ ImGui::TableSetupColumn("PID");+ ImGui::TableSetupColumn("Started");+ ImGui::TableSetupColumn("Actions");+ ImGui::TableHeadersRow();++ std::lock_guard lock(data_mutex_);+ for (auto& d : deployments_) {+ ImGui::TableNextRow();+ ImGui::TableNextColumn(); ImGui::Text("%s", d.strategy_name.c_str());+ ImGui::TableNextColumn();+ ImGui::TextColored(d.mode == "live" ? ImVec4(1,0.3f,0.3f,1) : ImVec4(0.3f,0.7f,1,1),+ "%s", d.mode.c_str());+ ImGui::TableNextColumn();+ auto sc = deployment_status_str(d.status);+ ImVec4 col = d.status == DeploymentStatus::Running ? ImVec4(0.2f,1,0.2f,1)+ : d.status == DeploymentStatus::Error ? ImVec4(1,0.2f,0.2f,1)+ : ImVec4(0.5f,0.5f,0.5f,1);+ ImGui::TextColored(col, "%s", sc);+ ImGui::TableNextColumn(); ImGui::Text("%d", d.pid);+ ImGui::TableNextColumn(); ImGui::Text("%s", d.started_at.c_str());+ ImGui::TableNextColumn();+ ImGui::PushID(d.id.c_str());+ if (d.status == DeploymentStatus::Running) {+ ImGui::PushStyleColor(ImGuiCol_Button, ImVec4(0.7f,0.2f,0.1f,1));+ if (ImGui::SmallButton("Stop")) stop_deployment(d.id);+ ImGui::PopStyleColor();+ } else {+ ImGui::PushStyleColor(ImGuiCol_Button, ImVec4(0.5f,0.1f,0.1f,1));+ if (ImGui::SmallButton("Delete")) delete_deployment_action(d.id);+ ImGui::PopStyleColor();+ }+ ImGui::PopID();+ }+ ImGui::EndTable();+ }++ // Backtest results (shown inline after running a backtest)+ render_backtest_results();++ ImGui::EndChild();+}++// ============================================================================+// Library sub-view (stub — full impl in Part 4)+// ============================================================================++void AlgoTradingScreen::render_library(float w, float h) {+ if (!library_loaded_) load_library();++ // Three-column layout: categories | strategy list | code preview+ float cat_w = 160.0f;+ float list_w = 280.0f;+ float code_w = w - cat_w - list_w - 20.0f;++ // --- Left: Category sidebar ---+ ImGui::BeginChild("##lib_cats", ImVec2(cat_w, h), true);+ ImGui::Text("Categories");+ ImGui::Separator();++ // "All" category+ bool all_sel = (library_category_idx_ == 0);+ if (ImGui::Selectable("All", all_sel))+ library_category_idx_ = 0;+ if (all_sel) {+ ImGui::SameLine(cat_w - 40);+ ImGui::TextDisabled("%d", (int)python_strategies_.size());+ }++ for (int i = 0; i < (int)library_categories_.size(); i++) {+ bool sel = (library_category_idx_ == i + 1);+ // Count strategies in this category+ int count = 0;+ for (auto& s : python_strategies_)+ if (s.category == library_categories_[i]) count++;++ if (ImGui::Selectable(library_categories_[i].c_str(), sel))+ library_category_idx_ = i + 1;+ if (sel || true) {+ ImGui::SameLine(cat_w - 40);+ ImGui::TextDisabled("%d", count);+ }+ }++ ImGui::Spacing();+ ImGui::Separator();+ ImGui::Text("Custom Strategies");+ ImGui::Separator();+ for (auto& cs : custom_strategies_) {+ ImGui::PushID(cs.id.c_str());+ if (ImGui::Selectable(cs.name.c_str(), selected_strategy_id_ == cs.id)) {+ selected_strategy_id_ = cs.id;+ code_preview_ = cs.code;+ editing_code_ = false;+ }+ ImGui::PopID();+ }++ ImGui::EndChild();++ ImGui::SameLine();++ // --- Middle: Strategy list ---+ ImGui::BeginChild("##lib_list", ImVec2(list_w, h), true);++ // Search bar+ ImGui::SetNextItemWidth(-1);+ ImGui::InputTextWithHint("##lib_search", "Search strategies...",+ library_search_, sizeof(library_search_));++ ImGui::Separator();++ std::string search_q = library_search_;+ // Convert to lowercase for matching+ for (auto& c : search_q) c = (char)tolower(c);++ std::string active_cat;+ if (library_category_idx_ > 0 && library_category_idx_ <= (int)library_categories_.size())+ active_cat = library_categories_[library_category_idx_ - 1];++ int shown = 0;+ for (auto& ps : python_strategies_) {+ // Category filter+ if (!active_cat.empty() && ps.category != active_cat) continue;++ // Search filter+ if (!search_q.empty()) {+ std::string name_lower = ps.name;+ for (auto& c : name_lower) c = (char)tolower(c);+ std::string id_lower = ps.id;+ for (auto& c : id_lower) c = (char)tolower(c);+ if (name_lower.find(search_q) == std::string::npos &&+ id_lower.find(search_q) == std::string::npos)+ continue;+ }++ bool sel = (selected_strategy_id_ == ps.id);+ ImGui::PushID(ps.id.c_str());++ // Format: name + category badge+ if (ImGui::Selectable("##sel", sel, 0, ImVec2(0, 36))) {+ selected_strategy_id_ = ps.id;+ editing_code_ = false;+ // Load code in background+ code_preview_ = "Loading...";+ loading_code_ = true;+ std::string sid = ps.id;+ std::thread([this, sid]() {+ auto code = AlgoService::instance().get_strategy_code(sid);+ code_preview_ = code;+ loading_code_ = false;+ }).detach();+ }+ // Draw name and category on the selectable+ ImGui::SameLine(4);+ ImGui::BeginGroup();+ // Insert spaces before capitals for readability+ std::string display_name = ps.name;+ std::string readable;+ for (size_t i = 0; i < display_name.size(); i++) {+ if (i > 0 && display_name[i] >= 'A' && display_name[i] <= 'Z' &&+ display_name[i-1] >= 'a' && display_name[i-1] <= 'z')+ readable += ' ';+ readable += display_name[i];+ }+ ImGui::Text("%s", readable.c_str());+ ImGui::TextColored(ImVec4(0.4f, 0.6f, 0.8f, 1.0f), "%s | %s",+ ps.category.c_str(), ps.id.c_str());+ ImGui::EndGroup();++ ImGui::PopID();+ shown++;+ }++ if (shown == 0) {+ ImGui::TextDisabled("No strategies match the filter");+ }++ ImGui::EndChild();++ ImGui::SameLine();++ // --- Right: Code preview / editor ---+ ImGui::BeginChild("##lib_code", ImVec2(code_w, h), true);++ if (selected_strategy_id_.empty()) {+ ImGui::TextDisabled("Select a strategy to view its code");+ } else if (loading_code_) {+ ImGui::Text("Loading code...");+ } else {+ // Toolbar+ if (!editing_code_) {+ if (ImGui::Button("Edit / Clone")) {+ editing_code_ = true;+ snprintf(custom_code_, sizeof(custom_code_), "%s", code_preview_.c_str());+ // Pre-fill name from strategy+ for (auto& ps : python_strategies_) {+ if (ps.id == selected_strategy_id_) {+ snprintf(custom_name_, sizeof(custom_name_), "%s_custom", ps.name.c_str());+ break;+ }+ }+ }+ ImGui::SameLine();+ if (ImGui::Button("Backtest")) {+ // Run python backtest with this code+ status_msg_ = "Running Python backtest...";+ backtest_running_ = true;+ std::string code = code_preview_;+ std::thread([this, code]() {+ try {+ auto result = AlgoService::instance().run_python_backtest(+ code, "NSE:NIFTY50", "2024-01-01", "2024-12-31", 100000.0);+ std::lock_guard lock(data_mutex_);+ backtest_result_ = result;+ status_msg_ = "Python backtest complete";+ } catch (const std::exception& e) {+ status_msg_ = std::string("Backtest failed: ") + e.what();+ }+ backtest_running_ = false;+ }).detach();+ }+ ImGui::SameLine();+ if (ImGui::Button("Copy Code")) {+ ImGui::SetClipboardText(code_preview_.c_str());+ status_msg_ = "Code copied to clipboard";+ }++ ImGui::Separator();++ // Read-only code display+ ImGui::InputTextMultiline("##code_ro", const_cast<char*>(code_preview_.c_str()),+ code_preview_.size() + 1,+ ImVec2(-1, h - 80),+ ImGuiInputTextFlags_ReadOnly);+ } else {+ // Edit mode+ ImGui::Text("Name:");+ ImGui::SameLine();+ ImGui::SetNextItemWidth(300);+ 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";+ }+ ImGui::SameLine();+ if (ImGui::Button("Save as Custom")) {+ CustomPythonStrategy cs;+ cs.id = db::generate_uuid();+ cs.name = custom_name_;+ cs.description = "Cloned from " + selected_strategy_id_;+ cs.code = custom_code_;+ cs.category = "custom";+ db::ops::save_custom_python_strategy(cs);+ status_msg_ = "Custom strategy saved: " + cs.name;+ editing_code_ = false;+ // Reload customs+ custom_strategies_ = db::ops::list_custom_python_strategies();+ }+ ImGui::SameLine();+ if (ImGui::Button("Cancel")) {+ editing_code_ = false;+ syntax_error_.clear();+ }++ if (!syntax_error_.empty()) {+ ImGui::TextColored(ImVec4(1, 0.3f, 0.3f, 1), "%s", syntax_error_.c_str());+ }++ ImGui::Separator();++ ImGui::InputTextMultiline("##code_edit", custom_code_, sizeof(custom_code_),+ ImVec2(-1, h - 100));+ }+ }++ ImGui::EndChild();+}++// ============================================================================+// Scanner sub-view+// ============================================================================++void AlgoTradingScreen::render_scanner(float w, float h) {+ ImGui::BeginChild("##scanner_view", ImVec2(w, h), false);+ ImGui::Text("Market Scanner");+ ImGui::Separator();++ // --- Controls row ---+ ImGui::Text("Symbols (comma-separated)");+ ImGui::SetNextItemWidth(w * 0.4f);+ ImGui::InputText("##scan_symbols", scan_symbols_, sizeof(scan_symbols_));++ ImGui::SameLine();+ ImGui::Text("Timeframe:");+ ImGui::SameLine();+ auto& tfs = get_timeframes();+ ImGui::SetNextItemWidth(100);+ if (ImGui::BeginCombo("##scan_tf", tfs[scan_tf_idx_].label)) {+ for (int i = 0; i < (int)tfs.size(); i++) {+ if (ImGui::Selectable(tfs[i].label, i == scan_tf_idx_))+ scan_tf_idx_ = i;+ }+ ImGui::EndCombo();+ }++ ImGui::SameLine();+ ImGui::Text("Provider:");+ ImGui::SameLine();+ auto& provs = get_broker_providers();+ ImGui::SetNextItemWidth(120);+ if (ImGui::BeginCombo("##scan_prov", provs[scan_prov_idx_].second)) {+ for (int i = 0; i < (int)provs.size(); i++) {+ if (ImGui::Selectable(provs[i].second, i == scan_prov_idx_))+ scan_prov_idx_ = i;+ }+ ImGui::EndCombo();+ }++ ImGui::SameLine();+ ImGui::PushStyleColor(ImGuiCol_Button,+ scanning_ ? ImVec4(0.5f, 0.5f, 0.5f, 1.0f) : ImVec4(0.2f, 0.6f, 0.2f, 1.0f));+ if (ImGui::Button(scanning_ ? "Scanning..." : "Run Scan", ImVec2(120, 0))) {+ if (!scanning_) run_scan();+ }+ ImGui::PopStyleColor();++ // --- Active conditions summary ---+ ImGui::Spacing();+ if (entry_conditions_.empty()) {+ ImGui::TextColored(ImVec4(1, 0.6f, 0.2f, 1),+ "No entry conditions defined. Go to Builder tab to add conditions.");+ } else {+ ImGui::TextColored(ImVec4(0.4f, 0.7f, 1, 1),+ "Scanning with %d entry condition(s) [%s]",+ (int)entry_conditions_.size(),+ entry_logic_idx_ == 0 ? "AND" : "OR");+ // Show conditions as a compact summary+ ImGui::SameLine();+ ImGui::TextDisabled("(");+ for (int i = 0; i < (int)entry_conditions_.size(); i++) {+ if (i > 0) { ImGui::SameLine(); ImGui::TextDisabled(entry_logic_idx_ == 0 ? "&&" : "||"); }+ ImGui::SameLine();+ auto& c = entry_conditions_[i];+ ImGui::Text("%s %s %s", c.indicator.c_str(), c.operator_type.c_str(), c.value.c_str());+ }+ ImGui::SameLine();+ ImGui::TextDisabled(")");+ }++ ImGui::Spacing();+ ImGui::Separator();++ // --- Results table ---+ if (scan_results_.empty() && !scanning_) {+ ImGui::TextDisabled("No scan results yet. Enter symbols and click Run Scan.");+ } else {+ ImGui::Text("Results: %d symbols", (int)scan_results_.size());+ ImGui::Spacing();++ if (ImGui::BeginTable("##scan_results", 6,+ ImGuiTableFlags_Borders | ImGuiTableFlags_RowBg |+ ImGuiTableFlags_Resizable | ImGuiTableFlags_ScrollY,+ ImVec2(0, h - 140))) {+ ImGui::TableSetupColumn("Symbol", ImGuiTableColumnFlags_WidthFixed, 120);+ ImGui::TableSetupColumn("Entry Match", ImGuiTableColumnFlags_WidthFixed, 90);+ ImGui::TableSetupColumn("Exit Match", ImGuiTableColumnFlags_WidthFixed, 90);+ ImGui::TableSetupColumn("Price", ImGuiTableColumnFlags_WidthFixed, 100);+ ImGui::TableSetupColumn("Volume", ImGuiTableColumnFlags_WidthFixed, 100);+ ImGui::TableSetupColumn("Details");+ ImGui::TableHeadersRow();++ for (auto& r : scan_results_) {+ ImGui::TableNextRow();+ ImGui::TableNextColumn(); ImGui::Text("%s", r.symbol.c_str());+ ImGui::TableNextColumn();+ ImGui::TextColored(r.entry_match ? ImVec4(0.2f,1,0.2f,1) : ImVec4(0.5f,0.5f,0.5f,1),+ r.entry_match ? "YES" : "NO");+ ImGui::TableNextColumn();+ ImGui::TextColored(r.exit_match ? ImVec4(1,0.3f,0.3f,1) : ImVec4(0.5f,0.5f,0.5f,1),+ r.exit_match ? "YES" : "NO");+ ImGui::TableNextColumn(); ImGui::Text("%.2f", r.last_price);+ ImGui::TableNextColumn(); ImGui::Text("%.0f", r.volume);+ ImGui::TableNextColumn();+ if (!r.details.empty() && r.details != "{}") {+ ImGui::TextWrapped("%s", r.details.c_str());+ } else {+ ImGui::TextDisabled("-");+ }+ }+ ImGui::EndTable();+ }+ }++ ImGui::EndChild();+}++// ============================================================================+// Dashboard sub-view+// ============================================================================++void AlgoTradingScreen::render_dashboard(float w, float h) {+ ImGui::BeginChild("##dashboard_view", ImVec2(w, h), false);++ // Toolbar+ if (ImGui::Button("Refresh Dashboard")) {+ load_deployments();+ load_dashboard_data();+ }+ ImGui::SameLine();+ if (running_count_ > 0) {+ ImGui::PushStyleColor(ImGuiCol_Button, ImVec4(0.7f, 0.1f, 0.1f, 1));+ if (ImGui::Button("STOP ALL")) stop_all_deployments();+ ImGui::PopStyleColor();+ }++ ImGui::Spacing();++ // Summary cards+ render_dashboard_summary();++ ImGui::Spacing();+ ImGui::Text("Deployment Metrics");+ ImGui::Separator();++ if (ImGui::BeginTable("##metrics_table", 8,+ ImGuiTableFlags_Borders | ImGuiTableFlags_RowBg |+ ImGuiTableFlags_ScrollY, ImVec2(0, h * 0.4f))) {+ ImGui::TableSetupColumn("Deployment");+ ImGui::TableSetupColumn("Total Trades");+ ImGui::TableSetupColumn("Win Rate");+ ImGui::TableSetupColumn("Total PnL");+ ImGui::TableSetupColumn("Max DD");+ ImGui::TableSetupColumn("Sharpe");+ ImGui::TableSetupColumn("Avg Win");+ ImGui::TableSetupColumn("Avg Loss");+ ImGui::TableHeadersRow();++ std::lock_guard lock(data_mutex_);+ for (auto& m : dashboard_metrics_) {+ ImGui::TableNextRow();+ ImGui::TableNextColumn(); ImGui::Text("%s", m.deployment_id.c_str());+ ImGui::TableNextColumn(); ImGui::Text("%d", m.total_trades);+ ImGui::TableNextColumn(); ImGui::Text("%.1f%%", m.win_rate * 100);+ ImGui::TableNextColumn();+ ImGui::TextColored(m.total_pnl >= 0 ? ImVec4(0.2f,1,0.2f,1) : ImVec4(1,0.2f,0.2f,1),+ "%.2f", m.total_pnl);+ ImGui::TableNextColumn(); ImGui::Text("%.2f%%", m.max_drawdown * 100);+ ImGui::TableNextColumn(); ImGui::Text("%.2f", m.sharpe_ratio);+ ImGui::TableNextColumn(); ImGui::Text("%.2f", m.avg_win);+ ImGui::TableNextColumn(); ImGui::Text("%.2f", m.avg_loss);+ }+ ImGui::EndTable();+ }++ ImGui::Spacing();+ ImGui::Text("Recent Trades");+ ImGui::Separator();++ if (ImGui::BeginTable("##trades_table", 7,+ ImGuiTableFlags_Borders | ImGuiTableFlags_RowBg |+ ImGuiTableFlags_ScrollY)) {+ ImGui::TableSetupColumn("Symbol");+ ImGui::TableSetupColumn("Side");+ ImGui::TableSetupColumn("Qty");+ ImGui::TableSetupColumn("Price");+ ImGui::TableSetupColumn("PnL");+ ImGui::TableSetupColumn("Status");+ ImGui::TableSetupColumn("Time");+ ImGui::TableHeadersRow();++ std::lock_guard lock(data_mutex_);+ for (auto& t : recent_trades_) {+ ImGui::TableNextRow();+ ImGui::TableNextColumn(); ImGui::Text("%s", t.symbol.c_str());+ ImGui::TableNextColumn();+ ImGui::TextColored(t.side == "buy" ? ImVec4(0.2f,1,0.2f,1) : ImVec4(1,0.3f,0.3f,1),+ "%s", t.side.c_str());+ ImGui::TableNextColumn(); ImGui::Text("%.4f", t.quantity);+ ImGui::TableNextColumn(); ImGui::Text("%.2f", t.price);+ ImGui::TableNextColumn();+ ImGui::TextColored(t.pnl >= 0 ? ImVec4(0.2f,1,0.2f,1) : ImVec4(1,0.2f,0.2f,1),+ "%.2f", t.pnl);+ ImGui::TableNextColumn(); ImGui::Text("%s", t.status.c_str());+ ImGui::TableNextColumn(); ImGui::Text("%s", t.executed_at.c_str());+ }+ ImGui::EndTable();+ }++ ImGui::EndChild();+}++// ============================================================================+// Actions (DB-backed — using placeholder implementations, full in Part 3)+// ============================================================================++void AlgoTradingScreen::save_strategy() {+ if (strategy_name_[0] == '\0') {+ status_msg_ = "Error: Strategy name required";+ return;+ }++ AlgoStrategy s;+ s.id = editing_strategy_id_.empty() ? db::generate_uuid() : editing_strategy_id_;+ s.name = strategy_name_;+ s.description = strategy_desc_;+ s.timeframe = get_timeframes()[timeframe_idx_].id;+ s.provider = get_broker_providers()[provider_idx_].first;+ s.stop_loss = stop_loss_;+ s.take_profit = take_profit_;+ s.trailing_stop = trailing_stop_;+ s.position_size = position_size_;+ s.max_positions = max_positions_;+ s.entry_logic = entry_logic_idx_ == 0 ? "AND" : "OR";+ s.exit_logic = exit_logic_idx_ == 0 ? "AND" : "OR";++ // Serialize symbols+ json sym_arr = json::array();+ std::string syms = symbols_buf_;+ size_t pos = 0;+ while ((pos = syms.find(',')) != std::string::npos) {+ auto tok = syms.substr(0, pos);+ if (!tok.empty()) sym_arr.push_back(tok);+ syms.erase(0, pos + 1);+ }+ if (!syms.empty()) sym_arr.push_back(syms);+ s.symbols = sym_arr.dump();++ // Serialize conditions+ json entry_j = json::array();+ for (auto& c : entry_conditions_) { json cj; to_json(cj, c); entry_j.push_back(cj); }+ s.entry_conditions = entry_j.dump();++ json exit_j = json::array();+ for (auto& c : exit_conditions_) { json cj; to_json(cj, c); exit_j.push_back(cj); }+ s.exit_conditions = exit_j.dump();++ db::ops::save_algo_strategy(s);+ status_msg_ = "Strategy saved: " + s.name;++ // Reset form+ editing_strategy_id_.clear();+ strategy_name_[0] = '\0';+ strategy_desc_[0] = '\0';+ symbols_buf_[0] = '\0';+ entry_conditions_.clear();+ exit_conditions_.clear();+ stop_loss_ = take_profit_ = trailing_stop_ = 0;+ position_size_ = 1.0f;+ max_positions_ = 1;++ load_strategies();+}++void AlgoTradingScreen::load_strategies() {+ std::lock_guard lock(data_mutex_);+ strategies_ = db::ops::list_algo_strategies();+ strategies_loaded_ = true;+}++void AlgoTradingScreen::delete_strategy(const std::string& id) {+ db::ops::delete_algo_strategy(id);+ status_msg_ = "Strategy deleted";+ load_strategies();+}++void AlgoTradingScreen::edit_strategy(const AlgoStrategy& s) {+ editing_strategy_id_ = s.id;+ snprintf(strategy_name_, sizeof(strategy_name_), "%s", s.name.c_str());+ snprintf(strategy_desc_, sizeof(strategy_desc_), "%s", s.description.c_str());++ // Parse symbols back+ try {+ auto arr = json::parse(s.symbols);+ std::string syms;+ for (auto& el : arr) {+ if (!syms.empty()) syms += ",";+ syms += el.get<std::string>();+ }+ snprintf(symbols_buf_, sizeof(symbols_buf_), "%s", syms.c_str());+ } catch (...) {+ snprintf(symbols_buf_, sizeof(symbols_buf_), "%s", s.symbols.c_str());+ }++ // Parse conditions back+ entry_conditions_.clear();+ exit_conditions_.clear();+ try {+ auto entry_j = json::parse(s.entry_conditions);+ for (auto& cj : entry_j) { ConditionItem c; from_json(cj, c); entry_conditions_.push_back(c); }+ } catch (...) {}+ try {+ auto exit_j = json::parse(s.exit_conditions);+ for (auto& cj : exit_j) { ConditionItem c; from_json(cj, c); exit_conditions_.push_back(c); }+ } catch (...) {}++ entry_logic_idx_ = s.entry_logic == "OR" ? 1 : 0;+ exit_logic_idx_ = s.exit_logic == "OR" ? 1 : 0;+ stop_loss_ = (float)s.stop_loss;+ take_profit_ = (float)s.take_profit;+ trailing_stop_ = (float)s.trailing_stop;+ position_size_ = (float)s.position_size;+ max_positions_ = s.max_positions;++ // Find timeframe & provider indices+ auto& tfs = get_timeframes();+ for (int i = 0; i < (int)tfs.size(); i++)+ if (s.timeframe == tfs[i].id) { timeframe_idx_ = i; break; }+ auto& provs = get_broker_providers();+ for (int i = 0; i < (int)provs.size(); i++)+ if (s.provider == provs[i].first) { provider_idx_ = i; break; }++ active_view_ = SubView::Builder;+ status_msg_ = "Editing: " + s.name;+}++void AlgoTradingScreen::deploy_strategy(const std::string& strategy_id,+ const std::string& mode) {+ // Find strategy+ AlgoStrategy* strat = nullptr;+ for (auto& s : strategies_) {+ if (s.id == strategy_id) { strat = &s; break; }+ }+ if (!strat) {+ status_msg_ = "Error: Strategy not found";+ return;+ }++ status_msg_ = "Deploying " + strat->name + " in " + mode + " mode...";++ // Parse first symbol from JSON array+ std::string symbol;+ try {+ auto arr = json::parse(strat->symbols);+ if (!arr.empty()) symbol = arr[0].get<std::string>();+ } catch (...) {+ symbol = strat->symbols;+ }++ // Launch deployment in background thread to avoid UI freeze+ std::string sid = strategy_id;+ std::string tf = strat->timeframe;+ std::string prov = strat->provider;+ double qty = strat->position_size;+ std::thread([this, sid, symbol, mode, prov, tf, qty]() {+ try {+ auto dep_id = AlgoService::instance().deploy_strategy(+ sid, symbol, mode, prov, tf, qty);+ status_msg_ = "Deployed: " + dep_id;+ } catch (const std::exception& e) {+ status_msg_ = std::string("Deploy failed: ") + e.what();+ }+ load_deployments();+ }).detach();+}++void AlgoTradingScreen::stop_deployment(const std::string& deployment_id) {+ status_msg_ = "Stopping deployment...";+ std::string did = deployment_id;+ std::thread([this, did]() {+ bool ok = AlgoService::instance().stop_deployment(did);+ status_msg_ = ok ? "Deployment stopped" : "Failed to stop deployment";+ load_deployments();+ }).detach();+}++void AlgoTradingScreen::load_deployments() {+ std::lock_guard lock(data_mutex_);+ deployments_ = db::ops::list_algo_deployments();+ deployments_loaded_ = true;+ refresh_running_count();+}++void AlgoTradingScreen::load_library() {+ python_strategies_ = AlgoService::instance().list_python_strategies();+ library_categories_ = AlgoService::instance().get_strategy_categories();+ custom_strategies_ = db::ops::list_custom_python_strategies();+ library_loaded_ = true;+}++void AlgoTradingScreen::run_scan() {+ if (entry_conditions_.empty()) {+ status_msg_ = "Error: Add entry conditions in Builder first";+ return;+ }++ // Parse symbols from scan input+ std::vector<std::string> symbols;+ std::string syms = scan_symbols_;+ size_t pos = 0;+ while ((pos = syms.find(',')) != std::string::npos) {+ auto tok = syms.substr(0, pos);+ // trim whitespace+ while (!tok.empty() && tok.front() == ' ') tok.erase(0, 1);+ while (!tok.empty() && tok.back() == ' ') tok.pop_back();+ if (!tok.empty()) symbols.push_back(tok);+ syms.erase(0, pos + 1);+ }+ while (!syms.empty() && syms.front() == ' ') syms.erase(0, 1);+ while (!syms.empty() && syms.back() == ' ') syms.pop_back();+ if (!syms.empty()) symbols.push_back(syms);++ if (symbols.empty()) {+ status_msg_ = "Error: Enter symbols to scan";+ return;+ }++ // Build conditions JSON from current entry conditions+ json conds = json::array();+ for (auto& c : entry_conditions_) { json cj; to_json(cj, c); conds.push_back(cj); }++ std::string tf = get_timeframes()[scan_tf_idx_].id;+ std::string prov = get_broker_providers()[scan_prov_idx_].first;+ std::string conds_str = conds.dump();++ status_msg_ = "Scanning " + std::to_string(symbols.size()) + " symbols...";+ scanning_ = true;++ std::thread([this, conds_str, symbols, tf, prov]() {+ try {+ auto results = AlgoService::instance().run_scan(conds_str, symbols, tf, prov);+ std::lock_guard lock(data_mutex_);+ scan_results_ = results;+ status_msg_ = "Scan complete: " + std::to_string(results.size()) + " results";+ } catch (const std::exception& e) {+ status_msg_ = std::string("Scan failed: ") + e.what();+ }+ scanning_ = false;+ }).detach();+}++void AlgoTradingScreen::run_backtest(const std::string& strategy_id) {+ // Find strategy+ AlgoStrategy* strat = nullptr;+ for (auto& s : strategies_) {+ if (s.id == strategy_id) { strat = &s; break; }+ }+ if (!strat) {+ status_msg_ = "Error: Strategy not found";+ return;+ }++ status_msg_ = "Running backtest for " + strat->name + "...";+ backtest_running_ = true;++ std::string sid = strategy_id;+ std::string symbol;+ try {+ auto arr = json::parse(strat->symbols);+ if (!arr.empty()) symbol = arr[0].get<std::string>();+ } catch (...) {+ symbol = strat->symbols;+ }+ std::string prov = strat->provider;++ std::thread([this, sid, symbol, prov]() {+ try {+ auto result = AlgoService::instance().run_backtest(+ sid, symbol,+ "2024-01-01", "2024-12-31", // default date range+ 100000.0, prov);++ std::lock_guard lock(data_mutex_);+ backtest_result_ = result;+ status_msg_ = "Backtest complete: " + std::to_string(result.metrics.total_trades) + " trades";+ } catch (const std::exception& e) {+ status_msg_ = std::string("Backtest failed: ") + e.what();+ }+ backtest_running_ = false;+ }).detach();+}++void AlgoTradingScreen::load_dashboard_data() {+ // Load metrics for all deployments+ std::lock_guard lock(data_mutex_);+ dashboard_metrics_.clear();+ recent_trades_.clear();+ for (auto& d : deployments_) {+ auto m = db::ops::get_algo_metrics(d.id);+ if (m) dashboard_metrics_.push_back(*m);+ auto trades = db::ops::get_algo_trades(d.id, 20);+ recent_trades_.insert(recent_trades_.end(), trades.begin(), trades.end());+ }+}++void AlgoTradingScreen::refresh_running_count() {+ running_count_ = 0;+ for (auto& d : deployments_) {+ if (d.status == DeploymentStatus::Running) running_count_++;+ }+}++void AlgoTradingScreen::stop_all_deployments() {+ status_msg_ = "Stopping all deployments...";+ std::thread([this]() {+ int stopped = AlgoService::instance().stop_all_deployments();+ status_msg_ = "Stopped " + std::to_string(stopped) + " deployment(s)";+ load_deployments();+ }).detach();+}++void AlgoTradingScreen::delete_deployment_action(const std::string& deployment_id) {+ std::string did = deployment_id;+ std::thread([this, did]() {+ AlgoService::instance().delete_deployment(did);+ status_msg_ = "Deployment deleted";+ load_deployments();+ }).detach();+}++// ============================================================================+// Backtest Results Panel+// ============================================================================++void AlgoTradingScreen::render_backtest_results() {+ if (!backtest_result_.success && backtest_result_.error.empty() && !backtest_running_)+ return; // No results to show++ ImGui::Spacing();+ ImGui::Separator();++ if (backtest_running_) {+ ImGui::TextColored(ImVec4(0.4f, 0.7f, 1, 1), "Backtest running...");+ return;+ }++ if (!backtest_result_.error.empty()) {+ ImGui::TextColored(ImVec4(1, 0.3f, 0.3f, 1), "Backtest Error: %s",+ backtest_result_.error.c_str());+ return;+ }++ ImGui::Text("Backtest Results");++ // Summary cards row+ auto& m = backtest_result_.metrics;+ float card_w = 130.0f;++ auto draw_card = [](const char* label, const char* value, ImVec4 color) {+ ImGui::BeginGroup();+ ImGui::PushStyleColor(ImGuiCol_ChildBg, ImVec4(0.10f, 0.10f, 0.15f, 1.0f));+ ImGui::BeginChild(label, ImVec2(125, 52), true);+ ImGui::TextDisabled("%s", label);+ ImGui::TextColored(color, "%s", value);+ ImGui::EndChild();+ ImGui::PopStyleColor();+ ImGui::EndGroup();+ };++ char buf[64];++ snprintf(buf, sizeof(buf), "%.2f%%", m.total_return_pct);+ draw_card("Total Return", buf, m.total_return_pct >= 0 ? ImVec4(0.2f,1,0.2f,1) : ImVec4(1,0.2f,0.2f,1));+ ImGui::SameLine();++ snprintf(buf, sizeof(buf), "%d", m.total_trades);+ draw_card("Trades", buf, ImVec4(0.8f, 0.8f, 1, 1));+ ImGui::SameLine();++ snprintf(buf, sizeof(buf), "%.1f%%", m.win_rate * 100);+ draw_card("Win Rate", buf, m.win_rate >= 0.5 ? ImVec4(0.2f,1,0.2f,1) : ImVec4(1,0.6f,0.2f,1));+ ImGui::SameLine();++ snprintf(buf, sizeof(buf), "%.2f", m.sharpe_ratio);+ draw_card("Sharpe", buf, m.sharpe_ratio >= 1.0 ? ImVec4(0.2f,1,0.2f,1) : ImVec4(1,0.6f,0.2f,1));+ ImGui::SameLine();++ snprintf(buf, sizeof(buf), "%.2f%%", m.max_drawdown * 100);+ draw_card("Max DD", buf, ImVec4(1, 0.4f, 0.4f, 1));++ // Trades table+ if (!backtest_result_.trades.empty()) {+ ImGui::Spacing();+ ImGui::Text("Backtest Trades (%d)", (int)backtest_result_.trades.size());++ if (ImGui::BeginTable("##bt_trades", 7,+ ImGuiTableFlags_Borders | ImGuiTableFlags_RowBg |+ ImGuiTableFlags_ScrollY, ImVec2(0, 200))) {+ ImGui::TableSetupColumn("Symbol");+ ImGui::TableSetupColumn("Side");+ ImGui::TableSetupColumn("Entry");+ ImGui::TableSetupColumn("Exit");+ ImGui::TableSetupColumn("Qty");+ ImGui::TableSetupColumn("PnL");+ ImGui::TableSetupColumn("PnL %");+ ImGui::TableHeadersRow();++ for (auto& t : backtest_result_.trades) {+ ImGui::TableNextRow();+ ImGui::TableNextColumn(); ImGui::Text("%s", t.symbol.c_str());+ ImGui::TableNextColumn();+ ImGui::TextColored(t.side == "buy" ? ImVec4(0.2f,1,0.2f,1) : ImVec4(1,0.3f,0.3f,1),+ "%s", t.side.c_str());+ ImGui::TableNextColumn(); ImGui::Text("%.2f", t.entry_price);+ ImGui::TableNextColumn(); ImGui::Text("%.2f", t.exit_price);+ ImGui::TableNextColumn(); ImGui::Text("%.2f", t.quantity);+ ImGui::TableNextColumn();+ ImGui::TextColored(t.pnl >= 0 ? ImVec4(0.2f,1,0.2f,1) : ImVec4(1,0.2f,0.2f,1),+ "%.2f", t.pnl);+ ImGui::TableNextColumn();+ ImGui::TextColored(t.pnl_pct >= 0 ? ImVec4(0.2f,1,0.2f,1) : ImVec4(1,0.2f,0.2f,1),+ "%.2f%%", t.pnl_pct);+ }+ ImGui::EndTable();+ }+ }++ if (ImGui::Button("Clear Results")) {+ backtest_result_ = BacktestResult{};+ }+}++// ============================================================================+// Dashboard Summary Cards+// ============================================================================++void AlgoTradingScreen::render_dashboard_summary() {+ // Compute aggregate stats+ double total_pnl = 0;+ int total_trades = 0;+ double total_wins = 0;+ int metrics_count = 0;++ for (auto& m : dashboard_metrics_) {+ total_pnl += m.total_pnl;+ total_trades += m.total_trades;+ total_wins += m.win_rate;+ metrics_count++;+ }+ double avg_win_rate = metrics_count > 0 ? (total_wins / metrics_count) : 0;++ float card_h = 60.0f;++ auto summary_card = [card_h](const char* label, const char* value, ImVec4 val_col) {+ ImGui::PushStyleColor(ImGuiCol_ChildBg, ImVec4(0.08f, 0.10f, 0.16f, 1.0f));+ ImGui::BeginChild(label, ImVec2(160, card_h), true);+ ImGui::TextDisabled("%s", label);+ ImGui::SetCursorPosY(32.0f);+ ImGui::TextColored(val_col, "%s", value);+ ImGui::EndChild();+ ImGui::PopStyleColor();+ };++ char buf[64];++ snprintf(buf, sizeof(buf), "%d", running_count_);+ summary_card("Active Deployments", buf,+ running_count_ > 0 ? ImVec4(0.2f, 1, 0.2f, 1) : ImVec4(0.5f, 0.5f, 0.5f, 1));+ ImGui::SameLine();++ snprintf(buf, sizeof(buf), "%.2f", total_pnl);+ summary_card("Total PnL", buf,+ total_pnl >= 0 ? ImVec4(0.2f, 1, 0.2f, 1) : ImVec4(1, 0.2f, 0.2f, 1));+ ImGui::SameLine();++ snprintf(buf, sizeof(buf), "%d", total_trades);+ summary_card("Total Trades", buf, ImVec4(0.8f, 0.8f, 1, 1));+ ImGui::SameLine();++ snprintf(buf, sizeof(buf), "%.1f%%", avg_win_rate * 100);+ summary_card("Avg Win Rate", buf,+ avg_win_rate >= 0.5 ? ImVec4(0.2f, 1, 0.2f, 1) : ImVec4(1, 0.6f, 0.2f, 1));+ ImGui::SameLine();++ snprintf(buf, sizeof(buf), "%d", (int)deployments_.size());+ summary_card("Total Deployments", buf, ImVec4(0.6f, 0.7f, 1, 1));+}++} // namespace fincept::algodiff --git a/fincept-cpp/src/screens/algo_trading/algo_trading_screen.h b/fincept-cpp/src/screens/algo_trading/algo_trading_screen.hnew file mode 100644index 000000000..c2aed5956--- /dev/null+++ b/fincept-cpp/src/screens/algo_trading/algo_trading_screen.h@@ -0,0 +1,130 @@+#pragma once+// Algo Trading Screen — condition-based strategy builder, deployment, monitoring+// Layout: TopNav (5 sub-views) + Content Area + Status Bar+//+// Sub-views: Builder | Strategies | Library | Scanner | Dashboard++#include "algo_types.h"+#include "algo_constants.h"+#include <imgui.h>+#include <string>+#include <vector>+#include <mutex>+#include <atomic>++namespace fincept::algo {++class AlgoTradingScreen {+public:+ void render();++private:+ bool initialized_ = false;+ void init();++ // --- Sub-view navigation ---+ enum class SubView { Builder, Strategies, Library, Scanner, Dashboard };+ SubView active_view_ = SubView::Builder;++ // --- Strategy Builder state ---+ char strategy_name_[128] = "";+ char strategy_desc_[256] = "";+ char symbols_buf_[256] = "";+ int timeframe_idx_ = 3; // default "5m"+ int provider_idx_ = 0; // default "fyers"+ float stop_loss_ = 0.0f;+ float take_profit_ = 0.0f;+ float trailing_stop_ = 0.0f;+ float position_size_ = 1.0f;+ int max_positions_ = 1;+ int entry_logic_idx_ = 0; // 0=AND, 1=OR+ int exit_logic_idx_ = 0;+ std::vector<ConditionItem> entry_conditions_;+ std::vector<ConditionItem> exit_conditions_;+ std::string editing_strategy_id_; // non-empty = editing existing++ // --- Strategy List state ---+ std::vector<AlgoStrategy> strategies_;+ bool strategies_loaded_ = false;++ // --- Deployment state ---+ std::vector<AlgoDeployment> deployments_;+ bool deployments_loaded_ = false;++ // --- Python Library state ---+ std::vector<PythonStrategy> python_strategies_;+ std::vector<CustomPythonStrategy> custom_strategies_;+ std::vector<std::string> library_categories_;+ bool library_loaded_ = false;+ int library_category_idx_ = 0; // 0 = All+ char library_search_[128] = "";+ std::string selected_strategy_id_;+ std::string code_preview_;+ bool loading_code_ = false;+ bool editing_code_ = false;+ char custom_code_[8192] = "";+ char custom_name_[128] = "";+ char custom_desc_[256] = "";+ std::string syntax_error_;++ // --- Scanner state ---+ char scan_symbols_[512] = "";+ bool scanning_ = false;+ std::vector<ScanResult> scan_results_;+ int scan_tf_idx_ = 3; // default "5m"+ int scan_prov_idx_ = 0; // default "fyers"++ // --- Dashboard state ---+ std::vector<AlgoMetrics> dashboard_metrics_;+ std::vector<AlgoTrade> recent_trades_;++ // --- Backtest state ---+ bool show_backtest_modal_ = false;+ char bt_start_date_[16] = "2025-03-15";+ char bt_end_date_[16] = "2026-03-14";+ float bt_capital_ = 100000.0f;+ BacktestResult backtest_result_;+ bool backtest_running_ = false;++ // --- Status ---+ std::string status_msg_;+ int running_count_ = 0;++ std::mutex data_mutex_;++ // --- Rendering methods ---+ void render_top_nav(float w);+ void render_status_bar(float w);++ // Sub-view renderers+ void render_builder(float w, float h);+ void render_strategies(float w, float h);+ void render_library(float w, float h);+ void render_scanner(float w, float h);+ void render_dashboard(float w, float h);++ // Builder helpers+ void render_condition_editor(const char* label, std::vector<ConditionItem>& conditions,+ int& logic_idx);+ void render_condition_row(ConditionItem& cond, int idx, bool& remove);+ void render_backtest_results();+ void render_dashboard_summary();++ // Actions+ void save_strategy();+ void load_strategies();+ void delete_strategy(const std::string& id);+ void edit_strategy(const AlgoStrategy& s);+ void deploy_strategy(const std::string& strategy_id, const std::string& mode);+ void stop_deployment(const std::string& deployment_id);+ void stop_all_deployments();+ void delete_deployment_action(const std::string& deployment_id);+ void load_deployments();+ void load_library();+ void run_scan();+ void run_backtest(const std::string& strategy_id);+ void load_dashboard_data();+ void refresh_running_count();+};++} // namespace fincept::algodiff --git a/fincept-cpp/src/screens/algo_trading/algo_types.h b/fincept-cpp/src/screens/algo_trading/algo_types.hnew file mode 100644index 000000000..3e7bb7d57--- /dev/null+++ b/fincept-cpp/src/screens/algo_trading/algo_types.h@@ -0,0 +1,303 @@+#pragma once+// Algo Trading Types — mirrors Tauri types.ts + Rust structs+// Used by algo_service, algo_trading_screen, and db operations++#include <string>+#include <vector>+#include <optional>+#include <cstdint>+#include <nlohmann/json.hpp>++namespace fincept::algo {++using json = nlohmann::json;++// ============================================================================+// Condition system — JSON-serialized condition trees+// ============================================================================++struct ConditionItem {+ std::string indicator; // e.g. "rsi", "sma", "close"+ std::string operator_type; // e.g. "crosses_above", ">", "between"+ std::string value; // threshold or second indicator+ std::string value2; // for "between" operator+ std::string field; // "value" or specific field like "close", "volume"+ std::string timeframe; // override per-condition timeframe+ int period = 14; // indicator period+ int period2 = 0; // second period (for MACD signal, etc.)+};++inline void to_json(json& j, const ConditionItem& c) {+ j = json{{"indicator", c.indicator}, {"operator", c.operator_type},+ {"value", c.value}, {"value2", c.value2}, {"field", c.field},+ {"timeframe", c.timeframe}, {"period", c.period}, {"period2", c.period2}};+}++inline void from_json(const json& j, ConditionItem& c) {+ c.indicator = j.value("indicator", "");+ c.operator_type = j.value("operator", ">");+ c.value = j.value("value", "");+ c.value2 = j.value("value2", "");+ c.field = j.value("field", "value");+ c.timeframe = j.value("timeframe", "");+ c.period = j.value("period", 14);+ c.period2 = j.value("period2", 0);+}++// ============================================================================+// Strategy+// ============================================================================++struct AlgoStrategy {+ std::string id;+ std::string name;+ std::string description;+ std::string symbols; // JSON array string e.g. '["RELIANCE","TCS"]'+ std::string entry_conditions; // JSON array of ConditionItem+ std::string exit_conditions; // JSON array of ConditionItem+ std::string entry_logic = "AND";+ std::string exit_logic = "AND";+ std::string timeframe = "5m";+ double stop_loss = 0;+ double take_profit = 0;+ double trailing_stop = 0;+ double position_size = 1;+ int max_positions = 1;+ std::string provider = "fyers";+ bool is_active = true;+ std::string created_at;+ std::string updated_at;+};++// ============================================================================+// Deployment+// ============================================================================++enum class DeploymentStatus {+ Starting,+ Running,+ Stopped,+ Error,+ Completed+};++inline const char* deployment_status_str(DeploymentStatus s) {+ switch (s) {+ case DeploymentStatus::Starting: return "starting";+ case DeploymentStatus::Running: return "running";+ case DeploymentStatus::Stopped: return "stopped";+ case DeploymentStatus::Error: return "error";+ case DeploymentStatus::Completed: return "completed";+ }+ return "unknown";+}++inline DeploymentStatus parse_deployment_status(const std::string& s) {+ if (s == "running") return DeploymentStatus::Running;+ if (s == "stopped") return DeploymentStatus::Stopped;+ if (s == "error") return DeploymentStatus::Error;+ if (s == "completed") return DeploymentStatus::Completed;+ return DeploymentStatus::Starting;+}++struct AlgoDeployment {+ std::string id;+ std::string strategy_id;+ std::string strategy_name;+ std::string mode = "paper"; // "paper" or "live"+ DeploymentStatus status = DeploymentStatus::Starting;+ int pid = 0;+ std::string portfolio_id;+ std::string started_at;+ std::string stopped_at;+ std::string error_message;+ std::string config; // JSON string+};++// ============================================================================+// Metrics+// ============================================================================++struct AlgoMetrics {+ std::string deployment_id;+ int total_trades = 0;+ int winning_trades = 0;+ int losing_trades = 0;+ double total_pnl = 0;+ double max_drawdown = 0;+ double win_rate = 0;+ double avg_win = 0;+ double avg_loss = 0;+ double sharpe_ratio = 0;+ std::string updated_at;+};++// ============================================================================+// Trades+// ============================================================================++struct AlgoTrade {+ std::string id;+ std::string deployment_id;+ std::string symbol;+ std::string side; // "buy" or "sell"+ double quantity = 0;+ double price = 0;+ double pnl = 0;+ double fees = 0;+ std::string order_type; // "market", "limit"+ std::string status; // "filled", "partial", "cancelled"+ std::string executed_at;+};++// ============================================================================+// Order Signals (bridge: Python runner -> order execution)+// ============================================================================++struct AlgoOrderSignal {+ std::string id;+ std::string deployment_id;+ std::string symbol;+ std::string side;+ double quantity = 0;+ std::string order_type = "market";+ double price = 0;+ double stop_price = 0;+ std::string status = "pending"; // "pending", "processing", "executed", "failed"+ std::string created_at;+ std::string executed_at;+ std::string error;+};++// ============================================================================+// Candle Data+// ============================================================================++struct CandleData {+ std::string symbol;+ std::string timeframe;+ int64_t timestamp = 0;+ double open = 0;+ double high = 0;+ double low = 0;+ double close = 0;+ double volume = 0;+ std::string provider;+};++// ============================================================================+// Scanner+// ============================================================================++struct ScanResult {+ std::string symbol;+ bool entry_match = false;+ bool exit_match = false;+ double last_price = 0;+ double volume = 0;+ std::string details; // JSON string with indicator values+ std::string scanned_at;+};++// ============================================================================+// Python Strategy Library+// ============================================================================++struct PythonStrategy {+ std::string id; // e.g. "FCT-00001"+ std::string name;+ std::string description;+ std::string category;+ std::string filename;+ std::vector<std::string> tags;+};++struct CustomPythonStrategy {+ std::string id;+ std::string name;+ std::string description;+ std::string code;+ std::string category = "custom";+ std::string parameters; // JSON string+ std::string created_at;+ std::string updated_at;+};++struct StrategyParameter {+ std::string name;+ std::string type; // "int", "float", "str", "bool"+ std::string default_value;+ std::string description;+};++// ============================================================================+// Backtest Results (returned from Python backtest scripts)+// ============================================================================++struct BacktestTrade {+ std::string symbol;+ std::string side;+ double entry_price = 0;+ double exit_price = 0;+ double quantity = 0;+ double pnl = 0;+ double pnl_pct = 0;+ std::string entry_time;+ std::string exit_time;+};++struct BacktestMetrics {+ double total_return = 0;+ double total_return_pct = 0;+ double max_drawdown = 0;+ double sharpe_ratio = 0;+ double win_rate = 0;+ int total_trades = 0;+ int winning_trades = 0;+ int losing_trades = 0;+ double avg_win = 0;+ double avg_loss = 0;+ double profit_factor = 0;+ double avg_trade_duration = 0;+};++struct EquityPoint {+ std::string date;+ double equity = 0;+ double drawdown = 0;+};++struct BacktestResult {+ bool success = false;+ std::string error;+ BacktestMetrics metrics;+ std::vector<BacktestTrade> trades;+ std::vector<EquityPoint> equity_curve;+};++// ============================================================================+// Price Cache Entry+// ============================================================================++struct PriceCacheEntry {+ std::string symbol;+ double price = 0;+ double volume = 0;+ double change_pct = 0;+ std::string updated_at;+};++// ============================================================================+// Trading mode for deployment+// ============================================================================++enum class AlgoTradingMode {+ Paper,+ Live+};++inline const char* trading_mode_str(AlgoTradingMode m) {+ return m == AlgoTradingMode::Live ? "live" : "paper";+}++} // namespace fincept::algodiff --git a/fincept-cpp/src/screens/backtesting/backtesting_constants.h b/fincept-cpp/src/screens/backtesting/backtesting_constants.hnew file mode 100644index 000000000..1e36cd02e--- /dev/null+++ b/fincept-cpp/src/screens/backtesting/backtesting_constants.h@@ -0,0 +1,649 @@+#pragma once+// Backtesting Tab — provider configs, strategies, colors, UI helpers++#include "backtesting_types.h"+#include "ui/theme.h"+#include <imgui.h>+#include <string>+#include <vector>+#include <map>+#include <cstdio>+#include <ctime>++namespace fincept::backtesting {++// =============================================================================+// Provider accent colors+// =============================================================================+namespace provider_colors {+ constexpr ImVec4 FINCEPT = {1.0f, 0.533f, 0.0f, 1.0f}; // #FF8800 orange+ constexpr ImVec4 VECTORBT = {0.0f, 0.898f, 1.0f, 1.0f}; // #00E5FF cyan+ constexpr ImVec4 BACKTESTINGPY= {0.0f, 0.839f, 0.435f, 1.0f}; // #00D66F green+ constexpr ImVec4 FASTTRADE = {1.0f, 0.843f, 0.0f, 1.0f}; // #FFD700 yellow+ constexpr ImVec4 ZIPLINE = {0.914f, 0.118f, 0.388f, 1.0f}; // #E91E63 pink+ constexpr ImVec4 BT = {1.0f, 0.420f, 0.208f, 1.0f}; // #FF6B35 orange-red+}++inline ImVec4 provider_color(ProviderSlug s) {+ switch (s) {+ case ProviderSlug::Fincept: return provider_colors::FINCEPT;+ case ProviderSlug::VectorBT: return provider_colors::VECTORBT;+ case ProviderSlug::BacktestingPy: return provider_colors::BACKTESTINGPY;+ case ProviderSlug::FastTrade: return provider_colors::FASTTRADE;+ case ProviderSlug::Zipline: return provider_colors::ZIPLINE;+ case ProviderSlug::BT: return provider_colors::BT;+ default: return provider_colors::FINCEPT;+ }+}++// =============================================================================+// Provider display names and script directories+// =============================================================================+struct ProviderInfo {+ ProviderSlug slug;+ const char* display_name;+ const char* script_dir; // folder under Analytics/backtesting/+};++inline const std::vector<ProviderInfo>& provider_list() {+ static const std::vector<ProviderInfo> p = {+ {ProviderSlug::Fincept, "FINCEPT ENGINE", "fincept"},+ {ProviderSlug::VectorBT, "VECTORBT", "vectorbt"},+ {ProviderSlug::BacktestingPy, "BACKTESTING.PY", "backtestingpy"},+ {ProviderSlug::FastTrade, "FAST-TRADE", "fasttrade"},+ {ProviderSlug::Zipline, "ZIPLINE", "zipline"},+ {ProviderSlug::BT, "BT", "bt"},+ };+ return p;+}++inline const ProviderInfo& get_provider_info(ProviderSlug s) {+ for (auto& p : provider_list()) {+ if (p.slug == s) return p;+ }+ return provider_list()[0];+}++// =============================================================================+// Command definitions+// =============================================================================+inline const std::vector<CommandDef>& all_commands() {+ using namespace theme::colors;+ static const std::vector<CommandDef> c = {+ {CommandType::Backtest, "Backtest", "Run strategy backtest", ACCENT},+ {CommandType::Optimize, "Optimize", "Parameter optimization", SUCCESS},+ {CommandType::WalkForward, "Walk Forward", "Walk-forward validation", INFO},+ {CommandType::Indicator, "Indicators", "Calculate indicators", {0.616f, 0.306f, 0.871f, 1.0f}},+ {CommandType::IndicatorSignals, "Ind. Signals", "Indicator-based signals", WARNING},+ {CommandType::Labels, "ML Labels", "Generate ML labels", {0.0f, 0.898f, 1.0f, 1.0f}},+ {CommandType::Splits, "Splitters", "Cross-validation splits", INFO},+ {CommandType::Returns, "Returns", "Returns analysis", SUCCESS},+ {CommandType::Signals, "Rand. Signals", "Random signal generators", WARNING},+ };+ return c;+}++// =============================================================================+// Commands per provider+// =============================================================================+inline std::vector<CommandType> provider_commands(ProviderSlug s) {+ switch (s) {+ case ProviderSlug::VectorBT:+ return {CommandType::Backtest, CommandType::Optimize, CommandType::WalkForward,+ CommandType::Indicator, CommandType::IndicatorSignals,+ CommandType::Labels, CommandType::Splits, CommandType::Returns, CommandType::Signals};+ case ProviderSlug::BacktestingPy:+ return {CommandType::Backtest, CommandType::Optimize, CommandType::WalkForward,+ CommandType::Indicator};+ case ProviderSlug::FastTrade:+ return {CommandType::Backtest};+ case ProviderSlug::Zipline:+ return {CommandType::Backtest, CommandType::Optimize, CommandType::WalkForward,+ CommandType::Indicator, CommandType::IndicatorSignals};+ case ProviderSlug::BT:+ return {CommandType::Backtest, CommandType::Optimize, CommandType::WalkForward,+ CommandType::Indicator, CommandType::IndicatorSignals};+ case ProviderSlug::Fincept:+ return {CommandType::Backtest};+ default:+ return {CommandType::Backtest};+ }+}++// =============================================================================+// Command -> Python action string mapping+// =============================================================================+inline const char* command_to_python(ProviderSlug /*provider*/, CommandType cmd) {+ switch (cmd) {+ case CommandType::Backtest: return "run_backtest";+ case CommandType::Optimize: return "optimize";+ case CommandType::WalkForward: return "walk_forward";+ case CommandType::Indicator: return "indicator_param_sweep";+ case CommandType::IndicatorSignals: return "indicator_signals";+ case CommandType::Labels: return "generate_labels";+ case CommandType::Splits: return "generate_splits";+ case CommandType::Returns: return "analyze_returns";+ case CommandType::Signals: return "generate_signals";+ default: return "run_backtest";+ }+}++inline const char* command_label(CommandType cmd) {+ for (auto& c : all_commands()) {+ if (c.type == cmd) return c.label;+ }+ return "Backtest";+}++// =============================================================================+// Strategy categories+// =============================================================================+inline const std::vector<CategoryInfo>& strategy_categories() {+ static const std::vector<CategoryInfo> cats = {+ {"trend", "Trend Following", {0.0f, 0.533f, 1.0f, 1.0f}},+ {"meanReversion", "Mean Reversion", {0.616f, 0.306f, 0.871f, 1.0f}},+ {"momentum", "Momentum", {1.0f, 0.843f, 0.0f, 1.0f}},+ {"breakout", "Breakout", {0.0f, 0.839f, 0.435f, 1.0f}},+ {"multiIndicator", "Multi-Indicator", {0.0f, 0.898f, 1.0f, 1.0f}},+ {"other", "Other", {0.471f, 0.471f, 0.471f, 1.0f}},+ {"custom", "Custom", {1.0f, 0.533f, 0.0f, 1.0f}},+ {"portfolio", "Portfolio Alloc.", {1.0f, 0.533f, 0.0f, 1.0f}},+ {"pipeline", "Pipeline", {1.0f, 0.533f, 0.0f, 1.0f}},+ };+ return cats;+}++// =============================================================================+// Shared strategies (used by multiple providers)+// =============================================================================+inline const std::vector<Strategy>& shared_trend() {+ static const std::vector<Strategy> s = {+ {"sma_crossover", "SMA Crossover", "Fast SMA crosses Slow SMA",+ {{"fastPeriod","Fast Period",10,2,100,1}, {"slowPeriod","Slow Period",20,5,200,1}}},+ {"ema_crossover", "EMA Crossover", "Fast EMA crosses Slow EMA",+ {{"fastPeriod","Fast Period",10,2,100,1}, {"slowPeriod","Slow Period",20,5,200,1}}},+ {"macd", "MACD Crossover", "MACD line crosses Signal line",+ {{"fastPeriod","Fast Period",12,2,50,1}, {"slowPeriod","Slow Period",26,10,100,1},+ {"signalPeriod","Signal Period",9,2,50,1}}},+ {"adx_trend", "ADX Trend Filter", "ADX-based trend following",+ {{"adxPeriod","ADX Period",14,5,50,1}, {"adxThreshold","ADX Threshold",25,10,50,1}}},+ };+ return s;+}++inline const std::vector<Strategy>& shared_mean_reversion() {+ static const std::vector<Strategy> s = {+ {"mean_reversion", "Z-Score Reversion", "Z-score mean reversion",+ {{"window","Window",20,5,100,1}, {"threshold","Z-Score Threshold",2.0f,0.5f,5.0f,0.1f}}},+ {"bollinger_bands", "Bollinger Bands", "Bollinger band mean reversion",+ {{"period","Period",20,5,100,1}, {"stdDev","Std Dev",2.0f,1.0f,4.0f,0.1f}}},+ {"rsi", "RSI Mean Reversion", "RSI oversold/overbought",+ {{"period","Period",14,2,50,1}, {"oversold","Oversold",30,10,40,1}, {"overbought","Overbought",70,60,90,1}}},+ {"stochastic", "Stochastic", "Stochastic oscillator",+ {{"kPeriod","K Period",14,5,50,1}, {"dPeriod","D Period",3,2,20,1},+ {"oversold","Oversold",20,10,30,1}, {"overbought","Overbought",80,70,90,1}}},+ };+ return s;+}++inline const std::vector<Strategy>& shared_momentum() {+ static const std::vector<Strategy> s = {+ {"momentum", "Momentum (ROC)", "Rate of change momentum",+ {{"period","Period",12,5,50,1}, {"threshold","Threshold",0.02f,0.01f,0.1f,0.01f}}},+ };+ return s;+}++inline const std::vector<Strategy>& shared_breakout() {+ static const std::vector<Strategy> s = {+ {"breakout", "Donchian Breakout", "Donchian channel breakout",+ {{"period","Period",20,5,100,1}}},+ };+ return s;+}++// =============================================================================+// Provider-specific extra strategies+// =============================================================================+inline const std::vector<Strategy>& vbt_extra_trend() {+ static const std::vector<Strategy> s = {+ {"keltner_breakout", "Keltner Channel", "Keltner channel breakout",+ {{"period","Period",20,5,100,1}, {"atrMultiplier","ATR Mult",2.0f,0.5f,5.0f,0.1f}}},+ {"triple_ma", "Triple MA", "Three moving average system",+ {{"fastPeriod","Fast",10,2,50,1}, {"mediumPeriod","Medium",20,5,100,1}, {"slowPeriod","Slow",50,10,200,1}}},+ {"williams_r", "Williams %R", "Williams %R trend indicator",+ {{"period","Period",14,5,50,1}, {"oversold","Oversold",-80,-90,-70,1}, {"overbought","Overbought",-20,-30,-10,1}}},+ {"cci", "CCI", "Commodity Channel Index trend",+ {{"period","Period",20,5,50,1}, {"oversold","Oversold",-100,-200,-50,1}, {"overbought","Overbought",100,50,200,1}}},+ {"obv_trend", "OBV Trend", "On-Balance Volume trend",+ {{"maPeriod","MA Period",20,5,100,1}}},+ };+ return s;+}++inline const std::vector<Strategy>& vbt_extra_momentum() {+ static const std::vector<Strategy> s = {+ {"dual_momentum", "Dual Momentum", "Absolute + relative momentum",+ {{"absolutePeriod","Absolute",12,3,24,1}, {"relativePeriod","Relative",12,3,24,1}}},+ };+ return s;+}++inline const std::vector<Strategy>& vbt_extra_breakout() {+ static const std::vector<Strategy> s = {+ {"volatility_breakout", "Volatility Breakout", "ATR-based volatility breakout",+ {{"atrPeriod","ATR Period",14,5,50,1}, {"atrMultiplier","ATR Mult",2.0f,0.5f,5.0f,0.1f}}},+ {"donchian_breakout", "Donchian Breakout", "Donchian channel breakout",+ {{"period","Period",20,5,100,1}}},+ };+ return s;+}++inline const std::vector<Strategy>& vbt_multi_indicator() {+ static const std::vector<Strategy> s = {+ {"rsi_macd", "RSI + MACD", "RSI and MACD confluence",+ {{"rsiPeriod","RSI Period",14,5,30,1}, {"macdFast","MACD Fast",12,5,30,1}, {"macdSlow","MACD Slow",26,10,50,1}}},+ {"macd_adx", "MACD + ADX Filter", "MACD with ADX trend filter",+ {{"macdFast","MACD Fast",12,5,30,1}, {"macdSlow","MACD Slow",26,10,50,1}, {"adxPeriod","ADX Period",14,5,30,1}}},+ {"bollinger_rsi", "Bollinger + RSI", "Bollinger bands with RSI",+ {{"bbPeriod","BB Period",20,10,50,1}, {"rsiPeriod","RSI Period",14,5,30,1}}},+ };+ return s;+}++inline const std::vector<Strategy>& vbt_custom() {+ static const std::vector<Strategy> s = {+ {"code", "Custom Code", "Python custom strategy", {}},+ };+ return s;+}++// BT portfolio strategies+inline const std::vector<Strategy>& bt_portfolio() {+ static const std::vector<Strategy> s = {+ {"equal_weight", "Equal Weight", "Equal-weight allocation across all assets",+ {{"rebalancePeriod","Rebalance Period",21,5,63,1}}},+ {"inv_vol", "Inverse Volatility", "Weight assets inversely by volatility",+ {{"lookback","Lookback (days)",20,10,120,1}}},+ {"mean_var", "Mean-Variance", "Markowitz mean-variance optimized portfolio",+ {{"lookback","Lookback (days)",60,20,252,1}}},+ {"risk_parity", "Risk Parity", "Equal risk contribution (ERC) portfolio",+ {{"lookback","Lookback (days)",60,20,252,1}}},+ {"target_vol", "Target Volatility", "Target a specific portfolio volatility",+ {{"targetVol","Target Vol (%)",10,1,50,1}, {"lookback","Lookback (days)",20,10,120,1}}},+ {"min_var", "Minimum Variance", "Minimum variance portfolio (lowest risk)",+ {{"lookback","Lookback (days)",60,20,252,1}}},+ };+ return s;+}++inline const std::vector<Strategy>& bt_extra_momentum() {+ static const std::vector<Strategy> s = {+ {"momentum_topn", "Momentum Top-N", "Select top N assets by momentum",+ {{"topN","Top N",5,1,50,1}, {"lookback","Momentum Lookback",60,10,252,1}}},+ {"momentum_inv_vol", "Momentum + Inv Vol", "Top-N momentum with inverse vol weighting",+ {{"topN","Top N",5,1,50,1}, {"lookback","Lookback",60,10,252,1}}},+ };+ return s;+}++// Zipline pipeline strategies+inline const std::vector<Strategy>& zipline_pipeline() {+ static const std::vector<Strategy> s = {+ {"pipeline", "Custom Pipeline", "Factor-based screening and ranking",+ {{"topN","Top N",5,1,50,1}, {"rebalanceDays","Rebalance Days",21,5,63,1}}},+ {"scheduled_rebalance", "Scheduled Rebalance", "Monthly rebalance using schedule_function",+ {{"momentumWindow","Momentum Window",63,21,252,1}}},+ };+ return s;+}++// FastTrade extra+inline const std::vector<Strategy>& fasttrade_extra_trend() {+ static const std::vector<Strategy> s = {+ {"ichimoku", "Ichimoku Cloud", "Ichimoku Kinko Hyo trend system",+ {{"tenkanPeriod","Tenkan",9,5,30,1}, {"kijunPeriod","Kijun",26,10,60,1}, {"senkouBPeriod","Senkou B",52,20,120,1}}},+ {"psar", "Parabolic SAR", "Parabolic stop and reverse",+ {{"afStep","AF Step",0.02f,0.01f,0.1f,0.01f}, {"afMax","AF Max",0.2f,0.1f,0.5f,0.01f}}},+ {"ma_ribbon", "MA Ribbon", "Multiple moving average ribbon",+ {{"shortestPeriod","Shortest MA",5,2,20,1}, {"longestPeriod","Longest MA",50,20,200,1}, {"count","MA Count",6,3,12,1}}},+ {"keltner_channel", "Keltner Channel", "Keltner channel trend system",+ {{"period","EMA Period",20,5,100,1}, {"atrMultiplier","ATR Mult",2.0f,0.5f,5.0f,0.1f}}},+ };+ return s;+}++inline const std::vector<Strategy>& fasttrade_extra_multi() {+ static const std::vector<Strategy> s = {+ {"trend_momentum", "Trend + Momentum", "MA trend filter with RSI momentum",+ {{"maPeriod","MA Period",50,10,200,1}, {"rsiPeriod","RSI Period",14,5,30,1}, {"rsiThreshold","RSI Threshold",50,30,70,1}}},+ };+ return s;+}++// =============================================================================+// Get strategies for provider + category+// =============================================================================+inline std::vector<Strategy> get_strategies(ProviderSlug provider, const std::string& category) {+ std::vector<Strategy> result;++ auto append = [&](const std::vector<Strategy>& src) {+ result.insert(result.end(), src.begin(), src.end());+ };++ if (category == "trend") {+ append(shared_trend());+ if (provider == ProviderSlug::VectorBT) append(vbt_extra_trend());+ if (provider == ProviderSlug::FastTrade) append(fasttrade_extra_trend());+ }+ else if (category == "meanReversion") {+ append(shared_mean_reversion());+ }+ else if (category == "momentum") {+ append(shared_momentum());+ if (provider == ProviderSlug::VectorBT) append(vbt_extra_momentum());+ if (provider == ProviderSlug::BT) append(bt_extra_momentum());+ }+ else if (category == "breakout") {+ append(shared_breakout());+ if (provider == ProviderSlug::VectorBT) append(vbt_extra_breakout());+ }+ else if (category == "multiIndicator") {+ if (provider == ProviderSlug::VectorBT || provider == ProviderSlug::BacktestingPy+ || provider == ProviderSlug::Zipline) append(vbt_multi_indicator());+ if (provider == ProviderSlug::FastTrade) append(fasttrade_extra_multi());+ }+ else if (category == "custom") {+ if (provider == ProviderSlug::VectorBT) append(vbt_custom());+ }+ else if (category == "portfolio") {+ if (provider == ProviderSlug::BT) append(bt_portfolio());+ }+ else if (category == "pipeline") {+ if (provider == ProviderSlug::Zipline) append(zipline_pipeline());+ }++ return result;+}++// =============================================================================+// Get categories for provider+// =============================================================================+inline std::vector<CategoryInfo> get_categories(ProviderSlug provider) {+ std::vector<CategoryInfo> result;+ for (auto& cat : strategy_categories()) {+ auto strats = get_strategies(provider, cat.key);+ if (!strats.empty()) result.push_back(cat);+ }+ return result;+}++// =============================================================================+// Indicator definitions+// =============================================================================+inline const std::vector<IndicatorDef>& indicators() {+ static const std::vector<IndicatorDef> ind = {+ {"ma", "Moving Average (SMA)", {"period"}},+ {"ema", "Moving Average (EMA)", {"period"}},+ {"mstd", "Moving Std Dev", {"period"}},+ {"rsi", "RSI", {"period"}},+ {"stoch", "Stochastic", {"k_period", "d_period"}},+ {"cci", "CCI", {"period"}},+ {"williams_r","Williams %R", {"period"}},+ {"macd", "MACD", {"fast", "slow", "signal"}},+ {"adx", "ADX", {"period"}},+ {"momentum", "Momentum", {"lookback"}},+ {"atr", "ATR", {"period"}},+ {"bbands", "Bollinger Bands", {"period"}},+ {"keltner", "Keltner Channel", {"period"}},+ {"donchian", "Donchian Channel", {"period"}},+ {"zscore", "Z-Score", {"period"}},+ {"obv", "OBV", {}},+ {"vwap", "VWAP", {}},+ };+ return ind;+}++// =============================================================================+// Position sizing options+// =============================================================================+inline const std::vector<PositionSizingOption>& position_sizing_options() {+ static const std::vector<PositionSizingOption> ps = {+ {"fixed", "Fixed Size"},+ {"percent", "Percent of Capital"},+ {"kelly", "Kelly Criterion"},+ {"volatility", "Volatility Target"},+ {"risk", "Risk-Based"},+ };+ return ps;+}++// =============================================================================+// Signal modes (for indicator signals command)+// =============================================================================+inline const std::vector<SignalMode>& signal_modes() {+ static const std::vector<SignalMode> sm = {+ {"crossover_signals", "Crossover", "MA/EMA crossover signals"},+ {"threshold_signals", "Threshold", "RSI/CCI threshold signals"},+ {"breakout_signals", "Breakout", "Channel breakout signals"},+ {"mean_reversion_signals","Mean Reversion", "Z-score mean reversion"},+ {"signal_filter", "Signal Filter", "Filter signals with indicators"},+ };+ return sm;+}++// =============================================================================+// Label types (ML)+// =============================================================================+inline const std::vector<LabelType>& label_types() {+ static const std::vector<LabelType> lt = {+ {"FIXLB", "Fixed Horizon", "Fixed-time horizon labeling", {"horizon", "threshold"}},+ {"MEANLB", "Mean Reversion", "Mean-reversion labeling", {"window", "threshold"}},+ {"LEXLB", "Local Extrema", "Local extrema labeling", {"window"}},+ {"TRENDLB","Trend Scan", "Trend-scanning labeling", {"window", "threshold"}},+ {"BOLB", "Bollinger Labels", "Bollinger band labeling", {"window", "alpha"}},+ };+ return lt;+}++// =============================================================================+// Splitter types (CV)+// =============================================================================+inline const std::vector<SplitterType>& splitter_types() {+ static const std::vector<SplitterType> st = {+ {"RollingSplitter", "Rolling Window", "Fixed-size rolling train/test splits", {"window_len", "test_len", "step"}},+ {"ExpandingSplitter", "Expanding Window", "Expanding train window", {"min_len", "test_len", "step"}},+ {"PurgedKFold", "Purged K-Fold", "K-fold with purge & embargo", {"n_splits", "purge_len", "embargo_len"}},+ };+ return st;+}++// =============================================================================+// Returns analysis types+// =============================================================================+inline const std::vector<ReturnsAnalysisType>& returns_analysis_types() {+ static const std::vector<ReturnsAnalysisType> rt = {+ {"full", "Full Analysis", "Complete returns summary"},+ {"rolling", "Rolling Metrics", "Rolling Sharpe, vol, returns"},+ {"distribution", "Distribution", "Returns distribution analysis"},+ {"benchmark_comparison", "Benchmark", "Compare vs benchmark"},+ };+ return rt;+}++// =============================================================================+// Signal generator types+// =============================================================================+inline const std::vector<SignalGeneratorType>& signal_generator_types() {+ static const std::vector<SignalGeneratorType> sg = {+ {"RAND", "Random", "Uniform random entry/exit", {"n", "seed"}},+ {"RANDX", "Random (Exclusive)", "Non-overlapping random signals", {"n", "seed"}},+ {"RANDNX", "Random N (Excl.)", "N random signals with hold range", {"n", "min_hold", "max_hold"}},+ {"RPROB", "Probability", "Probability-based entry/exit", {"entry_prob", "exit_prob", "cooldown"}},+ {"RPROBX", "Probability (Excl.)", "Non-overlapping probability signals", {"entry_prob", "exit_prob", "cooldown"}},+ };+ return sg;+}++// =============================================================================+// Optimize objectives+// =============================================================================+inline const char* const OPTIMIZE_OBJECTIVES[] = {"sharpe", "sortino", "calmar", "return"};+inline const char* const OPTIMIZE_OBJECTIVE_LABELS[] = {"Sharpe Ratio", "Sortino Ratio", "Calmar Ratio", "Total Return"};+inline const char* const OPTIMIZE_METHODS[] = {"grid", "random"};+inline const char* const OPTIMIZE_METHOD_LABELS[] = {"Grid Search", "Random Search"};++// =============================================================================+// UI Helpers — same pattern as gov_data_constants.h+// =============================================================================++// Colored tab button+inline bool ProviderTab(const char* label, ImVec4 color, bool active) {+ using namespace theme::colors;+ if (active) {+ ImGui::PushStyleColor(ImGuiCol_Button, color);+ ImGui::PushStyleColor(ImGuiCol_ButtonHovered, color);+ ImGui::PushStyleColor(ImGuiCol_Text, BG_DARKEST);+ } else {+ ImGui::PushStyleColor(ImGuiCol_Button, ImVec4(0,0,0,0));+ ImGui::PushStyleColor(ImGuiCol_ButtonHovered, BG_HOVER);+ ImGui::PushStyleColor(ImGuiCol_Text, TEXT_DIM);+ }+ bool clicked = ImGui::SmallButton(label);+ ImGui::PopStyleColor(3);+ return clicked;+}++// Command item with left border+inline bool CommandItem(const char* label, const char* desc, ImVec4 color, bool active) {+ using namespace theme::colors;+ ImVec2 cursor = ImGui::GetCursorScreenPos();+ float w = ImGui::GetContentRegionAvail().x;++ // Background+ ImVec4 bg = active ? ImVec4(color.x, color.y, color.z, 0.15f) : ImVec4(0,0,0,0);+ ImGui::PushStyleColor(ImGuiCol_Button, bg);+ ImGui::PushStyleColor(ImGuiCol_ButtonHovered, ImVec4(color.x, color.y, color.z, 0.10f));+ ImGui::PushStyleColor(ImGuiCol_ButtonActive, ImVec4(color.x, color.y, color.z, 0.20f));++ bool clicked = ImGui::Button(("##cmd_" + std::string(label)).c_str(), ImVec2(w, 36));+ ImGui::PopStyleColor(3);++ // Left accent bar+ if (active) {+ ImGui::GetWindowDrawList()->AddRectFilled(+ cursor, ImVec2(cursor.x + 3, cursor.y + 36),+ ImGui::ColorConvertFloat4ToU32(color));+ }++ // Text overlay+ ImGui::SetCursorScreenPos(ImVec2(cursor.x + 10, cursor.y + 4));+ ImGui::TextColored(active ? TEXT_PRIMARY : TEXT_SECONDARY, "%s", label);+ ImGui::SetCursorScreenPos(ImVec2(cursor.x + 10, cursor.y + 20));+ ImGui::TextColored(TEXT_DIM, "%s", desc);++ // Reset cursor+ ImGui::SetCursorScreenPos(ImVec2(cursor.x, cursor.y + 38));++ return clicked;+}++// Status message with fade+inline void StatusMsg(const std::string& msg, double time) {+ if (msg.empty()) return;+ float alpha = 1.0f;+ double elapsed = ImGui::GetTime() - time;+ if (elapsed > 5.0) alpha = std::max(0.0f, 1.0f - (float)(elapsed - 5.0) / 3.0f);+ if (alpha <= 0.01f) return;+ ImVec4 c = theme::colors::TEXT_DIM;+ c.w = alpha;+ ImGui::TextColored(c, "%s", msg.c_str());+}++// Empty state placeholder+inline void EmptyState(const char* title, const char* subtitle) {+ ImGui::Spacing(); ImGui::Spacing();+ float w = ImGui::GetContentRegionAvail().x;+ ImGui::SetCursorPosX(ImGui::GetCursorPosX() + w * 0.25f);+ ImGui::TextColored(theme::colors::TEXT_DIM, "%s", title);+ ImGui::SetCursorPosX(ImGui::GetCursorPosX() + w * 0.2f);+ ImGui::TextColored(theme::colors::TEXT_DISABLED, "%s", subtitle);+}++// Metric row (label + value with color)+inline void MetricRow(const char* label, const char* value, ImVec4 value_color) {+ using namespace theme::colors;+ ImGui::PushStyleColor(ImGuiCol_ChildBg, BG_PANEL);+ ImGui::BeginChild(("##mr_" + std::string(label)).c_str(), ImVec2(0, 24), ImGuiChildFlags_Borders);+ ImGui::TextColored(TEXT_DIM, "%s", label);+ ImGui::SameLine(ImGui::GetContentRegionAvail().x - ImGui::CalcTextSize(value).x);+ ImGui::TextColored(value_color, "%s", value);+ ImGui::EndChild();+ ImGui::PopStyleColor();+}++// Section header with collapsible toggle+inline bool SectionHeader(const char* label, bool* expanded) {+ using namespace theme::colors;+ ImGui::PushStyleColor(ImGuiCol_Header, BG_WIDGET);+ ImGui::PushStyleColor(ImGuiCol_HeaderHovered, BG_HOVER);+ ImGui::PushStyleColor(ImGuiCol_HeaderActive, BG_HOVER);+ bool open = ImGui::CollapsingHeader(label, *expanded ? ImGuiTreeNodeFlags_DefaultOpen : 0);+ ImGui::PopStyleColor(3);+ *expanded = open;+ return open;+}++// Labeled input field+inline bool InputField(const char* label, char* buf, size_t buf_size) {+ using namespace theme::colors;+ ImGui::TextColored(TEXT_DIM, "%s", label);+ ImGui::PushStyleColor(ImGuiCol_FrameBg, BG_INPUT);+ ImGui::PushItemWidth(-1);+ bool changed = ImGui::InputText(("##" + std::string(label)).c_str(), buf, buf_size);+ ImGui::PopItemWidth();+ ImGui::PopStyleColor();+ return changed;+}++// Labeled float input+inline bool InputFloat(const char* label, float* v, float step = 0, float step_fast = 0, const char* fmt = "%.2f") {+ using namespace theme::colors;+ ImGui::TextColored(TEXT_DIM, "%s", label);+ ImGui::PushStyleColor(ImGuiCol_FrameBg, BG_INPUT);+ ImGui::PushItemWidth(-1);+ bool changed = ImGui::InputFloat(("##" + std::string(label)).c_str(), v, step, step_fast, fmt);+ ImGui::PopItemWidth();+ ImGui::PopStyleColor();+ return changed;+}++// Labeled int input+inline bool InputInt(const char* label, int* v, int step = 0) {+ using namespace theme::colors;+ ImGui::TextColored(TEXT_DIM, "%s", label);+ ImGui::PushStyleColor(ImGuiCol_FrameBg, BG_INPUT);+ ImGui::PushItemWidth(-1);+ bool changed = ImGui::InputInt(("##" + std::string(label)).c_str(), v, step);+ ImGui::PopItemWidth();+ ImGui::PopStyleColor();+ return changed;+}++// Run button+inline bool RunButton(const char* label, bool loading, ImVec4 color) {+ using namespace theme::colors;+ if (loading) {+ ImGui::PushStyleColor(ImGuiCol_Button, TEXT_DISABLED);+ ImGui::PushStyleColor(ImGuiCol_ButtonHovered, TEXT_DISABLED);+ } else {+ ImGui::PushStyleColor(ImGuiCol_Button, color);+ ImGui::PushStyleColor(ImGuiCol_ButtonHovered, ImVec4(color.x*1.1f, color.y*1.1f, color.z*1.1f, 1.0f));+ }+ ImGui::PushStyleColor(ImGuiCol_Text, BG_DARKEST);+ bool clicked = ImGui::Button(loading ? "EXECUTING..." : label, ImVec2(140, 28));+ ImGui::PopStyleColor(3);+ return clicked && !loading;+}++} // namespace fincept::backtestingdiff --git a/fincept-cpp/src/screens/backtesting/backtesting_data.cpp b/fincept-cpp/src/screens/backtesting/backtesting_data.cppnew file mode 100644index 000000000..cd737fb2d--- /dev/null+++ b/fincept-cpp/src/screens/backtesting/backtesting_data.cpp@@ -0,0 +1,100 @@+#include "backtesting_data.h"+#include "python/python_runner.h"+#include "core/logger.h"+#include <thread>+#include <nlohmann/json.hpp>++namespace fincept::backtesting {++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;+ loading_.store(true);+ {+ std::lock_guard<std::mutex> lock(mutex_);+ has_result_ = false;+ error_.clear();+ result_ = json();+ }++ // Script path: Analytics/backtesting/{provider}/{provider}_provider.py+ std::string script = "Analytics/backtesting/" + provider_dir + "/" + provider_dir + "_provider.py";++ std::thread([this, script, command, args_json]() {+ 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) {+ parse_result(py_result.output);+ } else {+ error_ = py_result.error.empty()+ ? "Script failed (exit " + std::to_string(py_result.exit_code) + ")"+ : py_result.error;+ has_result_ = false;+ LOG_ERROR("BacktestData", "Script failed: %s — %s",+ script.c_str(), error_.c_str());+ }+ }+ loading_.store(false);+ }).detach();+}++bool BacktestData::has_result() const {+ return has_result_;+}++const std::string& BacktestData::error() const {+ return error_;+}++void BacktestData::clear() {+ std::lock_guard<std::mutex> lock(mutex_);+ result_ = json();+ error_.clear();+ has_result_ = false;+}++void BacktestData::parse_result(const std::string& output) {+ try {+ std::string json_str = python::extract_json(output);+ if (json_str.empty()) json_str = output;++ auto parsed = json::parse(json_str);++ // Handle {success: true, data: {...}} wrapper+ if (parsed.contains("success") && parsed["success"].is_boolean()) {+ if (parsed["success"].get<bool>()) {+ result_ = parsed; // Keep full response (has data + success)+ has_result_ = true;+ } else {+ error_ = parsed.value("error", "Unknown error from Python");+ has_result_ = false;+ }+ }+ // Handle {data: ..., error: null} wrapper+ else if (parsed.contains("data") && parsed.contains("error")) {+ if (parsed["error"].is_null()) {+ result_ = parsed;+ has_result_ = true;+ } else {+ error_ = parsed["error"].get<std::string>();+ has_result_ = false;+ }+ }+ else {+ // Raw JSON result — wrap it+ result_ = parsed;+ has_result_ = true;+ }+ } catch (const json::exception& e) {+ error_ = std::string("JSON parse error: ") + e.what();+ has_result_ = false;+ LOG_ERROR("BacktestData", "JSON parse failed: %s", e.what());+ }+}++} // namespace fincept::backtestingdiff --git a/fincept-cpp/src/screens/backtesting/backtesting_data.h b/fincept-cpp/src/screens/backtesting/backtesting_data.hnew file mode 100644index 000000000..fb7f9fdd3--- /dev/null+++ b/fincept-cpp/src/screens/backtesting/backtesting_data.h@@ -0,0 +1,44 @@+#pragma once+// Backtesting Tab — async Python execution layer+// Same pattern as GovData but for backtesting provider scripts++#include <mutex>+#include <atomic>+#include <string>+#include <vector>+#include <nlohmann/json.hpp>++namespace fincept::backtesting {++class BacktestData {+public:+ // Run a backtesting provider script asynchronously+ // provider_dir: folder name under Analytics/backtesting/ (e.g. "vectorbt")+ // command: python action (e.g. "run_backtest")+ // args_json: JSON string of arguments+ void run(const std::string& provider_dir, const std::string& command,+ const std::string& args_json);++ // State queries+ bool is_loading() const { return loading_.load(); }+ bool has_result() const;+ const std::string& error() const;++ // Access the JSON result (caller must hold mutex)+ std::mutex& mutex() { return mutex_; }+ const nlohmann::json& result() const { return result_; }++ // Clear previous result+ void clear();++private:+ std::mutex mutex_;+ std::atomic<bool> loading_{false};+ nlohmann::json result_;+ std::string error_;+ bool has_result_ = false;++ void parse_result(const std::string& output);+};++} // namespace fincept::backtestingdiff --git a/fincept-cpp/src/screens/backtesting/backtesting_screen.cpp b/fincept-cpp/src/screens/backtesting/backtesting_screen.cppnew file mode 100644index 000000000..a42530d54--- /dev/null+++ b/fincept-cpp/src/screens/backtesting/backtesting_screen.cpp@@ -0,0 +1,2278 @@+#include "backtesting_screen.h"+#include "backtesting_constants.h"+#include "ui/theme.h"+#include <imgui.h>+#include <cstdio>+#include <cstring>+#include <ctime>+#include <cmath>+#include <algorithm>+#include <sstream>++namespace fincept::backtesting {++using json = nlohmann::json;++// =============================================================================+// Main render+// =============================================================================+void BacktestingScreen::render() {+ pickup_result();++ // Top nav bar+ render_top_nav();++ // Three-panel layout — fills available content area+ float avail_h = ImGui::GetContentRegionAvail().y - 24; // reserve status bar+ float avail_w = ImGui::GetContentRegionAvail().x;++ float left_w = 260.0f;+ float right_w = 300.0f;+ float center_w = avail_w - left_w - right_w;+ if (center_w < 200) center_w = 200;++ ImGui::BeginChild("##bt_body", ImVec2(0, avail_h));++ // LEFT PANEL — Commands + Categories+ ImGui::BeginChild("##bt_left", ImVec2(left_w, 0), ImGuiChildFlags_Borders);+ render_command_panel();+ ImGui::EndChild();++ ImGui::SameLine(0, 0);++ // CENTER PANEL — Config (flex)+ ImGui::BeginChild("##bt_center", ImVec2(center_w, 0), ImGuiChildFlags_Borders);+ render_config_panel();+ ImGui::EndChild();++ ImGui::SameLine(0, 0);++ // RIGHT PANEL — Results+ ImGui::BeginChild("##bt_right", ImVec2(right_w, 0), ImGuiChildFlags_Borders);+ render_results_panel();+ ImGui::EndChild();++ ImGui::EndChild(); // bt_body++ // Status bar+ render_status_bar();+}++// =============================================================================+// Top navigation bar — provider tabs + advanced toggle + status+// =============================================================================+void BacktestingScreen::render_top_nav() {+ using namespace theme::colors;+ auto color = provider_color(selected_provider_);++ ImGui::PushStyleColor(ImGuiCol_ChildBg, BG_WIDGET);+ ImGui::BeginChild("##bt_topnav", ImVec2(0, 36), ImGuiChildFlags_Borders);++ // Title+ ImGui::TextColored(ACCENT, "BACKTESTING");+ ImGui::SameLine(0, 16);+ ImGui::TextColored(BORDER_BRIGHT, "|");+ ImGui::SameLine(0, 8);++ // Provider tabs+ for (auto& p : provider_list()) {+ if (ProviderTab(p.display_name, provider_color(p.slug), selected_provider_ == p.slug)) {+ selected_provider_ = p.slug;+ // Reset to first available command+ auto cmds = provider_commands(selected_provider_);+ if (!cmds.empty()) active_command_ = cmds[0];+ // Reset category+ auto cats = get_categories(selected_provider_);+ if (!cats.empty()) selected_category_ = cats[0].key;+ selected_strategy_idx_ = 0;+ init_strategy_params();+ result_ = json();+ has_error_ = false;+ }+ ImGui::SameLine(0, 2);+ }++ // Right side — Advanced toggle + Status+ float right_x = ImGui::GetWindowWidth() - 200;+ ImGui::SameLine(right_x);++ // Advanced toggle+ if (show_advanced_) {+ ImGui::PushStyleColor(ImGuiCol_Button, ACCENT_BG);+ ImGui::PushStyleColor(ImGuiCol_Text, ACCENT);+ } else {+ ImGui::PushStyleColor(ImGuiCol_Button, ImVec4(0,0,0,0));+ ImGui::PushStyleColor(ImGuiCol_Text, TEXT_DIM);+ }+ if (ImGui::SmallButton("ADVANCED")) show_advanced_ = !show_advanced_;+ ImGui::PopStyleColor(2);++ ImGui::SameLine(0, 12);++ // Status indicator+ bool running = data_.is_loading();+ ImVec4 status_color = running ? ACCENT : SUCCESS;+ ImGui::TextColored(status_color, "%s", running ? "RUNNING" : "READY");++ ImGui::EndChild();+ ImGui::PopStyleColor();+}++// =============================================================================+// Command panel (left)+// =============================================================================+void BacktestingScreen::render_command_panel() {+ using namespace theme::colors;++ auto cmds = provider_commands(selected_provider_);+ auto color = provider_color(selected_provider_);++ // Commands header+ ImGui::PushStyleColor(ImGuiCol_ChildBg, BG_WIDGET);+ ImGui::BeginChild("##bt_cmd_hdr", ImVec2(0, 24));+ ImGui::TextColored(TEXT_DIM, "COMMANDS");+ ImGui::SameLine(ImGui::GetContentRegionAvail().x - 20);+ ImGui::TextColored(color, "%d", (int)cmds.size());+ ImGui::EndChild();+ ImGui::PopStyleColor();++ // Command list+ for (auto& cmd_type : cmds) {+ const CommandDef* def = nullptr;+ for (auto& c : all_commands()) {+ if (c.type == cmd_type) { def = &c; break; }+ }+ if (!def) continue;++ if (CommandItem(def->label, def->description, def->color, active_command_ == cmd_type)) {+ active_command_ = cmd_type;+ }+ }++ // Strategy categories (only for backtest/optimize/walk_forward)+ bool show_categories = (active_command_ == CommandType::Backtest ||+ active_command_ == CommandType::Optimize ||+ active_command_ == CommandType::WalkForward);+ if (!show_categories) return;++ ImGui::Spacing();+ ImGui::Separator();++ ImGui::PushStyleColor(ImGuiCol_ChildBg, BG_WIDGET);+ ImGui::BeginChild("##bt_cat_hdr", ImVec2(0, 24));+ ImGui::TextColored(TEXT_DIM, "STRATEGIES");+ ImGui::EndChild();+ ImGui::PopStyleColor();++ auto cats = get_categories(selected_provider_);+ for (auto& cat : cats) {+ auto strats = get_strategies(selected_provider_, cat.key);+ bool active = (selected_category_ == cat.key);++ if (CommandItem(cat.label, "", cat.color, active)) {+ selected_category_ = cat.key;+ selected_strategy_idx_ = 0;+ init_strategy_params();+ }++ // Show count+ ImVec2 pos = ImGui::GetCursorScreenPos();+ ImGui::SetCursorScreenPos(ImVec2(pos.x + 220, pos.y - 30));+ ImGui::TextColored(active ? cat.color : TEXT_DISABLED, "%d", (int)strats.size());+ ImGui::SetCursorScreenPos(pos);+ }+}++// =============================================================================+// Config panel (center)+// =============================================================================+void BacktestingScreen::render_config_panel() {+ using namespace theme::colors;++ // Header with command name + run button+ ImGui::PushStyleColor(ImGuiCol_ChildBg, BG_WIDGET);+ ImGui::BeginChild("##bt_cfg_hdr", ImVec2(0, 36));++ ImGui::TextColored(TEXT_PRIMARY, "%s", command_label(active_command_));+ ImGui::SameLine(0, 8);+ ImGui::TextColored(TEXT_DISABLED, "CONFIGURATION");++ ImGui::SameLine(ImGui::GetWindowWidth() - 160);+ if (RunButton(("RUN " + std::string(command_label(active_command_))).c_str(),+ data_.is_loading(), provider_color(selected_provider_))) {+ execute_command();+ }++ ImGui::EndChild();+ ImGui::PopStyleColor();++ // Content area+ ImGui::BeginChild("##bt_cfg_content", ImVec2(0, 0));++ switch (active_command_) {+ case CommandType::Backtest:+ render_backtest_config();+ if (show_advanced_) render_advanced_config();+ break;+ case CommandType::Optimize:+ render_optimize_config();+ break;+ case CommandType::WalkForward:+ render_walk_forward_config();+ break;+ case CommandType::Indicator:+ render_indicator_config();+ break;+ case CommandType::IndicatorSignals:+ render_indicator_signals_config();+ break;+ case CommandType::Labels:+ render_labels_config();+ break;+ case CommandType::Splits:+ render_splitters_config();+ break;+ case CommandType::Returns:+ render_returns_config();+ break;+ case CommandType::Signals:+ render_signals_config();+ break;+ default: break;+ }++ ImGui::EndChild();+}++// =============================================================================+// Backtest config+// =============================================================================+void BacktestingScreen::render_backtest_config() {+ using namespace theme::colors;++ // Market Data section+ bool market_open = expanded_["market"];+ if (SectionHeader("MARKET DATA", &market_open)) {+ expanded_["market"] = true;+ if (ImGui::BeginTable("##bt_market", 2, ImGuiTableFlags_None)) {+ ImGui::TableNextColumn(); InputField("Symbols", symbols_, sizeof(symbols_));+ ImGui::TableNextColumn(); InputFloat("Initial Capital", &initial_capital_, 1000);+ ImGui::TableNextColumn(); InputField("Start Date", start_date_, sizeof(start_date_));+ ImGui::TableNextColumn(); InputField("End Date", end_date_, sizeof(end_date_));+ ImGui::EndTable();+ }+ } else { expanded_["market"] = false; }++ ImGui::Spacing();++ // Strategy selection section+ auto strats = get_strategies(selected_provider_, selected_category_);+ bool strat_open = expanded_["strategy"];+ auto cats = get_categories(selected_provider_);+ const char* cat_label = selected_category_.c_str();+ for (auto& c : cats) {+ if (selected_category_ == c.key) { cat_label = c.label; break; }+ }++ char section_label[128];+ snprintf(section_label, sizeof(section_label), "%s STRATEGIES", cat_label);++ if (SectionHeader(section_label, &strat_open)) {+ expanded_["strategy"] = true;++ // Strategy grid (2 columns)+ if (ImGui::BeginTable("##bt_strats", 2, ImGuiTableFlags_None)) {+ for (int i = 0; i < (int)strats.size(); i++) {+ ImGui::TableNextColumn();+ bool selected = (i == selected_strategy_idx_);+ ImVec4 btn_color = selected ? ACCENT : ImVec4(0,0,0,0);+ ImVec4 txt_color = selected ? BG_DARKEST : TEXT_SECONDARY;++ ImGui::PushStyleColor(ImGuiCol_Button, btn_color);+ ImGui::PushStyleColor(ImGuiCol_ButtonHovered, selected ? ACCENT_HOVER : BG_HOVER);+ ImGui::PushStyleColor(ImGuiCol_Text, txt_color);++ if (ImGui::Button(strats[i].name, ImVec2(-1, 40))) {+ selected_strategy_idx_ = i;+ init_strategy_params();+ }+ ImGui::PopStyleColor(3);++ // Description tooltip+ if (ImGui::IsItemHovered()) {+ ImGui::SetTooltip("%s", strats[i].description);+ }+ }+ ImGui::EndTable();+ }++ // Strategy parameters+ if (selected_strategy_idx_ < (int)strats.size()) {+ auto& strat = strats[selected_strategy_idx_];++ if (std::string(strat.id) == "code") {+ // Custom code editor+ ImGui::Spacing();+ ImGui::TextColored(TEXT_DIM, "CUSTOM PYTHON CODE");+ ImGui::PushStyleColor(ImGuiCol_FrameBg, BG_DARKEST);+ ImGui::InputTextMultiline("##bt_custom_code", custom_code_, sizeof(custom_code_),+ ImVec2(-1, 200));+ ImGui::PopStyleColor();+ }+ else if (!strat.params.empty()) {+ ImGui::Spacing();+ int cols = std::min(3, (int)strat.params.size());+ if (ImGui::BeginTable("##bt_params", cols, ImGuiTableFlags_None)) {+ for (auto& param : strat.params) {+ ImGui::TableNextColumn();+ float val = strategy_params_[param.name];+ if (InputFloat(param.label, &val, param.step)) {+ if (val >= param.min_val && val <= param.max_val)+ strategy_params_[param.name] = val;+ }+ }+ ImGui::EndTable();+ }+ }+ }+ } else { expanded_["strategy"] = false; }++ ImGui::Spacing();++ // Execution settings+ bool exec_open = expanded_["execution"];+ if (SectionHeader("EXECUTION SETTINGS", &exec_open)) {+ expanded_["execution"] = true;+ if (ImGui::BeginTable("##bt_exec", 2, ImGuiTableFlags_None)) {+ ImGui::TableNextColumn(); InputFloat("Commission (%)", &commission_, 0.01f);+ ImGui::TableNextColumn(); InputFloat("Slippage (%)", &slippage_, 0.01f);+ ImGui::EndTable();+ }+ } else { expanded_["execution"] = false; }+}++// =============================================================================+// Advanced config+// =============================================================================+void BacktestingScreen::render_advanced_config() {+ using namespace theme::colors;++ ImGui::Spacing();+ bool adv_open = expanded_["advanced"];+ if (SectionHeader("ADVANCED SETTINGS", &adv_open)) {+ expanded_["advanced"] = true;++ // Risk management+ ImGui::TextColored(INFO, "RISK MANAGEMENT");+ if (ImGui::BeginTable("##bt_risk", 3, ImGuiTableFlags_None)) {+ ImGui::TableNextColumn(); InputFloat("Stop Loss (%)", &stop_loss_, 0.1f);+ ImGui::TableNextColumn(); InputFloat("Take Profit (%)", &take_profit_, 0.1f);+ ImGui::TableNextColumn(); InputFloat("Trailing Stop (%)", &trailing_stop_, 0.1f);+ ImGui::EndTable();+ }++ ImGui::Spacing();++ // Position sizing+ ImGui::TextColored(INFO, "POSITION SIZING");+ auto& ps_opts = position_sizing_options();+ if (ImGui::BeginTable("##bt_pos", 2, ImGuiTableFlags_None)) {+ ImGui::TableNextColumn();+ ImGui::TextColored(TEXT_DIM, "METHOD");+ ImGui::PushStyleColor(ImGuiCol_FrameBg, BG_INPUT);+ ImGui::PushItemWidth(-1);+ if (ImGui::BeginCombo("##bt_ps_method", ps_opts[position_sizing_idx_].label)) {+ for (int i = 0; i < (int)ps_opts.size(); i++) {+ if (ImGui::Selectable(ps_opts[i].label, i == position_sizing_idx_))+ position_sizing_idx_ = i;+ }+ ImGui::EndCombo();+ }+ ImGui::PopItemWidth();+ ImGui::PopStyleColor();+ ImGui::TableNextColumn(); InputFloat("Size Value", &position_size_value_);+ ImGui::EndTable();+ }++ ImGui::Spacing();++ // Leverage & margin+ ImGui::TextColored(INFO, "LEVERAGE & MARGIN");+ if (ImGui::BeginTable("##bt_lev", 3, ImGuiTableFlags_None)) {+ ImGui::TableNextColumn(); InputFloat("Leverage", &leverage_, 0.1f);+ ImGui::TableNextColumn(); InputFloat("Margin", &margin_, 0.1f);+ ImGui::TableNextColumn();+ ImGui::Spacing();+ ImGui::Checkbox("Allow Short", &allow_short_);+ ImGui::EndTable();+ }++ ImGui::Spacing();++ // Benchmark+ ImGui::TextColored(INFO, "BENCHMARK COMPARISON");+ ImGui::Checkbox("Enable Benchmark", &enable_benchmark_);+ if (enable_benchmark_) {+ InputField("Benchmark Symbol", benchmark_symbol_, sizeof(benchmark_symbol_));+ ImGui::Checkbox("Random Benchmark", &random_benchmark_);+ }+ } else { expanded_["advanced"] = false; }+}++// =============================================================================+// Optimize config+// =============================================================================+void BacktestingScreen::render_optimize_config() {+ using namespace theme::colors;++ // Market data (same as backtest)+ bool market_open = expanded_["market"];+ if (SectionHeader("MARKET DATA", &market_open)) {+ expanded_["market"] = true;+ if (ImGui::BeginTable("##bt_opt_market", 2, ImGuiTableFlags_None)) {+ ImGui::TableNextColumn(); InputField("Symbols", symbols_, sizeof(symbols_));+ ImGui::TableNextColumn(); InputFloat("Initial Capital", &initial_capital_, 1000);+ ImGui::TableNextColumn(); InputField("Start Date", start_date_, sizeof(start_date_));+ ImGui::TableNextColumn(); InputField("End Date", end_date_, sizeof(end_date_));+ ImGui::EndTable();+ }+ } else { expanded_["market"] = false; }++ ImGui::Spacing();++ // Optimization settings+ bool opt_open = expanded_["optimization"];+ if (SectionHeader("OPTIMIZATION SETTINGS", &opt_open)) {+ expanded_["optimization"] = true;++ if (ImGui::BeginTable("##bt_opt_cfg", 3, ImGuiTableFlags_None)) {+ ImGui::TableNextColumn();+ ImGui::TextColored(TEXT_DIM, "OBJECTIVE");+ ImGui::PushStyleColor(ImGuiCol_FrameBg, BG_INPUT);+ ImGui::PushItemWidth(-1);+ if (ImGui::BeginCombo("##bt_opt_obj", OPTIMIZE_OBJECTIVE_LABELS[optimize_objective_idx_])) {+ for (int i = 0; i < 4; i++) {+ if (ImGui::Selectable(OPTIMIZE_OBJECTIVE_LABELS[i], i == optimize_objective_idx_))+ optimize_objective_idx_ = i;+ }+ ImGui::EndCombo();+ }+ ImGui::PopItemWidth();+ ImGui::PopStyleColor();++ ImGui::TableNextColumn();+ ImGui::TextColored(TEXT_DIM, "METHOD");+ ImGui::PushStyleColor(ImGuiCol_FrameBg, BG_INPUT);+ ImGui::PushItemWidth(-1);+ if (ImGui::BeginCombo("##bt_opt_method", OPTIMIZE_METHOD_LABELS[optimize_method_idx_])) {+ for (int i = 0; i < 2; i++) {+ if (ImGui::Selectable(OPTIMIZE_METHOD_LABELS[i], i == optimize_method_idx_))+ optimize_method_idx_ = i;+ }+ ImGui::EndCombo();+ }+ ImGui::PopItemWidth();+ ImGui::PopStyleColor();++ ImGui::TableNextColumn();+ InputInt("Max Iterations", &max_iterations_);+ ImGui::EndTable();+ }++ // Parameter ranges+ auto strats = get_strategies(selected_provider_, selected_category_);+ if (selected_strategy_idx_ < (int)strats.size()) {+ auto& strat = strats[selected_strategy_idx_];+ if (!strat.params.empty()) {+ ImGui::Spacing();+ ImGui::TextColored(INFO, "PARAMETER RANGES");+ if (ImGui::BeginTable("##bt_param_ranges", 4, ImGuiTableFlags_Borders | ImGuiTableFlags_RowBg)) {+ ImGui::TableSetupColumn("Parameter");+ ImGui::TableSetupColumn("Min");+ ImGui::TableSetupColumn("Max");+ ImGui::TableSetupColumn("Step");+ ImGui::TableHeadersRow();++ for (auto& param : strat.params) {+ auto& range = param_ranges_[param.name];+ if (range[0] == 0 && range[1] == 0) {+ range[0] = param.min_val;+ range[1] = param.max_val;+ range[2] = param.step > 0 ? param.step : 1.0f;+ }+ ImGui::TableNextRow();+ ImGui::TableNextColumn(); ImGui::Text("%s", param.label);+ ImGui::TableNextColumn();+ ImGui::PushItemWidth(-1);+ ImGui::InputFloat(("##rng_min_" + std::string(param.name)).c_str(), &range[0], 0, 0, "%.2f");+ ImGui::PopItemWidth();+ ImGui::TableNextColumn();+ ImGui::PushItemWidth(-1);+ ImGui::InputFloat(("##rng_max_" + std::string(param.name)).c_str(), &range[1], 0, 0, "%.2f");+ ImGui::PopItemWidth();+ ImGui::TableNextColumn();+ ImGui::PushItemWidth(-1);+ ImGui::InputFloat(("##rng_step_" + std::string(param.name)).c_str(), &range[2], 0, 0, "%.2f");+ ImGui::PopItemWidth();+ }+ ImGui::EndTable();+ }+ }+ }+ } else { expanded_["optimization"] = false; }+}++// =============================================================================+// Walk forward config+// =============================================================================+void BacktestingScreen::render_walk_forward_config() {+ using namespace theme::colors;++ // Market data+ bool market_open = expanded_["market"];+ if (SectionHeader("MARKET DATA", &market_open)) {+ expanded_["market"] = true;+ if (ImGui::BeginTable("##bt_wf_market", 2, ImGuiTableFlags_None)) {+ ImGui::TableNextColumn(); InputField("Symbols", symbols_, sizeof(symbols_));+ ImGui::TableNextColumn(); InputFloat("Initial Capital", &initial_capital_, 1000);+ ImGui::TableNextColumn(); InputField("Start Date", start_date_, sizeof(start_date_));+ ImGui::TableNextColumn(); InputField("End Date", end_date_, sizeof(end_date_));+ ImGui::EndTable();+ }+ } else { expanded_["market"] = false; }++ ImGui::Spacing();++ bool wf_open = expanded_["walk_forward"];+ if (SectionHeader("WALK FORWARD SETTINGS", &wf_open)) {+ expanded_["walk_forward"] = true;+ if (ImGui::BeginTable("##bt_wf_cfg", 2, ImGuiTableFlags_None)) {+ ImGui::TableNextColumn(); InputInt("Number of Splits", &wf_splits_);+ ImGui::TableNextColumn(); InputFloat("Train Ratio", &wf_train_ratio_, 0.05f);+ ImGui::EndTable();+ }+ } else { expanded_["walk_forward"] = false; }+}++// =============================================================================+// Indicator config+// =============================================================================+void BacktestingScreen::render_indicator_config() {+ using namespace theme::colors;++ auto& inds = indicators();+ ImGui::TextColored(TEXT_DIM, "INDICATOR");+ ImGui::PushStyleColor(ImGuiCol_FrameBg, BG_INPUT);+ ImGui::PushItemWidth(200);+ if (ImGui::BeginCombo("##bt_ind", inds[indicator_idx_].label)) {+ for (int i = 0; i < (int)inds.size(); i++) {+ if (ImGui::Selectable(inds[i].label, i == indicator_idx_))+ indicator_idx_ = i;+ }+ ImGui::EndCombo();+ }+ ImGui::PopItemWidth();+ ImGui::PopStyleColor();++ ImGui::Spacing();++ // Market data fields+ if (ImGui::BeginTable("##bt_ind_market", 2, ImGuiTableFlags_None)) {+ ImGui::TableNextColumn(); InputField("Symbols", symbols_, sizeof(symbols_));+ ImGui::TableNextColumn(); InputField("Start Date", start_date_, sizeof(start_date_));+ ImGui::TableNextColumn(); InputField("End Date", end_date_, sizeof(end_date_));+ ImGui::EndTable();+ }+}++// =============================================================================+// Indicator signals config+// =============================================================================+void BacktestingScreen::render_indicator_signals_config() {+ using namespace theme::colors;++ auto& modes = signal_modes();+ ImGui::TextColored(TEXT_DIM, "SIGNAL MODE");+ ImGui::PushStyleColor(ImGuiCol_FrameBg, BG_INPUT);+ ImGui::PushItemWidth(200);+ if (ImGui::BeginCombo("##bt_sig_mode", modes[signal_mode_idx_].label)) {+ for (int i = 0; i < (int)modes.size(); i++) {+ if (ImGui::Selectable(modes[i].label, i == signal_mode_idx_))+ signal_mode_idx_ = i;+ }+ ImGui::EndCombo();+ }+ ImGui::PopItemWidth();+ ImGui::PopStyleColor();++ if (ImGui::IsItemHovered())+ ImGui::SetTooltip("%s", modes[signal_mode_idx_].description);++ ImGui::Spacing();++ if (ImGui::BeginTable("##bt_indsig_market", 2, ImGuiTableFlags_None)) {+ ImGui::TableNextColumn(); InputField("Symbols", symbols_, sizeof(symbols_));+ ImGui::TableNextColumn(); InputField("Start Date", start_date_, sizeof(start_date_));+ ImGui::TableNextColumn(); InputField("End Date", end_date_, sizeof(end_date_));+ ImGui::EndTable();+ }+}++// =============================================================================+// Labels config (ML)+// =============================================================================+void BacktestingScreen::render_labels_config() {+ using namespace theme::colors;++ auto& lts = label_types();+ ImGui::TextColored(TEXT_DIM, "LABEL TYPE");+ ImGui::PushStyleColor(ImGuiCol_FrameBg, BG_INPUT);+ ImGui::PushItemWidth(200);+ if (ImGui::BeginCombo("##bt_lbl_type", lts[labels_type_idx_].label)) {+ for (int i = 0; i < (int)lts.size(); i++) {+ if (ImGui::Selectable(lts[i].label, i == labels_type_idx_))+ labels_type_idx_ = i;+ }+ ImGui::EndCombo();+ }+ ImGui::PopItemWidth();+ ImGui::PopStyleColor();++ if (ImGui::IsItemHovered())+ ImGui::SetTooltip("%s", lts[labels_type_idx_].description);++ ImGui::Spacing();++ // Label params+ auto& lt = lts[labels_type_idx_];+ for (auto& p : lt.params) {+ float val = labels_params_[p];+ if (val == 0.0f) {+ // Defaults+ if (std::string(p) == "horizon") val = 5;+ else if (std::string(p) == "threshold") val = 0.02f;+ else if (std::string(p) == "window") val = 20;+ else if (std::string(p) == "alpha") val = 2.0f;+ labels_params_[p] = val;+ }+ if (InputFloat(p, &val)) labels_params_[p] = val;+ }++ ImGui::Spacing();++ if (ImGui::BeginTable("##bt_lbl_market", 2, ImGuiTableFlags_None)) {+ ImGui::TableNextColumn(); InputField("Symbols", symbols_, sizeof(symbols_));+ ImGui::TableNextColumn(); InputField("Start Date", start_date_, sizeof(start_date_));+ ImGui::TableNextColumn(); InputField("End Date", end_date_, sizeof(end_date_));+ ImGui::EndTable();+ }+}++// =============================================================================+// Splitters config (CV)+// =============================================================================+void BacktestingScreen::render_splitters_config() {+ using namespace theme::colors;++ auto& sts = splitter_types();+ ImGui::TextColored(TEXT_DIM, "SPLITTER TYPE");+ ImGui::PushStyleColor(ImGuiCol_FrameBg, BG_INPUT);+ ImGui::PushItemWidth(200);+ if (ImGui::BeginCombo("##bt_spl_type", sts[splitter_type_idx_].label)) {+ for (int i = 0; i < (int)sts.size(); i++) {+ if (ImGui::Selectable(sts[i].label, i == splitter_type_idx_))+ splitter_type_idx_ = i;+ }+ ImGui::EndCombo();+ }+ ImGui::PopItemWidth();+ ImGui::PopStyleColor();++ if (ImGui::IsItemHovered())+ ImGui::SetTooltip("%s", sts[splitter_type_idx_].description);++ ImGui::Spacing();++ auto& st = sts[splitter_type_idx_];+ for (auto& p : st.params) {+ float val = splitter_params_[p];+ if (val == 0.0f) {+ if (std::string(p) == "window_len" || std::string(p) == "min_len") val = 252;+ else if (std::string(p) == "test_len") val = 63;+ else if (std::string(p) == "step") val = 21;+ else if (std::string(p) == "n_splits") val = 5;+ else if (std::string(p) == "purge_len" || std::string(p) == "embargo_len") val = 5;+ splitter_params_[p] = val;+ }+ if (InputFloat(p, &val)) splitter_params_[p] = val;+ }++ ImGui::Spacing();++ if (ImGui::BeginTable("##bt_spl_market", 2, ImGuiTableFlags_None)) {+ ImGui::TableNextColumn(); InputField("Symbols", symbols_, sizeof(symbols_));+ ImGui::TableNextColumn(); InputField("Start Date", start_date_, sizeof(start_date_));+ ImGui::TableNextColumn(); InputField("End Date", end_date_, sizeof(end_date_));+ ImGui::EndTable();+ }+}++// =============================================================================+// Returns config+// =============================================================================+void BacktestingScreen::render_returns_config() {+ using namespace theme::colors;++ auto& rts = returns_analysis_types();+ ImGui::TextColored(TEXT_DIM, "ANALYSIS TYPE");+ ImGui::PushStyleColor(ImGuiCol_FrameBg, BG_INPUT);+ ImGui::PushItemWidth(200);+ if (ImGui::BeginCombo("##bt_ret_type", rts[returns_type_idx_].label)) {+ for (int i = 0; i < (int)rts.size(); i++) {+ if (ImGui::Selectable(rts[i].label, i == returns_type_idx_))+ returns_type_idx_ = i;+ }+ ImGui::EndCombo();+ }+ ImGui::PopItemWidth();+ ImGui::PopStyleColor();++ ImGui::Spacing();+ InputInt("Rolling Window", &returns_rolling_window_);++ if (rts[returns_type_idx_].id == std::string("benchmark_comparison")) {+ InputField("Benchmark Symbol", benchmark_symbol_, sizeof(benchmark_symbol_));+ }++ ImGui::Spacing();+ if (ImGui::BeginTable("##bt_ret_market", 2, ImGuiTableFlags_None)) {+ ImGui::TableNextColumn(); InputField("Symbols", symbols_, sizeof(symbols_));+ ImGui::TableNextColumn(); InputField("Start Date", start_date_, sizeof(start_date_));+ ImGui::TableNextColumn(); InputField("End Date", end_date_, sizeof(end_date_));+ ImGui::EndTable();+ }+}++// =============================================================================+// Signals config (random signal generators)+// =============================================================================+void BacktestingScreen::render_signals_config() {+ using namespace theme::colors;++ auto& sgs = signal_generator_types();+ ImGui::TextColored(TEXT_DIM, "GENERATOR TYPE");+ ImGui::PushStyleColor(ImGuiCol_FrameBg, BG_INPUT);+ ImGui::PushItemWidth(200);+ if (ImGui::BeginCombo("##bt_siggen_type", sgs[signal_gen_idx_].label)) {+ for (int i = 0; i < (int)sgs.size(); i++) {+ if (ImGui::Selectable(sgs[i].label, i == signal_gen_idx_))+ signal_gen_idx_ = i;+ }+ ImGui::EndCombo();+ }+ ImGui::PopItemWidth();+ ImGui::PopStyleColor();++ if (ImGui::IsItemHovered())+ ImGui::SetTooltip("%s", sgs[signal_gen_idx_].description);++ ImGui::Spacing();++ auto& sg = sgs[signal_gen_idx_];+ for (auto& p : sg.params) {+ float val = signal_gen_params_[p];+ if (val == 0.0f) {+ if (std::string(p) == "n") val = 10;+ else if (std::string(p) == "seed") val = 42;+ else if (std::string(p) == "entry_prob" || std::string(p) == "exit_prob") val = 0.1f;+ else if (std::string(p) == "cooldown") val = 5;+ else if (std::string(p) == "min_hold") val = 5;+ else if (std::string(p) == "max_hold") val = 20;+ signal_gen_params_[p] = val;+ }+ if (InputFloat(p, &val)) signal_gen_params_[p] = val;+ }++ ImGui::Spacing();+ if (ImGui::BeginTable("##bt_sig_market", 2, ImGuiTableFlags_None)) {+ ImGui::TableNextColumn(); InputField("Symbols", symbols_, sizeof(symbols_));+ ImGui::TableNextColumn(); InputField("Start Date", start_date_, sizeof(start_date_));+ ImGui::TableNextColumn(); InputField("End Date", end_date_, sizeof(end_date_));+ ImGui::EndTable();+ }+}++// =============================================================================+// Results panel (right)+// =============================================================================+void BacktestingScreen::render_results_panel() {+ using namespace theme::colors;++ // Header+ ImGui::PushStyleColor(ImGuiCol_ChildBg, BG_WIDGET);+ ImGui::BeginChild("##bt_res_hdr", ImVec2(0, 56));++ ImGui::TextColored(ACCENT, "RESULTS");++ // View tabs (only for backtest with results)+ if (active_command_ == CommandType::Backtest && !result_.empty() && !data_.is_loading()) {+ const char* views[] = {"SUMMARY", "METRICS", "CHARTS", "TRADES", "RAW"};+ ResultView view_enums[] = {ResultView::Summary, ResultView::Metrics, ResultView::Charts, ResultView::Trades, ResultView::Raw};+ for (int i = 0; i < 5; i++) {+ if (i > 0) ImGui::SameLine(0, 2);+ if (ProviderTab(views[i], ACCENT, result_view_ == view_enums[i]))+ result_view_ = view_enums[i];+ }+ }++ ImGui::EndChild();+ ImGui::PopStyleColor();++ // Content+ ImGui::BeginChild("##bt_res_content", ImVec2(0, 0));++ // Error state+ if (has_error_) {+ ImGui::PushStyleColor(ImGuiCol_Text, ERROR_RED);+ ImGui::TextWrapped("ERROR: %s", error_msg_.c_str());+ ImGui::PopStyleColor();+ }+ // Loading state+ else if (data_.is_loading()) {+ ImGui::Spacing(); ImGui::Spacing();+ float w = ImGui::GetContentRegionAvail().x;+ ImGui::SetCursorPosX(ImGui::GetCursorPosX() + w * 0.3f);+ ImGui::TextColored(ACCENT, "Running %s...", command_label(active_command_));+ }+ // Results+ else if (!result_.empty()) {+ // Synthetic data warning+ if (result_.contains("data") && result_["data"].is_object()) {+ auto& data = result_["data"];+ if (data.value("usingSyntheticData", false) || data.contains("syntheticDataWarning")) {+ ImGui::PushStyleColor(ImGuiCol_Text, WARNING);+ ImGui::TextWrapped("SYNTHETIC DATA WARNING: Results use fake data. Install yfinance for real results.");+ ImGui::PopStyleColor();+ ImGui::Spacing();+ }+ }++ if (active_command_ == CommandType::Backtest) {+ switch (result_view_) {+ case ResultView::Summary: render_result_summary(); break;+ case ResultView::Metrics: render_result_metrics(); break;+ case ResultView::Charts: render_result_charts(); break;+ case ResultView::Trades: render_result_trades(); break;+ case ResultView::Raw: render_result_raw(); break;+ default: render_result_summary(); break;+ }+ }+ else if (active_command_ == CommandType::Optimize || active_command_ == CommandType::WalkForward) {+ render_result_metrics();+ ImGui::Spacing();+ render_result_drawdowns();+ ImGui::Spacing();+ render_result_raw();+ }+ else if (active_command_ == CommandType::Indicator) {+ render_result_indicator();+ }+ else if (active_command_ == CommandType::IndicatorSignals) {+ render_result_signals();+ }+ else if (active_command_ == CommandType::Labels) {+ render_result_labels();+ }+ else if (active_command_ == CommandType::Splits) {+ render_result_splitters();+ }+ else if (active_command_ == CommandType::Returns) {+ render_result_returns();+ }+ else if (active_command_ == CommandType::Signals) {+ render_result_signal_generator();+ }+ else {+ render_result_raw();+ }+ }+ // Empty state+ else {+ EmptyState("No results yet", "Configure and run a command");+ }++ ImGui::EndChild();+}++// =============================================================================+// Result summary+// =============================================================================+void BacktestingScreen::render_result_summary() {+ using namespace theme::colors;++ json perf;+ if (result_.contains("data") && result_["data"].is_object() && result_["data"].contains("performance"))+ perf = result_["data"]["performance"];+ else+ perf = result_.value("performance", json());++ if (perf.empty()) {+ ImGui::TextColored(WARNING, "No performance data available.");+ return;+ }++ float total_return = perf.value("totalReturn", 0.0f) * 100.0f;+ bool is_profit = total_return > 0;++ // Status badge+ ImGui::TextColored(SUCCESS, "BACKTEST COMPLETED");+ ImGui::Spacing();++ // Total return card+ ImVec4 ret_color = is_profit ? SUCCESS : ERROR_RED;+ char ret_str[32];+ snprintf(ret_str, sizeof(ret_str), "%+.2f%%", total_return);++ ImGui::PushStyleColor(ImGuiCol_ChildBg, BG_PANEL);+ ImGui::BeginChild("##bt_ret_card", ImVec2(0, 80), ImGuiChildFlags_Borders);+ ImGui::TextColored(TEXT_DIM, "TOTAL RETURN");+ ImGui::PushFont(nullptr); // Use default font at larger rendering+ ImGui::SetWindowFontScale(2.0f);+ ImGui::TextColored(ret_color, "%s", ret_str);+ ImGui::SetWindowFontScale(1.0f);+ ImGui::PopFont();++ json stats;+ if (result_.contains("data") && result_["data"].contains("statistics"))+ stats = result_["data"]["statistics"];+ float init_cap = stats.value("initialCapital", 0.0f);+ float final_cap = stats.value("finalCapital", 0.0f);+ if (init_cap > 0) {+ ImGui::TextColored(TEXT_DIM, "$%.0f -> $%.0f", init_cap, final_cap);+ }+ ImGui::EndChild();+ ImGui::PopStyleColor();++ ImGui::Spacing();++ // Key metrics grid (2x2)+ if (ImGui::BeginTable("##bt_key_metrics", 2, ImGuiTableFlags_None)) {+ float sharpe = perf.value("sharpeRatio", 0.0f);+ float max_dd = perf.value("maxDrawdown", 0.0f) * 100.0f;+ float win_rate = perf.value("winRate", 0.0f) * 100.0f;+ int total_trades = perf.value("totalTrades", 0);++ ImGui::TableNextColumn();+ ImGui::PushStyleColor(ImGuiCol_ChildBg, BG_PANEL);+ ImGui::BeginChild("##bt_sharpe", ImVec2(0, 52), ImGuiChildFlags_Borders);+ ImGui::TextColored(TEXT_DIM, "SHARPE RATIO");+ ImGui::TextColored(sharpe > 1 ? SUCCESS : INFO, "%.2f", sharpe);+ ImGui::EndChild();+ ImGui::PopStyleColor();++ ImGui::TableNextColumn();+ ImGui::PushStyleColor(ImGuiCol_ChildBg, BG_PANEL);+ ImGui::BeginChild("##bt_maxdd", ImVec2(0, 52), ImGuiChildFlags_Borders);+ ImGui::TextColored(TEXT_DIM, "MAX DRAWDOWN");+ ImGui::TextColored(ERROR_RED, "%.2f%%", max_dd);+ ImGui::EndChild();+ ImGui::PopStyleColor();++ ImGui::TableNextColumn();+ ImGui::PushStyleColor(ImGuiCol_ChildBg, BG_PANEL);+ ImGui::BeginChild("##bt_winrate", ImVec2(0, 52), ImGuiChildFlags_Borders);+ ImGui::TextColored(TEXT_DIM, "WIN RATE");+ ImGui::TextColored(win_rate > 50 ? SUCCESS : WARNING, "%.1f%%", win_rate);+ ImGui::EndChild();+ ImGui::PopStyleColor();++ ImGui::TableNextColumn();+ ImGui::PushStyleColor(ImGuiCol_ChildBg, BG_PANEL);+ ImGui::BeginChild("##bt_trades", ImVec2(0, 52), ImGuiChildFlags_Borders);+ ImGui::TextColored(TEXT_DIM, "TOTAL TRADES");+ ImGui::TextColored(INFO, "%d", total_trades);+ ImGui::EndChild();+ ImGui::PopStyleColor();++ ImGui::EndTable();+ }++ ImGui::Spacing();++ // Trade breakdown+ int total_trades = perf.value("totalTrades", 0);+ if (total_trades > 0) {+ int winning = perf.value("winningTrades", 0);+ int losing = perf.value("losingTrades", 0);+ float profit_factor = perf.value("profitFactor", 0.0f);++ char buf[32];+ snprintf(buf, sizeof(buf), "%d", winning);+ MetricRow("Winning Trades", buf, SUCCESS);+ snprintf(buf, sizeof(buf), "%d", losing);+ MetricRow("Losing Trades", buf, ERROR_RED);+ snprintf(buf, sizeof(buf), "%.2f", profit_factor);+ MetricRow("Profit Factor", buf, profit_factor > 1 ? SUCCESS : ERROR_RED);+ }+}++// =============================================================================+// Result metrics+// =============================================================================+void BacktestingScreen::render_result_metrics() {+ using namespace theme::colors;++ json perf;+ if (result_.contains("data") && result_["data"].is_object() && result_["data"].contains("performance"))+ perf = result_["data"]["performance"];+ else+ perf = result_.value("performance", json());++ if (perf.empty()) {+ ImGui::TextColored(TEXT_DIM, "No metrics available.");+ return;+ }++ struct MetricCategory {+ const char* name;+ std::vector<const char*> keys;+ };++ MetricCategory categories[] = {+ {"RETURNS", {"totalReturn", "annualizedReturn", "CAGR", "expectancy"}},+ {"RISK METRICS", {"sharpeRatio", "sortinoRatio", "calmarRatio", "volatility", "maxDrawdown"}},+ {"TRADE STATISTICS", {"totalTrades", "winningTrades", "losingTrades", "winRate", "profitFactor"}},+ {"TRADE PERFORMANCE", {"averageWin", "averageLoss", "largestWin", "largestLoss"}},+ };++ for (auto& cat : categories) {+ bool has_any = false;+ for (auto& key : cat.keys) {+ if (perf.contains(key)) { has_any = true; break; }+ }+ if (!has_any) continue;++ ImGui::TextColored(ACCENT, "%s", cat.name);+ ImGui::Spacing();++ for (auto& key : cat.keys) {+ if (!perf.contains(key)) continue;+ auto& val = perf[key];++ char value_str[64];+ ImVec4 color = INFO;++ // Format based on key type+ std::string k(key);+ if (k == "totalReturn" || k == "annualizedReturn" || k == "maxDrawdown"+ || k == "winRate" || k == "volatility") {+ float v = val.get<float>() * 100.0f;+ snprintf(value_str, sizeof(value_str), "%.2f%%", v);+ if (k == "maxDrawdown") color = ERROR_RED;+ else if (k == "winRate") color = v > 50 ? SUCCESS : WARNING;+ else color = v > 0 ? SUCCESS : ERROR_RED;+ }+ else if (k == "sharpeRatio" || k == "sortinoRatio" || k == "calmarRatio" || k == "profitFactor") {+ float v = val.get<float>();+ snprintf(value_str, sizeof(value_str), "%.2f", v);+ color = v > 0 ? SUCCESS : ERROR_RED;+ }+ else if (k == "totalTrades" || k == "winningTrades" || k == "losingTrades") {+ snprintf(value_str, sizeof(value_str), "%d", val.get<int>());+ color = INFO;+ }+ else if (k == "averageWin" || k == "averageLoss" || k == "largestWin"+ || k == "largestLoss" || k == "expectancy") {+ snprintf(value_str, sizeof(value_str), "$%.2f", val.get<float>());+ color = val.get<float>() > 0 ? SUCCESS : ERROR_RED;+ }+ else {+ snprintf(value_str, sizeof(value_str), "%s", val.dump().c_str());+ }++ // Display label with camelCase to readable+ std::string label(key);+ // Insert spaces before capitals+ std::string readable;+ for (size_t i = 0; i < label.size(); i++) {+ if (i > 0 && label[i] >= 'A' && label[i] <= 'Z')+ readable += ' ';+ readable += label[i];+ }++ MetricRow(readable.c_str(), value_str, color);+ }++ ImGui::Spacing();+ }+}++// =============================================================================+// Result trades+// =============================================================================+void BacktestingScreen::render_result_trades() {+ using namespace theme::colors;++ json trades;+ if (result_.contains("data") && result_["data"].is_object() && result_["data"].contains("trades"))+ trades = result_["data"]["trades"];++ if (!trades.is_array() || trades.empty()) {+ ImGui::TextColored(TEXT_DIM, "No trade data available.");+ return;+ }++ ImGui::TextColored(ACCENT, "TRADES (%zu)", trades.size());+ ImGui::Spacing();++ if (ImGui::BeginTable("##bt_trades_tbl", 5,+ ImGuiTableFlags_Borders | ImGuiTableFlags_RowBg |+ ImGuiTableFlags_ScrollY | ImGuiTableFlags_Resizable)) {+ ImGui::TableSetupScrollFreeze(0, 1);+ ImGui::TableSetupColumn("Entry Date");+ ImGui::TableSetupColumn("Exit Date");+ ImGui::TableSetupColumn("Side");+ ImGui::TableSetupColumn("PnL");+ ImGui::TableSetupColumn("Return");+ ImGui::TableHeadersRow();++ for (auto& trade : trades) {+ ImGui::TableNextRow();+ ImGui::TableNextColumn();+ ImGui::Text("%s", trade.value("entryDate", trade.value("entry_date", "-")).c_str());+ ImGui::TableNextColumn();+ ImGui::Text("%s", trade.value("exitDate", trade.value("exit_date", "-")).c_str());+ ImGui::TableNextColumn();+ ImGui::Text("%s", trade.value("side", trade.value("direction", "-")).c_str());+ ImGui::TableNextColumn();+ float pnl = trade.value("pnl", trade.value("profit", 0.0f));+ ImGui::TextColored(pnl >= 0 ? SUCCESS : ERROR_RED, "$%.2f", pnl);+ ImGui::TableNextColumn();+ float ret = trade.value("return", trade.value("returnPct", 0.0f));+ ImGui::TextColored(ret >= 0 ? SUCCESS : ERROR_RED, "%.2f%%", ret * 100);+ }+ ImGui::EndTable();+ }+}++// =============================================================================+// Result raw JSON+// =============================================================================+void BacktestingScreen::render_result_raw() {+ using namespace theme::colors;++ ImGui::TextColored(ACCENT, "RAW JSON");+ ImGui::Spacing();++ std::string raw = result_.dump(2);+ // Truncate for display+ if (raw.size() > 8000) raw = raw.substr(0, 8000) + "\n... (truncated)";++ ImGui::PushStyleColor(ImGuiCol_FrameBg, BG_DARKEST);+ ImGui::InputTextMultiline("##bt_raw_json", const_cast<char*>(raw.c_str()), raw.size() + 1,+ ImVec2(-1, -1), ImGuiInputTextFlags_ReadOnly);+ ImGui::PopStyleColor();+}++// =============================================================================+// Result charts — equity curve + drawdown using ImPlot+// =============================================================================+void BacktestingScreen::render_result_charts() {+ using namespace theme::colors;++ json equity_data;+ if (result_.contains("data") && result_["data"].is_object() && result_["data"].contains("equity"))+ equity_data = result_["data"]["equity"];++ if (!equity_data.is_array() || equity_data.empty()) {+ EmptyState("No equity curve data", "Run a backtest to see charts");+ return;+ }++ // Extract data into vectors+ std::vector<float> equity_vals;+ std::vector<float> drawdown_vals;+ std::vector<std::string> dates;++ for (size_t i = 0; i < equity_data.size(); i++) {+ auto& item = equity_data[i];+ if (item.is_number()) {+ equity_vals.push_back(item.get<float>());+ drawdown_vals.push_back(0.0f);+ char buf[16]; snprintf(buf, sizeof(buf), "Day %zu", i + 1);+ dates.push_back(buf);+ } else if (item.is_object()) {+ equity_vals.push_back(item.value("equity", item.value("value", 0.0f)));+ drawdown_vals.push_back(item.value("drawdown", 0.0f));+ dates.push_back(item.value("date", ""));+ }+ }++ int n = (int)equity_vals.size();+ if (n == 0) {+ EmptyState("No equity data points", "Check raw output");+ return;+ }++ // Equity Curve section+ ImGui::TextColored(SUCCESS, "EQUITY CURVE");+ ImGui::Spacing();++ ImGui::PushStyleColor(ImGuiCol_ChildBg, BG_PANEL);+ ImGui::BeginChild("##bt_equity_chart", ImVec2(0, 160), ImGuiChildFlags_Borders);++ // Simple text-based chart representation (ImPlot not always available)+ float min_eq = equity_vals[0], max_eq = equity_vals[0];+ for (float v : equity_vals) {+ if (v < min_eq) min_eq = v;+ if (v > max_eq) max_eq = v;+ }+ float range = max_eq - min_eq;+ if (range < 0.01f) range = 1.0f;++ // Show key data points+ ImGui::TextColored(TEXT_DIM, "Start: $%.0f | End: $%.0f | Points: %d", equity_vals.front(), equity_vals.back(), n);+ ImGui::TextColored(TEXT_DIM, "Min: $%.0f | Max: $%.0f", min_eq, max_eq);+ ImGui::Spacing();++ // Mini sparkline using progress bars+ float avail_w = ImGui::GetContentRegionAvail().x;+ int bars = std::min(n, (int)avail_w / 3);+ int step = std::max(1, n / bars);++ for (int i = 0; i < bars; i++) {+ int idx = std::min(i * step, n - 1);+ float frac = (equity_vals[idx] - min_eq) / range;+ ImVec4 bar_col = equity_vals[idx] >= equity_vals[0] ? SUCCESS : ERROR_RED;+ ImGui::PushStyleColor(ImGuiCol_PlotHistogram, bar_col);+ ImGui::PushStyleColor(ImGuiCol_FrameBg, BG_DARKEST);+ ImGui::SetCursorPosX(ImGui::GetCursorPosX() + i * 3.0f);+ ImGui::ProgressBar(frac, ImVec2(2, 80), "");+ ImGui::PopStyleColor(2);+ if (i < bars - 1) ImGui::SameLine(0, 1);+ }++ ImGui::EndChild();+ ImGui::PopStyleColor();++ ImGui::Spacing();++ // Drawdown section+ bool has_dd = false;+ for (float v : drawdown_vals) { if (v != 0.0f) { has_dd = true; break; } }++ if (has_dd) {+ ImGui::TextColored(ERROR_RED, "DRAWDOWN");+ ImGui::Spacing();++ float min_dd = 0, max_dd_abs = 0;+ for (float v : drawdown_vals) {+ if (v < min_dd) min_dd = v;+ if (std::abs(v) > max_dd_abs) max_dd_abs = std::abs(v);+ }++ ImGui::TextColored(TEXT_DIM, "Max Drawdown: %.2f%%", min_dd * 100.0f);+ ImGui::Spacing();++ // Drawdown bars+ if (max_dd_abs > 0) {+ int dd_bars = std::min(n, (int)avail_w / 3);+ int dd_step = std::max(1, n / dd_bars);+ for (int i = 0; i < dd_bars; i++) {+ int idx = std::min(i * dd_step, n - 1);+ float frac = std::abs(drawdown_vals[idx]) / max_dd_abs;+ ImGui::PushStyleColor(ImGuiCol_PlotHistogram, ERROR_RED);+ ImGui::PushStyleColor(ImGuiCol_FrameBg, BG_DARKEST);+ ImGui::ProgressBar(frac, ImVec2(2, 40), "");+ ImGui::PopStyleColor(2);+ if (i < dd_bars - 1) ImGui::SameLine(0, 1);+ }+ }+ }+}++// =============================================================================+// Result drawdowns — detailed drawdown metrics+// =============================================================================+void BacktestingScreen::render_result_drawdowns() {+ using namespace theme::colors;++ json perf;+ if (result_.contains("data") && result_["data"].is_object()) {+ if (result_["data"].contains("performance"))+ perf = result_["data"]["performance"];+ if (result_["data"].contains("drawdowns")) {+ auto& dd = result_["data"]["drawdowns"];+ for (auto it = dd.begin(); it != dd.end(); ++it)+ perf[it.key()] = it.value();+ }+ }++ if (perf.empty()) {+ ImGui::TextColored(TEXT_DIM, "No drawdown data available.");+ return;+ }++ // Max drawdown highlight+ if (perf.contains("maxDrawdown")) {+ float max_dd = perf["maxDrawdown"].get<float>() * 100.0f;++ ImGui::PushStyleColor(ImGuiCol_ChildBg, ImVec4(ERROR_RED.x, ERROR_RED.y, ERROR_RED.z, 0.1f));+ ImGui::BeginChild("##bt_maxdd_highlight", ImVec2(0, 52), ImGuiChildFlags_Borders);+ ImGui::TextColored(ERROR_RED, "MAX DRAWDOWN");+ ImGui::SetWindowFontScale(1.5f);+ ImGui::TextColored(ERROR_RED, "%.2f%%", max_dd);+ ImGui::SetWindowFontScale(1.0f);+ ImGui::EndChild();+ ImGui::PopStyleColor();+ ImGui::Spacing();+ }++ ImGui::TextColored(ACCENT, "DRAWDOWN METRICS");+ ImGui::Spacing();++ struct DDMetric { const char* key; const char* label; const char* desc; };+ static const DDMetric dd_metrics[] = {+ {"maxDrawdown", "Max Drawdown", "Largest peak-to-trough decline"},+ {"maxDrawdownDuration", "Max DD Duration", "Longest time in drawdown (days)"},+ {"avgDrawdown", "Avg Drawdown", "Average drawdown depth"},+ {"avgDrawdownDuration", "Avg DD Duration", "Average drawdown duration (days)"},+ {"avgRecoveryDuration", "Avg Recovery", "Average time to recover (days)"},+ {"activeDrawdown", "Active Drawdown", "Current unrecovered drawdown"},+ {"calmarRatio", "Calmar Ratio", "Annualized return / max drawdown"},+ {"ulcerIndex", "Ulcer Index", "Root mean square of drawdowns"},+ {"painIndex", "Pain Index", "Mean drawdown over period"},+ {"painRatio", "Pain Ratio", "Return / pain index"},+ {"martinRatio", "Martin Ratio", "Return / ulcer index"},+ {"burkeFactor", "Burke Factor", "Return adjusted by DD variability"},+ {"maxConsecutiveLosses", "Max Consecutive Losses", "Longest losing streak"},+ {"maxConsecutiveWins", "Max Consecutive Wins", "Longest winning streak"},+ };++ for (auto& m : dd_metrics) {+ if (!perf.contains(m.key)) continue;+ auto& val = perf[m.key];+ char buf[64];+ ImVec4 color = INFO;++ std::string k(m.key);+ if (k == "maxDrawdown" || k == "avgDrawdown" || k == "activeDrawdown") {+ snprintf(buf, sizeof(buf), "%.2f%%", val.get<float>() * 100.0f);+ color = ERROR_RED;+ } else if (k == "calmarRatio" || k == "painRatio" || k == "martinRatio" || k == "burkeFactor") {+ snprintf(buf, sizeof(buf), "%.2f", val.get<float>());+ color = val.get<float>() > 0 ? SUCCESS : ERROR_RED;+ } else if (val.is_number_float()) {+ snprintf(buf, sizeof(buf), "%.2f", val.get<float>());+ } else {+ snprintf(buf, sizeof(buf), "%s", val.dump().c_str());+ }++ // Row with description tooltip+ MetricRow(m.label, buf, color);+ if (ImGui::IsItemHovered()) ImGui::SetTooltip("%s", m.desc);+ }+}++// =============================================================================+// Result indicator — parameter sweep results+// =============================================================================+void BacktestingScreen::render_result_indicator() {+ using namespace theme::colors;++ json data;+ if (result_.contains("data") && result_["data"].is_object())+ data = result_["data"];+ else {+ render_result_raw();+ return;+ }++ std::string indicator = data.value("indicator", "Unknown");+ int total_combos = data.value("totalCombinations", 0);+ json results = data.value("results", json::array());++ // Status badge+ ImGui::TextColored(SUCCESS, "INDICATOR SWEEP COMPLETED");+ ImGui::Spacing();++ // Summary card+ ImGui::PushStyleColor(ImGuiCol_ChildBg, BG_PANEL);+ ImGui::BeginChild("##bt_ind_summary", ImVec2(0, 48), ImGuiChildFlags_Borders);+ std::string title = indicator;+ for (auto& c : title) c = (char)toupper(c);+ ImGui::TextColored(TEXT_PRIMARY, "%s PARAMETER SWEEP", title.c_str());+ ImGui::TextColored(TEXT_DIM, "Total Combinations: %d", total_combos);+ ImGui::EndChild();+ ImGui::PopStyleColor();++ ImGui::Spacing();++ if (results.is_array() && !results.empty()) {+ ImGui::TextColored(TEXT_DIM, "PARAMETER COMBINATIONS (showing first 20)");+ ImGui::Spacing();++ int shown = 0;+ for (auto& r : results) {+ if (shown >= 20) break;++ ImGui::PushStyleColor(ImGuiCol_ChildBg, ImVec4(ACCENT.x, ACCENT.y, ACCENT.z, 0.06f));+ char child_id[32]; snprintf(child_id, sizeof(child_id), "##bt_ind_r%d", shown);++ // Check if multi-output+ bool is_multi = r.contains("outputs") && r["outputs"].is_object() && !r["outputs"].empty();++ if (is_multi) {+ ImGui::BeginChild(child_id, ImVec2(0, 0), ImGuiChildFlags_Borders | ImGuiChildFlags_AutoResizeY);+ // Params+ ImGui::TextColored(TEXT_DIM, "Params:");+ ImGui::SameLine();+ ImGui::TextColored(TEXT_PRIMARY, "%s", r.value("params", json()).dump().c_str());+ ImGui::Separator();++ // Components+ auto& outputs = r["outputs"];+ for (auto it = outputs.begin(); it != outputs.end(); ++it) {+ auto& comp = it.value();+ std::string comp_name = it.key();+ for (auto& c : comp_name) c = (char)toupper(c);+ ImGui::TextColored(INFO, "%s", comp_name.c_str());+ if (comp.contains("mean"))+ ImGui::Text("Mean: %.2f Std: %.2f Last: %.2f Range: %.2f-%.2f",+ comp.value("mean", 0.0f), comp.value("std", 0.0f),+ comp.value("last", 0.0f), comp.value("min", 0.0f), comp.value("max", 0.0f));+ }+ ImGui::EndChild();+ } else {+ ImGui::BeginChild(child_id, ImVec2(0, 36), ImGuiChildFlags_Borders);+ ImGui::TextColored(TEXT_DIM, "Params:");+ ImGui::SameLine();+ ImGui::TextColored(TEXT_PRIMARY, "%s", r.value("params", json()).dump().c_str());+ ImGui::SameLine(0, 12);+ ImGui::TextColored(INFO, "Mean: %.2f", r.value("mean", 0.0f));+ ImGui::SameLine(0, 8);+ ImGui::TextColored(ACCENT, "Last: %.2f", r.value("last", 0.0f));+ ImGui::SameLine(0, 8);+ ImGui::TextColored(TEXT_DIM, "Range: %.2f-%.2f", r.value("min", 0.0f), r.value("max", 0.0f));+ ImGui::EndChild();+ }+ ImGui::PopStyleColor();+ shown++;+ }+ } else {+ ImGui::TextColored(WARNING, "No parameter combinations generated. Check parameter ranges.");+ }+}++// =============================================================================+// Result signals — entry/exit signals from indicator_signals command+// =============================================================================+void BacktestingScreen::render_result_signals() {+ using namespace theme::colors;++ json data;+ if (result_.contains("data") && result_["data"].is_object())+ data = result_["data"];+ else {+ render_result_raw();+ return;+ }++ std::string symbol = data.value("symbol", "");+ ImGui::TextColored(SUCCESS, "SIGNALS GENERATED%s%s", symbol.empty() ? "" : " - ", symbol.c_str());+ ImGui::Spacing();++ // Performance metrics (if available)+ bool has_metrics = data.contains("avgReturn");+ if (has_metrics) {+ ImGui::TextColored(ACCENT, "SIGNAL PERFORMANCE METRICS");+ ImGui::Spacing();++ if (ImGui::BeginTable("##bt_sig_perf", 4, ImGuiTableFlags_None)) {+ auto metric_cell = [](const char* label, const char* fmt, float val, ImVec4 col) {+ ImGui::TableNextColumn();+ ImGui::TextColored(ImVec4(0.5f, 0.5f, 0.5f, 1.0f), "%s", label);+ char buf[32]; snprintf(buf, sizeof(buf), fmt, val);+ ImGui::TextColored(col, "%s", buf);+ };++ float win_rate = data.value("winRate", 0.0f);+ float avg_ret = data.value("avgReturn", 0.0f);+ float pf = data.value("profitFactor", 0.0f);+ int total_sig = data.value("totalSignals", 0);++ metric_cell("WIN RATE", "%.1f%%", win_rate, win_rate >= 50 ? SUCCESS : ERROR_RED);+ metric_cell("AVG RETURN", "%.2f%%", avg_ret, avg_ret >= 0 ? SUCCESS : ERROR_RED);+ metric_cell("PROFIT FACTOR", "%.2f", pf, INFO);++ ImGui::TableNextColumn();+ ImGui::TextColored(ImVec4(0.5f, 0.5f, 0.5f, 1.0f), "SIGNALS");+ ImGui::TextColored(TEXT_PRIMARY, "%d", total_sig);++ // Second row+ float best = data.value("bestTrade", 0.0f);+ float worst = data.value("worstTrade", 0.0f);+ float avg_hold = data.value("avgHoldingPeriod", 0.0f);+ float sig_dens = data.value("signalDensity", 0.0f);++ metric_cell("BEST TRADE", "+%.2f%%", best, SUCCESS);+ metric_cell("WORST TRADE", "%.2f%%", worst, ERROR_RED);+ metric_cell("AVG HOLD (DAYS)", "%.0f", avg_hold, TEXT_PRIMARY);+ metric_cell("SIGNAL DENSITY", "%.1f%%", sig_dens, WARNING);++ ImGui::EndTable();+ }+ ImGui::Spacing();+ }++ // Signal counts+ int entry_count = data.value("entryCount", 0);+ int exit_count = data.value("exitCount", 0);+ int total_bars = data.value("totalBars", 0);++ ImGui::PushStyleColor(ImGuiCol_ChildBg, BG_PANEL);+ ImGui::BeginChild("##bt_sig_counts", ImVec2(0, 52), ImGuiChildFlags_Borders);+ if (ImGui::BeginTable("##bt_sig_cnt_tbl", 3, ImGuiTableFlags_None)) {+ ImGui::TableNextColumn();+ ImGui::TextColored(TEXT_DIM, "ENTRY SIGNALS");+ ImGui::TextColored(SUCCESS, "%d", entry_count);++ ImGui::TableNextColumn();+ ImGui::TextColored(TEXT_DIM, "EXIT SIGNALS");+ ImGui::TextColored(ERROR_RED, "%d", exit_count);++ ImGui::TableNextColumn();+ ImGui::TextColored(TEXT_DIM, "TOTAL BARS");+ ImGui::TextColored(TEXT_PRIMARY, "%d", total_bars);++ ImGui::EndTable();+ }+ ImGui::EndChild();+ ImGui::PopStyleColor();++ ImGui::Spacing();++ // Entry signals detail+ json entries = data.value("entrySignals", data.value("entries", json::array()));+ if (entries.is_array() && !entries.empty()) {+ ImGui::TextColored(TEXT_DIM, "ENTRY SIGNALS (showing first 10)");+ ImGui::Spacing();++ int shown = 0;+ for (auto& sig : entries) {+ if (shown >= 10) break;+ char id[32]; snprintf(id, sizeof(id), "##bt_entry_%d", shown);+ ImGui::PushStyleColor(ImGuiCol_ChildBg, ImVec4(SUCCESS.x, SUCCESS.y, SUCCESS.z, 0.08f));+ ImGui::BeginChild(id, ImVec2(0, 20), ImGuiChildFlags_Borders);+ if (sig.is_object()) {+ ImGui::TextColored(TEXT_DIM, "Date:"); ImGui::SameLine();+ ImGui::TextColored(TEXT_PRIMARY, "%s", sig.value("date", "-").c_str());+ ImGui::SameLine(0, 8);+ ImGui::TextColored(TEXT_DIM, "Price:"); ImGui::SameLine();+ ImGui::TextColored(INFO, "$%.2f", sig.value("price", 0.0f));+ } else {+ ImGui::TextColored(TEXT_PRIMARY, "%s", sig.dump().c_str());+ }+ ImGui::EndChild();+ ImGui::PopStyleColor();+ shown++;+ }+ ImGui::Spacing();+ }++ // Exit signals detail+ json exits = data.value("exitSignals", data.value("exits", json::array()));+ if (exits.is_array() && !exits.empty()) {+ ImGui::TextColored(TEXT_DIM, "EXIT SIGNALS (showing first 10)");+ ImGui::Spacing();++ int shown = 0;+ for (auto& sig : exits) {+ if (shown >= 10) break;+ char id[32]; snprintf(id, sizeof(id), "##bt_exit_%d", shown);+ ImGui::PushStyleColor(ImGuiCol_ChildBg, ImVec4(ERROR_RED.x, ERROR_RED.y, ERROR_RED.z, 0.08f));+ ImGui::BeginChild(id, ImVec2(0, 20), ImGuiChildFlags_Borders);+ if (sig.is_object()) {+ ImGui::TextColored(TEXT_DIM, "Date:"); ImGui::SameLine();+ ImGui::TextColored(TEXT_PRIMARY, "%s", sig.value("date", "-").c_str());+ ImGui::SameLine(0, 8);+ ImGui::TextColored(TEXT_DIM, "Price:"); ImGui::SameLine();+ ImGui::TextColored(INFO, "$%.2f", sig.value("price", 0.0f));+ } else {+ ImGui::TextColored(TEXT_PRIMARY, "%s", sig.dump().c_str());+ }+ ImGui::EndChild();+ ImGui::PopStyleColor();+ shown++;+ }+ }+}++// =============================================================================+// Result signal generator — random/generated signals display+// =============================================================================+void BacktestingScreen::render_result_signal_generator() {+ using namespace theme::colors;++ json data;+ if (result_.contains("data") && result_["data"].is_object())+ data = result_["data"];++ if (data.empty()) {+ EmptyState("No signal data available", "");+ return;+ }++ json entries = data.value("entries", data.value("entrySignals", json::array()));+ json exits = data.value("exits", data.value("exitSignals", json::array()));+ int total_entries = data.value("totalEntries", entries.is_array() ? (int)entries.size() : 0);+ int total_exits = data.value("totalExits", exits.is_array() ? (int)exits.size() : 0);++ ImGui::TextColored(ACCENT, "SIGNAL SUMMARY");+ ImGui::Spacing();++ // Summary grid+ ImGui::PushStyleColor(ImGuiCol_ChildBg, BG_PANEL);+ ImGui::BeginChild("##bt_siggen_summary", ImVec2(0, 52), ImGuiChildFlags_Borders);+ if (ImGui::BeginTable("##bt_siggen_tbl", 3, ImGuiTableFlags_None)) {+ ImGui::TableNextColumn();+ ImGui::TextColored(TEXT_DIM, "ENTRIES");+ ImGui::TextColored(SUCCESS, "%d", total_entries);++ ImGui::TableNextColumn();+ ImGui::TextColored(TEXT_DIM, "EXITS");+ ImGui::TextColored(ERROR_RED, "%d", total_exits);++ ImGui::TableNextColumn();+ if (data.contains("signalDensity")) {+ ImGui::TextColored(TEXT_DIM, "DENSITY");+ ImGui::TextColored(INFO, "%.1f%%", data["signalDensity"].get<float>() * 100.0f);+ }+ ImGui::EndTable();+ }+ ImGui::EndChild();+ ImGui::PopStyleColor();++ ImGui::Spacing();++ // Signal timeline preview+ json signals = data.value("signals", json::array());+ if (signals.is_array() && !signals.empty()) {+ ImGui::TextColored(ACCENT, "SIGNAL TIMELINE (FIRST 20)");+ ImGui::Spacing();++ int shown = 0;+ for (auto& sig : signals) {+ if (shown >= 20) break;+ bool is_entry = false;+ if (sig.is_object()) is_entry = sig.value("type", "") == "entry";+ else if (sig.is_number()) is_entry = sig.get<int>() == 1;+ else if (sig.is_boolean()) is_entry = sig.get<bool>();++ ImVec4 col = is_entry ? SUCCESS : ERROR_RED;+ const char* label = is_entry ? "E" : "X";++ ImGui::PushStyleColor(ImGuiCol_Button, ImVec4(col.x, col.y, col.z, 0.15f));+ ImGui::PushStyleColor(ImGuiCol_ButtonHovered, ImVec4(col.x, col.y, col.z, 0.25f));+ ImGui::PushStyleColor(ImGuiCol_Text, col);+ char btn_id[32]; snprintf(btn_id, sizeof(btn_id), "%s##sg%d", label, shown);+ ImGui::SmallButton(btn_id);+ ImGui::PopStyleColor(3);+ if (shown < 19) ImGui::SameLine(0, 2);+ shown++;+ }+ }+ // Entry timestamps fallback+ else if (entries.is_array() && !entries.empty()) {+ ImGui::TextColored(SUCCESS, "ENTRY SIGNALS (FIRST 20)");+ ImGui::Spacing();++ int shown = 0;+ for (auto& e : entries) {+ if (shown >= 20) break;+ ImGui::PushStyleColor(ImGuiCol_Button, ImVec4(SUCCESS.x, SUCCESS.y, SUCCESS.z, 0.15f));+ ImGui::PushStyleColor(ImGuiCol_Text, SUCCESS);+ char btn_id[64];+ if (e.is_string())+ snprintf(btn_id, sizeof(btn_id), "%s##se%d", e.get<std::string>().c_str(), shown);+ else+ snprintf(btn_id, sizeof(btn_id), "#%d##se%d", shown + 1, shown);+ ImGui::SmallButton(btn_id);+ ImGui::PopStyleColor(2);+ if (shown < 19) ImGui::SameLine(0, 2);+ shown++;+ }+ }+}++// =============================================================================+// Result labels — ML label generation results+// =============================================================================+void BacktestingScreen::render_result_labels() {+ using namespace theme::colors;++ json data;+ if (result_.contains("data") && result_["data"].is_object())+ data = result_["data"];++ if (data.empty()) {+ EmptyState("No label data available", "");+ return;+ }++ json distribution = data.value("distribution", json::object());+ json labels = data.value("labels", json::array());+ int total_labels = data.value("totalLabels", labels.is_array() ? (int)labels.size() : 0);++ ImGui::TextColored(ACCENT, "LABEL SUMMARY");+ ImGui::Spacing();++ // Summary+ ImGui::PushStyleColor(ImGuiCol_ChildBg, BG_PANEL);+ ImGui::BeginChild("##bt_lbl_summary", ImVec2(0, 52), ImGuiChildFlags_Borders);+ if (ImGui::BeginTable("##bt_lbl_sum_tbl", 2, ImGuiTableFlags_None)) {+ ImGui::TableNextColumn();+ ImGui::TextColored(TEXT_DIM, "TOTAL");+ ImGui::TextColored(TEXT_PRIMARY, "%d", total_labels);++ ImGui::TableNextColumn();+ if (data.contains("signalDensity")) {+ ImGui::TextColored(TEXT_DIM, "DENSITY");+ ImGui::TextColored(INFO, "%.1f%%", data["signalDensity"].get<float>() * 100.0f);+ }+ ImGui::EndTable();+ }+ ImGui::EndChild();+ ImGui::PopStyleColor();++ ImGui::Spacing();++ // Distribution+ if (distribution.is_object() && !distribution.empty()) {+ ImGui::TextColored(ACCENT, "LABEL DISTRIBUTION");+ ImGui::Spacing();++ for (auto it = distribution.begin(); it != distribution.end(); ++it) {+ std::string label = it.key();+ int count = it.value().is_number() ? it.value().get<int>() : 0;+ float pct = total_labels > 0 ? (float)count / total_labels * 100.0f : 0;++ ImVec4 col = TEXT_DIM;+ if (label == "1" || label == "buy") col = SUCCESS;+ else if (label == "-1" || label == "sell") col = ERROR_RED;++ char val_buf[64];+ snprintf(val_buf, sizeof(val_buf), "%d (%.1f%%)", count, pct);++ std::string upper_label = label;+ for (auto& c : upper_label) c = (char)toupper(c);++ MetricRow(upper_label.c_str(), val_buf, col);+ }+ ImGui::Spacing();+ }++ // Label preview+ if (labels.is_array() && !labels.empty()) {+ ImGui::TextColored(ACCENT, "LABEL PREVIEW (FIRST 20)");+ ImGui::Spacing();++ int shown = 0;+ for (auto& lbl : labels) {+ if (shown >= 20) break;++ int val = 0;+ if (lbl.is_number()) val = lbl.get<int>();+ else if (lbl.is_object() && lbl.contains("label")) val = lbl["label"].get<int>();++ ImVec4 col = TEXT_DIM;+ if (val == 1) col = SUCCESS;+ else if (val == -1) col = ERROR_RED;++ char btn_id[32]; snprintf(btn_id, sizeof(btn_id), "%d##lb%d", val, shown);+ ImGui::PushStyleColor(ImGuiCol_Button, ImVec4(col.x, col.y, col.z, 0.15f));+ ImGui::PushStyleColor(ImGuiCol_Text, col);+ ImGui::SmallButton(btn_id);+ ImGui::PopStyleColor(2);+ if (shown < 19) ImGui::SameLine(0, 2);+ shown++;+ }+ }+}++// =============================================================================+// Result splitters — cross-validation split results+// =============================================================================+void BacktestingScreen::render_result_splitters() {+ using namespace theme::colors;++ json data;+ if (result_.contains("data") && result_["data"].is_object())+ data = result_["data"];++ if (data.empty()) {+ EmptyState("No split data available", "");+ return;+ }++ json splits = data.value("splits", json::array());+ int n_splits = data.value("nSplits", splits.is_array() ? (int)splits.size() : 0);++ ImGui::TextColored(ACCENT, "SPLIT SUMMARY");+ ImGui::Spacing();++ // Summary+ ImGui::PushStyleColor(ImGuiCol_ChildBg, BG_PANEL);+ ImGui::BeginChild("##bt_spl_summary", ImVec2(0, 52), ImGuiChildFlags_Borders);+ if (ImGui::BeginTable("##bt_spl_sum_tbl", 2, ImGuiTableFlags_None)) {+ ImGui::TableNextColumn();+ ImGui::TextColored(TEXT_DIM, "SPLITS");+ ImGui::TextColored(TEXT_PRIMARY, "%d", n_splits);++ ImGui::TableNextColumn();+ if (data.contains("coverage")) {+ ImGui::TextColored(TEXT_DIM, "COVERAGE");+ auto& cov = data["coverage"];+ if (cov.is_number())+ ImGui::TextColored(INFO, "%.1f%%", cov.get<float>() * 100.0f);+ else+ ImGui::TextColored(INFO, "%s", cov.dump().c_str());+ }+ ImGui::EndTable();+ }+ ImGui::EndChild();+ ImGui::PopStyleColor();++ ImGui::Spacing();++ // Split ranges+ if (splits.is_array() && !splits.empty()) {+ ImGui::TextColored(ACCENT, "SPLIT RANGES");+ ImGui::Spacing();++ if (ImGui::BeginTable("##bt_split_ranges", 3,+ ImGuiTableFlags_Borders | ImGuiTableFlags_RowBg)) {+ ImGui::TableSetupColumn("#", ImGuiTableColumnFlags_WidthFixed, 30);+ ImGui::TableSetupColumn("Train");+ ImGui::TableSetupColumn("Test");+ ImGui::TableHeadersRow();++ int idx = 0;+ for (auto& split : splits) {+ ImGui::TableNextRow();+ ImGui::TableNextColumn();+ ImGui::TextColored(TEXT_DIM, "#%d", idx + 1);++ ImGui::TableNextColumn();+ std::string train_start = split.value("trainStart", split.value("train_start", "?"));+ std::string train_end = split.value("trainEnd", split.value("train_end", "?"));+ ImGui::TextColored(INFO, "%s -> %s", train_start.c_str(), train_end.c_str());++ ImGui::TableNextColumn();+ std::string test_start = split.value("testStart", split.value("test_start", "?"));+ std::string test_end = split.value("testEnd", split.value("test_end", "?"));+ ImGui::TextColored(SUCCESS, "%s -> %s", test_start.c_str(), test_end.c_str());++ idx++;+ }+ ImGui::EndTable();+ }+ }+}++// =============================================================================+// Result returns — returns analysis results+// =============================================================================+void BacktestingScreen::render_result_returns() {+ using namespace theme::colors;++ json data;+ if (result_.contains("data") && result_["data"].is_object())+ data = result_["data"];++ if (data.empty()) {+ EmptyState("No returns data available", "");+ return;+ }++ json metrics = data.value("performance", data.value("returns", data));++ struct RetMetric { const char* key; const char* label; };+ static const RetMetric ret_metrics[] = {+ {"totalReturn", "Total Return"},+ {"annualizedReturn", "Annualized Return"},+ {"volatility", "Volatility"},+ {"sharpeRatio", "Sharpe Ratio"},+ {"sortinoRatio", "Sortino Ratio"},+ {"calmarRatio", "Calmar Ratio"},+ {"VaR", "Value at Risk (95%)"},+ {"CVaR", "Conditional VaR"},+ {"upCapture", "Up Capture Ratio"},+ {"downCapture", "Down Capture Ratio"},+ {"skewness", "Skewness"},+ {"kurtosis", "Kurtosis"},+ {"CAGR", "CAGR"},+ {"tailRatio", "Tail Ratio"},+ {"commonSenseRatio", "Common Sense Ratio"},+ };++ // Check if any metrics exist+ bool has_any = false;+ for (auto& m : ret_metrics) {+ if (metrics.contains(m.key)) { has_any = true; break; }+ }++ if (has_any) {+ ImGui::TextColored(ACCENT, "RETURNS ANALYSIS");+ ImGui::Spacing();++ for (auto& m : ret_metrics) {+ if (!metrics.contains(m.key)) continue;+ auto& val = metrics[m.key];+ char buf[64];+ ImVec4 color = INFO;++ std::string k(m.key);+ if (k == "totalReturn" || k == "annualizedReturn" || k == "volatility" || k == "CAGR") {+ float v = val.get<float>() * 100.0f;+ snprintf(buf, sizeof(buf), "%.2f%%", v);+ color = v > 0 ? SUCCESS : ERROR_RED;+ } else if (k == "VaR" || k == "CVaR") {+ snprintf(buf, sizeof(buf), "%.4f", val.get<float>());+ color = ERROR_RED;+ } else {+ snprintf(buf, sizeof(buf), "%.4f", val.get<float>());+ color = val.get<float>() > 0 ? SUCCESS : ERROR_RED;+ }++ MetricRow(m.label, buf, color);+ }+ ImGui::Spacing();+ }++ // Rolling metrics+ json rolling = data.value("rolling", json());+ if (rolling.is_object() && !rolling.empty()) {+ ImGui::TextColored(INFO, "ROLLING METRICS");+ ImGui::Spacing();++ for (auto it = rolling.begin(); it != rolling.end(); ++it) {+ char buf[64];+ if (it.value().is_number())+ snprintf(buf, sizeof(buf), "%.4f", it.value().get<float>());+ else+ snprintf(buf, sizeof(buf), "%s", it.value().dump().c_str());++ // camelCase to readable+ std::string label = it.key();+ std::string readable;+ for (size_t i = 0; i < label.size(); i++) {+ if (i > 0 && label[i] >= 'A' && label[i] <= 'Z') readable += ' ';+ readable += label[i];+ }+ MetricRow(readable.c_str(), buf, INFO);+ }+ ImGui::Spacing();+ }++ // Benchmark comparison+ json benchmark = data.value("benchmark", json());+ if (benchmark.is_object() && !benchmark.empty()) {+ ImGui::TextColored(SUCCESS, "BENCHMARK COMPARISON");+ ImGui::Spacing();++ for (auto it = benchmark.begin(); it != benchmark.end(); ++it) {+ char buf[64];+ if (it.value().is_number())+ snprintf(buf, sizeof(buf), "%.4f", it.value().get<float>());+ else+ snprintf(buf, sizeof(buf), "%s", it.value().dump().c_str());++ std::string label = it.key();+ std::string readable;+ for (size_t i = 0; i < label.size(); i++) {+ if (i > 0 && label[i] >= 'A' && label[i] <= 'Z') readable += ' ';+ readable += label[i];+ }+ MetricRow(readable.c_str(), buf, SUCCESS);+ }+ }++ if (!has_any && rolling.empty() && benchmark.empty()) {+ ImGui::TextColored(TEXT_DIM, "Returns analysis returned no displayable metrics. Check raw output.");+ }+}++// =============================================================================+// Status bar+// =============================================================================+void BacktestingScreen::render_status_bar() {+ using namespace theme::colors;+ auto& info = get_provider_info(selected_provider_);+ auto color = provider_color(selected_provider_);++ ImGui::PushStyleColor(ImGuiCol_ChildBg, BG_WIDGET);+ ImGui::BeginChild("##bt_statusbar", ImVec2(0, 24));++ ImGui::TextColored(color, "%s", info.display_name);+ ImGui::SameLine(0, 12);+ ImGui::TextColored(BORDER_BRIGHT, "|");+ ImGui::SameLine(0, 8);+ ImGui::TextColored(TEXT_DIM, "CMD:");+ ImGui::SameLine(0, 4);+ ImGui::TextColored(TEXT_PRIMARY, "%s", command_label(active_command_));++ // Current strategy+ auto strats = get_strategies(selected_provider_, selected_category_);+ if (selected_strategy_idx_ < (int)strats.size()) {+ ImGui::SameLine(0, 12);+ ImGui::TextColored(BORDER_BRIGHT, "|");+ ImGui::SameLine(0, 8);+ ImGui::TextColored(TEXT_DIM, "STRATEGY:");+ ImGui::SameLine(0, 4);+ ImGui::TextColored(INFO, "%s", strats[selected_strategy_idx_].name);+ }++ // Status+ float right_x = ImGui::GetWindowWidth() - 80;+ ImGui::SameLine(right_x);+ bool running = data_.is_loading();+ ImGui::TextColored(running ? ACCENT : SUCCESS, "%s", running ? "RUNNING" : "READY");++ ImGui::EndChild();+ ImGui::PopStyleColor();+}++// =============================================================================+// Pickup result from async data+// =============================================================================+void BacktestingScreen::pickup_result() {+ if (!data_.has_result() && data_.error().empty()) return;+ std::lock_guard<std::mutex> lock(data_.mutex());+ if (data_.has_result()) {+ result_ = data_.result();+ has_error_ = false;+ error_msg_.clear();+ status_ = "Data loaded";+ status_time_ = ImGui::GetTime();+ } else if (!data_.error().empty()) {+ has_error_ = true;+ error_msg_ = data_.error();+ result_ = json();+ status_ = "Error: " + data_.error();+ status_time_ = ImGui::GetTime();+ }+ data_.clear();+}++// =============================================================================+// Execute command — build JSON args and run Python+// =============================================================================+void BacktestingScreen::execute_command() {+ auto& info = get_provider_info(selected_provider_);+ std::string py_command = command_to_python(selected_provider_, active_command_);+ std::string args_json = build_args_json();++ result_ = json();+ has_error_ = false;+ error_msg_.clear();+ status_ = "Running " + std::string(command_label(active_command_)) + "...";+ status_time_ = ImGui::GetTime();++ data_.run(info.script_dir, py_command, args_json);+}++// =============================================================================+// Build args JSON (mirrors Tauri handleRunCommand)+// =============================================================================+std::string BacktestingScreen::build_args_json() {+ json args;++ // Parse symbols+ json symbol_list = json::array();+ std::istringstream ss(symbols_);+ std::string sym;+ while (std::getline(ss, sym, ',')) {+ // Trim whitespace+ size_t start = sym.find_first_not_of(" \t");+ size_t end = sym.find_last_not_of(" \t");+ if (start != std::string::npos)+ symbol_list.push_back(sym.substr(start, end - start + 1));+ }++ auto strats = get_strategies(selected_provider_, selected_category_);+ std::string strat_id = (selected_strategy_idx_ < (int)strats.size())+ ? strats[selected_strategy_idx_].id : "sma_crossover";+ std::string strat_name = (selected_strategy_idx_ < (int)strats.size())+ ? strats[selected_strategy_idx_].name : "SMA Crossover";++ switch (active_command_) {+ case CommandType::Backtest: {+ json strategy;+ strategy["type"] = (strat_id == "code") ? "code" : strat_id;+ strategy["name"] = strat_name;+ if (strat_id == "code") {+ strategy["parameters"] = {{"code", custom_code_}};+ } else {+ json params;+ for (auto& [k, v] : strategy_params_) params[k] = v;+ strategy["parameters"] = params;+ }++ json assets = json::array();+ float weight = symbol_list.empty() ? 1.0f : 1.0f / (float)symbol_list.size();+ for (auto& s : symbol_list) {+ assets.push_back({{"symbol", s}, {"assetClass", "stocks"}, {"weight", weight}});+ }++ args["strategy"] = strategy;+ args["startDate"] = start_date_;+ args["endDate"] = end_date_;+ args["initialCapital"] = initial_capital_;+ args["assets"] = assets;+ args["commission"] = commission_ / 100.0f;+ args["slippage"] = slippage_ / 100.0f;+ args["leverage"] = leverage_;+ args["margin"] = margin_;+ args["stopLoss"] = stop_loss_ > 0 ? json(stop_loss_) : json(nullptr);+ args["takeProfit"] = take_profit_ > 0 ? json(take_profit_) : json(nullptr);+ args["trailingStop"] = trailing_stop_ > 0 ? json(trailing_stop_) : json(nullptr);+ args["positionSizing"] = position_sizing_options()[position_sizing_idx_].id;+ args["positionSizeValue"] = position_size_value_;+ args["allowShort"] = allow_short_;+ args["benchmarkSymbol"] = enable_benchmark_ ? json(benchmark_symbol_) : json(nullptr);+ args["randomBenchmark"] = random_benchmark_;+ break;+ }+ case CommandType::Optimize: {+ json strategy;+ strategy["type"] = strat_id;+ strategy["name"] = strat_name;++ json assets = json::array();+ float weight = symbol_list.empty() ? 1.0f : 1.0f / (float)symbol_list.size();+ for (auto& s : symbol_list) {+ assets.push_back({{"symbol", s}, {"assetClass", "stocks"}, {"weight", weight}});+ }++ json ranges;+ for (auto& [k, v] : param_ranges_) {+ ranges[k] = {{"min", v[0]}, {"max", v[1]}, {"step", v[2]}};+ }++ args["strategy"] = strategy;+ args["startDate"] = start_date_;+ args["endDate"] = end_date_;+ args["initialCapital"] = initial_capital_;+ args["assets"] = assets;+ args["parameters"] = ranges;+ args["objective"] = OPTIMIZE_OBJECTIVES[optimize_objective_idx_];+ args["method"] = OPTIMIZE_METHODS[optimize_method_idx_];+ args["maxIterations"] = max_iterations_;+ break;+ }+ case CommandType::WalkForward: {+ json strategy;+ strategy["type"] = strat_id;+ strategy["name"] = strat_name;+ json params;+ for (auto& [k, v] : strategy_params_) params[k] = v;+ strategy["parameters"] = params;++ json assets = json::array();+ float weight = symbol_list.empty() ? 1.0f : 1.0f / (float)symbol_list.size();+ for (auto& s : symbol_list) {+ assets.push_back({{"symbol", s}, {"assetClass", "stocks"}, {"weight", weight}});+ }++ args["strategy"] = strategy;+ args["startDate"] = start_date_;+ args["endDate"] = end_date_;+ args["initialCapital"] = initial_capital_;+ args["assets"] = assets;+ args["nSplits"] = wf_splits_;+ args["trainRatio"] = wf_train_ratio_;+ break;+ }+ case CommandType::Indicator: {+ auto& inds = indicators();+ args["symbols"] = symbol_list;+ args["startDate"] = start_date_;+ args["endDate"] = end_date_;+ args["indicator"] = inds[indicator_idx_].id;+ break;+ }+ case CommandType::IndicatorSignals: {+ auto& modes = signal_modes();+ auto& inds = indicators();+ args["symbols"] = symbol_list;+ args["startDate"] = start_date_;+ args["endDate"] = end_date_;+ args["mode"] = modes[signal_mode_idx_].id;+ args["indicator"] = inds[indicator_idx_].id;+ break;+ }+ case CommandType::Labels: {+ auto& lts = label_types();+ args["symbols"] = symbol_list;+ args["startDate"] = start_date_;+ args["endDate"] = end_date_;+ args["labelType"] = lts[labels_type_idx_].id;+ json lp;+ for (auto& [k, v] : labels_params_) lp[k] = v;+ args["params"] = lp;+ break;+ }+ case CommandType::Splits: {+ auto& sts = splitter_types();+ args["symbols"] = symbol_list;+ args["startDate"] = start_date_;+ args["endDate"] = end_date_;+ args["splitterType"] = sts[splitter_type_idx_].id;+ json sp;+ for (auto& [k, v] : splitter_params_) sp[k] = v;+ args["params"] = sp;+ break;+ }+ case CommandType::Returns: {+ auto& rts = returns_analysis_types();+ args["symbols"] = symbol_list;+ args["startDate"] = start_date_;+ args["endDate"] = end_date_;+ args["analysisType"] = rts[returns_type_idx_].id;+ args["rollingWindow"] = returns_rolling_window_;+ if (rts[returns_type_idx_].id == std::string("benchmark_comparison"))+ args["benchmarkSymbol"] = benchmark_symbol_;+ break;+ }+ case CommandType::Signals: {+ auto& sgs = signal_generator_types();+ args["symbols"] = symbol_list;+ args["startDate"] = start_date_;+ args["endDate"] = end_date_;+ args["generatorType"] = sgs[signal_gen_idx_].id;+ json gp;+ for (auto& [k, v] : signal_gen_params_) gp[k] = v;+ args["params"] = gp;+ break;+ }+ default: break;+ }++ return args.dump();+}++// =============================================================================+// Initialize strategy params from selected strategy defaults+// =============================================================================+void BacktestingScreen::init_strategy_params() {+ strategy_params_.clear();+ auto strats = get_strategies(selected_provider_, selected_category_);+ if (selected_strategy_idx_ < (int)strats.size()) {+ for (auto& p : strats[selected_strategy_idx_].params) {+ strategy_params_[p.name] = p.default_val;+ }+ }+}++} // namespace fincept::backtestingdiff --git a/fincept-cpp/src/screens/backtesting/backtesting_screen.h b/fincept-cpp/src/screens/backtesting/backtesting_screen.hnew file mode 100644index 000000000..0618f64fb--- /dev/null+++ b/fincept-cpp/src/screens/backtesting/backtesting_screen.h@@ -0,0 +1,147 @@+#pragma once+// Backtesting Tab — main screen with three-panel layout+// Multi-provider strategy backtesting terminal++#include "backtesting_types.h"+#include "backtesting_data.h"+#include <string>+#include <vector>+#include <map>+#include <nlohmann/json.hpp>++namespace fincept::backtesting {++class BacktestingScreen {+public:+ void render();++private:+ BacktestData data_;++ // Provider state+ ProviderSlug selected_provider_ = ProviderSlug::VectorBT;++ // Command state+ CommandType active_command_ = CommandType::Backtest;+ std::string selected_category_ = "trend";+ int selected_strategy_idx_ = 0;++ // Backtest config+ char symbols_[128] = "SPY";+ char start_date_[16] = "2025-03-15";+ char end_date_[16] = "2026-03-14";+ float initial_capital_ = 100000.0f;+ float commission_ = 0.1f; // percentage+ float slippage_ = 0.05f; // percentage++ // Strategy params (dynamic, keyed by param name)+ std::map<std::string, float> strategy_params_;+ char custom_code_[4096] = "# Custom strategy code\n";++ // Advanced config+ bool show_advanced_ = false;+ float leverage_ = 1.0f;+ float margin_ = 1.0f;+ float stop_loss_ = 0.0f;+ float take_profit_ = 0.0f;+ float trailing_stop_ = 0.0f;+ int position_sizing_idx_ = 1; // percent+ float position_size_value_ = 1.0f;+ bool allow_short_ = false;+ bool enable_benchmark_ = false;+ char benchmark_symbol_[32] = "SPY";+ bool random_benchmark_ = false;++ // Optimize config+ int optimize_objective_idx_ = 0; // sharpe+ int optimize_method_idx_ = 0; // grid+ int max_iterations_ = 500;+ std::map<std::string, std::array<float,3>> param_ranges_; // min,max,step++ // Walk forward config+ int wf_splits_ = 5;+ float wf_train_ratio_ = 0.7f;++ // Indicator config+ int indicator_idx_ = 0;+ std::map<std::string, float> indicator_params_;++ // Indicator signals config+ int signal_mode_idx_ = 0;+ std::map<std::string, float> ind_signal_params_;++ // Labels config+ int labels_type_idx_ = 0;+ std::map<std::string, float> labels_params_;++ // Splitters config+ int splitter_type_idx_ = 0;+ std::map<std::string, float> splitter_params_;++ // Returns config+ int returns_type_idx_ = 0;+ int returns_rolling_window_ = 21;++ // Signal generator config+ int signal_gen_idx_ = 0;+ std::map<std::string, float> signal_gen_params_;++ // Execution state+ nlohmann::json result_;+ bool has_error_ = false;+ std::string error_msg_;+ ResultView result_view_ = ResultView::Summary;++ // Status+ std::string status_;+ double status_time_ = 0;++ // Section expansion state+ std::map<std::string, bool> expanded_ = {+ {"market", true}, {"strategy", true}, {"execution", false}, {"advanced", false},+ {"optimization", true}, {"walk_forward", true},+ };++ // Rendering methods+ void render_top_nav();+ void render_command_panel();+ void render_config_panel();+ void render_results_panel();+ void render_status_bar();++ // Config sub-panels+ void render_backtest_config();+ void render_advanced_config();+ void render_optimize_config();+ void render_walk_forward_config();+ void render_indicator_config();+ void render_indicator_signals_config();+ void render_labels_config();+ void render_splitters_config();+ void render_returns_config();+ void render_signals_config();++ // Result sub-panels+ void render_result_summary();+ void render_result_metrics();+ void render_result_trades();+ void render_result_raw();+ void render_result_charts();+ void render_result_drawdowns();+ void render_result_indicator();+ void render_result_signals();+ void render_result_signal_generator();+ void render_result_labels();+ void render_result_splitters();+ void render_result_returns();++ // Actions+ void pickup_result();+ void execute_command();+ std::string build_args_json();++ // Helpers+ void init_strategy_params();+};++} // namespace fincept::backtestingdiff --git a/fincept-cpp/src/screens/backtesting/backtesting_types.h b/fincept-cpp/src/screens/backtesting/backtesting_types.hnew file mode 100644index 000000000..3364b17d8--- /dev/null+++ b/fincept-cpp/src/screens/backtesting/backtesting_types.h@@ -0,0 +1,172 @@+#pragma once+// Backtesting Tab — core types and enums++#include <string>+#include <vector>+#include <imgui.h>+#include <nlohmann/json.hpp>++namespace fincept::backtesting {++// =============================================================================+// Provider slugs — the 6 backtesting engines+// =============================================================================+enum class ProviderSlug {+ Fincept, // Fincept Engine (400+ strategies)+ VectorBT, // VectorBT Pro+ BacktestingPy, // Backtesting.py+ FastTrade, // Fast-Trade+ Zipline, // Zipline-Reloaded+ BT, // BT (portfolio backtesting)+ COUNT+};++// =============================================================================+// Command types — what the provider can do+// =============================================================================+enum class CommandType {+ Backtest,+ Optimize,+ WalkForward,+ Indicator,+ IndicatorSignals,+ Labels,+ Splits,+ Returns,+ Signals,+ COUNT+};++// =============================================================================+// Result view tabs+// =============================================================================+enum class ResultView {+ Summary,+ Metrics,+ Charts,+ Trades,+ Raw,+ COUNT+};++// =============================================================================+// Strategy parameter definition+// =============================================================================+struct StrategyParam {+ const char* name;+ const char* label;+ float default_val;+ float min_val;+ float max_val;+ float step;+};++// =============================================================================+// Strategy definition+// =============================================================================+struct Strategy {+ const char* id;+ const char* name;+ const char* description;+ std::vector<StrategyParam> params;+};++// =============================================================================+// Command definition (for command panel)+// =============================================================================+struct CommandDef {+ CommandType type;+ const char* label;+ const char* description;+ ImVec4 color;+};++// =============================================================================+// Category info+// =============================================================================+struct CategoryInfo {+ const char* key;+ const char* label;+ ImVec4 color;+};++// =============================================================================+// Provider configuration+// =============================================================================+struct ProviderConfig {+ ProviderSlug slug;+ const char* display_name;+ const char* script_dir; // e.g. "vectorbt"+ ImVec4 color;+ std::vector<CommandType> commands;+ // command_map: CommandType -> python command string+ // strategies: grouped by category key+ // category_info: list of categories+};++// =============================================================================+// Indicator definition+// =============================================================================+struct IndicatorDef {+ const char* id;+ const char* label;+ std::vector<const char*> params;+};++// =============================================================================+// Position sizing option+// =============================================================================+struct PositionSizingOption {+ const char* id;+ const char* label;+};++// =============================================================================+// Signal mode+// =============================================================================+struct SignalMode {+ const char* id;+ const char* label;+ const char* description;+};++// =============================================================================+// Label type (ML)+// =============================================================================+struct LabelType {+ const char* id;+ const char* label;+ const char* description;+ std::vector<const char*> params;+};++// =============================================================================+// Splitter type (cross-validation)+// =============================================================================+struct SplitterType {+ const char* id;+ const char* label;+ const char* description;+ std::vector<const char*> params;+};++// =============================================================================+// Returns analysis type+// =============================================================================+struct ReturnsAnalysisType {+ const char* id;+ const char* label;+ const char* description;+};++// =============================================================================+// Signal generator type+// =============================================================================+struct SignalGeneratorType {+ const char* id;+ const char* label;+ const char* description;+ std::vector<const char*> params;+};++} // namespace fincept::backtestingdiff --git a/fincept-cpp/src/screens/code_editor/code_editor_screen.cpp b/fincept-cpp/src/screens/code_editor/code_editor_screen.cppindex 76e9cb92e..5771355c9 100644--- a/fincept-cpp/src/screens/code_editor/code_editor_screen.cpp+++ b/fincept-cpp/src/screens/code_editor/code_editor_screen.cpp@@ -31,15 +31,112 @@ namespace fs = std::filesystem;NotebookTab& CodeEditorScreen::tab() { return tabs_[active_tab_idx_]; }Notebook& CodeEditorScreen::nb() { return tabs_[active_tab_idx_].notebook; }+// Forward declaration (defined further below)+static void file_log(const std::string& msg);++// =============================================================================+// Helper: Jupyter-like auto-display for last expression+// In Jupyter notebooks, the last expression in a cell is auto-displayed.+// In a Python script, bare expressions produce no output. This function+// detects if the last non-empty, non-comment line is a bare expression+// and wraps it in print() so users get Jupyter-like behavior.+// =============================================================================+static std::string jupyter_auto_display(const std::string& source) {+ // Split into lines+ std::vector<std::string> lines;+ std::istringstream ss(source);+ std::string line;+ while (std::getline(ss, line)) lines.push_back(line);++ // Find last non-empty, non-comment line+ int last_idx = -1;+ for (int i = static_cast<int>(lines.size()) - 1; i >= 0; i--) {+ std::string trimmed = lines[i];+ // Trim leading whitespace+ size_t start = trimmed.find_first_not_of(" \t\r\n");+ if (start == std::string::npos) continue; // blank line+ trimmed = trimmed.substr(start);+ if (trimmed[0] == '#') continue; // comment+ last_idx = i;+ break;+ }++ if (last_idx < 0) return source;++ std::string trimmed = lines[last_idx];+ size_t start = trimmed.find_first_not_of(" \t");+ if (start == std::string::npos) return source;+ std::string content = trimmed.substr(start);+ std::string indent = trimmed.substr(0, start);++ // Skip if it's indented (inside a block) — only auto-display top-level expressions+ if (!indent.empty()) return source;++ // Skip if it's a statement keyword+ static const std::set<std::string> STMT_PREFIXES = {+ "import ", "from ", "def ", "class ", "if ", "elif ", "else:",+ "for ", "while ", "try:", "except ", "except:", "finally:",+ "with ", "return ", "raise ", "pass", "break", "continue",+ "del ", "global ", "nonlocal ", "assert ", "yield ", "async ",+ "await ", "print(", "print ("+ };+ for (auto& prefix : STMT_PREFIXES) {+ if (content.substr(0, prefix.size()) == prefix) return source;+ if (content == "pass" || content == "break" || content == "continue") return source;+ }++ // Skip if it contains '=' but not '==' (assignment)+ // But allow lines like `df[df['col'] == 'val']`+ bool has_assign = false;+ for (size_t i = 0; i < content.size(); i++) {+ if (content[i] == '=' && i + 1 < content.size() && content[i + 1] != '=' &&+ (i == 0 || (content[i - 1] != '!' && content[i - 1] != '<' &&+ content[i - 1] != '>' && content[i - 1] != '='))) {+ // Could be assignment — check if left side looks like assignment target+ // Simple heuristic: if '=' appears outside of brackets/parens at top level+ int depth = 0;+ for (size_t j = 0; j < i; j++) {+ if (content[j] == '(' || content[j] == '[' || content[j] == '{') depth++;+ if (content[j] == ')' || content[j] == ']' || content[j] == '}') depth--;+ }+ if (depth == 0) { has_assign = true; break; }+ }+ }+ if (has_assign) return source;++ // Skip if it ends with ':' (block start)+ if (!content.empty() && content.back() == ':') return source;++ // It's likely a bare expression — wrap in print()+ lines[last_idx] = "print(" + content + ")";++ std::string result;+ for (size_t i = 0; i < lines.size(); i++) {+ result += lines[i];+ if (i + 1 < lines.size()) result += '\n';+ }+ return result;+}+// =============================================================================// Helper: write string to temp file, return path// =============================================================================static std::string write_temp_script(const std::string& source) {- fs::path tmp_dir = fs::temp_directory_path();- fs::path tmp_file = tmp_dir / "fincept_cell.py";- std::ofstream f(tmp_file);- if (f.is_open()) { f << source; f.close(); }- return tmp_file.string();+ try {+ // Apply Jupyter-like auto-display for bare expressions+ std::string transformed = jupyter_auto_display(source);+ file_log("write_temp_script: source_len=" + std::to_string(source.size()) ++ " transformed_len=" + std::to_string(transformed.size()));+ fs::path tmp_dir = fs::temp_directory_path();+ fs::path tmp_file = tmp_dir / "fincept_cell.py";+ std::ofstream f(tmp_file);+ if (f.is_open()) { f << transformed; f.close(); }+ else { file_log("write_temp_script: FAILED to open file for writing!"); }+ return tmp_file.string();+ } catch (const std::exception& e) {+ file_log("write_temp_script: EXCEPTION: " + std::string(e.what()));+ return "";+ }}// =============================================================================@@ -392,50 +489,113 @@ void CodeEditorScreen::render_markdown(const std::string& source) {// =============================================================================// Subprocess execution helper// =============================================================================+// Crash-safe file logger — writes directly to file, never throws+static std::mutex s_file_log_mutex;+static void file_log(const std::string& msg) {+ try {+ std::lock_guard<std::mutex> lock(s_file_log_mutex);+ static std::ofstream log_file;+ if (!log_file.is_open()) {+ log_file.open("C:/windowsdisk/finceptTerminal/fincept-cpp/debug_code_editor.log",+ std::ios::trunc);+ }+ if (log_file.is_open()) {+ auto now = std::chrono::system_clock::now();+ auto ms = std::chrono::duration_cast<std::chrono::milliseconds>(+ now.time_since_epoch()).count() % 100000;+ log_file << "[" << ms << "] " << msg << "\n";+ log_file.flush();+ }+ } catch (...) {}+}++// Debug log function accessible from static context via global pointer+static CodeEditorScreen* g_debug_instance = nullptr;+static void debug_log(const std::string& msg) {+ file_log(msg);+ try { if (g_debug_instance) g_debug_instance->add_debug(msg); } catch (...) {}+}+static python::PythonResult run_cell_subprocess(const std::string& tmp_path) {python::PythonResult result;- fs::path py = python::resolve_python_path("");- if (py.empty() || !fs::exists(py)) {+ try {+ file_log("subprocess: ENTER, tmp_path=" + tmp_path);++ file_log("subprocess: calling resolve_python_path...");+ fs::path py = python::resolve_python_path("");+ file_log("subprocess: resolve_python_path('') = '" + py.string() + "'");++ if (py.empty() || !fs::exists(py)) {#ifdef _WIN32- py = "python";+ py = "python";#else- py = "python3";+ py = "python3";#endif- }+ file_log("subprocess: falling back to '" + py.string() + "'");+ }- std::string cmd = "\"" + py.string() + "\" -u -B \"" + tmp_path + "\" 2>&1";+ // On Windows, _popen uses cmd.exe /c which requires the entire command+ // wrapped in an extra set of quotes when paths contain spaces.+#ifdef _WIN32+ std::string cmd = "\"\"" + py.string() + "\" -u -B \"" + tmp_path + "\" 2>&1\"";+#else+ std::string cmd = "\"" + py.string() + "\" -u -B \"" + tmp_path + "\" 2>&1";+#endif+ file_log("subprocess: CMD = " + cmd);+ file_log("subprocess: calling _popen...");#ifdef _WIN32- FILE* pipe = _popen(cmd.c_str(), "r");+ FILE* pipe = _popen(cmd.c_str(), "r");#else- FILE* pipe = popen(cmd.c_str(), "r");+ FILE* pipe = popen(cmd.c_str(), "r");#endif- if (!pipe) {- result.error = "Failed to start Python subprocess";- return result;- }+ if (!pipe) {+ result.error = "Failed to start Python subprocess";+ file_log("subprocess: FAIL - _popen returned NULL, errno=" + std::to_string(errno));+ return result;+ }+ file_log("subprocess: pipe opened OK, reading output...");- std::string output;- char buffer[4096];- while (std::fgets(buffer, sizeof(buffer), pipe)) {- output += buffer;- }+ std::string output;+ char buffer[4096];+ int read_count = 0;+ while (std::fgets(buffer, sizeof(buffer), pipe)) {+ output += buffer;+ read_count++;+ }+ file_log("subprocess: read " + std::to_string(output.size()) + " bytes in " ++ std::to_string(read_count) + " chunks from pipe");+ file_log("subprocess: calling _pclose...");#ifdef _WIN32- int status = _pclose(pipe);+ int status = _pclose(pipe);#else- int status = pclose(pipe);- status = WEXITSTATUS(status);+ int status = pclose(pipe);+ status = WEXITSTATUS(status);#endif- result.exit_code = status;- if (status == 0) {- result.success = true;- result.output = output;- } else {- result.error = output.empty() ? "Python exited with code " + std::to_string(status) : output;+ file_log("subprocess: _pclose returned status=" + std::to_string(status));++ result.exit_code = status;+ if (status == 0) {+ result.success = true;+ result.output = output;+ file_log("subprocess: SUCCESS");+ } else {+ result.error = output.empty() ? "Python exited with code " + std::to_string(status) : output;+ file_log("subprocess: FAIL - exit code " + std::to_string(status) ++ " output_len=" + std::to_string(output.size()));+ }+ } catch (const std::exception& e) {+ file_log("subprocess: EXCEPTION: " + std::string(e.what()));+ result.error = std::string("Subprocess exception: ") + e.what();+ } catch (...) {+ file_log("subprocess: UNKNOWN EXCEPTION");+ result.error = "Subprocess unknown exception";}++ file_log("subprocess: EXIT");return result;}@@ -445,50 +605,79 @@ static python::PythonResult run_cell_subprocess(const std::string& tmp_path) {void CodeEditorScreen::render() {using namespace theme::colors;+ g_debug_instance = this;++ try {+if (!initialized_) {+ file_log("render() initializing...");new_tab();detect_python_version();last_autosave_time_ = ImGui::GetTime();initialized_ = true;+ file_log("render() initialized OK");}if (tabs_.empty()) { new_tab(); }- // Check async execution result- if (exec_future_.valid() &&- exec_future_.wait_for(std::chrono::milliseconds(0)) == std::future_status::ready) {- exec_future_.get();- exec_pending_ = false;- running_cell_ = -1;+ // Check async execution result — MUST catch exceptions from async thread+ if (exec_future_.valid()) {+ auto status = exec_future_.wait_for(std::chrono::milliseconds(0));+ if (status == std::future_status::ready) {+ file_log("render() exec_future_ ready, calling .get()...");+ try {+ exec_future_.get();+ file_log("render() exec_future_.get() OK");+ } catch (const std::exception& e) {+ file_log("render() EXCEPTION from exec_future_.get(): " + std::string(e.what()));+ } catch (...) {+ file_log("render() UNKNOWN EXCEPTION from exec_future_.get()");+ }+ exec_pending_ = false;+ running_cell_ = -1;+ }}// Apply pending results from background thread (thread-safe){std::lock_guard<std::mutex> lock(result_mutex_);for (auto& pr : pending_results_) {- if (pr.tab_idx >= 0 && pr.tab_idx < static_cast<int>(tabs_.size())) {- auto& t = tabs_[pr.tab_idx];- if (pr.cell_idx >= 0 && pr.cell_idx < static_cast<int>(t.notebook.cells.size())) {- auto& c = t.notebook.cells[pr.cell_idx];- c.outputs.clear();- c.execution_count = pr.exec_num;- c.exec_time_ms = pr.elapsed_ms;- if (pr.success) {- if (!pr.output.empty()) {+ file_log("Applying result: tab=" + std::to_string(pr.tab_idx) ++ " cell=" + std::to_string(pr.cell_idx) ++ " success=" + (pr.success ? "true" : "false") ++ " elapsed=" + std::to_string(static_cast<int>(pr.elapsed_ms)) + "ms");+ try {+ if (pr.tab_idx >= 0 && pr.tab_idx < static_cast<int>(tabs_.size())) {+ auto& t = tabs_[pr.tab_idx];+ if (pr.cell_idx >= 0 && pr.cell_idx < static_cast<int>(t.notebook.cells.size())) {+ auto& c = t.notebook.cells[pr.cell_idx];+ c.outputs.clear();+ c.execution_count = pr.exec_num;+ c.exec_time_ms = pr.elapsed_ms;+ if (pr.success) {+ if (!pr.output.empty()) {+ CellOutput out;+ out.output_type = "stream";+ out.text = pr.output;+ c.outputs.push_back(std::move(out));+ }+ } else {CellOutput out;- out.output_type = "stream";- out.text = pr.output;+ out.output_type = "error";+ out.ename = "ExecutionError";+ out.evalue = pr.error.empty() ? "Unknown error" : pr.error;+ out.traceback = pr.error;c.outputs.push_back(std::move(out));}+ file_log("Result applied OK for cell " + std::to_string(pr.cell_idx));} else {- CellOutput out;- out.output_type = "error";- out.ename = "ExecutionError";- out.evalue = pr.error.empty() ? "Unknown error" : pr.error;- out.traceback = pr.error;- c.outputs.push_back(std::move(out));+ file_log("WARN: cell_idx out of range: " + std::to_string(pr.cell_idx));}+ } else {+ file_log("WARN: tab_idx out of range: " + std::to_string(pr.tab_idx));}+ } catch (const std::exception& e) {+ file_log("EXCEPTION applying result: " + std::string(e.what()));}}pending_results_.clear();@@ -535,6 +724,12 @@ void CodeEditorScreen::render() {ImGui::End();ImGui::PopStyleVar();ImGui::PopStyleColor();++ } catch (const std::exception& e) {+ file_log("FATAL EXCEPTION in render(): " + std::string(e.what()));+ } catch (...) {+ file_log("FATAL UNKNOWN EXCEPTION in render()");+ }}// =============================================================================@@ -825,6 +1020,13 @@ void CodeEditorScreen::render_cells() {// =============================================================================void CodeEditorScreen::render_cell(int idx) {using namespace theme::colors;+ try {++ if (idx < 0 || idx >= static_cast<int>(nb().cells.size())) {+ file_log("render_cell: idx " + std::to_string(idx) + " out of range, cells=" ++ std::to_string(nb().cells.size()));+ return;+ }auto& cell = nb().cells[idx];bool is_selected = (idx == tab().selected_cell);@@ -918,6 +1120,12 @@ void CodeEditorScreen::render_cell(int idx) {ImGui::PopStyleColor(); // ChildBgImGui::Spacing();++ } catch (const std::exception& e) {+ file_log("render_cell EXCEPTION idx=" + std::to_string(idx) + ": " + e.what());+ } catch (...) {+ file_log("render_cell UNKNOWN EXCEPTION idx=" + std::to_string(idx));+ }}// =============================================================================@@ -1187,6 +1395,7 @@ void CodeEditorScreen::render_cell_editor(int idx) {// =============================================================================void CodeEditorScreen::render_cell_output(int idx) {using namespace theme::colors;+ try {auto& cell = nb().cells[idx];bool has_error = false;@@ -1253,6 +1462,12 @@ void CodeEditorScreen::render_cell_output(int idx) {}ImGui::EndChild();++ } catch (const std::exception& e) {+ file_log("render_cell_output EXCEPTION idx=" + std::to_string(idx) + ": " + e.what());+ } catch (...) {+ file_log("render_cell_output UNKNOWN EXCEPTION idx=" + std::to_string(idx));+ }}// =============================================================================@@ -1615,11 +1830,25 @@ void CodeEditorScreen::redo() {// Execution (with timer — point 8, persistent feel via sequential cells — point 2)// =============================================================================void CodeEditorScreen::run_cell(int idx) {+ file_log("run_cell() ENTER idx=" + std::to_string(idx));+ try {auto& cells = nb().cells;- if (idx < 0 || idx >= static_cast<int>(cells.size())) return;+ file_log("run_cell() cells.size()=" + std::to_string(cells.size()));++ if (idx < 0 || idx >= static_cast<int>(cells.size())) {+ add_debug("ERROR: idx out of range, cells.size()=" + std::to_string(cells.size()));+ return;+ }auto& cell = cells[idx];- if (cell.cell_type != "code" || cell.source.empty()) return;- if (exec_pending_) return;+ if (cell.cell_type != "code" || cell.source.empty()) {+ add_debug("ERROR: cell not code or source empty, type=" + cell.cell_type ++ " source_len=" + std::to_string(cell.source.size()));+ return;+ }+ if (exec_pending_) {+ add_debug("ERROR: exec_pending_ is true, another cell is still running");+ return;+ }flush_edit_buffer();running_cell_ = idx;@@ -1629,41 +1858,110 @@ void CodeEditorScreen::run_cell(int idx) {int tab_idx = active_tab_idx_;std::string source = cell.source;+ add_debug("Cell source (" + std::to_string(source.size()) + " chars): " ++ source.substr(0, 80) + (source.size() > 80 ? "..." : ""));+// Persistent session (point 2): gather all previously executed cells' source// and prepend to current cell so variables carry overstd::string full_source;+ int prepended = 0;for (int i = 0; i < idx; i++) {if (cells[i].cell_type == "code" && cells[i].execution_count >= 0 && !cells[i].source.empty()) {full_source += cells[i].source;if (!cells[i].source.empty() && cells[i].source.back() != '\n') full_source += '\n';+ prepended++;}}full_source += source;+ add_debug("Prepended " + std::to_string(prepended) + " prior cells, total source: " ++ std::to_string(full_source.size()) + " chars");exec_future_ = std::async(std::launch::async, [this, idx, exec_num, tab_idx, full_source]() {- auto t_start = std::chrono::steady_clock::now();- std::string tmp_path = write_temp_script(full_source);- python::PythonResult result = run_cell_subprocess(tmp_path);- try { fs::remove(tmp_path); } catch (...) {}- auto t_end = std::chrono::steady_clock::now();- double elapsed_ms = std::chrono::duration<double, std::milli>(t_end - t_start).count();-- // If we prepended previous cells, strip their output- // The combined script runs everything, but we only want output from the last cell- // This is imperfect but workable — the last cell's print statements will include- // earlier cells' outputs too. A true persistent session needs a live REPL process.+ try {+ file_log("async: ENTER for cell " + std::to_string(idx));- std::lock_guard<std::mutex> lock(result_mutex_);- PendingResult pr;- pr.tab_idx = tab_idx;- pr.cell_idx = idx;- pr.exec_num = exec_num;- pr.success = result.success;- pr.output = result.output;- pr.error = result.error;- pr.elapsed_ms = elapsed_ms;- pending_results_.push_back(std::move(pr));+ auto t_start = std::chrono::steady_clock::now();++ file_log("async: writing temp script...");+ std::string tmp_path = write_temp_script(full_source);+ file_log("async: temp script written: " + tmp_path);++ // Log the resolved python path+ file_log("async: resolving python path...");+ fs::path py = python::resolve_python_path("");+ file_log("async: resolve_python_path('') = '" + py.string() + "' exists=" ++ (py.empty() ? "empty" : (fs::exists(py) ? "YES" : "NO")));++ file_log("async: calling run_cell_subprocess...");+ python::PythonResult result = run_cell_subprocess(tmp_path);++ file_log("async: subprocess returned, success=" + std::string(result.success ? "true" : "false") ++ " exit_code=" + std::to_string(result.exit_code));+ if (!result.output.empty()) {+ std::string preview = result.output.substr(0, 200);+ file_log("async: output (" + std::to_string(result.output.size()) + " chars): " + preview);+ }+ if (!result.error.empty()) {+ std::string preview = result.error.substr(0, 300);+ file_log("async: ERROR output: " + preview);+ }++ try { fs::remove(tmp_path); } catch (...) {}+ auto t_end = std::chrono::steady_clock::now();+ double elapsed_ms = std::chrono::duration<double, std::milli>(t_end - t_start).count();+ file_log("async: execution took " + std::to_string(static_cast<int>(elapsed_ms)) + "ms");++ file_log("async: locking result_mutex_ to push result...");+ std::lock_guard<std::mutex> lock(result_mutex_);+ PendingResult pr;+ pr.tab_idx = tab_idx;+ pr.cell_idx = idx;+ pr.exec_num = exec_num;+ pr.success = result.success;+ pr.output = result.output;+ pr.error = result.error;+ pr.elapsed_ms = elapsed_ms;+ pending_results_.push_back(std::move(pr));+ file_log("async: result pushed OK, EXIT");+ } catch (const std::exception& e) {+ file_log("async: EXCEPTION: " + std::string(e.what()));+ // Still push an error result so UI doesn't hang+ try {+ std::lock_guard<std::mutex> lock(result_mutex_);+ PendingResult pr;+ pr.tab_idx = tab_idx;+ pr.cell_idx = idx;+ pr.exec_num = exec_num;+ pr.success = false;+ pr.error = std::string("Internal error: ") + e.what();+ pr.elapsed_ms = 0;+ pending_results_.push_back(std::move(pr));+ } catch (...) {}+ } catch (...) {+ file_log("async: UNKNOWN EXCEPTION");+ try {+ std::lock_guard<std::mutex> lock(result_mutex_);+ PendingResult pr;+ pr.tab_idx = tab_idx;+ pr.cell_idx = idx;+ pr.exec_num = exec_num;+ pr.success = false;+ pr.error = "Internal unknown error";+ pr.elapsed_ms = 0;+ pending_results_.push_back(std::move(pr));+ } catch (...) {}+ }});+ file_log("run_cell() async launched OK");+ } catch (const std::exception& e) {+ file_log("run_cell() EXCEPTION: " + std::string(e.what()));+ exec_pending_ = false;+ running_cell_ = -1;+ } catch (...) {+ file_log("run_cell() UNKNOWN EXCEPTION");+ exec_pending_ = false;+ running_cell_ = -1;+ }}void CodeEditorScreen::run_all_cells() {@@ -1947,7 +2245,11 @@ void CodeEditorScreen::pip_install(const std::string& package) {#endif}+#ifdef _WIN32+ std::string cmd = "\"\"" + py.string() + "\" -m pip install " + package + " 2>&1\"";+#elsestd::string cmd = "\"" + py.string() + "\" -m pip install " + package + " 2>&1";+#endif#ifdef _WIN32FILE* pipe = _popen(cmd.c_str(), "r");@@ -2100,7 +2402,11 @@ void CodeEditorScreen::detect_python_version() {#endif}+#ifdef _WIN32+ std::string cmd = "\"\"" + py.string() + "\" -c \"import sys; print(f'Python {sys.version_info.major}.{sys.version_info.minor}.{sys.version_info.micro}')\" 2>&1\"";+#elsestd::string cmd = "\"" + py.string() + "\" -c \"import sys; print(f'Python {sys.version_info.major}.{sys.version_info.minor}.{sys.version_info.micro}')\" 2>&1";+#endif#ifdef _WIN32FILE* pipe = _popen(cmd.c_str(), "r");@@ -2141,4 +2447,65 @@ void CodeEditorScreen::flush_edit_buffer() {}}+void CodeEditorScreen::add_debug(const std::string& msg) {+ // File logging is handled by file_log() — just keep in-memory log here+ try {+ auto now = std::chrono::system_clock::now();+ auto ms = std::chrono::duration_cast<std::chrono::milliseconds>(+ now.time_since_epoch()).count() % 100000;+ char ts[16];+ std::snprintf(ts, sizeof(ts), "%05d", static_cast<int>(ms));++ std::lock_guard<std::mutex> lock(debug_mutex_);+ debug_log_.push_back({std::string(ts), msg});+ if (debug_log_.size() > 200)+ debug_log_.erase(debug_log_.begin());+ } catch (...) {}+}++void CodeEditorScreen::render_debug_panel() {+ using namespace theme::colors;++ ImGui::PushStyleColor(ImGuiCol_ChildBg, ImVec4(0.05f, 0.05f, 0.08f, 1.0f));+ ImGui::BeginChild("##ce_debug", ImVec2(0, 200), ImGuiChildFlags_Borders,+ ImGuiWindowFlags_HorizontalScrollbar);++ ImGui::TextColored(ACCENT, "DEBUG LOG");+ ImGui::SameLine(0, 16);+ if (ImGui::SmallButton("Clear##dbg_clear")) {+ std::lock_guard<std::mutex> lock(debug_mutex_);+ debug_log_.clear();+ }+ ImGui::SameLine(0, 8);+ if (ImGui::SmallButton("Hide##dbg_hide")) {+ show_debug_log_ = false;+ }+ ImGui::Separator();++ {+ std::lock_guard<std::mutex> lock(debug_mutex_);+ for (auto& entry : debug_log_) {+ ImGui::TextColored(TEXT_DIM, "[%s]", entry.timestamp.c_str());+ ImGui::SameLine(0, 4);++ // Color based on content+ ImVec4 col = TEXT_PRIMARY;+ if (entry.message.find("ERROR") != std::string::npos ||+ entry.message.find("FAIL") != std::string::npos) col = ERROR_RED;+ else if (entry.message.find("OK") != std::string::npos ||+ entry.message.find("SUCCESS") != std::string::npos) col = SUCCESS;+ else if (entry.message.find(">>>") != std::string::npos) col = WARNING;++ ImGui::TextColored(col, "%s", entry.message.c_str());+ }+ }++ // Auto-scroll+ if (ImGui::GetScrollY() >= ImGui::GetScrollMaxY() - 20)+ ImGui::SetScrollHereY(1.0f);++ ImGui::EndChild();+ ImGui::PopStyleColor();+}+} // namespace fincept::code_editordiff --git a/fincept-cpp/src/screens/code_editor/code_editor_screen.h b/fincept-cpp/src/screens/code_editor/code_editor_screen.hindex 23745dc9b..3f6238d9f 100644--- a/fincept-cpp/src/screens/code_editor/code_editor_screen.h+++ b/fincept-cpp/src/screens/code_editor/code_editor_screen.h@@ -19,6 +19,7 @@ namespace fincept::code_editor {class CodeEditorScreen {public:void render();+ void add_debug(const std::string& msg); // public so static helper can call itprivate:// === Multi-tab notebook state ===@@ -82,7 +83,17 @@ private:// === Drag reorder (point 7) ===int drag_source_cell_ = -1;+ // === Debug log ===+ bool show_debug_log_ = false;+ struct DebugEntry {+ std::string timestamp;+ std::string message;+ };+ std::mutex debug_mutex_;+ std::vector<DebugEntry> debug_log_;+// === Render methods ===+ void render_debug_panel();void render_tab_bar();void render_toolbar();void render_cells();diff --git a/fincept-cpp/src/screens/crypto_trading/crypto_trading_screen.cpp b/fincept-cpp/src/screens/crypto_trading/crypto_trading_screen.cppindex 364e1ce5c..d01d2e614 100644--- a/fincept-cpp/src/screens/crypto_trading/crypto_trading_screen.cpp+++ b/fincept-cpp/src/screens/crypto_trading/crypto_trading_screen.cpp@@ -43,6 +43,7 @@ CryptoTradingScreen::~CryptoTradingScreen() {if (ws_price_cb_id_ >= 0) svc.remove_price_callback(ws_price_cb_id_);if (ws_ob_cb_id_ >= 0) svc.remove_orderbook_callback(ws_ob_cb_id_);if (ws_candle_cb_id_ >= 0) svc.remove_candle_callback(ws_candle_cb_id_);+ if (ws_trade_cb_id_ >= 0) svc.remove_trade_callback(ws_trade_cb_id_);}// ============================================================================@@ -78,6 +79,22 @@ void CryptoTradingScreen::init() {// Create or load paper trading portfolio (DB only, fast)load_portfolio();+ // Register portfolio with exchange service so position prices get updated+ if (!portfolio_id_.empty()) {+ svc.watch_symbol(selected_symbol_, portfolio_id_);+ // Also watch all symbols that have open positions+ for (const auto& pos : positions_) {+ if (pos.symbol != selected_symbol_) {+ svc.watch_symbol(pos.symbol, portfolio_id_);+ }+ }+ }++ // Start the price feed for watched symbols (drives OrderMatcher + position updates)+ if (!svc.is_feed_running()) {+ svc.start_price_feed(3);+ }+initialized_ = true;LOG_INFO(TAG, "=== INIT COMPLETE === (portfolio_id=%s, balance=%.2f)",portfolio_id_.c_str(), portfolio_.balance);@@ -176,6 +193,18 @@ void CryptoTradingScreen::init() {}});+ // 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@@ -191,6 +220,10 @@ void CryptoTradingScreen::init() {last_error_ = std::string("WS start failed: ") + e.what();error_count_++;}++ // Fetch initial trades and market info via REST+ async_fetch_trades();+ async_fetch_market_info();}void CryptoTradingScreen::load_portfolio() {@@ -222,6 +255,23 @@ void CryptoTradingScreen::load_portfolio() {portfolio_id_.c_str(), portfolio_.balance);}+ // Cleanup: delete empty portfolios (not ours) to prevent DB bloat+ if (portfolios.size() > 10) {+ int cleaned = 0;+ for (const auto& p : portfolios) {+ if (p.id == portfolio_id_) continue;+ auto p_trades = trading::pt_get_trades(p.id, 1);+ auto p_positions = trading::pt_get_positions(p.id);+ if (p_trades.empty() && p_positions.empty()) {+ trading::pt_delete_portfolio(p.id);+ cleaned++;+ }+ }+ if (cleaned > 0) {+ LOG_INFO(TAG, "Cleaned up %d empty portfolios", cleaned);+ }+ }+// Load positions, orders, trades, stats from DBpositions_ = trading::pt_get_positions(portfolio_id_);orders_ = trading::pt_get_orders(portfolio_id_);@@ -409,6 +459,22 @@ void CryptoTradingScreen::refresh_portfolio_data() {if (portfolio_id_.empty()) return;try {+ // Update position mark-to-market prices using current ticker data+ double last_price = current_ticker_.last;+ if (last_price > 0) {+ trading::pt_update_position_price(portfolio_id_, selected_symbol_, last_price);+ }++ // Also update prices for positions in other symbols from the price cache+ auto& svc = trading::ExchangeService::instance();+ for (const auto& pos : positions_) {+ if (pos.symbol == selected_symbol_) continue;+ auto cached = svc.get_cached_price(pos.symbol);+ if (cached.last > 0) {+ trading::pt_update_position_price(portfolio_id_, pos.symbol, cached.last);+ }+ }+std::lock_guard<std::mutex> lock(data_mutex_);portfolio_ = trading::pt_get_portfolio(portfolio_id_);positions_ = trading::pt_get_positions(portfolio_id_);@@ -487,30 +553,37 @@ void CryptoTradingScreen::render() {bool ws_ok = trading::ExchangeService::instance().is_ws_connected();if (!ws_ok) {- // WS not connected — fall back to REST polling+ // WS not connected — fall back to faster REST pollingticker_timer_ += dt;ob_timer_ += dt;wl_timer_ += dt;- if (ticker_timer_ >= 10.0f) {+ if (ticker_timer_ >= 3.0f) {ticker_timer_ = 0;async_refresh_ticker();}- if (ob_timer_ >= 5.0f) {+ if (ob_timer_ >= 3.0f) {ob_timer_ = 0;async_refresh_orderbook();}- if (wl_timer_ >= 30.0f) {+ if (wl_timer_ >= 15.0f) {wl_timer_ = 0;async_refresh_watchlist_prices();}}- if (portfolio_timer_ >= 3.0f) {+ if (portfolio_timer_ >= 1.5f) {portfolio_timer_ = 0;refresh_portfolio_data();}+ // Market info refresh (every 30s)+ market_info_timer_ += dt;+ if (market_info_timer_ >= 30.0f) {+ market_info_timer_ = 0;+ async_fetch_market_info();+ }+// Clear success/error messages after timeoutif (order_form_.msg_timer > 0) {order_form_.msg_timer -= dt;@@ -760,6 +833,10 @@ 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@@ -1115,10 +1192,12 @@ void CryptoTradingScreen::render_bottom_panel(float w, float h) {{"Positions", BottomTab::Positions},{"Orders", BottomTab::Orders},{"History", BottomTab::History},+ {"Trades", BottomTab::Trades},+ {"Market Info", BottomTab::MarketInfo},{"Stats", BottomTab::Stats},};- for (int i = 0; i < 4; i++) {+ for (int i = 0; i < 6; i++) {if (i > 0) ImGui::SameLine(0, 2);bool active = (bottom_tab_ == tabs[i].tab);ImGui::PushStyleColor(ImGuiCol_Button, active ? ACCENT_BG : ImVec4(0, 0, 0, 0));@@ -1152,10 +1231,12 @@ void CryptoTradingScreen::render_bottom_panel(float w, float h) {ImGui::BeginChild("##bottom_content", ImVec2(0, 0), false);switch (bottom_tab_) {- case BottomTab::Positions: render_positions_tab(); break;- case BottomTab::Orders: render_orders_tab(); break;- case BottomTab::History: render_history_tab(); break;- case BottomTab::Stats: render_stats_tab(); break;+ case BottomTab::Positions: render_positions_tab(); break;+ case BottomTab::Orders: render_orders_tab(); break;+ case BottomTab::History: render_history_tab(); break;+ case BottomTab::Trades: render_trades_tab(); break;+ case BottomTab::MarketInfo: render_market_info_tab(); break;+ case BottomTab::Stats: render_stats_tab(); break;}ImGui::EndChild();@@ -1382,14 +1463,26 @@ void CryptoTradingScreen::render_stats_tab() {ImGui::Columns(2, "##stats_cols", false);- ImGui::TextColored(TEXT_DIM, "Total PnL");+ // Compute unrealized PnL from open positions+ double unrealized_pnl = 0.0;+ for (const auto& pos : positions_) {+ unrealized_pnl += pos.unrealized_pnl;+ }++ ImGui::TextColored(TEXT_DIM, "Realized PnL");ImVec4 pnl_col = stats_.total_pnl >= 0 ? MARKET_GREEN : MARKET_RED;std::snprintf(buf, sizeof(buf), "%s%.2f", stats_.total_pnl >= 0 ? "+" : "", stats_.total_pnl);ImGui::TextColored(pnl_col, "%s", buf);ImGui::Spacing();+ ImGui::TextColored(TEXT_DIM, "Unrealized PnL");+ ImVec4 upnl_col = unrealized_pnl >= 0 ? MARKET_GREEN : MARKET_RED;+ std::snprintf(buf, sizeof(buf), "%s%.2f", unrealized_pnl >= 0 ? "+" : "", unrealized_pnl);+ ImGui::TextColored(upnl_col, "%s", buf);+ ImGui::Spacing();+ImGui::TextColored(TEXT_DIM, "Win Rate");- std::snprintf(buf, sizeof(buf), "%.1f%%", stats_.win_rate * 100);+ std::snprintf(buf, sizeof(buf), "%.1f%%", stats_.win_rate);ImGui::TextColored(TEXT_PRIMARY, "%s", buf);ImGui::Spacing();@@ -1424,6 +1517,189 @@ void CryptoTradingScreen::render_stats_tab() {ImGui::TextColored(MARKET_RED, "%s", buf);ImGui::Columns(1);++ ImGui::Spacing();+ ImGui::Separator();+ ImGui::Spacing();+ ImGui::PushStyleColor(ImGuiCol_Button, ImVec4(0.5f, 0.1f, 0.1f, 1.0f));+ if (ImGui::Button("Reset Portfolio", ImVec2(-1, 0))) {+ portfolio_ = trading::pt_reset_portfolio(portfolio_id_);+ refresh_portfolio_data();+ LOG_INFO(TAG, "Portfolio reset");+ }+ ImGui::PopStyleColor();+}++// ============================================================================+// Trades tab — Time & Sales feed+// ============================================================================+void CryptoTradingScreen::render_trades_tab() {+ std::lock_guard<std::mutex> lock(data_mutex_);++ if (recent_trades_.empty()) {+ if (trades_fetching_) {+ ImGui::TextColored(TEXT_DIM, "Loading trades...");+ } else {+ ImGui::TextColored(TEXT_DIM, "No trades yet");+ }+ return;+ }++ ImGuiTableFlags flags = ImGuiTableFlags_RowBg | ImGuiTableFlags_BordersInnerH |+ ImGuiTableFlags_SizingStretchProp | ImGuiTableFlags_ScrollY;++ if (ImGui::BeginTable("##trades_feed", 4, flags)) {+ ImGui::TableSetupColumn("Time", ImGuiTableColumnFlags_WidthStretch, 1.0f);+ ImGui::TableSetupColumn("Side", ImGuiTableColumnFlags_WidthStretch, 0.5f);+ ImGui::TableSetupColumn("Price", ImGuiTableColumnFlags_WidthStretch, 1.0f);+ ImGui::TableSetupColumn("Amount", ImGuiTableColumnFlags_WidthStretch, 0.8f);+ ImGui::TableSetupScrollFreeze(0, 1);+ ImGui::PushStyleColor(ImGuiCol_TableHeaderBg, BG_DARKEST);+ ImGui::TableHeadersRow();+ ImGui::PopStyleColor();++ char buf[32];+ for (const auto& t : recent_trades_) {+ ImGui::TableNextRow();++ ImGui::TableSetColumnIndex(0);+ time_t ts = t.timestamp / 1000;+ struct tm tm_buf{};+#ifdef _WIN32+ localtime_s(&tm_buf, &ts);+#else+ localtime_r(&ts, &tm_buf);+#endif+ std::snprintf(buf, sizeof(buf), "%02d:%02d:%02d", tm_buf.tm_hour, tm_buf.tm_min, tm_buf.tm_sec);+ ImGui::TextColored(TEXT_DIM, "%s", buf);++ ImGui::TableSetColumnIndex(1);+ ImVec4 col = (t.side == "buy") ? MARKET_GREEN : MARKET_RED;+ ImGui::TextColored(col, "%s", t.side == "buy" ? "BUY" : "SELL");++ ImGui::TableSetColumnIndex(2);+ std::snprintf(buf, sizeof(buf), "%.2f", t.price);+ ImGui::TextColored(col, "%s", buf);++ ImGui::TableSetColumnIndex(3);+ std::snprintf(buf, sizeof(buf), "%.4f", t.amount);+ ImGui::TextColored(TEXT_SECONDARY, "%s", buf);+ }++ ImGui::EndTable();+ }+}++void CryptoTradingScreen::async_fetch_trades() {+ if (trades_fetching_) return;+ trades_fetching_ = true;++ std::string sym = selected_symbol_;+ std::thread([this, sym]() {+ try {+ auto trades = trading::ExchangeService::instance().fetch_trades(sym, 100);+ std::lock_guard<std::mutex> lock(data_mutex_);+ recent_trades_.clear();+ for (const auto& t : trades) {+ recent_trades_.push_back({t.id, t.side, t.price, t.amount, t.timestamp});+ }+ } catch (const std::exception& e) {+ LOG_ERROR("CryptoTrading", "Failed to fetch trades: %s", e.what());+ }+ trades_fetching_ = false;+ }).detach();+}++// ============================================================================+// Market Info tab — funding rate, open interest, fees+// ============================================================================+void CryptoTradingScreen::render_market_info_tab() {+ std::lock_guard<std::mutex> lock(data_mutex_);+ char buf[64];++ if (!market_info_.has_data) {+ if (market_info_fetching_) {+ ImGui::TextColored(TEXT_DIM, "Loading market info...");+ } else {+ ImGui::TextColored(TEXT_DIM, "No market info available (spot mode)");+ }+ return;+ }++ ImGui::Columns(2, "##mktinfo_cols", false);++ ImGui::TextColored(TEXT_DIM, "Funding Rate");+ std::snprintf(buf, sizeof(buf), "%.4f%%", market_info_.funding_rate * 100);+ ImVec4 fr_col = market_info_.funding_rate >= 0 ? MARKET_GREEN : MARKET_RED;+ ImGui::TextColored(fr_col, "%s", buf);+ ImGui::Spacing();++ ImGui::TextColored(TEXT_DIM, "Mark Price");+ std::snprintf(buf, sizeof(buf), "%.2f", market_info_.mark_price);+ ImGui::TextColored(TEXT_PRIMARY, "%s", buf);+ ImGui::Spacing();++ ImGui::TextColored(TEXT_DIM, "Index Price");+ std::snprintf(buf, sizeof(buf), "%.2f", market_info_.index_price);+ ImGui::TextColored(TEXT_PRIMARY, "%s", buf);++ ImGui::NextColumn();++ ImGui::TextColored(TEXT_DIM, "Open Interest");+ std::snprintf(buf, sizeof(buf), "%.2f", market_info_.open_interest);+ ImGui::TextColored(TEXT_PRIMARY, "%s", buf);+ ImGui::Spacing();++ ImGui::TextColored(TEXT_DIM, "OI Value (USD)");+ double oi_val = market_info_.open_interest_value;+ if (oi_val > 1e9) std::snprintf(buf, sizeof(buf), "%.2fB", oi_val / 1e9);+ else if (oi_val > 1e6) std::snprintf(buf, sizeof(buf), "%.2fM", oi_val / 1e6);+ else std::snprintf(buf, sizeof(buf), "%.0f", oi_val);+ ImGui::TextColored(TEXT_PRIMARY, "%s", buf);+ ImGui::Spacing();++ if (market_info_.next_funding_time > 0) {+ ImGui::TextColored(TEXT_DIM, "Next Funding");+ int64_t now_ms = std::chrono::duration_cast<std::chrono::milliseconds>(+ std::chrono::system_clock::now().time_since_epoch()).count();+ int64_t diff_s = (market_info_.next_funding_time - now_ms) / 1000;+ if (diff_s > 0) {+ int h = (int)(diff_s / 3600);+ int m = (int)((diff_s % 3600) / 60);+ std::snprintf(buf, sizeof(buf), "%dh %dm", h, m);+ } else {+ std::snprintf(buf, sizeof(buf), "Now");+ }+ ImGui::TextColored(TEXT_PRIMARY, "%s", buf);+ }++ ImGui::Columns(1);+}++void CryptoTradingScreen::async_fetch_market_info() {+ if (market_info_fetching_) return;+ market_info_fetching_ = true;++ std::string sym = selected_symbol_;+ std::thread([this, sym]() {+ try {+ auto& svc = trading::ExchangeService::instance();+ auto fr = svc.fetch_funding_rate(sym);+ auto oi = svc.fetch_open_interest(sym);++ std::lock_guard<std::mutex> lock(data_mutex_);+ market_info_.funding_rate = fr.funding_rate;+ market_info_.mark_price = fr.mark_price;+ market_info_.index_price = fr.index_price;+ market_info_.next_funding_time = fr.next_funding_timestamp;+ market_info_.open_interest = oi.open_interest;+ market_info_.open_interest_value = oi.open_interest_value;+ market_info_.has_data = true;+ } catch (const std::exception& e) {+ LOG_DEBUG("CryptoTrading", "Market info fetch failed: %s", e.what());+ }+ market_info_fetching_ = false;+ }).detach();}// ============================================================================@@ -1798,6 +2074,19 @@ void CryptoTradingScreen::submit_order() {std::optional<double> price;std::optional<double> stop_price;+ // For market orders, use current ticker price as reference for margin calculation+ if (order_form_.type_idx == 0) {+ double ref = (side == "buy") ? current_ticker_.ask : current_ticker_.bid;+ if (ref <= 0) ref = current_ticker_.last;+ if (ref <= 0) {+ order_form_.error = "No market price available yet";+ order_form_.msg_timer = 5.0f;+ LOG_ERROR(TAG, "Market order rejected: no price data");+ return;+ }+ price = ref;+ }+if (order_form_.type_idx == 1 || order_form_.type_idx == 3) {try {double p = std::stod(order_form_.price_buf);@@ -1831,33 +2120,47 @@ void CryptoTradingScreen::submit_order() {}try {- auto order = trading::pt_place_order(- portfolio_id_, selected_symbol_, side, order_type,- qty, price, stop_price, order_form_.reduce_only);-- LOG_INFO(TAG, "Order created: id=%s type=%s side=%s qty=%.6f",- order.id.c_str(), order_type.c_str(), side.c_str(), qty);-- // For market orders, immediately fill at current price- if (order_type == "market" && current_ticker_.last > 0) {- double fill_price = side == "buy" ? current_ticker_.ask : current_ticker_.bid;- if (fill_price <= 0) fill_price = current_ticker_.last;- LOG_INFO(TAG, "Market order fill at %.2f", fill_price);- trading::pt_fill_order(order.id, fill_price);+ 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;} else {- trading::OrderMatcher::instance().add_order(order);- LOG_INFO(TAG, "Order added to matcher");+ // Paper trading+ auto order = trading::pt_place_order(+ portfolio_id_, selected_symbol_, side, order_type,+ qty, price, stop_price, order_form_.reduce_only);++ LOG_INFO(TAG, "Order created: id=%s type=%s side=%s qty=%.6f",+ order.id.c_str(), order_type.c_str(), side.c_str(), qty);++ // For market orders, immediately fill at current price+ if (order_type == "market" && current_ticker_.last > 0) {+ double fill_price = side == "buy" ? current_ticker_.ask : current_ticker_.bid;+ if (fill_price <= 0) fill_price = current_ticker_.last;+ LOG_INFO(TAG, "Market order fill at %.2f", fill_price);+ trading::pt_fill_order(order.id, fill_price);+ } else {+ trading::OrderMatcher::instance().add_order(order);+ LOG_INFO(TAG, "Order added to matcher");+ }++ order_form_.success = "Order placed: " + order.id.substr(0, 8);+ order_form_.msg_timer = 3.0f;}- order_form_.success = "Order placed: " + order.id.substr(0, 8);- order_form_.msg_timer = 3.0f;+ // Ensure the traded symbol is watched for price updates+ trading::ExchangeService::instance().watch_symbol(selected_symbol_, portfolio_id_);// Clear formorder_form_.quantity_buf[0] = '\0';order_form_.price_buf[0] = '\0';order_form_.stop_price_buf[0] = '\0';- // Refresh portfolio data+ // Refresh portfolio data immediatelyrefresh_portfolio_data();} catch (const std::exception& e) {order_form_.error = e.what();diff --git a/fincept-cpp/src/screens/crypto_trading/crypto_trading_screen.h b/fincept-cpp/src/screens/crypto_trading/crypto_trading_screen.hindex 9eb11e63a..a0795348b 100644--- a/fincept-cpp/src/screens/crypto_trading/crypto_trading_screen.h+++ b/fincept-cpp/src/screens/crypto_trading/crypto_trading_screen.h@@ -47,8 +47,14 @@ private:void render_positions_tab();void render_orders_tab();void render_history_tab();+ void render_trades_tab();+ void render_market_info_tab();void render_stats_tab();+ // Async fetchers for new data+ void async_fetch_market_info();+ void async_fetch_trades();+// Actionsvoid submit_order();void cancel_order(const std::string& order_id);@@ -103,11 +109,22 @@ private:std::atomic<bool> candles_loading_{false};std::atomic<bool> candles_fetching_{false};+ // --- Trade feed (Time & Sales) ---+ std::vector<TradeEntry> recent_trades_;+ static constexpr int MAX_TRADES = 200;+ std::atomic<bool> trades_fetching_{false};++ // --- Market info (funding rate, OI) ---+ MarketInfoData market_info_;+ std::atomic<bool> market_info_fetching_{false};+ float market_info_timer_ = 0;+// --- WebSocket state ---bool ws_started_ = false;int ws_price_cb_id_ = -1;int ws_ob_cb_id_ = -1;int ws_candle_cb_id_ = -1;+ int ws_trade_cb_id_ = -1;// --- Timers ---float ticker_timer_ = 0;diff --git a/fincept-cpp/src/screens/crypto_trading/crypto_types.h b/fincept-cpp/src/screens/crypto_trading/crypto_types.hindex 8a3cbae51..548164917 100644--- a/fincept-cpp/src/screens/crypto_trading/crypto_types.h+++ b/fincept-cpp/src/screens/crypto_trading/crypto_types.h@@ -38,8 +38,30 @@ struct OrderFormState {float msg_timer = 0;};+// Trade entry for Time & Sales feed+struct TradeEntry {+ std::string id;+ std::string side; // "buy" | "sell"+ double price = 0.0;+ double amount = 0.0;+ int64_t timestamp = 0;+};++// Market info (funding rate, open interest, etc.)+struct MarketInfoData {+ double funding_rate = 0.0;+ double mark_price = 0.0;+ double index_price = 0.0;+ double open_interest = 0.0;+ double open_interest_value = 0.0;+ double maker_fee = 0.0;+ double taker_fee = 0.0;+ int64_t next_funding_time = 0;+ bool has_data = false;+};+// Bottom panel tab-enum class BottomTab { Positions, Orders, History, Stats };+enum class BottomTab { Positions, Orders, History, Trades, MarketInfo, Stats };// Trading modeenum class TradingMode { Paper, Live };diff --git a/fincept-cpp/src/screens/dashboard/dashboard_data.cpp b/fincept-cpp/src/screens/dashboard/dashboard_data.cppindex c98704e32..e87d929a0 100644--- a/fincept-cpp/src/screens/dashboard/dashboard_data.cpp+++ b/fincept-cpp/src/screens/dashboard/dashboard_data.cpp@@ -1,10 +1,12 @@#include "dashboard_data.h"#include "python/python_runner.h"+#include "http/http_client.h"#include <nlohmann/json.hpp>#include <thread>#include <sstream>#include <ctime>#include <cstdio>+#include <algorithm>#ifdef _WIN32#include <windows.h>@@ -26,49 +28,42 @@ std::vector<std::string> DashboardData::symbols_for(DataCategory cat) {switch (cat) {case DataCategory::Indices:return {- "^GSPC", "^DJI", "^IXIC", "^RUT", "^FTSE",- "^GDAXI", "^FCHI", "^N225", "^HSI", "000001.SS",- "^BSESN", "^NSEI", "^STOXX50E", "^AXJO"+ "^GSPC", "^DJI", "^IXIC", "^FTSE",+ "^GDAXI", "^N225", "^HSI", "^NSEI"};case DataCategory::Forex:return {+ // G10 Majors"EURUSD=X", "GBPUSD=X", "USDJPY=X", "USDCHF=X",- "USDCAD=X", "AUDUSD=X", "NZDUSD=X", "EURGBP=X",- "EURJPY=X", "GBPJPY=X", "USDCNY=X", "USDINR=X"+ "USDCAD=X", "AUDUSD=X", "NZDUSD=X", "EURCHF=X",+ // Key crosses+ "EURGBP=X", "EURJPY=X", "GBPJPY=X",+ // Key EM+ "USDCNY=X", "USDINR=X"};case DataCategory::Commodities:return {- "GC=F", "SI=F", "PL=F", "HG=F",- "CL=F", "BZ=F", "NG=F",- "ZC=F", "ZW=F", "ZS=F"+ "GC=F", "SI=F", "CL=F", "NG=F", "HG=F"};case DataCategory::Crypto:return {- "BTC-USD", "ETH-USD", "BNB-USD", "SOL-USD",- "XRP-USD", "ADA-USD", "DOGE-USD", "LINK-USD",- "DOT-USD", "AVAX-USD", "UNI-USD", "ATOM-USD"+ "BTC-USD", "ETH-USD", "SOL-USD", "XRP-USD",+ "BNB-USD", "ADA-USD", "DOGE-USD"};case DataCategory::SectorETFs:return {- "XLK", "XLV", "XLF", "XLE", "XLI",- "XLB", "XLU", "XLRE", "XLC", "XLP", "XLY"+ "XLK", "XLV", "XLF", "XLE", "XLI", "XLY",+ "XLB", "XLU", "XLRE", "XLC"};case DataCategory::TopMovers:return {- "SMCI", "PLTR", "MSTR", "NVDA", "AMD", "TSLA",- "INTC", "PFE", "BA", "NKE", "DIS", "PYPL"+ "NVDA", "TSLA", "AMD", "PLTR", "SMCI", "INTC"};case DataCategory::Ticker:- return {- "^GSPC", "^DJI", "^IXIC", "^RUT", "^FTSE", "^GDAXI", "^N225", "^HSI",- "AAPL", "MSFT", "GOOGL", "AMZN", "NVDA", "TSLA",- "BTC-USD", "ETH-USD",- "GC=F", "CL=F",- "EURUSD=X", "GBPUSD=X", "USDJPY=X"- };+ return {}; // reuses Indices + Crypto + Forex data, no separate fetchcase DataCategory::MarketPulse:return {- "^VIX", "^TNX", "DX-Y.NYB", "GC=F", "CL=F", "BTC-USD"+ "^VIX", "^TNX", "DX-Y.NYB"};default:return {};@@ -80,57 +75,42 @@ std::map<std::string, std::string> DashboardData::labels_for(DataCategory cat) {case DataCategory::Indices:return {{"^GSPC", "S&P 500"}, {"^DJI", "DOW JONES"}, {"^IXIC", "NASDAQ"},- {"^RUT", "RUSSELL 2000"}, {"^FTSE", "FTSE 100"}, {"^GDAXI", "DAX"},- {"^FCHI", "CAC 40"}, {"^N225", "NIKKEI 225"}, {"^HSI", "HANG SENG"},- {"000001.SS", "SHANGHAI"}, {"^BSESN", "SENSEX"}, {"^NSEI", "NIFTY 50"},- {"^STOXX50E", "EURO STOXX"}, {"^AXJO", "ASX 200"}+ {"^FTSE", "FTSE 100"}, {"^GDAXI", "DAX"},+ {"^N225", "NIKKEI 225"}, {"^HSI", "HANG SENG"}, {"^NSEI", "NIFTY 50"}};case DataCategory::Forex:return {{"EURUSD=X", "EUR/USD"}, {"GBPUSD=X", "GBP/USD"}, {"USDJPY=X", "USD/JPY"},{"USDCHF=X", "USD/CHF"}, {"USDCAD=X", "USD/CAD"}, {"AUDUSD=X", "AUD/USD"},- {"NZDUSD=X", "NZD/USD"}, {"EURGBP=X", "EUR/GBP"}, {"EURJPY=X", "EUR/JPY"},- {"GBPJPY=X", "GBP/JPY"}, {"USDCNY=X", "USD/CNY"}, {"USDINR=X", "USD/INR"}+ {"NZDUSD=X", "NZD/USD"}, {"EURCHF=X", "EUR/CHF"},+ {"EURGBP=X", "EUR/GBP"}, {"EURJPY=X", "EUR/JPY"}, {"GBPJPY=X", "GBP/JPY"},+ {"USDCNY=X", "USD/CNY"}, {"USDINR=X", "USD/INR"}};case DataCategory::Commodities:return {- {"GC=F", "Gold"}, {"SI=F", "Silver"}, {"PL=F", "Platinum"}, {"HG=F", "Copper"},- {"CL=F", "WTI Crude"}, {"BZ=F", "Brent Crude"}, {"NG=F", "Natural Gas"},- {"ZC=F", "Corn"}, {"ZW=F", "Wheat"}, {"ZS=F", "Soybeans"}+ {"GC=F", "Gold"}, {"SI=F", "Silver"},+ {"CL=F", "WTI Crude"}, {"NG=F", "Natural Gas"}, {"HG=F", "Copper"}};case DataCategory::Crypto:return {- {"BTC-USD", "Bitcoin"}, {"ETH-USD", "Ethereum"}, {"BNB-USD", "BNB"},- {"SOL-USD", "Solana"}, {"XRP-USD", "XRP"}, {"ADA-USD", "Cardano"},- {"DOGE-USD", "Dogecoin"}, {"LINK-USD", "Chainlink"},- {"DOT-USD", "Polkadot"}, {"AVAX-USD", "Avalanche"},- {"UNI-USD", "Uniswap"}, {"ATOM-USD", "Cosmos"}+ {"BTC-USD", "Bitcoin"}, {"ETH-USD", "Ethereum"}, {"SOL-USD", "Solana"},+ {"XRP-USD", "XRP"}, {"BNB-USD", "BNB"}, {"ADA-USD", "Cardano"},+ {"DOGE-USD", "Dogecoin"}};case DataCategory::SectorETFs:return {{"XLK", "Technology"}, {"XLV", "Healthcare"}, {"XLF", "Financials"},- {"XLE", "Energy"}, {"XLI", "Industrials"}, {"XLB", "Materials"},- {"XLU", "Utilities"}, {"XLRE", "Real Estate"}, {"XLC", "Comm. Services"},- {"XLP", "Consumer Staples"}, {"XLY", "Consumer Disc."}+ {"XLE", "Energy"}, {"XLI", "Industrials"}, {"XLY", "Consumer Disc."},+ {"XLB", "Materials"}, {"XLU", "Utilities"}, {"XLRE", "Real Estate"},+ {"XLC", "Comm. Services"}};case DataCategory::TopMovers:return {- {"SMCI", "Super Micro"}, {"PLTR", "Palantir"}, {"MSTR", "MicroStrategy"},- {"NVDA", "NVIDIA"}, {"AMD", "AMD"}, {"TSLA", "Tesla"},- {"INTC", "Intel"}, {"PFE", "Pfizer"}, {"BA", "Boeing"},- {"NKE", "Nike"}, {"DIS", "Disney"}, {"PYPL", "PayPal"}+ {"NVDA", "NVIDIA"}, {"TSLA", "Tesla"}, {"AMD", "AMD"},+ {"PLTR", "Palantir"}, {"SMCI", "Super Micro"}, {"INTC", "Intel"}};case DataCategory::Ticker:- return {- {"^GSPC", "S&P 500"}, {"^DJI", "DOW"}, {"^IXIC", "NASDAQ"},- {"^RUT", "RUSSELL"}, {"^FTSE", "FTSE"}, {"^GDAXI", "DAX"},- {"^N225", "NIKKEI"}, {"^HSI", "HANG SENG"},- {"AAPL", "AAPL"}, {"MSFT", "MSFT"}, {"GOOGL", "GOOGL"},- {"AMZN", "AMZN"}, {"NVDA", "NVDA"}, {"TSLA", "TSLA"},- {"BTC-USD", "BTC"}, {"ETH-USD", "ETH"},- {"GC=F", "GOLD"}, {"CL=F", "CRUDE"},- {"EURUSD=X", "EUR/USD"}, {"GBPUSD=X", "GBP/USD"}, {"USDJPY=X", "USD/JPY"}- };+ return {}; // ticker bar assembles from other categoriescase DataCategory::MarketPulse:return {{"^VIX", "VIX"}, {"^TNX", "US 10Y"}, {"DX-Y.NYB", "DXY"},@@ -305,9 +285,16 @@ void DashboardData::fetch_category(DataCategory cat) {int idx = static_cast<int>(cat);auto& state = categories_[idx];if (state.loading.load()) return;- state.loading = true;auto syms = symbols_for(cat);+ 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;+ }++ state.loading = true;auto lbls = labels_for(cat);std::thread([this, idx, syms, lbls]() {@@ -338,62 +325,153 @@ void DashboardData::fetch_news_feeds() {if (news_loading_.load()) return;news_loading_ = true;- // For now, news comes from hardcoded headlines with real timestamps- // In a future iteration, this will call RSS feeds like NewsScreen does+ // Fetch real RSS feeds from top financial news sourcesstd::thread([this]() {- // Placeholder: generate timestamped news items- // Real implementation would reuse NewsScreen::fetch_news() RSS parsing- std::vector<NewsItem> items;-- // We'll use the news from the existing news screen infrastructure- // For the dashboard widget, we provide recent market headlines- // This will be connected to the real RSS system in the next iteration- time_t now = time(nullptr);-- const char* headlines[] = {- "Fed officials signal cautious approach to rate decisions amid mixed economic signals",- "Tech sector leads market rally as AI spending accelerates across enterprise",- "Oil prices stabilize following OPEC+ production agreement extension",- "Treasury yields edge higher on stronger-than-expected employment data",- "Consumer spending shows resilience despite elevated inflation readings",- "European Central Bank maintains rates, signals data-dependent approach",- "Semiconductor stocks surge on robust demand forecasts for AI chips",- "Cryptocurrency markets gain as institutional adoption continues to expand",- "Manufacturing PMI crosses expansion threshold for first time in months",- "Emerging market currencies strengthen as dollar index pulls back",- "Housing starts decline as mortgage rates remain elevated above 6.5%",- "Corporate earnings season shows mixed results across financial sector",+ struct FeedDef {+ const char* url;+ const char* source;+ const char* category;+ int priority;};- const char* sources[] = {- "Reuters", "Bloomberg", "CNBC", "FT", "WSJ",- "MarketWatch", "Reuters", "CoinDesk", "ISM",- "Reuters", "NAR", "Bloomberg"+ // 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://www.coindesk.com/arc/outboundfeeds/rss/", "CoinDesk", "CRYPTO", 2},+ {"https://www.federalreserve.gov/feeds/press_all.xml","Fed Reserve", "ECONOMIC", 1},};- const char* cats[] = {- "ECONOMIC", "MARKETS", "ENERGY", "MARKETS", "ECONOMIC",- "ECONOMIC", "MARKETS", "CRYPTO", "ECONOMIC",- "MARKETS", "ECONOMIC", "MARKETS"- };+ auto& http = http::HttpClient::instance();+ std::vector<NewsItem> items;- for (int i = 0; i < 12; i++) {- NewsItem item;- item.headline = headlines[i];- item.source = sources[i];- item.category = cats[i];- item.sort_ts = now - i * 900; // 15 min apart- item.priority = (i < 2) ? 1 : 3;-- time_t ts = static_cast<time_t>(item.sort_ts);- struct tm* t = localtime(&ts);- char buf[32];- std::strftime(buf, sizeof(buf), "%H:%M", t);- item.time_str = buf;-- items.push_back(item);+ http::Headers hdrs;+ 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;++ // Simple RSS XML parsing — extract <item> blocks+ std::string& xml = resp.body;+ size_t pos = 0;+ int count = 0;+ while (count < 5 && pos < xml.size()) { // Max 5 items per feed+ size_t item_start = xml.find("<item>", pos);+ if (item_start == std::string::npos) item_start = xml.find("<entry>", pos);+ if (item_start == std::string::npos) break;++ size_t item_end = xml.find("</item>", item_start);+ if (item_end == std::string::npos) item_end = xml.find("</entry>", item_start);+ if (item_end == std::string::npos) break;++ std::string item_xml = xml.substr(item_start, item_end - item_start + 7);++ // Extract title+ auto extract_tag = [](const std::string& s, const std::string& tag) -> std::string {+ std::string open = "<" + tag + ">";+ std::string close = "</" + tag + ">";+ size_t a = s.find(open);+ if (a == std::string::npos) return "";+ a += open.size();+ // Handle CDATA+ if (s.compare(a, 9, "<![CDATA[") == 0) a += 9;+ size_t b = s.find(close, a);+ if (b == std::string::npos) return "";+ std::string val = s.substr(a, b - a);+ // Strip CDATA end+ if (val.size() >= 3 && val.substr(val.size() - 3) == "]]>")+ val = val.substr(0, val.size() - 3);+ return val;+ };++ std::string title = extract_tag(item_xml, "title");+ if (title.empty()) { pos = item_end + 7; continue; }++ // Strip HTML entities+ auto strip_entities = [](std::string& s) {+ size_t p2 = 0;+ while ((p2 = s.find("&", p2)) != std::string::npos) s.replace(p2, 5, "&");+ p2 = 0;+ while ((p2 = s.find("<", p2)) != std::string::npos) s.replace(p2, 4, "<");+ p2 = 0;+ while ((p2 = s.find(">", p2)) != std::string::npos) s.replace(p2, 4, ">");+ p2 = 0;+ while ((p2 = s.find(""", p2)) != std::string::npos) s.replace(p2, 6, "\"");+ p2 = 0;+ while ((p2 = s.find("'", p2)) != std::string::npos) s.replace(p2, 5, "'");+ p2 = 0;+ while ((p2 = s.find("'", p2)) != std::string::npos) s.replace(p2, 6, "'");+ };+ strip_entities(title);++ // Extract pubDate+ std::string date_str = extract_tag(item_xml, "pubDate");+ if (date_str.empty()) date_str = extract_tag(item_xml, "published");+ if (date_str.empty()) date_str = extract_tag(item_xml, "updated");++ NewsItem ni;+ ni.headline = title;+ ni.source = feed.source;+ ni.category = feed.category;+ ni.priority = feed.priority;++ // Parse date to timestamp (use current time if parse fails)+ ni.sort_ts = std::time(nullptr) - count * 60; // Default: stagger by 1 min+ if (!date_str.empty()) {+ // Try RFC 2822: "Wed, 15 Mar 2026 14:30:00 GMT"+ struct tm t = {};+ const char* months[] = {"Jan","Feb","Mar","Apr","May","Jun",+ "Jul","Aug","Sep","Oct","Nov","Dec"};+ int day = 0, year = 0, hour = 0, min2 = 0, sec = 0;+ char mon[8] = {};+ if (std::sscanf(date_str.c_str(), "%*[^,], %d %3s %d %d:%d:%d",+ &day, mon, &year, &hour, &min2, &sec) >= 4) {+ t.tm_mday = day; t.tm_year = year - 1900;+ t.tm_hour = hour; t.tm_min = min2; t.tm_sec = sec;+ for (int m = 0; m < 12; m++) {+ if (std::strncmp(mon, months[m], 3) == 0) { t.tm_mon = m; break; }+ }+ time_t parsed = mktime(&t);+ if (parsed > 0) ni.sort_ts = parsed;+ } else if (std::sscanf(date_str.c_str(), "%d-%*d-%*dT%d:%d:%d",+ &year, &hour, &min2, &sec) >= 1) {+ // ISO 8601 fallback — at least get the date+ int iy = 0, im = 0, id = 0;+ if (std::sscanf(date_str.c_str(), "%d-%d-%dT%d:%d:%d",+ &iy, &im, &id, &hour, &min2, &sec) >= 3) {+ t.tm_year = iy - 1900; t.tm_mon = im - 1; t.tm_mday = id;+ t.tm_hour = hour; t.tm_min = min2; t.tm_sec = sec;+ time_t parsed = mktime(&t);+ if (parsed > 0) ni.sort_ts = parsed;+ }+ }+ }++ time_t ts = static_cast<time_t>(ni.sort_ts);+ struct tm* lt = localtime(&ts);+ char tbuf[32];+ std::strftime(tbuf, sizeof(tbuf), "%H:%M", lt);+ ni.time_str = tbuf;++ items.push_back(ni);+ count++;+ pos = item_end + 7;+ }}+ // Sort newest first+ std::sort(items.begin(), items.end(),+ [](const NewsItem& a, const NewsItem& b) { return a.sort_ts > b.sort_ts; });++ // Limit to 30 items for dashboard widget+ if (items.size() > 30) items.resize(30);+{std::lock_guard<std::mutex> lock(mutex_);news_ = std::move(items);diff --git a/fincept-cpp/src/screens/dashboard/dashboard_panels.cpp b/fincept-cpp/src/screens/dashboard/dashboard_panels.cppindex 877bf8664..476f781f1 100644--- a/fincept-cpp/src/screens/dashboard/dashboard_panels.cpp+++ b/fincept-cpp/src/screens/dashboard/dashboard_panels.cpp@@ -3,11 +3,97 @@#include <imgui.h>#include <cmath>#include <algorithm>+#include <ctime>namespace fincept::dashboard {+// ============================================================================+// Helper: get market open/close status based on UTC time+// Matches original Tauri MarketPulsePanel getMarketStatus()+// ============================================================================+static const char* get_market_status(const char* region) {+ time_t now = time(nullptr);+ struct tm utc_tm;+#ifdef _WIN32+ gmtime_s(&utc_tm, &now);+#else+ gmtime_r(&now, &utc_tm);+#endif+ int h = utc_tm.tm_hour;+ int wd = utc_tm.tm_wday; // 0=Sun, 6=Sat++ // Weekend — all closed+ if (wd == 0 || wd == 6) return "CLOSED";++ if (strcmp(region, "US") == 0) {+ if (h >= 13 && h < 14) return "PRE";+ if (h >= 14 && h < 21) return "OPEN";+ return "CLOSED";+ }+ if (strcmp(region, "UK") == 0) {+ if (h >= 7 && h < 8) return "PRE";+ if (h >= 8 && h < 17) return "OPEN";+ return "CLOSED";+ }+ if (strcmp(region, "JP") == 0) {+ if (h >= 0 && h < 6) return "OPEN";+ return "CLOSED";+ }+ if (strcmp(region, "CN") == 0) {+ if (h >= 1 && h < 7) return "OPEN";+ return "CLOSED";+ }+ if (strcmp(region, "IN") == 0) {+ if (h >= 3 && h < 10) return "OPEN";+ return "CLOSED";+ }+ return "CLOSED";+}++// Helper: draw a section header bar matching the original SectionHeader component+static void section_header(float pad, float inner_w, const char* title, ImVec4 icon_col) {+ ImGui::PushStyleColor(ImGuiCol_ChildBg, ImVec4(0.102f, 0.102f, 0.102f, 1.0f));+ ImGui::BeginChild(title, ImVec2(inner_w + pad * 2, 20), false);+ ImGui::SetCursorPos(ImVec2(pad, 3));+ ImGui::TextColored(icon_col, "*");+ ImGui::SameLine(0, 4);+ ImGui::TextColored(ImVec4(0.47f, 0.47f, 0.47f, 1.0f), "%s", title);+ ImGui::EndChild();+ ImGui::PopStyleColor();+}++// Helper: draw a breadth bar (label, advancing/declining counts, colored bar)+static void breadth_bar(float pad, float inner_w, const char* label, int advancing, int declining) {+ ImGui::SetCursorPosX(pad);++ // Label and counts on same line+ ImGui::TextColored(ImVec4(0.47f, 0.47f, 0.47f, 1.0f), "%s", label);+ ImGui::SameLine(inner_w - 20);+ ImGui::TextColored(ImVec4(0.0f, 0.84f, 0.435f, 1.0f), "%d", advancing);+ ImGui::SameLine(0, 2);+ ImGui::TextColored(ImVec4(0.29f, 0.29f, 0.29f, 1.0f), "/");+ ImGui::SameLine(0, 2);+ ImGui::TextColored(ImVec4(1.0f, 0.231f, 0.231f, 1.0f), "%d", declining);++ // Bar+ int total = advancing + declining;+ float adv_pct = total > 0 ? (float)advancing / total : 0.5f;+ ImVec2 p = ImGui::GetCursorScreenPos();+ p.x += pad;+ float bw = inner_w;+ ImDrawList* dl = ImGui::GetWindowDrawList();+ dl->AddRectFilled(ImVec2(p.x, p.y), ImVec2(p.x + bw * adv_pct, p.y + 4),+ IM_COL32(0, 214, 111, 255), 2.0f);+ dl->AddRectFilled(ImVec2(p.x + bw * adv_pct, p.y), ImVec2(p.x + bw, p.y + 4),+ IM_COL32(255, 59, 59, 255), 2.0f);+ ImGui::Dummy(ImVec2(bw, 8));+}+// ============================================================================// Market Pulse Panel (Right Sidebar)+// Matches original Tauri MarketPulsePanel.tsx:+// Fear & Greed → Market Breadth → Top Gainers → Top Losers+// → Global Snapshot → Market Hours// ============================================================================void DashboardScreen::render_market_pulse(float width, float height) {ImGui::PushStyleColor(ImGuiCol_ChildBg, ImVec4(0.04f, 0.04f, 0.04f, 1.0f));@@ -18,29 +104,62 @@ void DashboardScreen::render_market_pulse(float width, float height) {float pad = 8.0f;float inner_w = width - pad * 2;- // Title+ // ── Panel Header with live pulse dot ──ImGui::SetCursorPos(ImVec2(pad, 4));+ ImGui::TextColored(FC_ORANGE, "*"); ImGui::SameLine(0, 4);ImGui::TextColored(FC_ORANGE, "MARKET PULSE");++ // Pulsing green dot (right side)+ {+ float dot_x = width - pad - 6;+ float dot_y = ImGui::GetCursorScreenPos().y - 10;+ ImDrawList* dl = ImGui::GetWindowDrawList();+ ImVec2 sp = ImGui::GetWindowPos();+ float pulse = (float)(0.5 + 0.5 * sin(ImGui::GetTime() * 3.14159));+ dl->AddCircleFilled(ImVec2(sp.x + dot_x, dot_y),+ 3.0f, IM_COL32(0, 214, 111, (int)(120 + 135 * pulse)));+ }+ImGui::Spacing();- ImGui::PushStyleColor(ImGuiCol_Separator, FC_BORDER);+ ImGui::PushStyleColor(ImGuiCol_Separator, ImVec4(1.0f, 0.533f, 0.0f, 0.25f));ImGui::Separator();ImGui::PopStyleColor();- // ---- Fear & Greed Gauge ----+ // ════════════════════════════════════════════════════════════════════════+ // 1. FEAR & GREED INDEX (VIX-derived, 5-level, matches original)+ // ════════════════════════════════════════════════════════════════════════ImGui::Spacing();ImGui::SetCursorPosX(pad);- ImGui::TextColored(FC_GRAY, "FEAR & GREED");+ ImGui::TextColored(FC_GRAY, "FEAR & GREED INDEX");+ ImGui::SameLine(inner_w);+ ImGui::TextColored(FC_ORANGE, "*"); // gauge icon+ // Assemble global snapshot from MarketPulse (VIX, TNX, DXY) + Commodities (Gold, Oil) + Crypto (BTC)auto pulse_quotes = DashboardData::instance().get_quotes(DataCategory::MarketPulse);+ for (auto& q : DashboardData::instance().get_quotes(DataCategory::Commodities)) {+ if (q.symbol == "GC=F" || q.symbol == "CL=F") pulse_quotes.push_back(q);+ }+ for (auto& q : DashboardData::instance().get_quotes(DataCategory::Crypto)) {+ if (q.symbol == "BTC-USD") pulse_quotes.push_back(q);+ }float vix_val = 0;for (auto& q : pulse_quotes) {if (q.symbol == "^VIX") { vix_val = (float)q.price; break; }}- float fear_greed = vix_val > 0 ?- std::max(0.0f, std::min(100.0f, 100.0f - (vix_val - 10.0f) * 3.0f)) : 55.0f;+ // VIX → Fear/Greed mapping (matches original exactly)+ float fear_greed = 50.0f;+ if (vix_val > 0) {+ if (vix_val <= 12.0f) fear_greed = 95.0f;+ else if (vix_val <= 15.0f) fear_greed = 80.0f + (15.0f - vix_val) * 5.0f;+ else if (vix_val <= 20.0f) fear_greed = 60.0f + (20.0f - vix_val) * 4.0f;+ else if (vix_val <= 25.0f) fear_greed = 40.0f + (25.0f - vix_val) * 4.0f;+ else if (vix_val <= 35.0f) fear_greed = 20.0f + (35.0f - vix_val) * 2.0f;+ else fear_greed = std::max(5.0f, 20.0f - (vix_val - 35.0f));+ fear_greed = std::round(fear_greed);+ }- // Gradient bar+ // Gradient bar: Red → Orange → Yellow → LightGreen → GreenImVec2 bar_start = ImGui::GetCursorScreenPos();bar_start.x += pad;float bar_w = inner_w;@@ -49,137 +168,323 @@ void DashboardScreen::render_market_pulse(float width, float height) {for (int i = 0; i < (int)bar_w; i++) {float t = (float)i / bar_w;- int r, g;- if (t < 0.5f) { r = 255; g = (int)(t * 2 * 255); }- else { r = (int)((1.0f - (t - 0.5f) * 2) * 255); g = 255; }+ int r, g, b = 0;+ if (t < 0.25f) {+ // Red → Orange+ float s = t / 0.25f;+ r = 255; g = (int)(102 * s); b = (int)(68 * (1.0f - s));+ } else if (t < 0.5f) {+ // Orange → Yellow+ float s = (t - 0.25f) / 0.25f;+ r = 255; g = 102 + (int)(153 * s); b = 0;+ } else if (t < 0.75f) {+ // Yellow → Light green+ float s = (t - 0.5f) / 0.25f;+ r = 255 - (int)(119 * s); g = 255 - (int)(51 * s); b = 0 + (int)(68 * s);+ } else {+ // Light green → Green+ float s = (t - 0.75f) / 0.25f;+ r = 136 - (int)(136 * s); g = 204 + (int)(10 * s); b = 68 + (int)(43 * s);+ }dl->AddRectFilled(ImVec2(bar_start.x + i, bar_start.y),ImVec2(bar_start.x + i + 1, bar_start.y + bar_h),- IM_COL32(r, g, 0, 180));+ IM_COL32(r, g, b, 220));}+ // Pointer circle on gaugefloat ptr_x = bar_start.x + (fear_greed / 100.0f) * bar_w;- dl->AddTriangleFilled(- ImVec2(ptr_x - 3, bar_start.y + bar_h + 1),- ImVec2(ptr_x + 3, bar_start.y + bar_h + 1),- ImVec2(ptr_x, bar_start.y + bar_h - 2),- IM_COL32(255, 255, 255, 220));- ImGui::Dummy(ImVec2(bar_w, bar_h + 6));+ // 5-level label & color (matches original)+ const char* fg_label; ImVec4 fg_color;+ if (fear_greed <= 20.0f) { fg_label = "EXTREME FEAR"; fg_color = FC_RED; }+ else if (fear_greed <= 40.0f) { fg_label = "FEAR"; fg_color = ImVec4(1.0f, 0.4f, 0.267f, 1.0f); }+ else if (fear_greed <= 60.0f) { fg_label = "NEUTRAL"; fg_color = FC_YELLOW; }+ else if (fear_greed <= 80.0f) { fg_label = "GREED"; fg_color = ImVec4(0.533f, 0.8f, 0.267f, 1.0f); }+ else { fg_label = "EXTREME GREED"; fg_color = FC_GREEN; }- const char* fg_label = fear_greed <= 25 ? "FEAR" : fear_greed <= 50 ? "CAUTIOUS" :- fear_greed <= 75 ? "NEUTRAL" : "GREED";- ImVec4 fg_color = fear_greed <= 25 ? FC_RED : fear_greed <= 50 ? FC_ORANGE :- fear_greed <= 75 ? FC_YELLOW : FC_GREEN;+ // Draw pointer with glow+ ImU32 ptr_col = ImGui::ColorConvertFloat4ToU32(fg_color);+ dl->AddCircleFilled(ImVec2(ptr_x, bar_start.y + bar_h / 2), 6.0f, IM_COL32(255, 255, 255, 240));+ dl->AddCircle(ImVec2(ptr_x, bar_start.y + bar_h / 2), 6.0f, ptr_col, 0, 2.0f);+ ImGui::Dummy(ImVec2(bar_w, bar_h + 8));++ // Value and labelImGui::SetCursorPosX(pad);- ImGui::TextColored(fg_color, "%.0f %s", fear_greed, fg_label);+ ImGui::PushStyleColor(ImGuiCol_Text, fg_color);+ ImGui::Text("%.0f", fear_greed);+ ImGui::PopStyleColor();+ ImGui::SameLine(0, 2);+ ImGui::TextColored(FC_MUTED, "/100");++ // Right-align the label+ {+ ImVec2 label_size = ImGui::CalcTextSize(fg_label);+ float label_x = pad + inner_w - label_size.x;+ ImGui::SameLine(label_x);+ ImGui::TextColored(fg_color, "%s", fg_label);+ }ImGui::Spacing();- ImGui::PushStyleColor(ImGuiCol_Separator, FC_BORDER); ImGui::Separator(); ImGui::PopStyleColor();- // ---- Global Snapshot ----- ImGui::Spacing();- ImGui::SetCursorPosX(pad);- ImGui::TextColored(FC_GRAY, "GLOBAL SNAPSHOT");+ // ════════════════════════════════════════════════════════════════════════+ // 2. MARKET BREADTH (NYSE / NASDAQ / S&P 500 — derived from movers)+ // ════════════════════════════════════════════════════════════════════════+ section_header(pad, inner_w, "MARKET BREADTH", FC_CYAN);ImGui::Spacing();- if (!pulse_quotes.empty()) {- if (ImGui::BeginTable("##pulse_snap", 3, ImGuiTableFlags_SizingStretchProp,- ImVec2(inner_w, 0))) {- ImGui::TableSetupColumn("Name", 0, 1.2f);- ImGui::TableSetupColumn("Price", 0, 1.0f);- ImGui::TableSetupColumn("Chg", 0, 0.9f);- for (auto& q : pulse_quotes) {- ImGui::TableNextRow();- ImGui::TableNextColumn(); ImGui::TextColored(FC_WHITE, "%s", q.label.c_str());- ImGui::TableNextColumn(); ImGui::Text("%s", fmt_price(q.price).c_str());- ImGui::TableNextColumn(); ImGui::TextColored(chg_col(q.change_percent), "%+.2f%%", q.change_percent);- }- ImGui::EndTable();+ auto movers = DashboardData::instance().get_quotes(DataCategory::TopMovers);+ if (!movers.empty()) {+ int adv = 0, dec = 0;+ for (auto& q : movers) {+ if (q.change_percent > 0) adv++;+ else if (q.change_percent < 0) dec++;}+ int total = (int)movers.size();+ if (total == 0) total = 1;++ // Scale to approximate real market breadth (like original)+ int nyse_adv = (int)((float)adv / total * 3000) + (int)(fmod(ImGui::GetTime() * 7.3, 50));+ int nyse_dec = (int)((float)dec / total * 3000) + (int)(fmod(ImGui::GetTime() * 3.1, 50));+ int nas_adv = (int)((float)adv / total * 3500) + (int)(fmod(ImGui::GetTime() * 5.7, 50));+ int nas_dec = (int)((float)dec / total * 3500) + (int)(fmod(ImGui::GetTime() * 2.3, 50));+ int sp_adv = (int)((float)adv / total * 500);+ int sp_dec = (int)((float)dec / total * 500);++ breadth_bar(pad, inner_w, "NYSE", nyse_adv, nyse_dec);+ breadth_bar(pad, inner_w, "NASDAQ", nas_adv, nas_dec);+ breadth_bar(pad, inner_w, "S&P 500", sp_adv, sp_dec);} else {ImGui::SetCursorPosX(pad);ImGui::TextColored(FC_MUTED, "Loading...");}ImGui::Spacing();- ImGui::PushStyleColor(ImGuiCol_Separator, FC_BORDER); ImGui::Separator(); ImGui::PopStyleColor();- // ---- Top Movers ----- ImGui::Spacing();- ImGui::SetCursorPosX(pad);- ImGui::TextColored(FC_GRAY, "TOP MOVERS");- ImGui::Spacing();+ // ════════════════════════════════════════════════════════════════════════+ // 3. TOP GAINERS+ // ════════════════════════════════════════════════════════════════════════+ section_header(pad, inner_w, "TOP GAINERS", FC_GREEN);- auto movers = DashboardData::instance().get_quotes(DataCategory::TopMovers);if (!movers.empty()) {auto sorted = movers;std::sort(sorted.begin(), sorted.end(), [](const QuoteEntry& a, const QuoteEntry& b) {- return std::abs(a.change_percent) > std::abs(b.change_percent);+ return a.change_percent > b.change_percent;});- int show = std::min(6, (int)sorted.size());-- if (ImGui::BeginTable("##pulse_movers", 3, ImGuiTableFlags_SizingStretchProp,- ImVec2(inner_w, 0))) {- ImGui::TableSetupColumn("Dir", 0, 0.8f);- ImGui::TableSetupColumn("Name", 0, 1.5f);- ImGui::TableSetupColumn("Price", 0, 1.0f);- for (int i = 0; i < show; i++) {- auto& q = sorted[i];++ int shown = 0;+ if (ImGui::BeginTable("##pulse_gainers", 3, ImGuiTableFlags_SizingStretchProp,+ ImVec2(inner_w + pad, 0))) {+ ImGui::TableSetupColumn("Sym", 0, 1.0f);+ ImGui::TableSetupColumn("Vol", 0, 0.8f);+ ImGui::TableSetupColumn("Chg", 0, 0.8f);+ for (auto& q : sorted) {+ if (q.change_percent <= 0) break;+ if (shown >= 3) break;ImGui::TableNextRow();ImGui::TableNextColumn();- ImGui::TextColored(chg_col(q.change_percent), "%s%+.1f%%",- q.change_percent >= 0 ? "+" : "", q.change_percent);+ ImGui::TextColored(FC_WHITE, "%s", q.symbol.c_str());+ ImGui::TextColored(FC_MUTED, "%s", q.label.c_str());ImGui::TableNextColumn();- ImGui::TextColored(FC_WHITE, "%s", q.label.c_str());+ if (q.volume > 0)+ ImGui::TextColored(FC_MUTED, "VOL: %s", fmt_volume(q.volume).c_str());ImGui::TableNextColumn();- ImGui::TextColored(FC_GRAY, "$%s", fmt_price(q.price).c_str());+ ImGui::TextColored(FC_GREEN, "+%.2f%%", q.change_percent);+ shown++;}ImGui::EndTable();}+ if (shown == 0) {+ ImGui::SetCursorPosX(pad);+ ImGui::TextColored(FC_MUTED, "No gainers data");+ }} else {+ // Skeleton loading+ for (int i = 0; i < 3; i++) {+ ImGui::SetCursorPosX(pad);+ ImVec2 sp = ImGui::GetCursorScreenPos();+ dl->AddRectFilled(sp, ImVec2(sp.x + 40, sp.y + 10), IM_COL32(42, 42, 42, 255), 2.0f);+ dl->AddRectFilled(ImVec2(sp.x + inner_w - 50, sp.y), ImVec2(sp.x + inner_w, sp.y + 10), IM_COL32(42, 42, 42, 255), 2.0f);+ ImGui::Dummy(ImVec2(inner_w, 16));+ }+ }++ // ════════════════════════════════════════════════════════════════════════+ // 4. TOP LOSERS+ // ════════════════════════════════════════════════════════════════════════+ section_header(pad, inner_w, "TOP LOSERS", FC_RED);++ if (!movers.empty()) {+ auto sorted = movers;+ std::sort(sorted.begin(), sorted.end(), [](const QuoteEntry& a, const QuoteEntry& b) {+ return a.change_percent < b.change_percent;+ });++ int shown = 0;+ if (ImGui::BeginTable("##pulse_losers", 3, ImGuiTableFlags_SizingStretchProp,+ ImVec2(inner_w + pad, 0))) {+ ImGui::TableSetupColumn("Sym", 0, 1.0f);+ ImGui::TableSetupColumn("Vol", 0, 0.8f);+ ImGui::TableSetupColumn("Chg", 0, 0.8f);+ for (auto& q : sorted) {+ if (q.change_percent >= 0) break;+ if (shown >= 3) break;+ ImGui::TableNextRow();+ ImGui::TableNextColumn();+ ImGui::TextColored(FC_WHITE, "%s", q.symbol.c_str());+ ImGui::TextColored(FC_MUTED, "%s", q.label.c_str());+ ImGui::TableNextColumn();+ if (q.volume > 0)+ ImGui::TextColored(FC_MUTED, "VOL: %s", fmt_volume(q.volume).c_str());+ ImGui::TableNextColumn();+ ImGui::TextColored(FC_RED, "%.2f%%", q.change_percent);+ shown++;+ }+ ImGui::EndTable();+ }+ if (shown == 0) {+ ImGui::SetCursorPosX(pad);+ ImGui::TextColored(FC_MUTED, "No losers data");+ }+ } else {+ for (int i = 0; i < 3; i++) {+ ImGui::SetCursorPosX(pad);+ ImVec2 sp = ImGui::GetCursorScreenPos();+ dl->AddRectFilled(sp, ImVec2(sp.x + 40, sp.y + 10), IM_COL32(42, 42, 42, 255), 2.0f);+ dl->AddRectFilled(ImVec2(sp.x + inner_w - 50, sp.y), ImVec2(sp.x + inner_w, sp.y + 10), IM_COL32(42, 42, 42, 255), 2.0f);+ ImGui::Dummy(ImVec2(inner_w, 16));+ }+ }++ // ════════════════════════════════════════════════════════════════════════+ // 5. GLOBAL SNAPSHOT (formatted like original: VIX, 10Y, DXY, GOLD, OIL, BTC)+ // ════════════════════════════════════════════════════════════════════════+ section_header(pad, inner_w, "GLOBAL SNAPSHOT", FC_BLUE);++ struct SnapItem {+ const char* label;+ const char* symbol;+ ImVec4 color;+ bool is_yield; // TNX special handling+ bool is_btc; // BTC formatting+ bool is_gold; // no decimals+ };+ SnapItem snaps[] = {+ {"VIX", "^VIX", FC_YELLOW, false, false, false},+ {"US 10Y", "^TNX", FC_CYAN, true, false, false},+ {"DXY", "DX-Y.NYB", FC_CYAN, false, false, false},+ {"GOLD", "GC=F", FC_YELLOW, false, false, true},+ {"OIL WTI", "CL=F", FC_CYAN, false, false, false},+ {"BTC", "BTC-USD", FC_ORANGE, false, true, false},+ };++ bool has_global = !pulse_quotes.empty();+ for (auto& s : snaps) {ImGui::SetCursorPosX(pad);- ImGui::TextColored(FC_MUTED, "Loading...");++ // Label+ ImGui::TextColored(FC_GRAY, "%s", s.label);++ // Value + change (right aligned)+ if (!has_global) {+ // Loading skeleton+ ImVec2 sp = ImGui::GetCursorScreenPos();+ float rx = sp.x + inner_w - 60;+ dl->AddRectFilled(ImVec2(rx, sp.y - 14), ImVec2(rx + 60, sp.y - 4), IM_COL32(42, 42, 42, 255), 2.0f);+ } else {+ // Find the quote+ const QuoteEntry* found = nullptr;+ for (auto& q : pulse_quotes) {+ if (q.symbol == s.symbol) { found = &q; break; }+ }++ char val_buf[32] = "--";+ char chg_buf[32] = "";+ if (found && found->price > 0) {+ if (s.is_yield) {+ std::snprintf(val_buf, sizeof(val_buf), "%.2f%%", found->price / 10.0);+ } else if (s.is_btc) {+ std::snprintf(val_buf, sizeof(val_buf), "$%.1fK", found->price / 1000.0);+ } else if (s.is_gold) {+ std::snprintf(val_buf, sizeof(val_buf), "$%.0f", found->price);+ } else {+ std::snprintf(val_buf, sizeof(val_buf), "%.2f", found->price);+ }+ std::snprintf(chg_buf, sizeof(chg_buf), "%+.2f%%", found->change_percent);+ }++ // Right-align value+ ImVec2 val_size = ImGui::CalcTextSize(val_buf);+ ImVec2 chg_size = ImGui::CalcTextSize(chg_buf);+ float total_w = val_size.x + (chg_buf[0] ? chg_size.x + 6 : 0);+ float rx = pad + inner_w - total_w;++ ImGui::SameLine(rx);+ ImGui::TextColored(s.color, "%s", val_buf);+ if (chg_buf[0]) {+ ImGui::SameLine(0, 6);+ ImVec4 cc = (chg_buf[0] == '+') ? FC_GREEN :+ (chg_buf[0] == '-') ? FC_RED : FC_MUTED;+ ImGui::TextColored(cc, "%s", chg_buf);+ }+ }++ // Separator line+ ImGui::PushStyleColor(ImGuiCol_Separator, FC_BORDER);+ ImGui::Separator();+ ImGui::PopStyleColor();}ImGui::Spacing();- ImGui::PushStyleColor(ImGuiCol_Separator, FC_BORDER); ImGui::Separator(); ImGui::PopStyleColor();- // ---- Market Breadth ----- ImGui::Spacing();- ImGui::SetCursorPosX(pad);- ImGui::TextColored(FC_GRAY, "MARKET BREADTH");+ // ════════════════════════════════════════════════════════════════════════+ // 6. MARKET HOURS (matches original: NYSE, LSE, TSE, SSE, NSE)+ // ════════════════════════════════════════════════════════════════════════+ section_header(pad, inner_w, "MARKET HOURS", FC_YELLOW);ImGui::Spacing();- auto indices = DashboardData::instance().get_quotes(DataCategory::Indices);- if (!indices.empty()) {- int advancing = 0, declining = 0;- for (auto& q : indices) {- if (q.change_percent > 0) advancing++;- else if (q.change_percent < 0) declining++;- }- int total = (int)indices.size();+ struct ExchangeInfo {+ const char* name;+ const char* region;+ ImVec4 accent;+ };+ ExchangeInfo exchanges[] = {+ {"NYSE/NASDAQ", "US", FC_GREEN},+ {"LSE", "UK", FC_BLUE},+ {"TSE (TOKYO)", "JP", FC_PURPLE},+ {"SSE (SHANGHAI)","CN", FC_RED},+ {"NSE (INDIA)", "IN", FC_ORANGE},+ };++ for (auto& ex : exchanges) {+ const char* status = get_market_status(ex.region);+ ImVec4 status_col;+ if (strcmp(status, "OPEN") == 0) status_col = FC_GREEN;+ else if (strcmp(status, "PRE") == 0) status_col = FC_YELLOW;+ else status_col = FC_RED;ImGui::SetCursorPosX(pad);- ImGui::TextColored(FC_GREEN, "Adv: %d", advancing);- ImGui::SameLine(0, 8);- ImGui::TextColored(FC_RED, "Dec: %d", declining);- ImGui::SameLine(0, 8);- ImGui::TextColored(FC_GRAY, "Unch: %d", total - advancing - declining);-- if (total > 0) {- float adv_pct = (float)advancing / total;- ImVec2 p = ImGui::GetCursorScreenPos();- p.x += pad;- float bw = inner_w;- dl = ImGui::GetWindowDrawList();- dl->AddRectFilled(ImVec2(p.x, p.y), ImVec2(p.x + bw * adv_pct, p.y + 5),- ImGui::ColorConvertFloat4ToU32(FC_GREEN), 2.0f);- dl->AddRectFilled(ImVec2(p.x + bw * adv_pct, p.y), ImVec2(p.x + bw, p.y + 5),- ImGui::ColorConvertFloat4ToU32(FC_RED), 2.0f);- ImGui::Dummy(ImVec2(bw, 8));+ ImGui::TextColored(FC_GRAY, "%s", ex.name);++ // Right-align status with dot+ {+ ImVec2 st_size = ImGui::CalcTextSize(status);+ float rx = pad + inner_w - st_size.x - 10;+ ImGui::SameLine(rx);++ // Status dot+ ImVec2 sp = ImGui::GetCursorScreenPos();+ dl->AddCircleFilled(ImVec2(sp.x, sp.y + 6), 2.5f,+ ImGui::ColorConvertFloat4ToU32(status_col));+ ImGui::Dummy(ImVec2(8, 0));+ ImGui::SameLine(0, 0);+ ImGui::TextColored(status_col, "%s", status);}++ ImGui::PushStyleColor(ImGuiCol_Separator, FC_BORDER);+ ImGui::Separator();+ ImGui::PopStyleColor();}ImGui::EndChild();diff --git a/fincept-cpp/src/screens/dashboard/dashboard_screen.cpp b/fincept-cpp/src/screens/dashboard/dashboard_screen.cppindex afbe2208d..ecde47ba5 100644--- a/fincept-cpp/src/screens/dashboard/dashboard_screen.cpp+++ b/fincept-cpp/src/screens/dashboard/dashboard_screen.cpp@@ -48,28 +48,72 @@ void DashboardScreen::init() {DashboardData::instance().initialize();load_layout();if (layout_.widgets.empty()) layout_ = default_layout();- init_static_data();+ refresh_live_panels();initialized_ = true;}-void DashboardScreen::init_static_data() {- econ_data_ = {- {"US 10Y Treasury", 4.35f, 0.05f}, {"US GDP Growth", 2.8f, 0.1f},- {"US Unemployment", 3.6f, -0.1f}, {"US CPI YoY", 3.2f, -0.1f},- {"Fed Funds Rate", 5.50f, 0.0f}, {"PMI Manufacturing", 50.3f, 0.5f},- {"Consumer Confidence", 104.7f, 2.3f}, {"Retail Sales MoM", 0.6f, 0.3f},- };- geo_data_ = {- {"Global Risk", 62.5f, 2.3f}, {"US-China", 78.3f, -1.5f},- {"Europe", 45.2f, 0.8f}, {"Middle East", 82.7f, 5.2f},- {"Asia-Pacific", 38.5f, -0.3f}, {"Latin America", 52.1f, 1.1f},- {"Africa", 58.4f, 0.6f}, {"Cyber Risk", 71.2f, 3.8f},- };- perf_data_ = {- {"Total Return", 0.0f, 8.67f}, {"Day P/L", 15243.56f, 1.23f},- {"Week P/L", 42567.89f, 3.45f}, {"Month P/L", 125678.90f, 8.12f},- {"Sharpe Ratio", 1.85f, 0.0f}, {"Max Drawdown", -5.23f, 0.0f},+void DashboardScreen::refresh_live_panels() {+ // Economic indicators — derived from real MarketPulse quotes (^TNX, ^VIX, DXY, etc.)+ auto pulse = DashboardData::instance().get_quotes(DataCategory::MarketPulse);+ econ_data_.clear();+ for (auto& q : pulse) {+ econ_data_.push_back({q.label, (float)q.price, (float)q.change});+ }+ if (econ_data_.empty()) {+ // Fallback: show loading state+ econ_data_.push_back({"Waiting for market data...", 0, 0});+ }++ // Geopolitics risk — derived from real regional index volatility+ // Uses actual index change% as a risk proxy (bigger move = higher risk)+ auto indices = DashboardData::instance().get_quotes(DataCategory::Indices);+ geo_data_.clear();+ // Map regional indices to regions+ struct RegionMap { const char* symbol; const char* region; };+ RegionMap regions[] = {+ {"^GSPC", "North America"}, {"^DJI", "US Large Cap"},+ {"^FTSE", "UK / Europe"}, {"^GDAXI", "Germany"},+ {"^FCHI", "France"}, {"^N225", "Japan"},+ {"^HSI", "Hong Kong"}, {"000001.SS", "China"},+ {"^BSESN", "India"}, {"^NSEI", "India (Nifty)"},+ {"^STOXX50E", "Euro Zone"}, {"^AXJO", "Australia"},};+ for (auto& rm : regions) {+ for (auto& q : indices) {+ if (q.symbol == rm.symbol) {+ // Risk = abs(change%) scaled: 0-1% = low (20-40), 1-3% = medium (40-70), >3% = high (70-100)+ float abs_chg = std::abs((float)q.change_percent);+ float risk = std::min(100.0f, 20.0f + abs_chg * 25.0f);+ geo_data_.push_back({rm.region, risk, (float)q.change_percent});+ break;+ }+ }+ }+ if (geo_data_.empty()) {+ geo_data_.push_back({"Waiting for index data...", 0, 0});+ }++ // Performance — derived from real portfolio index returns+ perf_data_.clear();+ for (auto& q : indices) {+ if (q.symbol == "^GSPC") {+ perf_data_.push_back({"S&P 500 Return", (float)q.price, (float)q.change_percent});+ } else if (q.symbol == "^IXIC") {+ perf_data_.push_back({"NASDAQ Return", (float)q.price, (float)q.change_percent});+ } else if (q.symbol == "^DJI") {+ perf_data_.push_back({"DOW Return", (float)q.price, (float)q.change_percent});+ }+ }+ for (auto& q : pulse) {+ if (q.symbol == "^VIX") {+ perf_data_.push_back({"Volatility (VIX)", (float)q.price, (float)q.change});+ } else if (q.symbol == "^TNX") {+ perf_data_.push_back({"10Y Yield", (float)q.price, (float)q.change});+ }+ }+ if (perf_data_.empty()) {+ perf_data_.push_back({"Waiting for data...", 0, 0});+ }}// ============================================================================@@ -230,7 +274,12 @@ void DashboardScreen::render_ticker_bar(float width) {ImGui::PushStyleColor(ImGuiCol_ChildBg, ImVec4(0.02f, 0.02f, 0.02f, 1.0f));ImGui::BeginChild("##ticker_bar", ImVec2(width, 20), false);- auto ticker_quotes = DashboardData::instance().get_quotes(DataCategory::Ticker);+ // Assemble ticker from existing categories (no separate fetch needed)+ std::vector<QuoteEntry> ticker_quotes;+ for (auto cat : {DataCategory::Indices, DataCategory::Crypto, DataCategory::Forex, DataCategory::MarketPulse}) {+ auto q = DashboardData::instance().get_quotes(cat);+ ticker_quotes.insert(ticker_quotes.end(), q.begin(), q.end());+ }if (ticker_quotes.empty()) {ImGui::SetCursorPos(ImVec2(width / 2 - 60, 2));@@ -332,6 +381,9 @@ void DashboardScreen::render() {DashboardData::instance().update(ImGui::GetIO().DeltaTime);+ // Refresh econ/geo/perf panels from live data every frame (cheap — just copies)+ refresh_live_panels();+// ScreenFrame replaces all manual viewport mathui::ScreenFrame frame("##dash", ImVec2(0, 0), FC_DARK);if (!frame.begin()) { frame.end(); return; }diff --git a/fincept-cpp/src/screens/dashboard/dashboard_screen.h b/fincept-cpp/src/screens/dashboard/dashboard_screen.hindex c9a150e4a..eb159952e 100644--- a/fincept-cpp/src/screens/dashboard/dashboard_screen.h+++ b/fincept-cpp/src/screens/dashboard/dashboard_screen.h@@ -28,20 +28,20 @@ private:bool first_run_ = true;int refresh_interval_idx_ = 2; // 0=1m, 1=5m, 2=10m, 3=30m- // Economic indicator data (hardcoded for now — FRED integration later)+ // Economic indicator data (live from MarketPulse yfinance quotes)struct EconEntry { std::string name; float value; float change; };std::vector<EconEntry> econ_data_;- // Geopolitics risk data (hardcoded for now — API integration later)+ // Geopolitics risk data (derived from regional index volatility)struct GeoEntry { std::string region; float risk; float trend; };std::vector<GeoEntry> geo_data_;- // Performance data (hardcoded for now — portfolio integration later)+ // Performance data (derived from major index returns)struct PerfEntry { std::string metric; float value; float change; };std::vector<PerfEntry> perf_data_;void init();- void init_static_data(); // econ, geo, perf (until APIs are connected)+ void refresh_live_panels(); // econ, geo, perf from live market data// Top-level layout sectionsvoid render_header_bar(float width);diff --git a/fincept-cpp/src/screens/dashboard/widgets/market_overview.cpp b/fincept-cpp/src/screens/dashboard/widgets/market_overview.cppindex c31fca342..9df8672a1 100644--- a/fincept-cpp/src/screens/dashboard/widgets/market_overview.cpp+++ b/fincept-cpp/src/screens/dashboard/widgets/market_overview.cpp@@ -1,7 +1,8 @@#include "market_overview.h"+#include "../dashboard_data.h"+#include "../dashboard_helpers.h"#include "ui/theme.h"#include <imgui.h>-#include <cmath>namespace fincept::dashboard::widgets {@@ -10,7 +11,12 @@ void MarketOverview::render() {theme::SectionHeader("INDICES");ImGui::Spacing();- if (ImGui::BeginTable("##indices", 4,+ auto indices = DashboardData::instance().get_quotes(DataCategory::Indices);+ bool idx_loading = DashboardData::instance().is_loading(DataCategory::Indices);++ if (indices.empty()) {+ ImGui::TextColored(FC_MUTED, idx_loading ? "Loading indices..." : "No index data available");+ } else if (ImGui::BeginTable("##indices", 4,ImGuiTableFlags_Borders | ImGuiTableFlags_RowBg | ImGuiTableFlags_SizingStretchSame)) {ImGui::TableSetupColumn("Index", ImGuiTableColumnFlags_WidthStretch);@@ -19,34 +25,22 @@ void MarketOverview::render() {ImGui::TableSetupColumn("%Chg", ImGuiTableColumnFlags_WidthFixed, 70);ImGui::TableHeadersRow();- struct IndexData { const char* name; float last; float change; };- IndexData indices[] = {- {"S&P 500", 5234.18f, +28.72f},- {"DJIA", 39512.84f, +125.08f},- {"NASDAQ", 16384.47f, +85.32f},- {"Russell 2000", 2084.15f, -12.43f},- {"VIX", 13.42f, -0.28f},- {"DXY", 104.28f, +0.15f},- };-- for (auto& idx : indices) {+ for (auto& q : indices) {ImGui::TableNextRow();ImGui::TableNextColumn();- ImGui::TextColored(theme::colors::TEXT_PRIMARY, "%s", idx.name);+ ImGui::TextColored(FC_WHITE, "%s", q.label.c_str());ImGui::TableNextColumn();- ImGui::TextColored(theme::colors::TEXT_SECONDARY, "%.2f", idx.last);+ ImGui::TextColored(theme::colors::TEXT_SECONDARY, "%s", fmt_price(q.price).c_str());ImGui::TableNextColumn();- bool positive = idx.change >= 0;- ImGui::TextColored(positive ? theme::colors::MARKET_GREEN : theme::colors::MARKET_RED,- "%s%.2f", positive ? "+" : "", idx.change);+ ImGui::TextColored(chg_col(q.change), "%s%.2f",+ q.change >= 0 ? "+" : "", q.change);ImGui::TableNextColumn();- float pct = (idx.change / idx.last) * 100.0f;- ImGui::TextColored(positive ? theme::colors::MARKET_GREEN : theme::colors::MARKET_RED,- "%s%.2f%%", pct >= 0 ? "+" : "", pct);+ ImGui::TextColored(chg_col(q.change_percent), "%s%.2f%%",+ q.change_percent >= 0 ? "+" : "", q.change_percent);}ImGui::EndTable();@@ -57,7 +51,12 @@ void MarketOverview::render() {theme::SectionHeader("COMMODITIES");ImGui::Spacing();- if (ImGui::BeginTable("##commodities", 3,+ auto commodities = DashboardData::instance().get_quotes(DataCategory::Commodities);+ bool cmd_loading = DashboardData::instance().is_loading(DataCategory::Commodities);++ if (commodities.empty()) {+ ImGui::TextColored(FC_MUTED, cmd_loading ? "Loading commodities..." : "No commodity data available");+ } else if (ImGui::BeginTable("##commodities", 3,ImGuiTableFlags_Borders | ImGuiTableFlags_RowBg | ImGuiTableFlags_SizingStretchSame)) {ImGui::TableSetupColumn("Commodity");@@ -65,31 +64,25 @@ void MarketOverview::render() {ImGui::TableSetupColumn("Change");ImGui::TableHeadersRow();- struct CommodityData { const char* name; const char* price; const char* change; bool pos; };- CommodityData commodities[] = {- {"Gold", "$2,178.30", "+$12.40", true},- {"Silver", "$24.85", "-$0.32", false},- {"WTI Oil","$78.42", "+$1.15", true},- {"Nat Gas","$1.72", "-$0.08", false},- {"Copper", "$3.92", "+$0.05", true},- };-- for (auto& c : commodities) {+ for (auto& q : commodities) {ImGui::TableNextRow();ImGui::TableNextColumn();- ImGui::TextColored(theme::colors::TEXT_PRIMARY, "%s", c.name);+ ImGui::TextColored(FC_WHITE, "%s", q.label.c_str());ImGui::TableNextColumn();- ImGui::TextColored(theme::colors::TEXT_SECONDARY, "%s", c.price);+ ImGui::TextColored(theme::colors::TEXT_SECONDARY, "$%s", fmt_price(q.price).c_str());ImGui::TableNextColumn();- ImGui::TextColored(c.pos ? theme::colors::MARKET_GREEN : theme::colors::MARKET_RED,- "%s", c.change);+ ImGui::TextColored(chg_col(q.change_percent), "%s%.2f%%",+ q.change_percent >= 0 ? "+" : "", q.change_percent);}ImGui::EndTable();}ImGui::Spacing();- ImGui::TextColored(theme::colors::TEXT_DIM, "Sample data - connect to live market feed");+ auto last_idx = DashboardData::instance().last_refresh_str(DataCategory::Indices);+ if (!last_idx.empty()) {+ ImGui::TextColored(FC_MUTED, "Last updated: %s", last_idx.c_str());+ }}ImGui::End();}diff --git a/fincept-cpp/src/screens/data_sources/data_sources_screen.cpp b/fincept-cpp/src/screens/data_sources/data_sources_screen.cppindex fbceea233..dd7137a22 100644--- a/fincept-cpp/src/screens/data_sources/data_sources_screen.cpp+++ b/fincept-cpp/src/screens/data_sources/data_sources_screen.cpp@@ -1,7 +1,9 @@-// Data Sources Screen — 83 connector gallery with connection management+// Data Sources Screen — Bloomberg Terminal-inspired connector gallery+// Dense, data-focused layout with category sidebar, command bar, table views#include "data_sources_screen.h"#include "ui/theme.h"+#include "ui/yoga_helpers.h"#include "core/logger.h"#include <imgui.h>#include <cstring>@@ -13,6 +15,158 @@namespace fincept::data_sources {using json = nlohmann::json;+using namespace theme::colors;++// Bloomberg-style colors+static constexpr ImVec4 BB_BG = {0.055f, 0.055f, 0.060f, 1.0f}; // near black+static constexpr ImVec4 BB_PANEL = {0.075f, 0.075f, 0.082f, 1.0f}; // panel bg+static constexpr ImVec4 BB_SIDEBAR = {0.062f, 0.062f, 0.068f, 1.0f}; // sidebar bg+static constexpr ImVec4 BB_ROW_ALT = {0.082f, 0.082f, 0.090f, 1.0f}; // alternate row+static constexpr ImVec4 BB_HEADER_BG = {0.090f, 0.090f, 0.098f, 1.0f}; // table header+static constexpr ImVec4 BB_SELECTED = {1.0f, 0.45f, 0.05f, 0.12f}; // selected row+static constexpr ImVec4 BB_CMD_BG = {0.067f, 0.067f, 0.073f, 1.0f}; // command bar bg+static constexpr ImVec4 BB_AMBER = {1.0f, 0.65f, 0.0f, 1.0f}; // bloomberg amber+static constexpr ImVec4 BB_GREEN = {0.0f, 0.85f, 0.35f, 1.0f}; // connected+static constexpr ImVec4 BB_RED = {1.0f, 0.25f, 0.20f, 1.0f}; // error+static constexpr ImVec4 BB_CYAN = {0.0f, 0.75f, 0.85f, 1.0f}; // info highlight+static constexpr ImVec4 BB_WHITE = {0.92f, 0.92f, 0.93f, 1.0f}; // primary text+static constexpr ImVec4 BB_GRAY = {0.50f, 0.50f, 0.54f, 1.0f}; // secondary text+static constexpr ImVec4 BB_DIM = {0.35f, 0.35f, 0.38f, 1.0f}; // dim text+static constexpr ImVec4 BB_BORDER = {0.16f, 0.16f, 0.18f, 1.0f}; // subtle borders++// ============================================================================+// Emoji icon map — exact same emoji as the Tauri desktop app+// Requires IMGUI_USE_WCHAR32 + IMGUI_ENABLE_FREETYPE + seguiemj.ttf merge+// ============================================================================+static const char* get_source_symbol(const char* type) {+ struct Entry { const char* key; const char* emoji; };+ static const Entry map[] = {+ // Relational Databases+ {"postgresql", "\xf0\x9f\x90\x98"}, // 🐘+ {"mysql", "\xf0\x9f\x90\xac"}, // 🐬+ {"mariadb", "\xf0\x9f\xa6\xad"}, // 🦭+ {"sqlite", "\xf0\x9f\x92\xbe"}, // 💾+ {"oracle", "\xf0\x9f\x94\xb4"}, // 🔴+ {"mssql", "\xf0\x9f\xaa\x9f"}, // 🪟+ {"cockroachdb", "\xf0\x9f\xaa\xb3"}, // 🪳+ {"snowflake", "\xe2\x9d\x84\xef\xb8\x8f"}, // ❄️+ {"vertica", "\xf0\x9f\x94\xb7"}, // 🔷+ // NoSQL+ {"mongodb", "\xf0\x9f\x8d\x83"}, // 🍃+ {"redis", "\xf0\x9f\x94\xb4"}, // 🔴+ {"cassandra", "\xf0\x9f\x94\xb8"}, // 🔸+ {"couchdb", "\xf0\x9f\x9b\x8b\xef\xb8\x8f"}, // 🛋️+ {"dynamodb", "\xe2\x9a\xa1"}, // ⚡+ {"neo4j", "\xf0\x9f\x95\xb8\xef\xb8\x8f"}, // 🕸️+ {"arangodb", "\xf0\x9f\xa5\x91"}, // 🥑+ {"memcached", "\xf0\x9f\xa7\xa0"}, // 🧠+ {"rethinkdb", "\xf0\x9f\x94\x84"}, // 🔄+ {"firestore", "\xf0\x9f\x94\xa5"}, // 🔥+ {"hbase", "\xf0\x9f\x90\x9d"}, // 🐝+ {"scylladb", "\xf0\x9f\xa6\x82"}, // 🦂+ {"orientdb", "\xf0\x9f\x8c\x90"}, // 🌐+ {"cosmosdb", "\xf0\x9f\x8c\x8d"}, // 🌍+ {"etcd", "\xf0\x9f\x94\x90"}, // 🔐+ // Time Series+ {"influxdb", "\xf0\x9f\x93\x88"}, // 📈+ {"questdb", "\xf0\x9f\x93\x8a"}, // 📊+ {"timescaledb", "\xf0\x9f\x93\x89"}, // 📉+ {"prometheus", "\xf0\x9f\x94\xa5"}, // 🔥+ {"victoriametrics", "\xf0\x9f\x93\x8a"}, // 📊+ {"opentsdb", "\xf0\x9f\x93\x88"}, // 📈+ {"kdb", "\xf0\x9f\x8e\xaf"}, // 🎯+ {"clickhouse", "\xf0\x9f\x96\xb1\xef\xb8\x8f"}, // 🖱️+ // File+ {"csv", "\xf0\x9f\x93\x84"}, // 📄+ {"excel", "\xf0\x9f\x93\x8a"}, // 📊+ {"json", "\xf0\x9f\x93\x8b"}, // 📋+ {"parquet", "\xf0\x9f\x93\xa6"}, // 📦+ {"xml", "\xf0\x9f\x93\x9d"}, // 📝+ {"avro", "\xf0\x9f\x94\xb7"}, // 🔷+ {"orc", "\xf0\x9f\x9f\xa6"}, // 🟦+ {"feather", "\xf0\x9f\xaa\xb6"}, // 🪶+ {"ftp", "\xf0\x9f\x93\x81"}, // 📁+ {"sftp", "\xf0\x9f\x94\x92"}, // 🔒+ // API+ {"rest", "\xf0\x9f\x8c\x90"}, // 🌐+ {"graphql", "\xe2\x97\x86"}, // ◆+ {"grpc", "\xf0\x9f\x94\x8c"}, // 🔌+ {"soap", "\xf0\x9f\xa7\xbc"}, // 🧼+ {"odata", "\xf0\x9f\x94\x97"}, // 🔗+ {"msgraph", "\xf0\x9f\x94\x97"}, // 🔗+ // Streaming+ {"websocket", "\xf0\x9f\x94\x8c"}, // 🔌+ {"mqtt", "\xf0\x9f\x93\xa1"}, // 📡+ {"kafka", "\xf0\x9f\x8c\x8a"}, // 🌊+ {"rabbitmq", "\xf0\x9f\x90\xb0"}, // 🐰+ {"nats", "\xf0\x9f\x93\xae"}, // 📮+ // Cloud+ {"s3", "\xe2\x98\x81\xef\xb8\x8f"}, // ☁️+ {"gcp-storage", "\xe2\x98\x81\xef\xb8\x8f"}, // ☁️+ {"azure-blob", "\xe2\x98\x81\xef\xb8\x8f"}, // ☁️+ {"do-spaces", "\xf0\x9f\x8c\x8a"}, // 🌊+ {"minio", "\xf0\x9f\x97\x84\xef\xb8\x8f"}, // 🗄️+ {"backblaze-b2", "\xf0\x9f\x92\xbe"}, // 💾+ {"wasabi", "\xf0\x9f\xa5\xac"}, // 🥬+ {"cloudflare-r2", "\xf0\x9f\x94\xb6"}, // 🔶+ {"oracle-cloud-storage", "\xf0\x9f\x94\xb4"}, // 🔴+ {"ibm-cloud-storage", "\xf0\x9f\x94\xb5"}, // 🔵+ // Market Data+ {"yahoo-finance", "\xf0\x9f\x93\x88"}, // 📈+ {"alpha-vantage", "\xf0\x9f\x93\x8a"}, // 📊+ {"finnhub", "\xf0\x9f\x93\x89"}, // 📉+ {"iex-cloud", "\xf0\x9f\x92\xb9"}, // 💹+ {"twelve-data", "\xf0\x9f\x93\x8a"}, // 📊+ {"quandl", "\xf0\x9f\x93\x9a"}, // 📚+ {"binance", "\xe2\x82\xbf"}, // ₿+ {"coinbase", "\xf0\x9f\xaa\x99"}, // 🪙+ {"kraken", "\xf0\x9f\x90\x99"}, // 🐙+ {"coinmarketcap", "\xf0\x9f\x92\xb0"}, // 💰+ {"coingecko", "\xf0\x9f\xa6\x8e"}, // 🦎+ {"eod-historical", "\xf0\x9f\x93\x9c"}, // 📜+ {"tiingo", "\xf0\x9f\x94\x94"}, // 🔔+ {"intrinio", "\xf0\x9f\x8f\xa2"}, // 🏢+ {"fincept-data", "\xf0\x9f\x93\xb0"}, // 📰+ {"reuters", "\xf0\x9f\x93\xa1"}, // 📡+ {"marketstack", "\xf0\x9f\x8f\xa6"}, // 🏦+ {"finage", "\xf0\x9f\x92\xb5"}, // 💵+ {"tradier", "\xf0\x9f\x8e\xaf"}, // 🎯+ // Search & Analytics+ {"elasticsearch", "\xf0\x9f\x94\x8d"}, // 🔍+ {"opensearch", "\xf0\x9f\x94\x8e"}, // 🔎+ {"solr", "\xe2\x98\x80\xef\xb8\x8f"}, // ☀️+ {"algolia", "\xf0\x9f\x94\xb7"}, // 🔷+ {"meilisearch", "\xf0\x9f\x94\x8d"}, // 🔍+ // Data Warehouses+ {"bigquery", "\xf0\x9f\x93\x8a"}, // 📊+ {"redshift", "\xf0\x9f\x94\xb4"}, // 🔴+ {"databricks", "\xf0\x9f\xa7\xb1"}, // 🧱+ {"azure-synapse", "\xf0\x9f\x94\xb7"}, // 🔷+ };++ std::string t(type);+ for (auto& e : map) {+ if (t == e.key) return e.emoji;+ }+ return "\xf0\x9f\x94\xb7"; // 🔷 default+}++// Category stats helper+struct CatStats { int total; int connected; };++static CatStats count_category(const std::vector<DataSourceDef>& defs,+ const std::vector<db::DataSource>& conns,+ int cat_filter) {+ CatStats s{0, 0};+ for (auto& d : defs) {+ if (cat_filter >= 0 && static_cast<int>(d.category) != cat_filter) continue;+ s.total++;+ for (auto& c : conns) {+ if (c.type == std::string(d.type)) { s.connected++; break; }+ }+ }+ return s;+}// ============================================================================// Init@@ -30,415 +184,631 @@ void DataSourcesScreen::load_connections() {}// ============================================================================-// Main render+// Main render — Bloomberg-style three-panel layout// ============================================================================void DataSourcesScreen::render() {init();- using namespace theme::colors;- // Poll async test futures (modal test)+ // Poll async test futuresif (testing_ && test_future_.valid()) {- auto status = test_future_.wait_for(std::chrono::milliseconds(0));- if (status == std::future_status::ready) {+ if (test_future_.wait_for(std::chrono::milliseconds(0)) == std::future_status::ready) {test_result_ = test_future_.get();testing_ = false;}}- // Poll per-connection test futuresif (!testing_conn_id_.empty() && conn_test_future_.valid()) {- auto status = conn_test_future_.wait_for(std::chrono::milliseconds(0));- if (status == std::future_status::ready) {+ if (conn_test_future_.wait_for(std::chrono::milliseconds(0)) == std::future_status::ready) {conn_test_results_[testing_conn_id_] = conn_test_future_.get();testing_conn_id_.clear();}}- ImGuiViewport* vp = ImGui::GetMainViewport();- float tab_bar_h = ImGui::GetFrameHeight() + 4;- float footer_h = ImGui::GetFrameHeight();+ ui::ScreenFrame frame("##data_sources_screen", ImVec2(0, 0), BB_BG);+ if (!frame.begin()) { frame.end(); return; }- 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;+ float W = frame.width();+ float H = frame.height();- ImGui::SetNextWindowPos(ImVec2(x, y));- ImGui::SetNextWindowSize(ImVec2(w, h));+ // Vertical stack: command bar (32) + orange line (2) + body (flex) + status bar (22)+ auto vstack = ui::vstack_layout(W, H, {32, 2, -1, 22});- ImGui::PushStyleColor(ImGuiCol_WindowBg, BG_DARK);- ImGui::PushStyleVar(ImGuiStyleVar_WindowPadding, ImVec2(0, 0));+ // ── Command bar ──+ render_command_bar(W, vstack.heights[0]);- ImGui::Begin("##data_sources", nullptr,- ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_NoResize |- ImGuiWindowFlags_NoMove | ImGuiWindowFlags_NoScrollbar |- ImGuiWindowFlags_NoDocking);+ // ── Orange accent line ──+ {+ ImVec2 p = ImGui::GetCursorScreenPos();+ ImGui::GetWindowDrawList()->AddRectFilled(+ p, ImVec2(p.x + W, p.y + 2),+ IM_COL32(255, 140, 0, 255));+ ImGui::Dummy(ImVec2(W, 2));+ }- render_header();+ // ── Body: sidebar + main table ──+ float body_h = vstack.heights[2];+ float sidebar_w = frame.is_compact() ? 0.0f : (frame.is_medium() ? 180.0f : 220.0f);- if (view_ == 0) {- render_filter_bar();- render_gallery();- } else {- render_connections();- }+ ImGui::BeginChild("##ds_body", ImVec2(W, body_h), false, ImGuiWindowFlags_NoScrollbar);+ {+ if (sidebar_w > 0) {+ render_sidebar(sidebar_w, body_h);+ ImGui::SameLine(0, 0);+ }- // Status bar- ImGui::SetCursorPos(ImVec2(0, h - 22));- ImGui::PushStyleColor(ImGuiCol_ChildBg, BG_DARKEST);- ImGui::BeginChild("##ds_status", ImVec2(w, 22), true);- ImGui::TextColored(TEXT_DIM, "SOURCES: %zu | CONNECTIONS: %zu | VIEW: %s",- all_defs_.size(), connections_.size(),- view_ == 0 ? "GALLERY" : "CONNECTIONS");+ float main_w = W - sidebar_w;+ ImGui::BeginChild("##ds_main", ImVec2(main_w, body_h), false);+ {+ if (view_ == 0) {+ render_gallery_table(main_w, body_h);+ } else {+ render_connections_table(main_w, body_h);+ }+ }+ ImGui::EndChild();+ }ImGui::EndChild();- ImGui::PopStyleColor();- ImGui::End();- ImGui::PopStyleVar();- ImGui::PopStyleColor();+ // ── Status bar ──+ render_status_bar(W, vstack.heights[3]);++ frame.end();+ // Modal overlayif (show_modal_) render_config_modal();}// ============================================================================-// Header+// Command Bar — Bloomberg-style top bar with search + actions// ============================================================================-void DataSourcesScreen::render_header() {- using namespace theme::colors;+void DataSourcesScreen::render_command_bar(float w, float h) {+ ImGui::PushStyleColor(ImGuiCol_ChildBg, BB_CMD_BG);+ ImGui::BeginChild("##ds_cmdbar", ImVec2(w, h), false, ImGuiWindowFlags_NoScrollbar);- ImGui::PushStyleColor(ImGuiCol_ChildBg, BG_PANEL);- ImGui::BeginChild("##ds_header", ImVec2(-1, 38), true);+ float pad = 6.0f;+ ImGui::SetCursorPos(ImVec2(pad, (h - 20) * 0.5f));- ImGui::SetCursorPos(ImVec2(16, 8));- ImGui::TextColored(ACCENT, "DATA SOURCES");- ImGui::SameLine();+ // Title+ ImGui::TextColored(BB_AMBER, "DATA SOURCES");+ ImGui::SameLine(0, 12);// Separator- ImVec2 sep_pos = ImGui::GetCursorScreenPos();+ ImVec2 sp = ImGui::GetCursorScreenPos();ImGui::GetWindowDrawList()->AddRectFilled(- ImVec2(sep_pos.x + 8, sep_pos.y - 2),- ImVec2(sep_pos.x + 9, sep_pos.y + 14),- IM_COL32(50, 50, 55, 255));- ImGui::Dummy(ImVec2(16, 0));+ ImVec2(sp.x, sp.y - 2), ImVec2(sp.x + 1, sp.y + 16),+ IM_COL32(80, 80, 88, 255));+ ImGui::Dummy(ImVec2(8, 0));ImGui::SameLine();- ImGui::TextColored(TEXT_DIM, "%zu AVAILABLE | %zu CONNECTED",- all_defs_.size(), connections_.size());+ // View toggle: GALLERY | CONNECTIONS+ auto view_btn = [&](const char* label, int idx, int count) {+ bool active = (view_ == idx);+ ImGui::PushStyleColor(ImGuiCol_Button, active ? ImVec4(BB_AMBER.x, BB_AMBER.y, BB_AMBER.z, 0.2f) : ImVec4(0, 0, 0, 0));+ ImGui::PushStyleColor(ImGuiCol_ButtonHovered, ImVec4(BB_AMBER.x, BB_AMBER.y, BB_AMBER.z, 0.15f));+ ImGui::PushStyleColor(ImGuiCol_Text, active ? BB_AMBER : BB_GRAY);+ ImGui::PushStyleVar(ImGuiStyleVar_FramePadding, ImVec2(10, 2));+ ImGui::PushStyleVar(ImGuiStyleVar_FrameRounding, 0);- // View switcher on the right- float btn_x = ImGui::GetContentRegionAvail().x - 200;- ImGui::SameLine(btn_x);+ char buf[64];+ std::snprintf(buf, sizeof(buf), "%s (%d)", label, count);+ if (ImGui::Button(buf, ImVec2(0, 20))) view_ = idx;- // Gallery button- if (view_ == 0) {- ImGui::PushStyleColor(ImGuiCol_Button, ACCENT_DIM);- ImGui::PushStyleColor(ImGuiCol_Text, BG_DARK);- } else {- ImGui::PushStyleColor(ImGuiCol_Button, ImVec4(0, 0, 0, 0));- ImGui::PushStyleColor(ImGuiCol_Text, TEXT_DIM);- }- if (ImGui::Button("GALLERY", ImVec2(80, 22))) view_ = 0;- ImGui::PopStyleColor(2);+ ImGui::PopStyleVar(2);+ ImGui::PopStyleColor(3);+ ImGui::SameLine(0, 2);+ };++ view_btn("GALLERY", 0, (int)all_defs_.size());+ view_btn("CONNECTIONS", 1, (int)connections_.size());+ ImGui::SameLine(0, 16);++ // Separator+ sp = ImGui::GetCursorScreenPos();+ ImGui::GetWindowDrawList()->AddRectFilled(+ ImVec2(sp.x, sp.y - 2), ImVec2(sp.x + 1, sp.y + 16),+ IM_COL32(80, 80, 88, 255));+ ImGui::Dummy(ImVec2(8, 0));ImGui::SameLine();- // Connections button- if (view_ == 1) {- ImGui::PushStyleColor(ImGuiCol_Button, ACCENT_DIM);- ImGui::PushStyleColor(ImGuiCol_Text, BG_DARK);- } else {- ImGui::PushStyleColor(ImGuiCol_Button, ImVec4(0, 0, 0, 0));- ImGui::PushStyleColor(ImGuiCol_Text, TEXT_DIM);- }- char conn_label[64];- std::snprintf(conn_label, sizeof(conn_label), "CONNECTIONS (%zu)", connections_.size());- if (ImGui::Button(conn_label, ImVec2(120, 22))) view_ = 1;+ // Search+ ImGui::PushStyleColor(ImGuiCol_FrameBg, ImVec4(0.04f, 0.04f, 0.05f, 1.0f));+ ImGui::PushStyleColor(ImGuiCol_Border, BB_BORDER);+ ImGui::PushStyleVar(ImGuiStyleVar_FramePadding, ImVec2(6, 2));+ ImGui::PushStyleVar(ImGuiStyleVar_FrameBorderSize, 1.0f);+ ImGui::SetNextItemWidth(200);+ ImGui::InputTextWithHint("##ds_cmd", "SEARCH <GO>", search_buf_, sizeof(search_buf_));+ ImGui::PopStyleVar(2);ImGui::PopStyleColor(2);+ // Right-side: Refresh + count+ float right_w = 120;+ ImGui::SameLine(w - right_w);+ ImGui::PushStyleColor(ImGuiCol_Button, ImVec4(0, 0, 0, 0));+ ImGui::PushStyleColor(ImGuiCol_ButtonHovered, ImVec4(BB_AMBER.x, BB_AMBER.y, BB_AMBER.z, 0.15f));+ ImGui::PushStyleColor(ImGuiCol_Text, BB_GRAY);+ ImGui::PushStyleVar(ImGuiStyleVar_FramePadding, ImVec2(6, 2));+ if (ImGui::Button("REFRESH", ImVec2(0, 20))) {+ initialized_ = false;+ }+ ImGui::PopStyleVar();+ ImGui::PopStyleColor(3);+ImGui::EndChild();ImGui::PopStyleColor();-- // Orange accent line- ImVec2 p = ImGui::GetCursorScreenPos();- ImGui::GetWindowDrawList()->AddRectFilled(p,- ImVec2(p.x + ImGui::GetContentRegionAvail().x, p.y + 2),- IM_COL32(255, 136, 0, 255));- ImGui::Dummy(ImVec2(0, 2));}// ============================================================================-// Filter bar (gallery view)+// Sidebar — Bloomberg-style category panel with counts// ============================================================================-void DataSourcesScreen::render_filter_bar() {- using namespace theme::colors;-- ImGui::PushStyleColor(ImGuiCol_ChildBg, BG_PANEL);- ImGui::BeginChild("##ds_filter", ImVec2(-1, 38), true);-- ImGui::SetCursorPos(ImVec2(16, 8));-- // Search box- ImGui::PushStyleColor(ImGuiCol_FrameBg, BG_INPUT);- ImGui::SetNextItemWidth(220);- ImGui::InputTextWithHint("##ds_search", "Search data sources...", search_buf_, sizeof(search_buf_));- ImGui::PopStyleColor();- ImGui::SameLine();-- ImGui::Dummy(ImVec2(8, 0));- ImGui::SameLine();+void DataSourcesScreen::render_sidebar(float w, float h) {+ ImGui::PushStyleColor(ImGuiCol_ChildBg, BB_SIDEBAR);+ ImGui::PushStyleColor(ImGuiCol_Border, BB_BORDER);+ ImGui::BeginChild("##ds_sidebar", ImVec2(w, h), true, ImGuiWindowFlags_NoScrollbar);++ float pad = 8.0f;+ ImGui::SetCursorPos(ImVec2(pad, 8));+ ImGui::TextColored(BB_DIM, "CATEGORIES");+ ImGui::Spacing();- // Category filter buttons- static const struct { int val; const char* label; } cats[] = {- {-1, "ALL"}, {0, "DATABASE"}, {1, "API"}, {2, "FILE"},- {3, "STREAMING"}, {4, "CLOUD"}, {5, "TIMESERIES"}, {6, "MARKET DATA"},+ // Draw each category as a dense row+ struct CatEntry { int val; const char* label; const char* code; };+ static const CatEntry cats[] = {+ {-1, "ALL SOURCES", "ALL"},+ { 0, "DATABASE", "DB "},+ { 1, "API", "API"},+ { 2, "FILE", "FIL"},+ { 3, "STREAMING", "STR"},+ { 4, "CLOUD", "CLD"},+ { 5, "TIMESERIES", "TSR"},+ { 6, "MARKET DATA", "MKT"},};for (auto& cat : cats) {bool active = (selected_category_ == cat.val);+ CatStats stats = count_category(all_defs_, connections_, cat.val);++ ImVec2 cursor = ImGui::GetCursorScreenPos();+ float row_h = 26.0f;+ float row_w = w - pad * 2;++ // Highlight bg for selectedif (active) {- ImGui::PushStyleColor(ImGuiCol_Button, ACCENT_BG);- ImGui::PushStyleColor(ImGuiCol_Text, ACCENT);- ImGui::PushStyleColor(ImGuiCol_Border, ACCENT);- } else {- ImGui::PushStyleColor(ImGuiCol_Button, ImVec4(0, 0, 0, 0));- ImGui::PushStyleColor(ImGuiCol_Text, TEXT_DIM);- ImGui::PushStyleColor(ImGuiCol_Border, BORDER_DIM);+ ImGui::GetWindowDrawList()->AddRectFilled(+ ImVec2(cursor.x - 2, cursor.y),+ ImVec2(cursor.x + row_w + 2, cursor.y + row_h),+ ImGui::ColorConvertFloat4ToU32(BB_SELECTED));+ // Left accent bar+ ImGui::GetWindowDrawList()->AddRectFilled(+ ImVec2(cursor.x - 2, cursor.y),+ ImVec2(cursor.x + 2, cursor.y + row_h),+ IM_COL32(255, 140, 0, 255));}- ImGui::PushStyleVar(ImGuiStyleVar_FrameBorderSize, 1.0f);- if (ImGui::Button(cat.label, ImVec2(0, 20))) {+ ImGui::SetCursorPosX(pad + 6);++ // Code badge+ ImGui::TextColored(active ? BB_AMBER : BB_DIM, "%s", cat.code);+ ImGui::SameLine(0, 8);++ // Label+ ImGui::TextColored(active ? BB_WHITE : BB_GRAY, "%s", cat.label);++ // Right-aligned counts+ char count_str[32];+ std::snprintf(count_str, sizeof(count_str), "%d/%d", stats.connected, stats.total);+ float count_w = ImGui::CalcTextSize(count_str).x;+ ImGui::SameLine(w - pad - count_w - 8);+ ImGui::TextColored(stats.connected > 0 ? BB_GREEN : BB_DIM, "%s", count_str);++ // Invisible button for click detection+ ImGui::SetCursorScreenPos(cursor);+ char btn_id[32];+ std::snprintf(btn_id, sizeof(btn_id), "##cat_%d", cat.val);+ if (ImGui::InvisibleButton(btn_id, ImVec2(row_w, row_h))) {selected_category_ = cat.val;}- ImGui::PopStyleVar();- ImGui::PopStyleColor(3);- ImGui::SameLine();}- ImGui::EndChild();+ // Bottom: summary+ ImGui::SetCursorPosY(h - 60);+ ImGui::SetCursorPosX(pad);+ ImGui::PushStyleColor(ImGuiCol_Separator, BB_BORDER);+ ImGui::Separator();ImGui::PopStyleColor();+ ImGui::Spacing();+ ImGui::SetCursorPosX(pad);+ ImGui::TextColored(BB_DIM, "TOTAL");+ ImGui::SetCursorPosX(pad);+ ImGui::TextColored(BB_AMBER, "%zu", all_defs_.size());+ ImGui::SameLine(0, 4);+ ImGui::TextColored(BB_DIM, "sources");+ ImGui::SameLine(0, 8);+ ImGui::TextColored(BB_GREEN, "%zu", connections_.size());+ ImGui::SameLine(0, 4);+ ImGui::TextColored(BB_DIM, "active");++ ImGui::EndChild();+ ImGui::PopStyleColor(2);}// ============================================================================-// Gallery view — grid of source cards+// Gallery Table — Bloomberg-style dense table of data sources// ============================================================================-void DataSourcesScreen::render_gallery() {- using namespace theme::colors;-- ImGui::BeginChild("##ds_gallery", ImVec2(-1, -24), false);- ImGui::PushStyleVar(ImGuiStyleVar_WindowPadding, ImVec2(16, 12));-+void DataSourcesScreen::render_gallery_table(float w, float h) {std::string search_lower;for (char c : std::string(search_buf_)) search_lower += (char)std::tolower(c);- float avail_w = ImGui::GetContentRegionAvail().x - 16;- float card_w = 270.0f;- int cols = std::max(1, (int)(avail_w / card_w));- float actual_card_w = (avail_w - (cols - 1) * 8) / cols;-- int col = 0;+ // Build filtered list+ std::vector<const DataSourceDef*> filtered;for (auto& def : all_defs_) {- // Category filter- if (selected_category_ >= 0) {- Category filter_cat = static_cast<Category>(selected_category_);- if (def.category != filter_cat) continue;+ if (selected_category_ >= 0 && static_cast<int>(def.category) != selected_category_) continue;+ if (!search_lower.empty()) {+ std::string name_l, desc_l;+ for (char c : std::string(def.name)) name_l += (char)std::tolower(c);+ for (char c : std::string(def.description)) desc_l += (char)std::tolower(c);+ if (name_l.find(search_lower) == std::string::npos &&+ desc_l.find(search_lower) == std::string::npos) continue;}+ filtered.push_back(&def);+ }++ ImGuiTableFlags flags =+ ImGuiTableFlags_ScrollY | ImGuiTableFlags_RowBg |+ ImGuiTableFlags_BordersInnerH | ImGuiTableFlags_Resizable |+ ImGuiTableFlags_SizingStretchProp | ImGuiTableFlags_PadOuterX;++ ImGui::PushStyleColor(ImGuiCol_TableHeaderBg, BB_HEADER_BG);+ ImGui::PushStyleColor(ImGuiCol_TableBorderLight, BB_BORDER);+ ImGui::PushStyleColor(ImGuiCol_TableRowBg, BB_PANEL);+ ImGui::PushStyleColor(ImGuiCol_TableRowBgAlt, BB_ROW_ALT);+ ImGui::PushStyleVar(ImGuiStyleVar_CellPadding, ImVec2(8, 4));++ if (ImGui::BeginTable("##ds_gallery_tbl", 7, flags, ImVec2(w, h))) {+ ImGui::TableSetupScrollFreeze(0, 1);+ ImGui::TableSetupColumn("", ImGuiTableColumnFlags_WidthFixed, 30); // icon+ ImGui::TableSetupColumn("SOURCE", ImGuiTableColumnFlags_WidthStretch, 3.0f);+ ImGui::TableSetupColumn("TYPE", ImGuiTableColumnFlags_WidthFixed, 90);+ ImGui::TableSetupColumn("AUTH", ImGuiTableColumnFlags_WidthFixed, 50);+ ImGui::TableSetupColumn("TEST", ImGuiTableColumnFlags_WidthFixed, 50);+ ImGui::TableSetupColumn("STATUS", ImGuiTableColumnFlags_WidthFixed, 80);+ ImGui::TableSetupColumn("", ImGuiTableColumnFlags_WidthFixed, 90); // action- // Search filter- if (search_lower.length() > 0) {- std::string name_lower, desc_lower;- for (char c : std::string(def.name)) name_lower += (char)std::tolower(c);- for (char c : std::string(def.description)) desc_lower += (char)std::tolower(c);- if (name_lower.find(search_lower) == std::string::npos &&- desc_lower.find(search_lower) == std::string::npos) continue;+ // Header+ ImGui::TableNextRow(ImGuiTableRowFlags_Headers);+ for (int col = 0; col < 7; col++) {+ ImGui::TableSetColumnIndex(col);+ const char* name = ImGui::TableGetColumnName(col);+ ImGui::PushStyleColor(ImGuiCol_Text, BB_AMBER);+ ImGui::TableHeader(name);+ ImGui::PopStyleColor();}- if (col > 0) ImGui::SameLine(0, 8);+ // Rows+ int row_idx = 0;+ for (auto* def : filtered) {+ ImGui::TableNextRow();+ ImGui::PushID(row_idx);- // Card- ImGui::PushStyleColor(ImGuiCol_ChildBg, BG_PANEL);- ImGui::PushStyleColor(ImGuiCol_Border, BORDER_DIM);+ // Check if this source has a connection+ bool has_conn = false;+ for (auto& c : connections_) {+ if (c.type == std::string(def->type)) { has_conn = true; break; }+ }- char card_id[64];- std::snprintf(card_id, sizeof(card_id), "##dsc_%s", def.id);- ImGui::BeginChild(card_id, ImVec2(actual_card_w, 100), true);+ // Icon — Unicode symbol from lookup map+ ImGui::TableSetColumnIndex(0);+ ImGui::PushStyleColor(ImGuiCol_Text, BB_CYAN);+ ImGui::Text("%s", get_source_symbol(def->type));+ ImGui::PopStyleColor();- // Icon + Name- ImGui::TextColored(ACCENT, "%s", def.icon);- ImGui::SameLine();- ImGui::TextColored(TEXT_PRIMARY, "%s", def.name);+ // Source name + description+ ImGui::TableSetColumnIndex(1);+ ImGui::TextColored(BB_WHITE, "%s", def->name);+ ImGui::SameLine(0, 8);+ // Truncate description+ std::string desc = def->description;+ if (desc.size() > 60) desc = desc.substr(0, 57) + "...";+ ImGui::TextColored(BB_DIM, "%s", desc.c_str());++ // Type badge+ ImGui::TableSetColumnIndex(2);+ ImVec4 type_col = BB_CYAN;+ if (def->category == Category::Database) type_col = ImVec4(0.6f, 0.4f, 1.0f, 1.0f);+ if (def->category == Category::Streaming) type_col = ImVec4(1.0f, 0.6f, 0.2f, 1.0f);+ if (def->category == Category::MarketData) type_col = BB_GREEN;+ if (def->category == Category::Cloud) type_col = ImVec4(0.4f, 0.7f, 1.0f, 1.0f);+ ImGui::TextColored(type_col, "%s", category_label(def->category));++ // Auth required+ ImGui::TableSetColumnIndex(3);+ if (def->requires_auth) {+ ImGui::TextColored(BB_AMBER, "KEY");+ } else {+ ImGui::TextColored(BB_DIM, "--");+ }- // Category badge- ImGui::SameLine();- ImGui::TextColored(INFO, "[%s]", category_label(def.category));+ // Testable+ ImGui::TableSetColumnIndex(4);+ if (def->testable) {+ ImGui::TextColored(BB_GREEN, "YES");+ } else {+ ImGui::TextColored(BB_DIM, "--");+ }- // Description- ImGui::TextColored(TEXT_DIM, "%s", def.description);+ // Status+ ImGui::TableSetColumnIndex(5);+ if (has_conn) {+ ImGui::TextColored(BB_GREEN, "CONNECTED");+ } else {+ ImGui::TextColored(BB_DIM, "AVAILABLE");+ }- // Badges- if (def.requires_auth) {- ImGui::TextColored(TEXT_DISABLED, "AUTH");- ImGui::SameLine();- }- if (def.testable) {- ImGui::TextColored(SUCCESS, "TESTABLE");- ImGui::SameLine();- }+ // Action button+ ImGui::TableSetColumnIndex(6);+ ImGui::PushStyleColor(ImGuiCol_Button, ImVec4(BB_AMBER.x, BB_AMBER.y, BB_AMBER.z, 0.15f));+ ImGui::PushStyleColor(ImGuiCol_ButtonHovered, ImVec4(BB_AMBER.x, BB_AMBER.y, BB_AMBER.z, 0.3f));+ ImGui::PushStyleColor(ImGuiCol_Text, BB_AMBER);+ ImGui::PushStyleVar(ImGuiStyleVar_FramePadding, ImVec2(8, 1));+ ImGui::PushStyleVar(ImGuiStyleVar_FrameRounding, 0);+ char cfg_id[64];+ std::snprintf(cfg_id, sizeof(cfg_id), "CONNECT##gc_%d", row_idx);+ if (ImGui::SmallButton(cfg_id)) {+ open_config(*def);+ }+ ImGui::PopStyleVar(2);+ ImGui::PopStyleColor(3);- // Configure button- ImGui::SameLine(actual_card_w - 90);- char cfg_id[64];- std::snprintf(cfg_id, sizeof(cfg_id), "Configure##cfg_%s", def.id);- if (theme::AccentButton(cfg_id, ImVec2(75, 18))) {- open_config(def);+ ImGui::PopID();+ row_idx++;}- ImGui::EndChild();- ImGui::PopStyleColor(2);-- col++;- if (col >= cols) col = 0;+ ImGui::EndTable();}ImGui::PopStyleVar();- ImGui::EndChild();+ ImGui::PopStyleColor(4);}// ============================================================================-// Connections view — list of saved connections+// Connections Table — Bloomberg-style table of active connections// ============================================================================-void DataSourcesScreen::render_connections() {- using namespace theme::colors;-- ImGui::BeginChild("##ds_conns", ImVec2(-1, -24), false);- ImGui::PushStyleVar(ImGuiStyleVar_WindowPadding, ImVec2(16, 12));-+void DataSourcesScreen::render_connections_table(float w, float h) {if (connections_.empty()) {- float avail_h = ImGui::GetContentRegionAvail().y;- ImGui::SetCursorPosY(avail_h / 2 - 40);- float text_w = ImGui::CalcTextSize("NO CONNECTIONS CONFIGURED").x;- ImGui::SetCursorPosX((ImGui::GetContentRegionAvail().x - text_w) / 2);- ImGui::TextColored(TEXT_DIM, "NO CONNECTIONS CONFIGURED");-+ ImGui::SetCursorPos(ImVec2(w * 0.5f - 120, h * 0.4f));+ ImGui::TextColored(BB_DIM, "NO ACTIVE CONNECTIONS");+ ImGui::SetCursorPosX(w * 0.5f - 80);ImGui::Spacing();- float btn_w = 160;- ImGui::SetCursorPosX((ImGui::GetContentRegionAvail().x - btn_w) / 2);- if (theme::AccentButton("BROWSE DATA SOURCES", ImVec2(btn_w, 24))) {- view_ = 0;- }- } else {- for (auto& conn : connections_) {- render_connection_row(conn);- ImGui::Spacing();- }+ ImGui::SetCursorPosX(w * 0.5f - 80);+ ImGui::PushStyleColor(ImGuiCol_Button, ImVec4(BB_AMBER.x, BB_AMBER.y, BB_AMBER.z, 0.15f));+ ImGui::PushStyleColor(ImGuiCol_ButtonHovered, ImVec4(BB_AMBER.x, BB_AMBER.y, BB_AMBER.z, 0.3f));+ ImGui::PushStyleColor(ImGuiCol_Text, BB_AMBER);+ if (ImGui::Button("BROWSE SOURCES", ImVec2(160, 24))) view_ = 0;+ ImGui::PopStyleColor(3);+ return;}- ImGui::PopStyleVar();- ImGui::EndChild();-}--void DataSourcesScreen::render_connection_row(const db::DataSource& conn) {- using namespace theme::colors;+ ImGuiTableFlags flags =+ ImGuiTableFlags_ScrollY | ImGuiTableFlags_RowBg |+ ImGuiTableFlags_BordersInnerH | ImGuiTableFlags_Resizable |+ ImGuiTableFlags_SizingStretchProp | ImGuiTableFlags_PadOuterX;++ ImGui::PushStyleColor(ImGuiCol_TableHeaderBg, BB_HEADER_BG);+ ImGui::PushStyleColor(ImGuiCol_TableBorderLight, BB_BORDER);+ ImGui::PushStyleColor(ImGuiCol_TableRowBg, BB_PANEL);+ ImGui::PushStyleColor(ImGuiCol_TableRowBgAlt, BB_ROW_ALT);+ ImGui::PushStyleVar(ImGuiStyleVar_CellPadding, ImVec2(8, 5));++ if (ImGui::BeginTable("##ds_conn_tbl", 9, flags, ImVec2(w, h))) {+ ImGui::TableSetupScrollFreeze(0, 1);+ ImGui::TableSetupColumn("", ImGuiTableColumnFlags_WidthFixed, 20); // status dot+ ImGui::TableSetupColumn("", ImGuiTableColumnFlags_WidthFixed, 24); // icon+ ImGui::TableSetupColumn("NAME", ImGuiTableColumnFlags_WidthStretch, 2.5f);+ ImGui::TableSetupColumn("PROVIDER", ImGuiTableColumnFlags_WidthStretch, 2.0f);+ ImGui::TableSetupColumn("TYPE", ImGuiTableColumnFlags_WidthFixed, 90);+ ImGui::TableSetupColumn("STATE", ImGuiTableColumnFlags_WidthFixed, 70);+ ImGui::TableSetupColumn("LATENCY", ImGuiTableColumnFlags_WidthFixed, 70);+ ImGui::TableSetupColumn("CREATED", ImGuiTableColumnFlags_WidthFixed, 100);+ ImGui::TableSetupColumn("ACTIONS", ImGuiTableColumnFlags_WidthFixed, 160);- ImGui::PushStyleColor(ImGuiCol_ChildBg, BG_PANEL);- ImGui::PushStyleColor(ImGuiCol_Border, BORDER_DIM);+ // Header+ ImGui::TableNextRow(ImGuiTableRowFlags_Headers);+ for (int col = 0; col < 9; col++) {+ ImGui::TableSetColumnIndex(col);+ ImGui::PushStyleColor(ImGuiCol_Text, BB_AMBER);+ ImGui::TableHeader(ImGui::TableGetColumnName(col));+ ImGui::PopStyleColor();+ }- char row_id[64];- std::snprintf(row_id, sizeof(row_id), "##conn_%s", conn.id.c_str());- ImGui::BeginChild(row_id, ImVec2(-1, 50), true);+ int row = 0;+ for (auto& conn : connections_) {+ ImGui::TableNextRow();+ ImGui::PushID(row);++ // Status dot+ ImGui::TableSetColumnIndex(0);+ ImVec4 dot_col = conn.enabled ? BB_GREEN : BB_RED;+ ImVec2 dot_p = ImGui::GetCursorScreenPos();+ dot_p.x += 8;+ dot_p.y += 7;+ ImGui::GetWindowDrawList()->AddCircleFilled(dot_p, 4.0f,+ ImGui::ColorConvertFloat4ToU32(dot_col));+ ImGui::Dummy(ImVec2(20, 14));++ // Icon symbol+ ImGui::TableSetColumnIndex(1);+ ImGui::TextColored(BB_CYAN, "%s", get_source_symbol(conn.type.c_str()));++ // Name+ ImGui::TableSetColumnIndex(2);+ ImGui::TextColored(BB_WHITE, "%s", conn.display_name.c_str());++ // Provider+ ImGui::TableSetColumnIndex(3);+ ImGui::TextColored(BB_CYAN, "%s", conn.provider.c_str());++ // Type+ ImGui::TableSetColumnIndex(4);+ ImGui::TextColored(BB_GRAY, "%s", conn.type.c_str());++ // State+ ImGui::TableSetColumnIndex(5);+ if (conn.enabled) {+ ImGui::TextColored(BB_GREEN, "ACTIVE");+ } else {+ ImGui::TextColored(BB_RED, "INACTIVE");+ }- // Name- ImGui::TextColored(TEXT_PRIMARY, "%s", conn.display_name.c_str());- ImGui::SameLine();+ // Latency / Test result+ ImGui::TableSetColumnIndex(6);+ auto tr_it = conn_test_results_.find(conn.id);+ if (testing_conn_id_ == conn.id) {+ ImGui::TextColored(BB_AMBER, "...");+ } else if (tr_it != conn_test_results_.end()) {+ auto& tr = tr_it->second;+ ImGui::TextColored(tr.success ? BB_GREEN : BB_RED, "%.0fms", tr.elapsed_ms);+ } else {+ ImGui::TextColored(BB_DIM, "--");+ }- // Type badge- ImGui::TextColored(INFO, "[%s]", conn.type.c_str());- ImGui::SameLine();+ // Created+ ImGui::TableSetColumnIndex(7);+ std::string date = conn.created_at;+ if (date.size() > 10) date = date.substr(0, 10);+ ImGui::TextColored(BB_DIM, "%s", date.c_str());++ // Actions+ ImGui::TableSetColumnIndex(8);+ ImGui::PushStyleVar(ImGuiStyleVar_FramePadding, ImVec2(6, 1));+ ImGui::PushStyleVar(ImGuiStyleVar_FrameRounding, 0);++ // Test+ bool is_testing_this = (testing_conn_id_ == conn.id);+ if (!is_testing_this) {+ ImGui::PushStyleColor(ImGuiCol_Button, ImVec4(0, 0, 0, 0));+ ImGui::PushStyleColor(ImGuiCol_ButtonHovered, ImVec4(BB_GREEN.x, BB_GREEN.y, BB_GREEN.z, 0.15f));+ ImGui::PushStyleColor(ImGuiCol_Text, BB_GREEN);+ char test_id[64];+ std::snprintf(test_id, sizeof(test_id), "TEST##ct_%d", row);+ if (ImGui::SmallButton(test_id)) {+ std::map<std::string, std::string> cfg;+ try {+ auto j = json::parse(conn.config);+ for (auto& [k, v] : j.items())+ cfg[k] = v.is_string() ? v.get<std::string>() : v.dump();+ } catch (...) {}+ testing_conn_id_ = conn.id;+ conn_test_future_ = adapters::AdapterRegistry::instance().test_connection_async(conn.type, cfg);+ }+ ImGui::PopStyleColor(3);+ } else {+ ImGui::TextColored(BB_AMBER, "...");+ }+ ImGui::SameLine(0, 4);- // Provider- if (!conn.provider.empty()) {- ImGui::TextColored(TEXT_DIM, "(%s)", conn.provider.c_str());- ImGui::SameLine();- }+ // Edit+ ImGui::PushStyleColor(ImGuiCol_Button, ImVec4(0, 0, 0, 0));+ ImGui::PushStyleColor(ImGuiCol_ButtonHovered, ImVec4(BB_CYAN.x, BB_CYAN.y, BB_CYAN.z, 0.15f));+ ImGui::PushStyleColor(ImGuiCol_Text, BB_CYAN);+ char edit_id[64];+ std::snprintf(edit_id, sizeof(edit_id), "EDIT##ce_%d", row);+ if (ImGui::SmallButton(edit_id)) {+ for (auto& def : all_defs_) {+ if (std::string(def.type) == conn.type) {+ editing_id_ = conn.id;+ modal_def_ = &def;+ show_modal_ = true;+ form_data_.clear();+ form_data_["name"] = conn.display_name;+ try {+ auto cfg = json::parse(conn.config);+ for (auto& [k, v] : cfg.items())+ form_data_[k] = v.is_string() ? v.get<std::string>() : v.dump();+ } catch (...) {}+ break;+ }+ }+ }+ ImGui::PopStyleColor(3);+ ImGui::SameLine(0, 4);- // Enabled status- ImGui::TextColored(conn.enabled ? SUCCESS : TEXT_DISABLED,- conn.enabled ? "ENABLED" : "DISABLED");+ // Delete+ ImGui::PushStyleColor(ImGuiCol_Button, ImVec4(0, 0, 0, 0));+ ImGui::PushStyleColor(ImGuiCol_ButtonHovered, ImVec4(BB_RED.x, BB_RED.y, BB_RED.z, 0.15f));+ ImGui::PushStyleColor(ImGuiCol_Text, BB_RED);+ char del_id[64];+ std::snprintf(del_id, sizeof(del_id), "DEL##cd_%d", row);+ if (ImGui::SmallButton(del_id)) {+ delete_connection(conn.id);+ }+ ImGui::PopStyleColor(3);- // Second row: buttons- // Test button- bool is_testing_this = (testing_conn_id_ == conn.id);- if (is_testing_this) {- ImGui::TextColored(WARNING, "TESTING...");- } else {- char test_id[64];- std::snprintf(test_id, sizeof(test_id), "Test##tst_%s", conn.id.c_str());- ImGui::PushStyleColor(ImGuiCol_Button, ImVec4(0.1f, 0.3f, 0.15f, 1.0f));- if (ImGui::SmallButton(test_id)) {- // Parse config JSON to map- std::map<std::string, std::string> cfg;- try {- auto j = json::parse(conn.config);- for (auto& [k, v] : j.items())- cfg[k] = v.is_string() ? v.get<std::string>() : v.dump();- } catch (...) {}- testing_conn_id_ = conn.id;- conn_test_future_ = adapters::AdapterRegistry::instance().test_connection_async(conn.type, cfg);+ ImGui::PopStyleVar(2);+ ImGui::PopID();+ row++;}- ImGui::PopStyleColor();- }- ImGui::SameLine();- // Show test result inline if available- auto tr_it = conn_test_results_.find(conn.id);- if (tr_it != conn_test_results_.end()) {- auto& tr = tr_it->second;- ImGui::TextColored(tr.success ? SUCCESS : ERROR_RED, "%s (%.0fms)",- tr.success ? "OK" : "FAIL", tr.elapsed_ms);- ImGui::SameLine();+ ImGui::EndTable();}- // Edit button- char edit_id[64];- std::snprintf(edit_id, sizeof(edit_id), "Edit##ed_%s", conn.id.c_str());- if (ImGui::SmallButton(edit_id)) {- // Find the def for this type- for (auto& def : all_defs_) {- if (std::string(def.type) == conn.type) {- editing_id_ = conn.id;- modal_def_ = &def;- show_modal_ = true;- form_data_.clear();- form_data_["name"] = conn.display_name;- // Parse existing config JSON- try {- auto cfg = json::parse(conn.config);- for (auto& [k, v] : cfg.items()) {- form_data_[k] = v.is_string() ? v.get<std::string>() : v.dump();- }- } catch (...) {}- break;- }- }- }- ImGui::SameLine();+ ImGui::PopStyleVar();+ ImGui::PopStyleColor(4);+}- // Delete button- ImGui::PushStyleColor(ImGuiCol_Text, ERROR_RED);- char del_id[64];- std::snprintf(del_id, sizeof(del_id), "Delete##del_%s", conn.id.c_str());- if (ImGui::SmallButton(del_id)) {- delete_connection(conn.id);+// ============================================================================+// Status Bar — Bloomberg-style bottom ticker bar+// ============================================================================+void DataSourcesScreen::render_status_bar(float w, float h) {+ ImGui::PushStyleColor(ImGuiCol_ChildBg, ImVec4(0.04f, 0.04f, 0.045f, 1.0f));+ ImGui::BeginChild("##ds_status", ImVec2(w, h), false, ImGuiWindowFlags_NoScrollbar);++ ImGui::SetCursorPos(ImVec2(8, (h - 14) * 0.5f));++ // Left: counts+ CatStats total = count_category(all_defs_, connections_, -1);+ ImGui::TextColored(BB_DIM, "SOURCES:");+ ImGui::SameLine(0, 4);+ ImGui::TextColored(BB_AMBER, "%d", total.total);+ ImGui::SameLine(0, 12);++ ImGui::TextColored(BB_DIM, "CONNECTED:");+ ImGui::SameLine(0, 4);+ ImGui::TextColored(BB_GREEN, "%d", total.connected);+ ImGui::SameLine(0, 12);++ ImGui::TextColored(BB_DIM, "AVAILABLE:");+ ImGui::SameLine(0, 4);+ ImGui::TextColored(BB_CYAN, "%d", total.total - total.connected);+ ImGui::SameLine(0, 16);++ ImGui::TextColored(BB_BORDER, "|");+ ImGui::SameLine(0, 16);++ ImGui::TextColored(BB_DIM, "VIEW:");+ ImGui::SameLine(0, 4);+ ImGui::TextColored(BB_AMBER, "%s", view_ == 0 ? "GALLERY" : "CONNECTIONS");++ if (selected_category_ >= 0) {+ ImGui::SameLine(0, 16);+ ImGui::TextColored(BB_DIM, "FILTER:");+ ImGui::SameLine(0, 4);+ ImGui::TextColored(BB_CYAN, "%s", category_label(static_cast<Category>(selected_category_)));}- ImGui::PopStyleColor();- ImGui::SameLine();- ImGui::TextColored(TEXT_DISABLED, "Created: %s", conn.created_at.c_str());+ // Right: timestamp+ time_t now = time(nullptr);+ struct tm* t = localtime(&now);+ char ts[32];+ std::strftime(ts, sizeof(ts), "%H:%M:%S", t);+ float ts_w = ImGui::CalcTextSize(ts).x + 12;+ ImGui::SameLine(w - ts_w);+ ImGui::TextColored(BB_DIM, "%s", ts);ImGui::EndChild();- ImGui::PopStyleColor(2);+ ImGui::PopStyleColor();}// ============================================================================-// Config modal — dynamic form for configuring a data source+// Config modal — Bloomberg-style form overlay// ============================================================================void DataSourcesScreen::open_config(const DataSourceDef& def) {modal_def_ = &def;@@ -455,55 +825,63 @@ void DataSourcesScreen::open_config(const DataSourceDef& def) {}void DataSourcesScreen::render_config_modal() {- using namespace theme::colors;if (!modal_def_) return;- // Center modalImGuiViewport* vp = ImGui::GetMainViewport();ImVec2 center = ImVec2(vp->WorkPos.x + vp->WorkSize.x * 0.5f,vp->WorkPos.y + vp->WorkSize.y * 0.5f);ImGui::SetNextWindowPos(center, ImGuiCond_Always, ImVec2(0.5f, 0.5f));- ImGui::SetNextWindowSize(ImVec2(460, 0));+ ImGui::SetNextWindowSize(ImVec2(480, 0));- ImGui::PushStyleColor(ImGuiCol_WindowBg, BG_PANEL);- ImGui::PushStyleColor(ImGuiCol_Border, ACCENT);+ ImGui::PushStyleColor(ImGuiCol_WindowBg, BB_PANEL);+ ImGui::PushStyleColor(ImGuiCol_Border, BB_AMBER);ImGui::PushStyleVar(ImGuiStyleVar_WindowBorderSize, 1.0f);+ ImGui::PushStyleVar(ImGuiStyleVar_WindowPadding, ImVec2(16, 12));bool open = true;- char modal_title[128];- std::snprintf(modal_title, sizeof(modal_title), "%s %s###ds_config_modal",- editing_id_.empty() ? "CONFIGURE" : "EDIT",- modal_def_->name);+ char title[128];+ std::snprintf(title, sizeof(title), "%s %s###ds_cfg_modal",+ editing_id_.empty() ? "CONFIGURE" : "EDIT", modal_def_->name);- if (ImGui::Begin(modal_title, &open,- ImGuiWindowFlags_NoCollapse | ImGuiWindowFlags_NoResize | ImGuiWindowFlags_AlwaysAutoResize)) {+ if (ImGui::Begin(title, &open,+ ImGuiWindowFlags_NoCollapse | ImGuiWindowFlags_NoResize |+ ImGuiWindowFlags_AlwaysAutoResize)) {// Header- ImGui::TextColored(ACCENT, "%s", modal_def_->icon);- ImGui::SameLine();- ImGui::TextColored(TEXT_PRIMARY, "%s", modal_def_->name);- ImGui::TextColored(TEXT_DIM, "%s", modal_def_->description);- ImGui::Separator();+ ImGui::TextColored(BB_CYAN, "%s", get_source_symbol(modal_def_->type));+ ImGui::SameLine(0, 8);+ ImGui::TextColored(BB_WHITE, "%s", modal_def_->name);+ ImGui::SameLine(0, 8);+ ImGui::TextColored(BB_DIM, "- %s", category_label(modal_def_->category));+ImGui::Spacing();+ ImGui::TextColored(BB_GRAY, "%s", modal_def_->description);++ ImGui::Spacing();+ ImVec2 sep_p = ImGui::GetCursorScreenPos();+ ImGui::GetWindowDrawList()->AddRectFilled(+ sep_p, ImVec2(sep_p.x + 448, sep_p.y + 1),+ IM_COL32(255, 140, 0, 100));+ ImGui::Dummy(ImVec2(0, 4));// Errorif (!save_error_.empty()) {- ImGui::PushStyleColor(ImGuiCol_Text, ERROR_RED);- ImGui::TextWrapped("%s", save_error_.c_str());- ImGui::PopStyleColor();+ ImGui::TextColored(BB_RED, "%s", save_error_.c_str());ImGui::Spacing();}- // Connection name field- ImGui::TextColored(TEXT_DIM, "CONNECTION NAME *");+ // Connection name+ ImGui::TextColored(BB_AMBER, "CONNECTION NAME");auto& name_val = form_data_["name"];char name_buf[128];std::strncpy(name_buf, name_val.c_str(), sizeof(name_buf) - 1);name_buf[sizeof(name_buf) - 1] = '\0';+ ImGui::PushStyleColor(ImGuiCol_FrameBg, ImVec4(0.04f, 0.04f, 0.05f, 1.0f));ImGui::SetNextItemWidth(-1);if (ImGui::InputText("##ds_conn_name", name_buf, sizeof(name_buf))) {name_val = name_buf;}+ ImGui::PopStyleColor();ImGui::Spacing();// Dynamic fields@@ -512,37 +890,40 @@ void DataSourcesScreen::render_config_modal() {}ImGui::Spacing();- ImGui::Separator();- ImGui::Spacing();+ sep_p = ImGui::GetCursorScreenPos();+ ImGui::GetWindowDrawList()->AddRectFilled(+ sep_p, ImVec2(sep_p.x + 448, sep_p.y + 1),+ IM_COL32(255, 140, 0, 100));+ ImGui::Dummy(ImVec2(0, 6));- // Test connection result display+ // Test resultif (test_result_.has_value()) {- ImGui::Spacing();auto& r = test_result_.value();- ImVec4 col = r.success ? SUCCESS : ERROR_RED;- ImGui::PushStyleColor(ImGuiCol_ChildBg, ImVec4(col.x * 0.15f, col.y * 0.15f, col.z * 0.15f, 1.0f));- ImGui::PushStyleColor(ImGuiCol_Border, col);- ImGui::BeginChild("##test_result", ImVec2(-1, 40), true);- ImGui::TextColored(col, "%s %s",- r.success ? "OK" : "FAIL", r.message.c_str());- if (r.elapsed_ms > 0)- ImGui::TextColored(TEXT_DIM, "%.0f ms", r.elapsed_ms);- ImGui::EndChild();- ImGui::PopStyleColor(2);+ ImVec4 col = r.success ? BB_GREEN : BB_RED;+ ImGui::TextColored(col, "%s", r.success ? "CONNECTION OK" : "CONNECTION FAILED");+ ImGui::SameLine(0, 8);+ ImGui::TextColored(BB_DIM, "%s", r.message.c_str());+ if (r.elapsed_ms > 0) {+ ImGui::SameLine(0, 8);+ ImGui::TextColored(BB_DIM, "(%.0fms)", r.elapsed_ms);+ }ImGui::Spacing();}// Buttons- // Test Connection button+ ImGui::PushStyleVar(ImGuiStyleVar_FrameRounding, 0);++ // Testif (testing_) {- ImGui::PushStyleColor(ImGuiCol_Button, ImVec4(0.3f, 0.3f, 0.1f, 1.0f));- ImGui::Button("TESTING...", ImVec2(120, 24));- ImGui::PopStyleColor();+ ImGui::PushStyleColor(ImGuiCol_Button, ImVec4(0.3f, 0.25f, 0.05f, 1.0f));+ ImGui::PushStyleColor(ImGuiCol_Text, BB_AMBER);+ ImGui::Button("TESTING...", ImVec2(120, 26));+ ImGui::PopStyleColor(2);} else {- ImGui::PushStyleColor(ImGuiCol_Button, ImVec4(0.1f, 0.3f, 0.15f, 1.0f));- ImGui::PushStyleColor(ImGuiCol_ButtonHovered, ImVec4(0.15f, 0.4f, 0.2f, 1.0f));- if (ImGui::Button("TEST CONNECTION", ImVec2(120, 24))) {- // Build config map from form data+ ImGui::PushStyleColor(ImGuiCol_Button, ImVec4(BB_GREEN.x * 0.2f, BB_GREEN.y * 0.2f, BB_GREEN.z * 0.2f, 1.0f));+ ImGui::PushStyleColor(ImGuiCol_ButtonHovered, ImVec4(BB_GREEN.x * 0.3f, BB_GREEN.y * 0.3f, BB_GREEN.z * 0.3f, 1.0f));+ ImGui::PushStyleColor(ImGuiCol_Text, BB_GREEN);+ if (ImGui::Button("TEST", ImVec2(120, 26))) {std::map<std::string, std::string> cfg;for (auto& [k, v] : form_data_) {if (k != "name") cfg[k] = v;@@ -552,24 +933,36 @@ void DataSourcesScreen::render_config_modal() {test_future_ = adapters::AdapterRegistry::instance().test_connection_async(std::string(modal_def_->type), cfg);}- ImGui::PopStyleColor(2);+ ImGui::PopStyleColor(3);}- ImGui::SameLine();+ ImGui::SameLine(0, 6);- if (theme::AccentButton(editing_id_.empty() ? "SAVE CONNECTION" : "UPDATE CONNECTION",- ImVec2(150, 24))) {+ // Save+ ImGui::PushStyleColor(ImGuiCol_Button, ImVec4(BB_AMBER.x * 0.3f, BB_AMBER.y * 0.3f, 0, 1.0f));+ ImGui::PushStyleColor(ImGuiCol_ButtonHovered, ImVec4(BB_AMBER.x * 0.45f, BB_AMBER.y * 0.45f, 0, 1.0f));+ ImGui::PushStyleColor(ImGuiCol_Text, BB_AMBER);+ if (ImGui::Button(editing_id_.empty() ? "SAVE" : "UPDATE", ImVec2(120, 26))) {save_connection();}- ImGui::SameLine();- if (ImGui::Button("CANCEL", ImVec2(80, 24))) {+ ImGui::PopStyleColor(3);+ ImGui::SameLine(0, 6);++ // Cancel+ ImGui::PushStyleColor(ImGuiCol_Button, ImVec4(0.12f, 0.12f, 0.13f, 1.0f));+ ImGui::PushStyleColor(ImGuiCol_ButtonHovered, ImVec4(0.18f, 0.18f, 0.20f, 1.0f));+ ImGui::PushStyleColor(ImGuiCol_Text, BB_GRAY);+ if (ImGui::Button("CANCEL", ImVec2(80, 26))) {show_modal_ = false;modal_def_ = nullptr;test_result_.reset();testing_ = false;}+ ImGui::PopStyleColor(3);++ ImGui::PopStyleVar();}ImGui::End();- ImGui::PopStyleVar();+ ImGui::PopStyleVar(2);ImGui::PopStyleColor(2);if (!open) {@@ -581,11 +974,9 @@ void DataSourcesScreen::render_config_modal() {}void DataSourcesScreen::render_field(const FieldDef& field, const std::string& /*ds_id*/) {- using namespace theme::colors;-char label[128];std::snprintf(label, sizeof(label), "%s%s", field.label, field.required ? " *" : "");- ImGui::TextColored(TEXT_DIM, "%s", label);+ ImGui::TextColored(BB_AMBER, "%s", label);auto& val = form_data_[field.name];if (val.empty() && field.default_value && field.default_value[0] != '\0') {@@ -595,6 +986,7 @@ void DataSourcesScreen::render_field(const FieldDef& field, const std::string& /char input_id[128];std::snprintf(input_id, sizeof(input_id), "##dsf_%s", field.name);+ ImGui::PushStyleColor(ImGuiCol_FrameBg, ImVec4(0.04f, 0.04f, 0.05f, 1.0f));ImGui::SetNextItemWidth(-1);switch (field.type) {@@ -648,6 +1040,7 @@ void DataSourcesScreen::render_field(const FieldDef& field, const std::string& /}}+ ImGui::PopStyleColor();ImGui::Spacing();}@@ -663,7 +1056,6 @@ void DataSourcesScreen::save_connection() {return;}- // Build config JSON from form data (excluding "name")json config;for (auto& [k, v] : form_data_) {if (k == "name") continue;@@ -672,7 +1064,6 @@ void DataSourcesScreen::save_connection() {db::DataSource ds;if (editing_id_.empty()) {- // Generate IDauto now = std::chrono::system_clock::now();auto ms = std::chrono::duration_cast<std::chrono::milliseconds>(now.time_since_epoch()).count();@@ -696,7 +1087,7 @@ void DataSourcesScreen::save_connection() {modal_def_ = nullptr;editing_id_.clear();save_error_.clear();- view_ = 1; // Switch to connections view+ view_ = 1;LOG_INFO("DataSources", "Saved connection: %s", ds.display_name.c_str());}diff --git a/fincept-cpp/src/screens/data_sources/data_sources_screen.h b/fincept-cpp/src/screens/data_sources/data_sources_screen.hindex 8e562dcf7..b7507839a 100644--- a/fincept-cpp/src/screens/data_sources/data_sources_screen.h+++ b/fincept-cpp/src/screens/data_sources/data_sources_screen.h@@ -1,6 +1,6 @@#pragma once-// Data Sources Screen — 83 connector gallery with connection management-// Two views: Gallery (browse/configure) and Connections (manage saved)+// Data Sources Screen — Bloomberg Terminal-inspired connector gallery+// Dense table layout with category sidebar, command bar, status ticker#include "data_sources_types.h"#include "adapters/adapter_registry.h"@@ -20,16 +20,15 @@ public:private:void init();- // Views- void render_header();- void render_filter_bar();- void render_gallery();- void render_connections();+ // Bloomberg-style panels+ void render_command_bar(float w, float h);+ void render_sidebar(float w, float h);+ void render_gallery_table(float w, float h);+ void render_connections_table(float w, float h);+ void render_status_bar(float w, float h);void render_config_modal();// Helpers- void render_source_card(const DataSourceDef& def);- void render_connection_row(const db::DataSource& conn);void render_field(const FieldDef& field, const std::string& ds_id);// Actions@@ -47,7 +46,7 @@ private:// Config modal statebool show_modal_ = false;const DataSourceDef* modal_def_ = nullptr;- std::string editing_id_; // empty = new, non-empty = editing+ std::string editing_id_;std::map<std::string, std::string> form_data_;std::string save_error_;@@ -56,7 +55,7 @@ private:std::future<adapters::TestResult> test_future_;std::optional<adapters::TestResult> test_result_;- // Per-connection test (from connections view)+ // Per-connection teststd::string testing_conn_id_;std::future<adapters::TestResult> conn_test_future_;std::map<std::string, adapters::TestResult> conn_test_results_;diff --git a/fincept-cpp/src/screens/node_editor/node_executor.cpp b/fincept-cpp/src/screens/node_editor/node_executor.cppindex 4593e8098..bb61e48a2 100644--- a/fincept-cpp/src/screens/node_editor/node_executor.cpp+++ b/fincept-cpp/src/screens/node_editor/node_executor.cpp@@ -472,14 +472,14 @@ ExecutionResult NodeExecutor::exec_results_display(const NodeInstance& node, con}// ============================================================================-// Stub executors+// Paper-mode executors (safe, no real orders — clearly labeled)// ============================================================================ExecutionResult NodeExecutor::exec_trigger_stub(const NodeInstance& node, const json& /*input*/) {ExecutionResult result;result.success = true;- result.data = json{{"trigger_type", node.type}, {"triggered", true}};- result.display_text = "Triggered: " + node.label;+ result.data = json{{"trigger_type", node.type}, {"triggered", true}, {"mode", "paper"}};+ result.display_text = "[PAPER] Trigger fired: " + node.label;return result;}@@ -490,29 +490,29 @@ ExecutionResult NodeExecutor::exec_trading_stub(const NodeInstance& node, constif (node.type == "signal-generator") {std::string strategy = get_param_str(node, "strategy", "crossover");result.data = json{- {"strategy", strategy}, {"signals", 47},- {"buy", 23}, {"sell", 24}, {"win_rate", 0.617}, {"mock", true}+ {"strategy", strategy}, {"mode", "paper"},+ {"note", "Signal generation requires live market data connection"}};- result.display_text = "Generated 47 signals: 23 BUY, 24 SELL (win rate 61.7%)";+ result.display_text = "[PAPER] Signal generator configured: " + strategy + " (connect live data for real signals)";} else if (node.type == "order-executor") {std::string mode = get_param_str(node, "mode", "paper");- result.data = json{{"mode", mode}, {"orders_executed", 12}, {"avg_slippage", 0.0002}, {"mock", true}};- result.display_text = mode + ": 12 orders executed, avg fill 0.02% slippage";+ result.data = json{{"mode", mode}, {"note", "Paper trading mode — no real orders placed"}};+ result.display_text = "[PAPER] Order executor ready in " + mode + " mode";} else if (node.type == "place-order") {std::string symbol = get_param_str(node, "symbol", "AAPL");std::string side = get_param_str(node, "side", "buy");int qty = get_param_int(node, "qty", 100);- result.data = json{{"symbol", symbol}, {"side", side}, {"qty", qty}, {"status", "filled"}, {"mock", true}};- result.display_text = side + " " + std::to_string(qty) + " " + symbol + " (paper - filled)";+ result.data = json{{"symbol", symbol}, {"side", side}, {"qty", qty}, {"status", "paper"}, {"mode", "paper"}};+ result.display_text = "[PAPER] Would " + side + " " + std::to_string(qty) + " " + symbol + " (no real order placed)";} else if (node.type == "get-balance") {- result.data = json{{"balance", 100000.0}, {"buying_power", 200000.0}, {"mock", true}};- result.display_text = "Balance: $100,000 | Buying Power: $200,000";+ result.data = json{{"note", "Connect broker API in Settings > Credentials for real balance"}, {"mode", "paper"}};+ result.display_text = "[PAPER] Balance: connect broker for live data";} else if (node.type == "get-positions") {- result.data = json{{"positions", json::array()}, {"count", 0}, {"mock", true}};- result.display_text = "No open positions";+ result.data = json{{"positions", json::array()}, {"note", "No broker connected"}, {"mode", "paper"}};+ result.display_text = "[PAPER] Positions: connect broker for live data";} else {- result.data = json{{"action", node.type}, {"status", "simulated"}, {"mock", true}};- result.display_text = node.label + " (simulated)";+ result.data = json{{"action", node.type}, {"mode", "paper"}};+ result.display_text = "[PAPER] " + node.label + " (connect broker for live execution)";}result.data["input"] = input;@@ -524,9 +524,9 @@ ExecutionResult NodeExecutor::exec_notification_stub(const NodeInstance& node, cresult.success = true;std::string msg = get_param_str(node, "message_template", "{{result}}");- result.data = json{{"channel", node.type}, {"message", msg}, {"sent", false}, {"mock", true}};- result.display_text = "[" + node.label + "] Would send: " + msg;- LOG_INFO("NodeExecutor", "Notification stub (%s): %s", node.type.c_str(), msg.c_str());+ result.data = json{{"channel", node.type}, {"message", msg}, {"sent", false}, {"mode", "paper"}};+ result.display_text = "[PAPER] " + node.label + ": message queued (configure notification channel to send)";+ LOG_INFO("NodeExecutor", "Notification paper-mode (%s): %s", node.type.c_str(), msg.c_str());(void)input;return result;@@ -562,8 +562,8 @@ ExecutionResult NodeExecutor::exec_file_stub(const NodeInstance& node, const jsoresult.success = true;std::string op = get_param_str(node, "operation", "read");std::string path = get_param_str(node, "path", get_param_str(node, "filename", ""));- result.data = json{{"operation", op}, {"path", path}, {"mock", true}};- result.display_text = "File " + op + ": " + (path.empty() ? "(no path)" : path) + " (stub)";+ result.data = json{{"operation", op}, {"path", path}, {"mode", "paper"}};+ result.display_text = "[PAPER] File " + op + ": " + (path.empty() ? "(specify path)" : path);(void)input;return result;}@@ -576,28 +576,28 @@ ExecutionResult NodeExecutor::exec_generic(const NodeInstance& node, const json&// Special handling for some node typesif (node.type == "correlation") {- result.display_text = "Correlation matrix: avg corr 0.42, max 0.87";+ result.display_text = "[PAPER] Correlation matrix configured (connect data source for real computation)";} else if (node.type == "monte-carlo") {int sims = get_param_int(node, "simulations", 10000);- result.display_text = "MC(" + std::to_string(sims) + " paths): E[return]=8.2%, P(loss)=18.3%";+ result.display_text = "[PAPER] Monte Carlo configured: " + std::to_string(sims) + " paths (connect data for results)";} else if (node.type == "risk-metrics") {std::string metric = get_param_str(node, "metric", "VaR");- result.display_text = metric + "(95%): -2.3%, Sharpe: 1.45";+ result.display_text = "[PAPER] " + metric + " configured (connect portfolio data for computation)";} else if (node.type == "stress-test") {std::string scenario = get_param_str(node, "scenario", "2008_gfc");- result.display_text = "Stress (" + scenario + "): portfolio -34.2%";+ result.display_text = "[PAPER] Stress test scenario: " + scenario + " (connect portfolio for results)";} else if (node.type == "optimization") {std::string method = get_param_str(node, "method", "grid");- result.display_text = "Optimized via " + method + ": best params found";+ result.display_text = "[PAPER] Optimization method: " + method + " (connect data source)";} else if (node.type == "portfolio-allocator") {std::string method = get_param_str(node, "method", "equal_weight");- result.display_text = "Allocated (" + method + "): AAPL 25%, MSFT 20%, GOOGL 18%";+ result.display_text = "[PAPER] Allocation method: " + method + " (connect portfolio for weights)";} else if (node.type == "sentiment-analyzer") {- result.display_text = "Sentiment: 62% positive, 18% negative, 20% neutral";+ result.display_text = "[PAPER] Sentiment analyzer configured (connect news feed for analysis)";} else if (node.type == "screener") {- result.display_text = "Screened: 127 stocks matched criteria";+ result.display_text = "[PAPER] Screener configured (connect data source to run screen)";} else if (node.type == "news-feed") {- result.display_text = "Fetched 50 articles, latest: 2h ago";+ result.display_text = "[PAPER] News feed configured (connect RSS source for articles)";} else if (node.type == "code") {std::string lang = get_param_str(node, "language", "expression");result.display_text = "Code executed (" + lang + ")";diff --git a/fincept-cpp/src/screens/notes/notes_screen.cpp b/fincept-cpp/src/screens/notes/notes_screen.cppindex 5504773d2..8c4fc3ce8 100644--- a/fincept-cpp/src/screens/notes/notes_screen.cpp+++ b/fincept-cpp/src/screens/notes/notes_screen.cpp@@ -4,6 +4,7 @@#include "notes_screen.h"#include "notes_types.h"#include "ui/theme.h"+#include "ui/yoga_helpers.h"#include "imgui.h"#include <algorithm>#include <cstring>@@ -29,14 +30,17 @@ void NotesScreen::render() {apply_filters();}- auto avail = ImGui::GetContentRegionAvail();+ // Use ScreenFrame to render inline in the main content area (not a separate window)+ ui::ScreenFrame frame("##notes_screen", ImVec2(8, 8), theme::colors::BG_DARKEST);+ if (!frame.begin()) { frame.end(); return; }// Toolbar at toprender_toolbar();float toolbar_h = ImGui::GetCursorPosY();float status_h = 28.0f;- float body_h = avail.y - toolbar_h - status_h;+ float body_h = frame.height() - toolbar_h - status_h;+ if (body_h < 100) body_h = 100;// Body: sidebar + list + editor/viewerImGui::BeginChild("##notes_body", ImVec2(0, body_h), false);@@ -79,7 +83,9 @@ void NotesScreen::render() {// Status barrender_status_bar();- // Delete confirmation popup+ frame.end();++ // Delete confirmation popup (rendered outside frame so it overlays properly)render_delete_confirm_popup();}diff --git a/fincept-cpp/src/screens/quantlib/quantlib_screen.cpp b/fincept-cpp/src/screens/quantlib/quantlib_screen.cppindex d8a634876..d55ff47cc 100644--- a/fincept-cpp/src/screens/quantlib/quantlib_screen.cpp+++ b/fincept-cpp/src/screens/quantlib/quantlib_screen.cpp@@ -1155,122 +1155,1548 @@ void QuantLibScreen::render_periods() {}// ============================================================================-// Stub panels — remaining 69 sections (to be implemented in phases 3-7)-// Each renders a "coming soon" placeholder+// Regulatory Panels// ============================================================================-#define STUB_PANEL(name, label) \-void QuantLibScreen::name() { \- using namespace theme::colors; \- ImGui::TextColored(TEXT_DIM, label " — endpoints coming soon"); \- ImGui::Spacing(); \- ImGui::TextColored(TEXT_DISABLED, "This panel will contain full endpoint cards"); \- ImGui::TextColored(TEXT_DISABLED, "with input fields, Run buttons, and JSON results."); \-}--// Regulatory-STUB_PANEL(render_basel, "Basel III")-STUB_PANEL(render_saccr, "SA-CCR")-STUB_PANEL(render_ifrs9, "IFRS 9")-STUB_PANEL(render_liquidity,"Liquidity")-STUB_PANEL(render_stress, "Stress Test")--// Volatility-STUB_PANEL(render_surface, "Volatility Surface")-STUB_PANEL(render_sabr, "SABR")-STUB_PANEL(render_localvol,"Local Vol")--// Models-STUB_PANEL(render_shortrate,"Short Rate")-STUB_PANEL(render_hullwhite,"Hull-White")-STUB_PANEL(render_heston, "Heston")-STUB_PANEL(render_jumpdiff,"Jump Diffusion")-STUB_PANEL(render_volmodels,"Dupire / SVI")--// Stochastic-STUB_PANEL(render_processes,"Stochastic Processes")-STUB_PANEL(render_exact, "Exact Solutions")-STUB_PANEL(render_simulation,"Simulation")-STUB_PANEL(render_sampling,"Sampling Methods")-STUB_PANEL(render_theory, "Probability Theory")--// ML-STUB_PANEL(render_ml_credit, "ML Credit")-STUB_PANEL(render_ml_regression, "ML Regression")-STUB_PANEL(render_ml_clustering, "ML Clustering")-STUB_PANEL(render_ml_preprocessing,"ML Preprocessing")-STUB_PANEL(render_ml_features, "ML Features")-STUB_PANEL(render_ml_validation, "ML Validation")-STUB_PANEL(render_ml_timeseries, "ML Time Series")-STUB_PANEL(render_ml_gpnn, "GP / Neural Net")-STUB_PANEL(render_ml_factor, "Factor / Cov")--// Statistics-STUB_PANEL(render_stat_continuous, "Continuous Distributions")-STUB_PANEL(render_stat_discrete, "Discrete Distributions")-STUB_PANEL(render_stat_timeseries, "Time Series Stats")--// Portfolio-STUB_PANEL(render_port_optimize, "Portfolio Optimization")-STUB_PANEL(render_port_risk, "Portfolio Risk")--// Scheduling-STUB_PANEL(render_sched_calendar, "Calendars")-STUB_PANEL(render_sched_daycount, "Day Count")--// Physics-STUB_PANEL(render_phys_entropy, "Entropy")-STUB_PANEL(render_phys_thermo, "Thermodynamics")--// Curves-STUB_PANEL(render_curves_build, "Curve Build & Query")-STUB_PANEL(render_curves_transform, "Curve Transforms")-STUB_PANEL(render_curves_fitting, "NS / NSS Fitting")-STUB_PANEL(render_curves_specialized, "Specialized Curves")--// Pricing-STUB_PANEL(render_pricing_bs, "Black-Scholes Pricing")-STUB_PANEL(render_pricing_black76, "Black76 Pricing")-STUB_PANEL(render_pricing_bachelier, "Bachelier Pricing")-STUB_PANEL(render_pricing_numerical, "Numerical Pricing")--// Risk-STUB_PANEL(render_risk_var, "VaR / Stress")-STUB_PANEL(render_risk_evt_xva, "EVT / XVA")-STUB_PANEL(render_risk_sensitivities, "Sensitivities")--// Economics-STUB_PANEL(render_econ_equilibrium, "Equilibrium")-STUB_PANEL(render_econ_gametheory, "Game Theory")-STUB_PANEL(render_econ_auctions, "Auctions")-STUB_PANEL(render_econ_utility, "Utility Theory")--// Solver-STUB_PANEL(render_solver_bond, "Bond Analytics")-STUB_PANEL(render_solver_rates, "Rates / IV")-STUB_PANEL(render_solver_cashflow, "Cashflows")--// Numerical-STUB_PANEL(render_num_difffft, "Diff / FFT / Integration")-STUB_PANEL(render_num_interplinalg, "Interp / LinAlg")-STUB_PANEL(render_num_solvers, "ODE / Roots / Opt")--// Instruments-STUB_PANEL(render_instr_bonds, "Bonds")-STUB_PANEL(render_instr_swaps, "Swaps / FRA")-STUB_PANEL(render_instr_markets, "Market Instruments")-STUB_PANEL(render_instr_creditfut, "Credit / Futures")--// Analysis-STUB_PANEL(render_analysis_fundamentals, "Fundamentals")-STUB_PANEL(render_analysis_profit_liq, "Profit / Liquidity")-STUB_PANEL(render_analysis_eff_growth, "Efficiency / Growth")-STUB_PANEL(render_analysis_lev_cf, "Leverage / CF")-STUB_PANEL(render_analysis_val_qual, "Val Ratios / Quality")-STUB_PANEL(render_analysis_industry, "Industry Analysis")-STUB_PANEL(render_analysis_dcf, "DCF Valuation")-STUB_PANEL(render_analysis_models, "Valuation Models")--#undef STUB_PANEL+void QuantLibScreen::render_basel() {+ if (begin_endpoint_card("basel-capital", "Capital Ratios", "Calculate CET1, Tier1, Total capital ratios")) {+ input_float("basel-capital", "CET1 Capital", "cet1_capital", "50000");+ input_float("basel-capital", "Tier1 Capital", "tier1_capital", "60000");+ input_float("basel-capital", "Total Capital", "total_capital", "80000");+ input_float("basel-capital", "RWA", "rwa", "500000");+ if (run_button("basel-capital")) {+ auto& s = ep("basel-capital");+ fire_post("basel-capital", "regulatory/basel/capital-ratios", {+ {"cet1_capital", s.getd("cet1_capital")}, {"tier1_capital", s.getd("tier1_capital")},+ {"total_capital", s.getd("total_capital")}, {"risk_weighted_assets", s.getd("rwa")}+ });+ }+ render_result("basel-capital");+ end_endpoint_card();+ }+ if (begin_endpoint_card("basel-oprwa", "Operational RWA", "Basic indicator approach")) {+ input_array("basel-oprwa", "Gross Income (3y)", "gross_income_3y", "100000,110000,120000");+ if (run_button("basel-oprwa")) {+ auto& s = ep("basel-oprwa");+ auto arr = json::array({100000, 110000, 120000});+ fire_post("basel-oprwa", "regulatory/basel/operational-rwa", {{"gross_income_3y", arr}});+ }+ render_result("basel-oprwa");+ end_endpoint_card();+ }+}++void QuantLibScreen::render_saccr() {+ if (begin_endpoint_card("saccr-ead", "SA-CCR EAD", "Standardised approach for counterparty credit risk")) {+ input_float("saccr-ead", "MtM Value", "mtm_value", "1000000");+ input_float("saccr-ead", "Add-on", "addon", "50000");+ input_float("saccr-ead", "Collateral", "collateral", "200000");+ input_float("saccr-ead", "Alpha", "alpha", "1.4");+ if (run_button("saccr-ead")) {+ auto& s = ep("saccr-ead");+ fire_post("saccr-ead", "regulatory/saccr/ead", {+ {"mtm_value", s.getd("mtm_value")}, {"addon", s.getd("addon")},+ {"collateral", s.getd("collateral")}, {"alpha", s.getd("alpha", 1.4)}+ });+ }+ render_result("saccr-ead");+ end_endpoint_card();+ }+}++void QuantLibScreen::render_ifrs9() {+ if (begin_endpoint_card("ifrs9-stage", "Stage Assessment", "IFRS 9 staging classification")) {+ input_int("ifrs9-stage", "Days Past Due", "dpd", "30");+ input_float("ifrs9-stage", "Rating Downgrade", "downgrade", "2");+ input_float("ifrs9-stage", "PD Increase Ratio", "pd_ratio", "2.5");+ if (run_button("ifrs9-stage")) {+ auto& s = ep("ifrs9-stage");+ fire_post("ifrs9-stage", "regulatory/ifrs9/stage-assessment", {+ {"days_past_due", s.geti("dpd")}, {"rating_downgrade", s.getd("downgrade")},+ {"pd_increase_ratio", s.getd("pd_ratio")}+ });+ }+ render_result("ifrs9-stage");+ end_endpoint_card();+ }+ if (begin_endpoint_card("ifrs9-ecl12m", "ECL 12-Month", "12-month expected credit loss")) {+ input_float("ifrs9-ecl12m", "PD 12m", "pd", "0.02");+ input_float("ifrs9-ecl12m", "LGD", "lgd", "0.45");+ input_float("ifrs9-ecl12m", "EAD", "ead", "1000000");+ input_float("ifrs9-ecl12m", "Discount Rate", "dr", "0.05");+ if (run_button("ifrs9-ecl12m")) {+ auto& s = ep("ifrs9-ecl12m");+ fire_post("ifrs9-ecl12m", "regulatory/ifrs9/ecl-12m", {+ {"pd_12m", s.getd("pd")}, {"lgd", s.getd("lgd")},+ {"ead", s.getd("ead")}, {"discount_rate", s.getd("dr")}+ });+ }+ render_result("ifrs9-ecl12m");+ end_endpoint_card();+ }+}++void QuantLibScreen::render_liquidity() {+ if (begin_endpoint_card("liq-lcr", "Liquidity Coverage Ratio", "Basel III LCR calculation")) {+ input_float("liq-lcr", "HQLA Level 1", "hqla1", "500000");+ input_float("liq-lcr", "Retail Deposits (stable)", "rd_stable", "200000");+ input_float("liq-lcr", "Unsecured Wholesale", "wholesale", "300000");+ if (run_button("liq-lcr")) {+ auto& s = ep("liq-lcr");+ fire_post("liq-lcr", "regulatory/liquidity/lcr", {+ {"hqla_level1", s.getd("hqla1")},+ {"retail_deposits_stable", s.getd("rd_stable")},+ {"unsecured_wholesale", s.getd("wholesale")}+ });+ }+ render_result("liq-lcr");+ end_endpoint_card();+ }+ if (begin_endpoint_card("liq-nsfr", "Net Stable Funding Ratio", "Basel III NSFR calculation")) {+ input_float("liq-nsfr", "Capital", "capital", "100000");+ input_float("liq-nsfr", "Stable Deposits", "stable", "300000");+ input_float("liq-nsfr", "Loans Retail", "loans_retail", "400000");+ if (run_button("liq-nsfr")) {+ auto& s = ep("liq-nsfr");+ fire_post("liq-nsfr", "regulatory/liquidity/nsfr", {+ {"capital", s.getd("capital")}, {"stable_deposits_retail", s.getd("stable")},+ {"loans_retail", s.getd("loans_retail")}+ });+ }+ render_result("liq-nsfr");+ end_endpoint_card();+ }+}++void QuantLibScreen::render_stress() {+ if (begin_endpoint_card("stress-proj", "Capital Projection", "Multi-period stress test capital projection")) {+ input_float("stress-proj", "Initial Capital", "capital", "100000");+ input_float("stress-proj", "Initial RWA", "rwa", "500000");+ input_array("stress-proj", "Earnings", "earnings", "10000,9000,8000");+ input_array("stress-proj", "Losses", "losses", "5000,15000,20000");+ if (run_button("stress-proj")) {+ auto& s = ep("stress-proj");+ fire_post("stress-proj", "regulatory/stress/capital-projection", {+ {"initial_capital", s.getd("capital")}, {"initial_rwa", s.getd("rwa")},+ {"earnings", json::array({10000,9000,8000})},+ {"losses", json::array({5000,15000,20000})},+ {"rwa_changes", json::array({0,10000,20000})}+ });+ }+ render_result("stress-proj");+ end_endpoint_card();+ }+}++// ============================================================================+// Volatility Panels+// ============================================================================++void QuantLibScreen::render_surface() {+ if (begin_endpoint_card("vol-flat", "Flat Surface", "Constant volatility surface")) {+ input_float("vol-flat", "Volatility", "vol", "0.20");+ input_float("vol-flat", "Query Expiry", "expiry", "1.0");+ input_float("vol-flat", "Query Strike", "strike", "100");+ if (run_button("vol-flat")) {+ auto& s = ep("vol-flat");+ fire_post("vol-flat", "volatility/surface/flat", {+ {"volatility", s.getd("vol")}, {"query_expiry", s.getd("expiry")}, {"query_strike", s.getd("strike")}+ });+ }+ render_result("vol-flat");+ end_endpoint_card();+ }+ if (begin_endpoint_card("vol-term", "Term Structure", "Volatility term structure interpolation")) {+ input_array("vol-term", "Expiries", "expiries", "0.25,0.5,1.0,2.0");+ input_array("vol-term", "Volatilities", "vols", "0.25,0.22,0.20,0.19");+ input_float("vol-term", "Query Expiry", "query", "0.75");+ if (run_button("vol-term")) {+ fire_post("vol-term", "volatility/surface/term-structure", {+ {"expiries", json::array({0.25,0.5,1.0,2.0})},+ {"volatilities", json::array({0.25,0.22,0.20,0.19})},+ {"query_expiry", ep("vol-term").getd("query", 0.75)}+ });+ }+ render_result("vol-term");+ end_endpoint_card();+ }+}++void QuantLibScreen::render_sabr() {+ if (begin_endpoint_card("sabr-iv", "SABR Implied Vol", "SABR model implied volatility")) {+ input_float("sabr-iv", "Forward", "fwd", "100");+ input_float("sabr-iv", "Strike", "strike", "100");+ input_float("sabr-iv", "Expiry", "expiry", "1.0");+ input_float("sabr-iv", "Alpha", "alpha", "0.3");+ input_float("sabr-iv", "Beta", "beta", "0.5");+ input_float("sabr-iv", "Rho", "rho", "-0.3");+ input_float("sabr-iv", "Nu", "nu", "0.4");+ if (run_button("sabr-iv")) {+ auto& s = ep("sabr-iv");+ fire_post("sabr-iv", "volatility/sabr/implied-vol", {+ {"forward", s.getd("fwd")}, {"strike", s.getd("strike")}, {"expiry", s.getd("expiry")},+ {"alpha", s.getd("alpha")}, {"beta", s.getd("beta")}, {"rho", s.getd("rho")}, {"nu", s.getd("nu")}+ });+ }+ render_result("sabr-iv");+ end_endpoint_card();+ }+ if (begin_endpoint_card("sabr-cal", "SABR Calibrate", "Calibrate SABR to market vols")) {+ input_float("sabr-cal", "Forward", "fwd", "100");+ input_float("sabr-cal", "Expiry", "expiry", "1.0");+ input_array("sabr-cal", "Strikes", "strikes", "90,95,100,105,110");+ input_array("sabr-cal", "Market Vols", "vols", "0.25,0.22,0.20,0.21,0.24");+ if (run_button("sabr-cal")) {+ fire_post("sabr-cal", "volatility/sabr/calibrate", {+ {"forward", ep("sabr-cal").getd("fwd")}, {"expiry", ep("sabr-cal").getd("expiry")},+ {"strikes", json::array({90,95,100,105,110})},+ {"market_vols", json::array({0.25,0.22,0.20,0.21,0.24})}+ });+ }+ render_result("sabr-cal");+ end_endpoint_card();+ }+}++void QuantLibScreen::render_localvol() {+ if (begin_endpoint_card("lv-const", "Constant Local Vol", "Constant local volatility")) {+ input_float("lv-const", "Volatility", "vol", "0.20");+ input_float("lv-const", "Spot", "spot", "100");+ input_float("lv-const", "Time", "time", "1.0");+ if (run_button("lv-const")) {+ auto& s = ep("lv-const");+ fire_post("lv-const", "volatility/local-vol/constant", {+ {"volatility", s.getd("vol")}, {"spot", s.getd("spot")}, {"time", s.getd("time")}+ });+ }+ render_result("lv-const");+ end_endpoint_card();+ }+ if (begin_endpoint_card("lv-impl", "Implied to Local", "Convert implied vol to local vol via Dupire")) {+ input_float("lv-impl", "Spot", "spot", "100");+ input_float("lv-impl", "Rate", "rate", "0.05");+ input_float("lv-impl", "Strike", "strike", "100");+ input_float("lv-impl", "Expiry", "expiry", "1.0");+ input_float("lv-impl", "Implied Vol", "iv", "0.20");+ if (run_button("lv-impl")) {+ auto& s = ep("lv-impl");+ fire_post("lv-impl", "volatility/local-vol/implied-to-local", {+ {"spot", s.getd("spot")}, {"rate", s.getd("rate")}, {"strike", s.getd("strike")},+ {"expiry", s.getd("expiry")}, {"implied_vol", s.getd("iv")}+ });+ }+ render_result("lv-impl");+ end_endpoint_card();+ }+}++// ============================================================================+// Models Panels+// ============================================================================++void QuantLibScreen::render_shortrate() {+ if (begin_endpoint_card("sr-bond", "Bond Price", "Short rate model bond pricing")) {+ input_select("sr-bond", "Model", "model", {"vasicek", "cir", "hw"});+ input_float("sr-bond", "Kappa", "kappa", "0.5");+ input_float("sr-bond", "Theta", "theta", "0.05");+ input_float("sr-bond", "Sigma", "sigma", "0.01");+ input_float("sr-bond", "r0", "r0", "0.03");+ if (run_button("sr-bond")) {+ auto& s = ep("sr-bond");+ fire_post("sr-bond", "models/short-rate/bond-price", {+ {"model", s.get("model", "vasicek")}, {"kappa", s.getd("kappa")},+ {"theta", s.getd("theta")}, {"sigma", s.getd("sigma")}, {"r0", s.getd("r0")}+ });+ }+ render_result("sr-bond");+ end_endpoint_card();+ }+ if (begin_endpoint_card("sr-mc", "Monte Carlo", "Short rate Monte Carlo simulation")) {+ input_select("sr-mc", "Model", "model", {"vasicek", "cir", "hw"});+ input_float("sr-mc", "r0", "r0", "0.03"); input_float("sr-mc", "T", "T", "1.0");+ input_int("sr-mc", "Steps", "steps", "100"); input_int("sr-mc", "Paths", "paths", "1000");+ if (run_button("sr-mc")) {+ auto& s = ep("sr-mc");+ fire_post("sr-mc", "models/short-rate/monte-carlo", {+ {"model", s.get("model")}, {"r0", s.getd("r0")}, {"T", s.getd("T")},+ {"n_steps", s.geti("steps")}, {"n_paths", s.geti("paths")}+ });+ }+ render_result("sr-mc");+ end_endpoint_card();+ }+}++void QuantLibScreen::render_hullwhite() {+ if (begin_endpoint_card("hw-cal", "Hull-White Calibrate", "Calibrate Hull-White model to market")) {+ input_float("hw-cal", "Kappa", "kappa", "0.1");+ input_float("hw-cal", "Sigma", "sigma", "0.01");+ input_float("hw-cal", "r0", "r0", "0.03");+ if (run_button("hw-cal")) {+ auto& s = ep("hw-cal");+ fire_post("hw-cal", "models/hull-white/calibrate", {+ {"kappa", s.getd("kappa")}, {"sigma", s.getd("sigma")}, {"r0", s.getd("r0")}+ });+ }+ render_result("hw-cal");+ end_endpoint_card();+ }+}++void QuantLibScreen::render_heston() {+ if (begin_endpoint_card("hes-price", "Heston Price", "Heston stochastic vol option pricing")) {+ input_float("hes-price", "S0", "S0", "100"); input_float("hes-price", "v0", "v0", "0.04");+ input_float("hes-price", "r", "r", "0.05"); input_float("hes-price", "Kappa", "kappa", "2.0");+ input_float("hes-price", "Theta", "theta", "0.04"); input_float("hes-price", "Sigma_v", "sigma_v", "0.3");+ input_float("hes-price", "Rho", "rho", "-0.7"); input_float("hes-price", "Strike", "strike", "100");+ input_float("hes-price", "T", "T", "1.0");+ if (run_button("hes-price")) {+ auto& s = ep("hes-price");+ fire_post("hes-price", "models/heston/price", {+ {"S0", s.getd("S0")}, {"v0", s.getd("v0")}, {"r", s.getd("r")},+ {"kappa", s.getd("kappa")}, {"theta", s.getd("theta")}, {"sigma_v", s.getd("sigma_v")},+ {"rho", s.getd("rho")}, {"strike", s.getd("strike")}, {"T", s.getd("T")}+ });+ }+ render_result("hes-price");+ end_endpoint_card();+ }+}++void QuantLibScreen::render_jumpdiff() {+ if (begin_endpoint_card("jd-merton", "Merton Jump-Diffusion", "Merton model option pricing")) {+ input_float("jd-merton", "S", "S", "100"); input_float("jd-merton", "K", "K", "100");+ input_float("jd-merton", "T", "T", "1.0"); input_float("jd-merton", "r", "r", "0.05");+ input_float("jd-merton", "Sigma", "sigma", "0.2"); input_float("jd-merton", "Lambda", "lambda", "0.1");+ input_float("jd-merton", "Jump Mean", "mu_j", "-0.1"); input_float("jd-merton", "Jump Std", "sigma_j", "0.3");+ if (run_button("jd-merton")) {+ auto& s = ep("jd-merton");+ fire_post("jd-merton", "models/merton/price", {+ {"S", s.getd("S")}, {"K", s.getd("K")}, {"T", s.getd("T")}, {"r", s.getd("r")},+ {"sigma", s.getd("sigma")}, {"lambda_jump", s.getd("lambda")},+ {"mu_jump", s.getd("mu_j")}, {"sigma_jump", s.getd("sigma_j")}+ });+ }+ render_result("jd-merton");+ end_endpoint_card();+ }+ if (begin_endpoint_card("jd-kou", "Kou Double Exponential", "Kou model option pricing")) {+ input_float("jd-kou", "S", "S", "100"); input_float("jd-kou", "K", "K", "100");+ input_float("jd-kou", "T", "T", "1.0"); input_float("jd-kou", "r", "r", "0.05");+ input_float("jd-kou", "Sigma", "sigma", "0.2"); input_float("jd-kou", "Lambda", "lambda", "0.1");+ input_float("jd-kou", "p (up prob)", "p", "0.4");+ input_float("jd-kou", "Eta1", "eta1", "10"); input_float("jd-kou", "Eta2", "eta2", "5");+ if (run_button("jd-kou")) {+ auto& s = ep("jd-kou");+ fire_post("jd-kou", "models/kou/price", {+ {"S", s.getd("S")}, {"K", s.getd("K")}, {"T", s.getd("T")}, {"r", s.getd("r")},+ {"sigma", s.getd("sigma")}, {"lambda_jump", s.getd("lambda")},+ {"p", s.getd("p")}, {"eta1", s.getd("eta1")}, {"eta2", s.getd("eta2")}+ });+ }+ render_result("jd-kou");+ end_endpoint_card();+ }+}++void QuantLibScreen::render_volmodels() {+ if (begin_endpoint_card("dupire-price", "Dupire Price", "Local vol model pricing")) {+ input_float("dupire-price", "Spot", "spot", "100"); input_float("dupire-price", "r", "r", "0.05");+ input_float("dupire-price", "Sigma", "sigma", "0.2");+ input_float("dupire-price", "Strike", "strike", "100"); input_float("dupire-price", "T", "T", "1.0");+ if (run_button("dupire-price")) {+ auto& s = ep("dupire-price");+ fire_post("dupire-price", "models/dupire/price", {+ {"spot", s.getd("spot")}, {"r", s.getd("r")}, {"sigma", s.getd("sigma")},+ {"strike", s.getd("strike")}, {"T", s.getd("T")}+ });+ }+ render_result("dupire-price");+ end_endpoint_card();+ }+ if (begin_endpoint_card("svi-cal", "SVI Calibrate", "SVI volatility smile calibration")) {+ input_float("svi-cal", "Forward", "fwd", "100"); input_float("svi-cal", "T", "T", "1.0");+ input_array("svi-cal", "Strikes", "strikes", "90,95,100,105,110");+ input_array("svi-cal", "Market Vols", "vols", "0.25,0.22,0.20,0.21,0.24");+ if (run_button("svi-cal")) {+ fire_post("svi-cal", "models/svi/calibrate", {+ {"forward", ep("svi-cal").getd("fwd")}, {"T", ep("svi-cal").getd("T")},+ {"strikes", json::array({90,95,100,105,110})},+ {"market_vols", json::array({0.25,0.22,0.20,0.21,0.24})}+ });+ }+ render_result("svi-cal");+ end_endpoint_card();+ }+}++// ============================================================================+// Stochastic Panels+// ============================================================================++void QuantLibScreen::render_processes() {+ if (begin_endpoint_card("gbm-sim", "GBM Simulate", "Geometric Brownian Motion simulation")) {+ input_float("gbm-sim", "S0", "S0", "100"); input_float("gbm-sim", "Mu", "mu", "0.1");+ input_float("gbm-sim", "Sigma", "sigma", "0.2"); input_float("gbm-sim", "T", "T", "1.0");+ input_int("gbm-sim", "Steps", "steps", "252"); input_int("gbm-sim", "Paths", "paths", "5");+ if (run_button("gbm-sim")) {+ auto& s = ep("gbm-sim");+ fire_post("gbm-sim", "stochastic/gbm/simulate", {+ {"S0", s.getd("S0")}, {"mu", s.getd("mu")}, {"sigma", s.getd("sigma")},+ {"T", s.getd("T")}, {"n_steps", s.geti("steps")}, {"n_paths", s.geti("paths")}+ });+ }+ render_result("gbm-sim");+ end_endpoint_card();+ }+ if (begin_endpoint_card("ou-sim", "OU Simulate", "Ornstein-Uhlenbeck mean-reverting process")) {+ input_float("ou-sim", "X0", "X0", "0.05"); input_float("ou-sim", "Kappa", "kappa", "5.0");+ input_float("ou-sim", "Theta", "theta", "0.05"); input_float("ou-sim", "Sigma", "sigma", "0.01");+ input_float("ou-sim", "T", "T", "1.0");+ if (run_button("ou-sim")) {+ auto& s = ep("ou-sim");+ fire_post("ou-sim", "stochastic/ou/simulate", {+ {"X0", s.getd("X0")}, {"kappa", s.getd("kappa")}, {"theta", s.getd("theta")},+ {"sigma", s.getd("sigma")}, {"T", s.getd("T")}+ });+ }+ render_result("ou-sim");+ end_endpoint_card();+ }+ if (begin_endpoint_card("cir-sim", "CIR Simulate", "Cox-Ingersoll-Ross interest rate model")) {+ input_float("cir-sim", "r0", "r0", "0.05"); input_float("cir-sim", "Kappa", "kappa", "0.5");+ input_float("cir-sim", "Theta", "theta", "0.05"); input_float("cir-sim", "Sigma", "sigma", "0.1");+ input_float("cir-sim", "T", "T", "5.0");+ if (run_button("cir-sim")) {+ auto& s = ep("cir-sim");+ fire_post("cir-sim", "stochastic/cir/simulate", {+ {"r0", s.getd("r0")}, {"kappa", s.getd("kappa")}, {"theta", s.getd("theta")},+ {"sigma", s.getd("sigma")}, {"T", s.getd("T")}+ });+ }+ render_result("cir-sim");+ end_endpoint_card();+ }+}++void QuantLibScreen::render_exact() {+ if (begin_endpoint_card("exact-gbm", "Exact GBM", "Exact analytical GBM solution")) {+ input_float("exact-gbm", "S0", "S0", "100"); input_float("exact-gbm", "Mu", "mu", "0.1");+ input_float("exact-gbm", "Sigma", "sigma", "0.2"); input_float("exact-gbm", "T", "T", "1.0");+ if (run_button("exact-gbm")) {+ auto& s = ep("exact-gbm");+ fire_post("exact-gbm", "stochastic/exact/gbm", {+ {"S0", s.getd("S0")}, {"mu", s.getd("mu")}, {"sigma", s.getd("sigma")}, {"T", s.getd("T")}+ });+ }+ render_result("exact-gbm");+ end_endpoint_card();+ }+}++void QuantLibScreen::render_simulation() {+ if (begin_endpoint_card("sim-euler", "Euler-Maruyama", "SDE numerical integration")) {+ input_float("sim-euler", "x0", "x0", "1.0"); input_float("sim-euler", "T", "T", "1.0");+ input_float("sim-euler", "Mu", "mu", "0.1"); input_float("sim-euler", "Sigma", "sigma", "0.2");+ input_int("sim-euler", "Steps", "steps", "1000"); input_int("sim-euler", "Paths", "paths", "10");+ if (run_button("sim-euler")) {+ auto& s = ep("sim-euler");+ fire_post("sim-euler", "stochastic/simulation/euler-maruyama", {+ {"x0", s.getd("x0")}, {"T", s.getd("T")}, {"mu", s.getd("mu")},+ {"sigma", s.getd("sigma")}, {"n_steps", s.geti("steps")}, {"n_paths", s.geti("paths")}+ });+ }+ render_result("sim-euler");+ end_endpoint_card();+ }+ if (begin_endpoint_card("sim-milstein", "Milstein", "Higher-order SDE integration")) {+ input_float("sim-milstein", "x0", "x0", "1.0"); input_float("sim-milstein", "T", "T", "1.0");+ input_float("sim-milstein", "Mu", "mu", "0.1"); input_float("sim-milstein", "Sigma", "sigma", "0.2");+ if (run_button("sim-milstein")) {+ auto& s = ep("sim-milstein");+ fire_post("sim-milstein", "stochastic/simulation/milstein", {+ {"x0", s.getd("x0")}, {"T", s.getd("T")}, {"mu", s.getd("mu")}, {"sigma", s.getd("sigma")}+ });+ }+ render_result("sim-milstein");+ end_endpoint_card();+ }+}++void QuantLibScreen::render_sampling() {+ if (begin_endpoint_card("samp-sobol", "Sobol Sequence", "Quasi-random low-discrepancy sequence")) {+ input_int("samp-sobol", "Dimensions", "dim", "2"); input_int("samp-sobol", "N Points", "n", "100");+ if (run_button("samp-sobol")) {+ auto& s = ep("samp-sobol");+ fire_post("samp-sobol", "stochastic/sampling/sobol", {{"dim", s.geti("dim")}, {"n", s.geti("n")}});+ }+ render_result("samp-sobol");+ end_endpoint_card();+ }+ if (begin_endpoint_card("samp-anti", "Antithetic Sampling", "Variance reduction via antithetic variates")) {+ input_int("samp-anti", "N", "n", "1000");+ if (run_button("samp-anti")) {+ fire_post("samp-anti", "stochastic/sampling/antithetic", {{"n", ep("samp-anti").geti("n")}});+ }+ render_result("samp-anti");+ end_endpoint_card();+ }+}++void QuantLibScreen::render_theory() {+ if (begin_endpoint_card("th-qv", "Quadratic Variation", "Compute quadratic variation of a path")) {+ input_array("th-qv", "Path", "path", "1.0,1.1,1.05,1.15,1.2");+ input_array("th-qv", "Times", "times", "0,0.25,0.5,0.75,1.0");+ if (run_button("th-qv")) {+ fire_post("th-qv", "stochastic/theory/quadratic-variation", {+ {"path", json::array({1.0,1.1,1.05,1.15,1.2})},+ {"times", json::array({0,0.25,0.5,0.75,1.0})}+ });+ }+ render_result("th-qv");+ end_endpoint_card();+ }+ if (begin_endpoint_card("th-rnd", "Risk-Neutral Drift", "Girsanov risk-neutral drift")) {+ input_float("th-rnd", "Mu", "mu", "0.1"); input_float("th-rnd", "r", "r", "0.05");+ input_float("th-rnd", "Sigma", "sigma", "0.2");+ if (run_button("th-rnd")) {+ auto& s = ep("th-rnd");+ fire_post("th-rnd", "stochastic/theory/girsanov/risk-neutral-drift", {+ {"mu", s.getd("mu")}, {"r", s.getd("r")}, {"sigma", s.getd("sigma")}+ });+ }+ render_result("th-rnd");+ end_endpoint_card();+ }+}++// ============================================================================+// ML Panels+// ============================================================================++void QuantLibScreen::render_ml_credit() {+ if (begin_endpoint_card("ml-cr-disc", "Discrimination Metrics", "AUC, KS, Gini for credit scoring")) {+ input_array("ml-cr-disc", "y_true", "y_true", "0,0,1,1,0,1"); input_array("ml-cr-disc", "y_score", "y_score", "0.1,0.3,0.8,0.9,0.2,0.7");+ if (run_button("ml-cr-disc")) {+ fire_post("ml-cr-disc", "ml/credit/discrimination", {+ {"y_true", json::array({0,0,1,1,0,1})}, {"y_score", json::array({0.1,0.3,0.8,0.9,0.2,0.7})}+ });+ }+ render_result("ml-cr-disc");+ end_endpoint_card();+ }+ if (begin_endpoint_card("ml-cr-perf", "Model Performance", "Credit model performance metrics")) {+ input_array("ml-cr-perf", "y_true", "y_true", "0,0,1,1,0,1"); input_array("ml-cr-perf", "y_score", "y_score", "0.1,0.3,0.8,0.9,0.2,0.7");+ if (run_button("ml-cr-perf")) {+ fire_post("ml-cr-perf", "ml/credit/performance", {+ {"y_true", json::array({0,0,1,1,0,1})}, {"y_score", json::array({0.1,0.3,0.8,0.9,0.2,0.7})}+ });+ }+ render_result("ml-cr-perf");+ end_endpoint_card();+ }+}++void QuantLibScreen::render_ml_regression() {+ if (begin_endpoint_card("ml-reg-fit", "Regression Fit", "Linear/Ridge/Lasso regression")) {+ input_select("ml-reg-fit", "Method", "method", {"ols", "ridge", "lasso", "elastic_net"});+ input_float("ml-reg-fit", "Alpha", "alpha", "1.0");+ if (run_button("ml-reg-fit")) {+ fire_post("ml-reg-fit", "ml/regression/fit", {+ {"X", json::array({json::array({1,2}), json::array({3,4}), json::array({5,6})})},+ {"y", json::array({1.5, 3.5, 5.5})}, {"method", ep("ml-reg-fit").get("method", "ols")}+ });+ }+ render_result("ml-reg-fit");+ end_endpoint_card();+ }+}++void QuantLibScreen::render_ml_clustering() {+ if (begin_endpoint_card("ml-cl-km", "K-Means", "K-Means clustering")) {+ input_int("ml-cl-km", "K Clusters", "k", "3"); input_int("ml-cl-km", "Max Iter", "max_iter", "100");+ if (run_button("ml-cl-km")) {+ fire_post("ml-cl-km", "ml/clustering/kmeans", {+ {"X", json::array({json::array({1,2}), json::array({1.5,1.8}), json::array({5,8}), json::array({8,8}), json::array({1,0.6}), json::array({9,11})})},+ {"n_clusters", ep("ml-cl-km").geti("k", 3)}+ });+ }+ render_result("ml-cl-km");+ end_endpoint_card();+ }+ if (begin_endpoint_card("ml-cl-pca", "PCA", "Principal Component Analysis")) {+ input_int("ml-cl-pca", "N Components", "n", "2");+ if (run_button("ml-cl-pca")) {+ fire_post("ml-cl-pca", "ml/clustering/pca", {+ {"X", json::array({json::array({1,2,3}), json::array({4,5,6}), json::array({7,8,9})})},+ {"n_components", ep("ml-cl-pca").geti("n", 2)}+ });+ }+ render_result("ml-cl-pca");+ end_endpoint_card();+ }+}++void QuantLibScreen::render_ml_preprocessing() {+ if (begin_endpoint_card("ml-pp-scale", "Scale Data", "StandardScaler / MinMaxScaler / RobustScaler")) {+ input_select("ml-pp-scale", "Method", "method", {"standard", "minmax", "robust"});+ if (run_button("ml-pp-scale")) {+ fire_post("ml-pp-scale", "ml/preprocessing/scale", {+ {"X", json::array({json::array({1,200}), json::array({2,300}), json::array({3,400})})},+ {"method", ep("ml-pp-scale").get("method", "standard")}+ });+ }+ render_result("ml-pp-scale");+ end_endpoint_card();+ }+ if (begin_endpoint_card("ml-pp-stat", "Stationarity Test", "ADF/KPSS stationarity tests")) {+ input_array("ml-pp-stat", "Data", "data", "1,2,3,4,5,6,7,8,9,10");+ if (run_button("ml-pp-stat")) {+ fire_post("ml-pp-stat", "ml/preprocessing/stationarity", {+ {"data", json::array({1,2,3,4,5,6,7,8,9,10})}+ });+ }+ render_result("ml-pp-stat");+ end_endpoint_card();+ }+}++void QuantLibScreen::render_ml_features() {+ if (begin_endpoint_card("ml-ft-tech", "Technical Features", "Generate technical indicator features")) {+ input_select("ml-ft-tech", "Indicator", "indicator", {"sma", "ema", "rsi", "macd", "bbands"});+ input_int("ml-ft-tech", "Period", "period", "14");+ input_array("ml-ft-tech", "Prices", "prices", "100,101,102,100,99,101,103,105,104,106");+ if (run_button("ml-ft-tech")) {+ fire_post("ml-ft-tech", "ml/features/technical", {+ {"prices", json::array({100,101,102,100,99,101,103,105,104,106})},+ {"indicator", ep("ml-ft-tech").get("indicator", "sma")},+ {"period", ep("ml-ft-tech").geti("period", 14)}+ });+ }+ render_result("ml-ft-tech");+ end_endpoint_card();+ }+ if (begin_endpoint_card("ml-ft-roll", "Rolling Features", "Rolling window statistics")) {+ input_int("ml-ft-roll", "Window", "window", "5");+ input_select("ml-ft-roll", "Statistic", "stat", {"mean", "std", "skew", "kurt", "sharpe"});+ if (run_button("ml-ft-roll")) {+ fire_post("ml-ft-roll", "ml/features/rolling", {+ {"data", json::array({1,2,3,4,5,6,7,8,9,10})},+ {"window", ep("ml-ft-roll").geti("window", 5)},+ {"statistic", ep("ml-ft-roll").get("stat", "mean")}+ });+ }+ render_result("ml-ft-roll");+ end_endpoint_card();+ }+}++void QuantLibScreen::render_ml_validation() {+ if (begin_endpoint_card("ml-val-stab", "Stability (PSI)", "Population Stability Index")) {+ input_array("ml-val-stab", "Expected", "expected", "0.1,0.2,0.3,0.2,0.1,0.05,0.05");+ input_array("ml-val-stab", "Actual", "actual", "0.12,0.18,0.28,0.22,0.1,0.05,0.05");+ if (run_button("ml-val-stab")) {+ fire_post("ml-val-stab", "ml/validation/stability", {+ {"expected", json::array({0.1,0.2,0.3,0.2,0.1,0.05,0.05})},+ {"actual", json::array({0.12,0.18,0.28,0.22,0.1,0.05,0.05})}+ });+ }+ render_result("ml-val-stab");+ end_endpoint_card();+ }+}++void QuantLibScreen::render_ml_timeseries() {+ if (begin_endpoint_card("ml-ts-hmm", "HMM Regime Detection", "Hidden Markov Model for regime detection")) {+ input_array("ml-ts-hmm", "Returns", "returns", "0.01,-0.02,0.015,-0.01,0.02,-0.03,0.005");+ input_int("ml-ts-hmm", "N States", "states", "2");+ if (run_button("ml-ts-hmm")) {+ fire_post("ml-ts-hmm", "ml/hmm/fit", {+ {"returns", json::array({0.01,-0.02,0.015,-0.01,0.02,-0.03,0.005})},+ {"n_states", ep("ml-ts-hmm").geti("states", 2)}+ });+ }+ render_result("ml-ts-hmm");+ end_endpoint_card();+ }+}++void QuantLibScreen::render_ml_gpnn() {+ if (begin_endpoint_card("ml-gp-curve", "GP Yield Curve", "Gaussian Process yield curve fitting")) {+ input_array("ml-gp-curve", "Tenors", "tenors", "0.25,0.5,1,2,5,10,30");+ input_array("ml-gp-curve", "Rates", "rates", "0.04,0.041,0.043,0.045,0.047,0.048,0.049");+ input_array("ml-gp-curve", "Query", "query", "0.5,1.5,3,7,15,20");+ if (run_button("ml-gp-curve")) {+ fire_post("ml-gp-curve", "ml/gp/curve", {+ {"tenors", json::array({0.25,0.5,1,2,5,10,30})},+ {"rates", json::array({0.04,0.041,0.043,0.045,0.047,0.048,0.049})},+ {"query_tenors", json::array({0.5,1.5,3,7,15,20})}+ });+ }+ render_result("ml-gp-curve");+ end_endpoint_card();+ }+}++void QuantLibScreen::render_ml_factor() {+ if (begin_endpoint_card("ml-fac-stat", "Statistical Factor Model", "PCA-based factor decomposition")) {+ input_int("ml-fac-stat", "N Factors", "n", "3");+ if (run_button("ml-fac-stat")) {+ fire_post("ml-fac-stat", "ml/factor/statistical", {+ {"returns", json::array({json::array({0.01,0.02,-0.01}), json::array({0.015,-0.01,0.02}), json::array({-0.005,0.01,0.005})})},+ {"n_factors", ep("ml-fac-stat").geti("n", 3)}+ });+ }+ render_result("ml-fac-stat");+ end_endpoint_card();+ }+ if (begin_endpoint_card("ml-cov-est", "Covariance Estimation", "Shrinkage and factor covariance estimation")) {+ input_select("ml-cov-est", "Method", "method", {"sample", "ledoit_wolf", "oas", "factor"});+ if (run_button("ml-cov-est")) {+ fire_post("ml-cov-est", "ml/covariance/estimate", {+ {"returns", json::array({json::array({0.01,0.02}), json::array({0.015,-0.01}), json::array({-0.005,0.01})})},+ {"method", ep("ml-cov-est").get("method", "ledoit_wolf")}+ });+ }+ render_result("ml-cov-est");+ end_endpoint_card();+ }+}++// ============================================================================+// Statistics Panels+// ============================================================================++void QuantLibScreen::render_stat_continuous() {+ if (begin_endpoint_card("st-norm", "Normal Distribution", "Properties, PDF, CDF, PPF")) {+ input_float("st-norm", "Mu", "mu", "0"); input_float("st-norm", "Sigma", "sigma", "1");+ input_float("st-norm", "x", "x", "1.96");+ input_select("st-norm", "Function", "func", {"properties", "pdf", "cdf", "ppf"});+ if (run_button("st-norm")) {+ auto& s = ep("st-norm");+ std::string func = s.get("func", "properties");+ fire_post("st-norm", "statistics/distributions/normal/" + func, {+ {"mu", s.getd("mu")}, {"sigma", s.getd("sigma")}, {"x", s.getd("x")}+ });+ }+ render_result("st-norm");+ end_endpoint_card();+ }+ if (begin_endpoint_card("st-lognorm", "Lognormal", "Lognormal distribution")) {+ input_float("st-lognorm", "Mu", "mu", "0"); input_float("st-lognorm", "Sigma", "sigma", "0.5");+ input_float("st-lognorm", "x", "x", "2.0");+ if (run_button("st-lognorm")) {+ auto& s = ep("st-lognorm");+ fire_post("st-lognorm", "statistics/distributions/lognormal/properties", {+ {"mu", s.getd("mu")}, {"sigma", s.getd("sigma")}+ });+ }+ render_result("st-lognorm");+ end_endpoint_card();+ }+ if (begin_endpoint_card("st-t", "Student-t", "Student-t distribution")) {+ input_float("st-t", "df", "df", "5"); input_float("st-t", "x", "x", "2.0");+ if (run_button("st-t")) {+ fire_post("st-t", "statistics/distributions/student-t/properties", {{"df", ep("st-t").getd("df")}});+ }+ render_result("st-t");+ end_endpoint_card();+ }+}++void QuantLibScreen::render_stat_discrete() {+ if (begin_endpoint_card("st-binom", "Binomial", "Binomial distribution")) {+ input_int("st-binom", "n", "n", "10"); input_float("st-binom", "p", "p", "0.5");+ input_int("st-binom", "k", "k", "5");+ input_select("st-binom", "Function", "func", {"properties", "pmf", "cdf"});+ if (run_button("st-binom")) {+ auto& s = ep("st-binom");+ fire_post("st-binom", "statistics/distributions/binomial/" + s.get("func", "properties"), {+ {"n", s.geti("n")}, {"p", s.getd("p")}, {"k", s.geti("k")}+ });+ }+ render_result("st-binom");+ end_endpoint_card();+ }+ if (begin_endpoint_card("st-poisson", "Poisson", "Poisson distribution")) {+ input_float("st-poisson", "Lambda", "lam", "5.0"); input_int("st-poisson", "k", "k", "3");+ if (run_button("st-poisson")) {+ auto& s = ep("st-poisson");+ fire_post("st-poisson", "statistics/distributions/poisson/properties", {{"lam", s.getd("lam")}});+ }+ render_result("st-poisson");+ end_endpoint_card();+ }+}++void QuantLibScreen::render_stat_timeseries() {+ if (begin_endpoint_card("st-arima", "ARIMA Fit", "Fit ARIMA(p,d,q) model")) {+ input_int("st-arima", "p", "p", "1"); input_int("st-arima", "d", "d", "1"); input_int("st-arima", "q", "q", "1");+ input_array("st-arima", "Data", "data", "100,102,101,105,108,107,110,112");+ if (run_button("st-arima")) {+ auto& s = ep("st-arima");+ fire_post("st-arima", "statistics/timeseries/arima/fit", {+ {"data", json::array({100,102,101,105,108,107,110,112})},+ {"p", s.geti("p")}, {"d", s.geti("d")}, {"q", s.geti("q")}+ });+ }+ render_result("st-arima");+ end_endpoint_card();+ }+ if (begin_endpoint_card("st-garch", "GARCH Fit", "Fit GARCH(p,q) volatility model")) {+ input_int("st-garch", "p", "p", "1"); input_int("st-garch", "q", "q", "1");+ input_array("st-garch", "Returns", "returns", "0.01,-0.02,0.015,-0.01,0.02,-0.03,0.005,0.01");+ if (run_button("st-garch")) {+ fire_post("st-garch", "statistics/timeseries/garch/fit", {+ {"returns", json::array({0.01,-0.02,0.015,-0.01,0.02,-0.03,0.005,0.01})},+ {"p", ep("st-garch").geti("p")}, {"q", ep("st-garch").geti("q")}+ });+ }+ render_result("st-garch");+ end_endpoint_card();+ }+}++// ============================================================================+// Portfolio Panels+// ============================================================================++void QuantLibScreen::render_port_optimize() {+ if (begin_endpoint_card("pt-minsv", "Min Variance", "Minimum variance portfolio optimization")) {+ input_array("pt-minsv", "Expected Returns", "rets", "0.1,0.12,0.08");+ input_float("pt-minsv", "Risk-Free Rate", "rf", "0.03");+ if (run_button("pt-minsv")) {+ fire_post("pt-minsv", "portfolio/optimize/min-variance", {+ {"expected_returns", json::array({0.1,0.12,0.08})},+ {"covariance_matrix", json::array({json::array({0.04,0.006,0.002}), json::array({0.006,0.09,0.009}), json::array({0.002,0.009,0.01})})},+ {"rf_rate", ep("pt-minsv").getd("rf", 0.03)}+ });+ }+ render_result("pt-minsv");+ end_endpoint_card();+ }+ if (begin_endpoint_card("pt-maxsr", "Max Sharpe", "Maximum Sharpe ratio portfolio")) {+ input_float("pt-maxsr", "Risk-Free Rate", "rf", "0.03");+ if (run_button("pt-maxsr")) {+ fire_post("pt-maxsr", "portfolio/optimize/max-sharpe", {+ {"expected_returns", json::array({0.1,0.12,0.08})},+ {"covariance_matrix", json::array({json::array({0.04,0.006,0.002}), json::array({0.006,0.09,0.009}), json::array({0.002,0.009,0.01})})},+ {"rf_rate", ep("pt-maxsr").getd("rf", 0.03)}+ });+ }+ render_result("pt-maxsr");+ end_endpoint_card();+ }+}++void QuantLibScreen::render_port_risk() {+ if (begin_endpoint_card("pt-var", "Portfolio VaR", "Value at Risk computation")) {+ input_float("pt-var", "Confidence", "conf", "0.95");+ input_float("pt-var", "Portfolio Value", "pv", "1000000");+ input_select("pt-var", "Method", "method", {"parametric", "historical", "monte_carlo"});+ if (run_button("pt-var")) {+ auto& s = ep("pt-var");+ fire_post("pt-var", "portfolio/risk/var", {+ {"weights", json::array({0.4,0.35,0.25})},+ {"covariance_matrix", json::array({json::array({0.04,0.006,0.002}), json::array({0.006,0.09,0.009}), json::array({0.002,0.009,0.01})})},+ {"confidence", s.getd("conf")}, {"portfolio_value", s.getd("pv")}, {"method", s.get("method")}+ });+ }+ render_result("pt-var");+ end_endpoint_card();+ }+ if (begin_endpoint_card("pt-ratios", "Performance Ratios", "Sharpe, Sortino, Calmar, Information ratio")) {+ input_float("pt-ratios", "Risk-Free Rate", "rf", "0.03");+ if (run_button("pt-ratios")) {+ fire_post("pt-ratios", "portfolio/risk/ratios", {+ {"returns", json::array({0.01,-0.02,0.015,-0.01,0.02,-0.03,0.005,0.01,0.008,-0.005})},+ {"rf_rate", ep("pt-ratios").getd("rf", 0.03)}+ });+ }+ render_result("pt-ratios");+ end_endpoint_card();+ }+}++// ============================================================================+// Scheduling Panels+// ============================================================================++void QuantLibScreen::render_sched_calendar() {+ if (begin_endpoint_card("sc-isbd", "Is Business Day", "Check if date is a business day")) {+ input_text("sc-isbd", "Date", "date", "2024-12-25");+ input_select("sc-isbd", "Calendar", "calendar", {"us", "uk", "de", "jp", "cn", "in"});+ if (run_button("sc-isbd")) {+ auto& s = ep("sc-isbd");+ fire_post("sc-isbd", "scheduling/calendar/is-business-day", {{"date", s.get("date")}, {"calendar", s.get("calendar")}});+ }+ render_result("sc-isbd");+ end_endpoint_card();+ }+ if (begin_endpoint_card("sc-addbd", "Add Business Days", "Add N business days to a date")) {+ input_text("sc-addbd", "Date", "date", "2024-01-15");+ input_int("sc-addbd", "Days", "days", "10");+ input_select("sc-addbd", "Calendar", "calendar", {"us", "uk", "de", "jp"});+ if (run_button("sc-addbd")) {+ auto& s = ep("sc-addbd");+ fire_post("sc-addbd", "scheduling/calendar/add-business-days", {+ {"date", s.get("date")}, {"days", s.geti("days")}, {"calendar", s.get("calendar")}+ });+ }+ render_result("sc-addbd");+ end_endpoint_card();+ }+}++void QuantLibScreen::render_sched_daycount() {+ if (begin_endpoint_card("sc-yf", "Year Fraction", "Compute year fraction between dates")) {+ input_text("sc-yf", "Start Date", "start", "2024-01-15");+ input_text("sc-yf", "End Date", "end", "2024-07-15");+ input_select("sc-yf", "Convention", "conv", {"act/360", "act/365", "30/360", "act/act"});+ if (run_button("sc-yf")) {+ auto& s = ep("sc-yf");+ fire_post("sc-yf", "scheduling/daycount/year-fraction", {+ {"start_date", s.get("start")}, {"end_date", s.get("end")}, {"convention", s.get("conv")}+ });+ }+ render_result("sc-yf");+ end_endpoint_card();+ }+ if (begin_endpoint_card("sc-dc", "Day Count", "Count days between dates")) {+ input_text("sc-dc", "Start Date", "start", "2024-01-15");+ input_text("sc-dc", "End Date", "end", "2024-07-15");+ if (run_button("sc-dc")) {+ auto& s = ep("sc-dc");+ fire_post("sc-dc", "scheduling/daycount/day-count", {{"start_date", s.get("start")}, {"end_date", s.get("end")}});+ }+ render_result("sc-dc");+ end_endpoint_card();+ }+}++// ============================================================================+// Physics Panels+// ============================================================================++void QuantLibScreen::render_phys_entropy() {+ if (begin_endpoint_card("ph-ent", "Shannon Entropy", "Information entropy of a distribution")) {+ input_array("ph-ent", "Probabilities", "probs", "0.25,0.25,0.25,0.25");+ if (run_button("ph-ent")) {+ fire_post("ph-ent", "physics/entropy/shannon", {{"probabilities", json::array({0.25,0.25,0.25,0.25})}});+ }+ render_result("ph-ent");+ end_endpoint_card();+ }+ if (begin_endpoint_card("ph-kl", "KL Divergence", "Kullback-Leibler divergence")) {+ input_array("ph-kl", "P", "p", "0.3,0.4,0.3"); input_array("ph-kl", "Q", "q", "0.33,0.34,0.33");+ if (run_button("ph-kl")) {+ fire_post("ph-kl", "physics/entropy/kl-divergence", {+ {"p", json::array({0.3,0.4,0.3})}, {"q", json::array({0.33,0.34,0.33})}+ });+ }+ render_result("ph-kl");+ end_endpoint_card();+ }+}++void QuantLibScreen::render_phys_thermo() {+ if (begin_endpoint_card("ph-boltz", "Boltzmann Distribution", "Boltzmann energy distribution")) {+ input_array("ph-boltz", "Energy Levels", "energies", "0,1,2,3,4");+ input_float("ph-boltz", "Temperature", "temp", "300");+ if (run_button("ph-boltz")) {+ fire_post("ph-boltz", "physics/thermo/boltzmann", {+ {"energy_levels", json::array({0,1,2,3,4})}, {"temperature", ep("ph-boltz").getd("temp")}+ });+ }+ render_result("ph-boltz");+ end_endpoint_card();+ }+}++// ============================================================================+// Curves Panels+// ============================================================================++void QuantLibScreen::render_curves_build() {+ if (begin_endpoint_card("cv-build", "Build Curve", "Construct yield curve from market data")) {+ input_array("cv-build", "Tenors", "tenors", "0.25,0.5,1,2,5,10,30");+ input_array("cv-build", "Rates", "rates", "0.04,0.041,0.043,0.045,0.047,0.048,0.049");+ input_select("cv-build", "Method", "method", {"linear", "cubic_spline", "monotone_cubic"});+ if (run_button("cv-build")) {+ fire_post("cv-build", "curves/build", {+ {"tenors", json::array({0.25,0.5,1,2,5,10,30})},+ {"rates", json::array({0.04,0.041,0.043,0.045,0.047,0.048,0.049})},+ {"method", ep("cv-build").get("method", "cubic_spline")}+ });+ }+ render_result("cv-build");+ end_endpoint_card();+ }+}++void QuantLibScreen::render_curves_transform() {+ if (begin_endpoint_card("cv-fwd", "Forward Rates", "Extract forward rates from yield curve")) {+ input_array("cv-fwd", "Tenors", "tenors", "0.25,0.5,1,2,5,10");+ input_array("cv-fwd", "Rates", "rates", "0.04,0.041,0.043,0.045,0.047,0.048");+ if (run_button("cv-fwd")) {+ fire_post("cv-fwd", "curves/forward-rates", {+ {"tenors", json::array({0.25,0.5,1,2,5,10})},+ {"rates", json::array({0.04,0.041,0.043,0.045,0.047,0.048})}+ });+ }+ render_result("cv-fwd");+ end_endpoint_card();+ }+}++void QuantLibScreen::render_curves_fitting() {+ if (begin_endpoint_card("cv-ns", "Nelson-Siegel Fit", "Fit NS/NSS parametric model to yields")) {+ input_array("cv-ns", "Tenors", "tenors", "0.25,0.5,1,2,5,10,30");+ input_array("cv-ns", "Rates", "rates", "0.04,0.041,0.043,0.045,0.047,0.048,0.049");+ input_select("cv-ns", "Model", "model", {"nelson_siegel", "svensson"});+ if (run_button("cv-ns")) {+ fire_post("cv-ns", "curves/fitting/nelson-siegel", {+ {"tenors", json::array({0.25,0.5,1,2,5,10,30})},+ {"rates", json::array({0.04,0.041,0.043,0.045,0.047,0.048,0.049})},+ {"model", ep("cv-ns").get("model", "nelson_siegel")}+ });+ }+ render_result("cv-ns");+ end_endpoint_card();+ }+}++void QuantLibScreen::render_curves_specialized() {+ if (begin_endpoint_card("cv-disc", "Discount Factors", "Compute discount factors from yield curve")) {+ input_array("cv-disc", "Tenors", "tenors", "0.25,0.5,1,2,5,10");+ input_array("cv-disc", "Rates", "rates", "0.04,0.041,0.043,0.045,0.047,0.048");+ if (run_button("cv-disc")) {+ fire_post("cv-disc", "curves/discount-factors", {+ {"tenors", json::array({0.25,0.5,1,2,5,10})},+ {"rates", json::array({0.04,0.041,0.043,0.045,0.047,0.048})}+ });+ }+ render_result("cv-disc");+ end_endpoint_card();+ }+}++// ============================================================================+// Pricing Panels+// ============================================================================++void QuantLibScreen::render_pricing_bs() {+ if (begin_endpoint_card("pr-bs", "Black-Scholes", "European option pricing")) {+ input_float("pr-bs", "Spot", "S", "100"); input_float("pr-bs", "Strike", "K", "100");+ input_float("pr-bs", "T", "T", "1.0"); input_float("pr-bs", "r", "r", "0.05");+ input_float("pr-bs", "Sigma", "sigma", "0.2"); input_float("pr-bs", "q", "q", "0");+ input_select("pr-bs", "Type", "type", {"call", "put"});+ if (run_button("pr-bs")) {+ auto& s = ep("pr-bs");+ fire_post("pr-bs", "pricing/black-scholes/price", {+ {"S", s.getd("S")}, {"K", s.getd("K")}, {"T", s.getd("T")}, {"r", s.getd("r")},+ {"sigma", s.getd("sigma")}, {"q", s.getd("q")}, {"option_type", s.get("type", "call")}+ });+ }+ render_result("pr-bs");+ end_endpoint_card();+ }+ if (begin_endpoint_card("pr-bs-greeks", "BS Greeks", "Option sensitivities")) {+ input_float("pr-bs-greeks", "S", "S", "100"); input_float("pr-bs-greeks", "K", "K", "100");+ input_float("pr-bs-greeks", "T", "T", "1.0"); input_float("pr-bs-greeks", "r", "r", "0.05");+ input_float("pr-bs-greeks", "Sigma", "sigma", "0.2");+ if (run_button("pr-bs-greeks")) {+ auto& s = ep("pr-bs-greeks");+ fire_post("pr-bs-greeks", "pricing/black-scholes/greeks", {+ {"S", s.getd("S")}, {"K", s.getd("K")}, {"T", s.getd("T")},+ {"r", s.getd("r")}, {"sigma", s.getd("sigma")}+ });+ }+ render_result("pr-bs-greeks");+ end_endpoint_card();+ }+}++void QuantLibScreen::render_pricing_black76() {+ if (begin_endpoint_card("pr-b76", "Black76 Price", "Futures/forward option pricing")) {+ input_float("pr-b76", "Forward", "F", "100"); input_float("pr-b76", "Strike", "K", "100");+ input_float("pr-b76", "T", "T", "1.0"); input_float("pr-b76", "r", "r", "0.05");+ input_float("pr-b76", "Sigma", "sigma", "0.2");+ input_select("pr-b76", "Type", "type", {"call", "put"});+ if (run_button("pr-b76")) {+ auto& s = ep("pr-b76");+ fire_post("pr-b76", "pricing/black76/price", {+ {"F", s.getd("F")}, {"K", s.getd("K")}, {"T", s.getd("T")},+ {"r", s.getd("r")}, {"sigma", s.getd("sigma")}, {"option_type", s.get("type")}+ });+ }+ render_result("pr-b76");+ end_endpoint_card();+ }+}++void QuantLibScreen::render_pricing_bachelier() {+ if (begin_endpoint_card("pr-bach", "Bachelier Price", "Normal model option pricing")) {+ input_float("pr-bach", "Forward", "F", "100"); input_float("pr-bach", "Strike", "K", "100");+ input_float("pr-bach", "T", "T", "1.0"); input_float("pr-bach", "r", "r", "0.05");+ input_float("pr-bach", "Sigma (normal)", "sigma", "20");+ input_select("pr-bach", "Type", "type", {"call", "put"});+ if (run_button("pr-bach")) {+ auto& s = ep("pr-bach");+ fire_post("pr-bach", "pricing/bachelier/price", {+ {"F", s.getd("F")}, {"K", s.getd("K")}, {"T", s.getd("T")},+ {"r", s.getd("r")}, {"sigma", s.getd("sigma")}, {"option_type", s.get("type")}+ });+ }+ render_result("pr-bach");+ end_endpoint_card();+ }+}++void QuantLibScreen::render_pricing_numerical() {+ if (begin_endpoint_card("pr-binom", "Binomial Tree", "CRR binomial tree option pricing")) {+ input_float("pr-binom", "S", "S", "100"); input_float("pr-binom", "K", "K", "100");+ input_float("pr-binom", "T", "T", "1.0"); input_float("pr-binom", "r", "r", "0.05");+ input_float("pr-binom", "Sigma", "sigma", "0.2"); input_int("pr-binom", "Steps", "steps", "100");+ input_select("pr-binom", "Type", "type", {"call", "put"});+ input_select("pr-binom", "Style", "style", {"european", "american"});+ if (run_button("pr-binom")) {+ auto& s = ep("pr-binom");+ fire_post("pr-binom", "pricing/numerical/binomial", {+ {"S", s.getd("S")}, {"K", s.getd("K")}, {"T", s.getd("T")}, {"r", s.getd("r")},+ {"sigma", s.getd("sigma")}, {"n_steps", s.geti("steps")},+ {"option_type", s.get("type")}, {"style", s.get("style")}+ });+ }+ render_result("pr-binom");+ end_endpoint_card();+ }+}++// ============================================================================+// Risk Panels+// ============================================================================++void QuantLibScreen::render_risk_var() {+ if (begin_endpoint_card("rk-var", "Value at Risk", "Parametric/Historical/MC VaR")) {+ input_array("rk-var", "Returns", "returns", "0.01,-0.02,0.015,-0.01,0.02,-0.03,0.005,0.01");+ input_float("rk-var", "Confidence", "conf", "0.95");+ input_select("rk-var", "Method", "method", {"parametric", "historical", "cornish_fisher"});+ if (run_button("rk-var")) {+ fire_post("rk-var", "risk/var", {+ {"returns", json::array({0.01,-0.02,0.015,-0.01,0.02,-0.03,0.005,0.01})},+ {"confidence", ep("rk-var").getd("conf")}, {"method", ep("rk-var").get("method")}+ });+ }+ render_result("rk-var");+ end_endpoint_card();+ }+}++void QuantLibScreen::render_risk_evt_xva() {+ if (begin_endpoint_card("rk-evt", "EVT Tail Risk", "Extreme Value Theory tail estimation")) {+ input_array("rk-evt", "Losses", "losses", "0.01,0.02,0.03,0.05,0.08,0.12,0.15");+ input_float("rk-evt", "Threshold", "threshold", "0.05");+ if (run_button("rk-evt")) {+ fire_post("rk-evt", "risk/evt/fit", {+ {"losses", json::array({0.01,0.02,0.03,0.05,0.08,0.12,0.15})},+ {"threshold", ep("rk-evt").getd("threshold")}+ });+ }+ render_result("rk-evt");+ end_endpoint_card();+ }+}++void QuantLibScreen::render_risk_sensitivities() {+ if (begin_endpoint_card("rk-sens", "Greeks / Sensitivities", "Compute option sensitivities")) {+ input_float("rk-sens", "S", "S", "100"); input_float("rk-sens", "K", "K", "100");+ input_float("rk-sens", "T", "T", "1.0"); input_float("rk-sens", "r", "r", "0.05");+ input_float("rk-sens", "Sigma", "sigma", "0.2");+ if (run_button("rk-sens")) {+ auto& s = ep("rk-sens");+ fire_post("rk-sens", "risk/sensitivities", {+ {"S", s.getd("S")}, {"K", s.getd("K")}, {"T", s.getd("T")},+ {"r", s.getd("r")}, {"sigma", s.getd("sigma")}+ });+ }+ render_result("rk-sens");+ end_endpoint_card();+ }+}++// ============================================================================+// Economics Panels+// ============================================================================++void QuantLibScreen::render_econ_equilibrium() {+ if (begin_endpoint_card("ec-eq", "Market Equilibrium", "Supply-demand equilibrium solver")) {+ input_float("ec-eq", "Supply Slope", "s_slope", "1.0");+ input_float("ec-eq", "Supply Intercept", "s_int", "0");+ input_float("ec-eq", "Demand Slope", "d_slope", "-1.0");+ input_float("ec-eq", "Demand Intercept", "d_int", "100");+ if (run_button("ec-eq")) {+ auto& s = ep("ec-eq");+ fire_post("ec-eq", "economics/equilibrium", {+ {"supply_slope", s.getd("s_slope")}, {"supply_intercept", s.getd("s_int")},+ {"demand_slope", s.getd("d_slope")}, {"demand_intercept", s.getd("d_int")}+ });+ }+ render_result("ec-eq");+ end_endpoint_card();+ }+}++void QuantLibScreen::render_econ_gametheory() {+ if (begin_endpoint_card("ec-nash", "Nash Equilibrium", "Find Nash equilibria in 2-player games")) {+ input_array("ec-nash", "Payoff Matrix (flat)", "payoffs", "3,0,5,1,1,5,0,3");+ if (run_button("ec-nash")) {+ fire_post("ec-nash", "economics/game-theory/nash", {+ {"payoff_matrix", json::array({json::array({3,0}), json::array({5,1}), json::array({1,5}), json::array({0,3})})}+ });+ }+ render_result("ec-nash");+ end_endpoint_card();+ }+}++void QuantLibScreen::render_econ_auctions() {+ if (begin_endpoint_card("ec-auc", "Auction Simulation", "First/Second price auction analysis")) {+ input_select("ec-auc", "Type", "type", {"first_price", "second_price", "english", "dutch"});+ input_array("ec-auc", "Bids", "bids", "10,15,12,8,20");+ if (run_button("ec-auc")) {+ fire_post("ec-auc", "economics/auctions/simulate", {+ {"auction_type", ep("ec-auc").get("type")},+ {"bids", json::array({10,15,12,8,20})}+ });+ }+ render_result("ec-auc");+ end_endpoint_card();+ }+}++void QuantLibScreen::render_econ_utility() {+ if (begin_endpoint_card("ec-util", "Utility Function", "CRRA/CARA utility computation")) {+ input_select("ec-util", "Type", "type", {"crra", "cara", "log"});+ input_float("ec-util", "Wealth", "wealth", "1000000");+ input_float("ec-util", "Risk Aversion", "gamma", "2.0");+ if (run_button("ec-util")) {+ auto& s = ep("ec-util");+ fire_post("ec-util", "economics/utility", {+ {"utility_type", s.get("type")}, {"wealth", s.getd("wealth")}, {"gamma", s.getd("gamma")}+ });+ }+ render_result("ec-util");+ end_endpoint_card();+ }+}++// ============================================================================+// Solver Panels+// ============================================================================++void QuantLibScreen::render_solver_bond() {+ if (begin_endpoint_card("sv-bond-ytm", "Bond YTM", "Calculate yield to maturity")) {+ input_float("sv-bond-ytm", "Face Value", "face", "1000");+ input_float("sv-bond-ytm", "Price", "price", "980");+ input_float("sv-bond-ytm", "Coupon Rate", "coupon", "0.05");+ input_float("sv-bond-ytm", "Maturity (years)", "maturity", "10");+ input_int("sv-bond-ytm", "Frequency", "freq", "2");+ if (run_button("sv-bond-ytm")) {+ auto& s = ep("sv-bond-ytm");+ fire_post("sv-bond-ytm", "solver/bond/ytm", {+ {"face_value", s.getd("face")}, {"price", s.getd("price")},+ {"coupon_rate", s.getd("coupon")}, {"maturity", s.getd("maturity")},+ {"frequency", s.geti("freq")}+ });+ }+ render_result("sv-bond-ytm");+ end_endpoint_card();+ }+ if (begin_endpoint_card("sv-bond-dur", "Bond Duration", "Macaulay and modified duration")) {+ input_float("sv-bond-dur", "Face Value", "face", "1000");+ input_float("sv-bond-dur", "Coupon Rate", "coupon", "0.05");+ input_float("sv-bond-dur", "YTM", "ytm", "0.06");+ input_float("sv-bond-dur", "Maturity", "maturity", "10");+ if (run_button("sv-bond-dur")) {+ auto& s = ep("sv-bond-dur");+ fire_post("sv-bond-dur", "solver/bond/duration", {+ {"face_value", s.getd("face")}, {"coupon_rate", s.getd("coupon")},+ {"ytm", s.getd("ytm")}, {"maturity", s.getd("maturity")}+ });+ }+ render_result("sv-bond-dur");+ end_endpoint_card();+ }+}++void QuantLibScreen::render_solver_rates() {+ if (begin_endpoint_card("sv-iv", "Implied Volatility", "Solve for BS implied vol from market price")) {+ input_float("sv-iv", "Market Price", "price", "10.5"); input_float("sv-iv", "S", "S", "100");+ input_float("sv-iv", "K", "K", "100"); input_float("sv-iv", "T", "T", "1.0");+ input_float("sv-iv", "r", "r", "0.05");+ input_select("sv-iv", "Type", "type", {"call", "put"});+ if (run_button("sv-iv")) {+ auto& s = ep("sv-iv");+ fire_post("sv-iv", "solver/implied-volatility", {+ {"market_price", s.getd("price")}, {"S", s.getd("S")}, {"K", s.getd("K")},+ {"T", s.getd("T")}, {"r", s.getd("r")}, {"option_type", s.get("type")}+ });+ }+ render_result("sv-iv");+ end_endpoint_card();+ }+}++void QuantLibScreen::render_solver_cashflow() {+ if (begin_endpoint_card("sv-irr", "IRR / NPV", "Internal rate of return and net present value")) {+ input_array("sv-irr", "Cash Flows", "cf", "-1000,200,300,400,500");+ input_float("sv-irr", "Discount Rate", "rate", "0.10");+ if (run_button("sv-irr")) {+ fire_post("sv-irr", "solver/cashflow/irr", {+ {"cashflows", json::array({-1000,200,300,400,500})},+ {"discount_rate", ep("sv-irr").getd("rate")}+ });+ }+ render_result("sv-irr");+ end_endpoint_card();+ }+}++// ============================================================================+// Numerical Panels+// ============================================================================++void QuantLibScreen::render_num_difffft() {+ if (begin_endpoint_card("nm-fft", "FFT", "Fast Fourier Transform")) {+ input_array("nm-fft", "Signal", "signal", "1,0,1,0,1,0,1,0");+ if (run_button("nm-fft")) {+ fire_post("nm-fft", "numerical/fft", {{"signal", json::array({1,0,1,0,1,0,1,0})}});+ }+ render_result("nm-fft");+ end_endpoint_card();+ }+ if (begin_endpoint_card("nm-integ", "Numerical Integration", "Trapezoidal/Simpson integration")) {+ input_text("nm-integ", "Function", "func", "x^2"); input_float("nm-integ", "a", "a", "0");+ input_float("nm-integ", "b", "b", "1"); input_int("nm-integ", "N", "n", "100");+ if (run_button("nm-integ")) {+ auto& s = ep("nm-integ");+ fire_post("nm-integ", "numerical/integrate", {+ {"function", s.get("func")}, {"a", s.getd("a")}, {"b", s.getd("b")}, {"n", s.geti("n")}+ });+ }+ render_result("nm-integ");+ end_endpoint_card();+ }+}++void QuantLibScreen::render_num_interplinalg() {+ if (begin_endpoint_card("nm-interp", "Interpolation", "1D interpolation (linear, cubic, etc.)")) {+ input_array("nm-interp", "X", "x", "0,1,2,3,4");+ input_array("nm-interp", "Y", "y", "0,1,4,9,16");+ input_float("nm-interp", "Query", "query", "2.5");+ input_select("nm-interp", "Method", "method", {"linear", "cubic", "akima"});+ if (run_button("nm-interp")) {+ fire_post("nm-interp", "numerical/interpolate", {+ {"x", json::array({0,1,2,3,4})}, {"y", json::array({0,1,4,9,16})},+ {"query", ep("nm-interp").getd("query")}, {"method", ep("nm-interp").get("method")}+ });+ }+ render_result("nm-interp");+ end_endpoint_card();+ }+}++void QuantLibScreen::render_num_solvers() {+ if (begin_endpoint_card("nm-root", "Root Finding", "Bisection/Newton/Brent root finder")) {+ input_text("nm-root", "Function", "func", "x^2 - 2");+ input_float("nm-root", "a", "a", "0"); input_float("nm-root", "b", "b", "2");+ input_select("nm-root", "Method", "method", {"bisection", "newton", "brent"});+ if (run_button("nm-root")) {+ auto& s = ep("nm-root");+ fire_post("nm-root", "numerical/root-find", {+ {"function", s.get("func")}, {"a", s.getd("a")}, {"b", s.getd("b")}, {"method", s.get("method")}+ });+ }+ render_result("nm-root");+ end_endpoint_card();+ }+}++// ============================================================================+// Instruments Panels+// ============================================================================++void QuantLibScreen::render_instr_bonds() {+ if (begin_endpoint_card("in-bond", "Bond Pricing", "Price a fixed-rate bond")) {+ input_float("in-bond", "Face Value", "face", "1000"); input_float("in-bond", "Coupon", "coupon", "0.05");+ input_float("in-bond", "YTM", "ytm", "0.06"); input_float("in-bond", "Maturity", "mat", "10");+ input_int("in-bond", "Frequency", "freq", "2");+ if (run_button("in-bond")) {+ auto& s = ep("in-bond");+ fire_post("in-bond", "instruments/bond/price", {+ {"face_value", s.getd("face")}, {"coupon_rate", s.getd("coupon")},+ {"ytm", s.getd("ytm")}, {"maturity", s.getd("mat")}, {"frequency", s.geti("freq")}+ });+ }+ render_result("in-bond");+ end_endpoint_card();+ }+}++void QuantLibScreen::render_instr_swaps() {+ if (begin_endpoint_card("in-irs", "Interest Rate Swap", "IRS NPV and DV01")) {+ input_float("in-irs", "Notional", "notional", "10000000");+ input_float("in-irs", "Fixed Rate", "fixed_rate", "0.05");+ input_float("in-irs", "Float Spread", "spread", "0.001");+ input_float("in-irs", "Maturity", "maturity", "5");+ if (run_button("in-irs")) {+ auto& s = ep("in-irs");+ fire_post("in-irs", "instruments/swap/irs", {+ {"notional", s.getd("notional")}, {"fixed_rate", s.getd("fixed_rate")},+ {"float_spread", s.getd("spread")}, {"maturity", s.getd("maturity")}+ });+ }+ render_result("in-irs");+ end_endpoint_card();+ }+}++void QuantLibScreen::render_instr_markets() {+ if (begin_endpoint_card("in-fwd", "Forward Contract", "Forward/futures pricing")) {+ input_float("in-fwd", "Spot", "spot", "100"); input_float("in-fwd", "r", "r", "0.05");+ input_float("in-fwd", "q", "q", "0.02"); input_float("in-fwd", "T", "T", "1.0");+ if (run_button("in-fwd")) {+ auto& s = ep("in-fwd");+ fire_post("in-fwd", "instruments/forward/price", {+ {"spot", s.getd("spot")}, {"r", s.getd("r")}, {"q", s.getd("q")}, {"T", s.getd("T")}+ });+ }+ render_result("in-fwd");+ end_endpoint_card();+ }+}++void QuantLibScreen::render_instr_creditfut() {+ if (begin_endpoint_card("in-cds", "CDS Spread", "Credit default swap spread calculation")) {+ input_float("in-cds", "Notional", "notional", "10000000");+ input_float("in-cds", "Recovery", "recovery", "0.4");+ input_float("in-cds", "PD", "pd", "0.02");+ input_float("in-cds", "Maturity", "maturity", "5");+ if (run_button("in-cds")) {+ auto& s = ep("in-cds");+ fire_post("in-cds", "instruments/cds/spread", {+ {"notional", s.getd("notional")}, {"recovery_rate", s.getd("recovery")},+ {"default_probability", s.getd("pd")}, {"maturity", s.getd("maturity")}+ });+ }+ render_result("in-cds");+ end_endpoint_card();+ }+}++// ============================================================================+// Analysis Panels+// ============================================================================++void QuantLibScreen::render_analysis_fundamentals() {+ if (begin_endpoint_card("an-fund", "Financial Ratios", "Compute key financial ratios from statements")) {+ input_text("an-fund", "Symbol", "symbol", "AAPL");+ if (run_button("an-fund")) {+ fire_post("an-fund", "analysis/fundamentals/ratios", {{"symbol", ep("an-fund").get("symbol")}});+ }+ render_result("an-fund");+ end_endpoint_card();+ }+}++void QuantLibScreen::render_analysis_profit_liq() {+ if (begin_endpoint_card("an-prof", "Profitability & Liquidity", "ROE, ROA, current ratio, quick ratio")) {+ input_text("an-prof", "Symbol", "symbol", "MSFT");+ if (run_button("an-prof")) {+ fire_post("an-prof", "analysis/profitability-liquidity", {{"symbol", ep("an-prof").get("symbol")}});+ }+ render_result("an-prof");+ end_endpoint_card();+ }+}++void QuantLibScreen::render_analysis_eff_growth() {+ if (begin_endpoint_card("an-eff", "Efficiency & Growth", "Asset turnover, revenue growth, earnings growth")) {+ input_text("an-eff", "Symbol", "symbol", "GOOGL");+ if (run_button("an-eff")) {+ fire_post("an-eff", "analysis/efficiency-growth", {{"symbol", ep("an-eff").get("symbol")}});+ }+ render_result("an-eff");+ end_endpoint_card();+ }+}++void QuantLibScreen::render_analysis_lev_cf() {+ if (begin_endpoint_card("an-lev", "Leverage & Cash Flow", "Debt ratios, FCF, coverage")) {+ input_text("an-lev", "Symbol", "symbol", "AMZN");+ if (run_button("an-lev")) {+ fire_post("an-lev", "analysis/leverage-cashflow", {{"symbol", ep("an-lev").get("symbol")}});+ }+ render_result("an-lev");+ end_endpoint_card();+ }+}++void QuantLibScreen::render_analysis_val_qual() {+ if (begin_endpoint_card("an-val", "Valuation Ratios", "P/E, P/B, EV/EBITDA, PEG")) {+ input_text("an-val", "Symbol", "symbol", "NVDA");+ if (run_button("an-val")) {+ fire_post("an-val", "analysis/valuation-quality", {{"symbol", ep("an-val").get("symbol")}});+ }+ render_result("an-val");+ end_endpoint_card();+ }+}++void QuantLibScreen::render_analysis_industry() {+ if (begin_endpoint_card("an-ind", "Industry Comparison", "Compare metrics across sector peers")) {+ input_text("an-ind", "Symbol", "symbol", "TSLA");+ if (run_button("an-ind")) {+ fire_post("an-ind", "analysis/industry", {{"symbol", ep("an-ind").get("symbol")}});+ }+ render_result("an-ind");+ end_endpoint_card();+ }+}++void QuantLibScreen::render_analysis_dcf() {+ if (begin_endpoint_card("an-dcf", "DCF Valuation", "Discounted cash flow intrinsic value")) {+ input_text("an-dcf", "Symbol", "symbol", "AAPL");+ input_float("an-dcf", "WACC", "wacc", "0.10");+ input_float("an-dcf", "Terminal Growth", "tg", "0.025");+ input_int("an-dcf", "Forecast Years", "years", "5");+ if (run_button("an-dcf")) {+ auto& s = ep("an-dcf");+ fire_post("an-dcf", "analysis/dcf", {+ {"symbol", s.get("symbol")}, {"wacc", s.getd("wacc")},+ {"terminal_growth", s.getd("tg")}, {"forecast_years", s.geti("years")}+ });+ }+ render_result("an-dcf");+ end_endpoint_card();+ }+}++void QuantLibScreen::render_analysis_models() {+ if (begin_endpoint_card("an-ddm", "Dividend Discount Model", "DDM / Gordon growth model valuation")) {+ input_float("an-ddm", "Dividend", "div", "3.0");+ input_float("an-ddm", "Required Return", "r", "0.10");+ input_float("an-ddm", "Growth Rate", "g", "0.05");+ if (run_button("an-ddm")) {+ auto& s = ep("an-ddm");+ fire_post("an-ddm", "analysis/valuation-models/ddm", {+ {"dividend", s.getd("div")}, {"required_return", s.getd("r")}, {"growth_rate", s.getd("g")}+ });+ }+ render_result("an-ddm");+ end_endpoint_card();+ }+}} // namespace fincept::quantlibdiff --git a/fincept-cpp/src/screens/settings/sections/storage_cache_section.cpp b/fincept-cpp/src/screens/settings/sections/storage_cache_section.cppindex 72cfb13b4..cfacd0f6f 100644--- a/fincept-cpp/src/screens/settings/sections/storage_cache_section.cpp+++ b/fincept-cpp/src/screens/settings/sections/storage_cache_section.cpp@@ -1,5 +1,6 @@#include "storage_cache_section.h"#include "storage/database.h"+#include "storage/cache_service.h"#include "ui/theme.h"#include <imgui.h>#include <cstring>@@ -14,10 +15,15 @@ void StorageCacheSection::init() {}void StorageCacheSection::refresh_cache_stats() {- auto stats = db::ops::cache_stats();+ auto& svc = fincept::CacheService::instance();+ auto stats = svc.get_stats();cache_entries_ = stats.total_entries;cache_size_ = stats.total_size_bytes;cache_expired_ = stats.expired_entries;+ category_stats_.clear();+ for (auto& cat : stats.categories) {+ category_stats_.push_back({cat.name, cat.entry_count, cat.total_size});+ }}void StorageCacheSection::load_table_list() {@@ -156,7 +162,7 @@ void StorageCacheSection::render_cache_panel() {ImGui::PushStyleColor(ImGuiCol_ButtonHovered, ERROR_RED);ImGui::PushStyleColor(ImGuiCol_Text, TEXT_PRIMARY);if (ImGui::Button("Clear All Cache")) {- db::ops::cache_clear_all();+ fincept::CacheService::instance().clear_all();refresh_cache_stats();status_ = "Cache cleared";status_time_ = ImGui::GetTime();@@ -165,13 +171,43 @@ void StorageCacheSection::render_cache_panel() {ImGui::SameLine();if (theme::SecondaryButton("Cleanup Expired")) {- int64_t removed = db::ops::cache_cleanup();+ int64_t removed = fincept::CacheService::instance().cleanup();refresh_cache_stats();char buf[64];std::snprintf(buf, sizeof(buf), "Removed %lld expired entries", (long long)removed);status_ = buf;status_time_ = ImGui::GetTime();}++ // Per-category breakdown+ if (!category_stats_.empty()) {+ ImGui::Spacing();+ theme::SectionHeader("CACHE CATEGORIES");++ if (ImGui::BeginTable("##cache_categories", 3, ImGuiTableFlags_Borders | ImGuiTableFlags_RowBg)) {+ ImGui::TableSetupColumn("Category");+ ImGui::TableSetupColumn("Entries");+ ImGui::TableSetupColumn("Size");+ ImGui::TableHeadersRow();++ for (auto& cat : category_stats_) {+ ImGui::TableNextRow();+ ImGui::TableNextColumn();+ ImGui::TextColored(ACCENT, "%s", cat.name.c_str());+ ImGui::TableNextColumn();+ ImGui::TextColored(TEXT_PRIMARY, "%lld", (long long)cat.count);+ ImGui::TableNextColumn();+ // Human readable size+ if (cat.size > 1024 * 1024)+ ImGui::TextColored(TEXT_PRIMARY, "%.1f MB", (double)cat.size / (1024.0 * 1024.0));+ else if (cat.size > 1024)+ ImGui::TextColored(TEXT_PRIMARY, "%.1f KB", (double)cat.size / 1024.0);+ else+ ImGui::TextColored(TEXT_PRIMARY, "%lld B", (long long)cat.size);+ }+ ImGui::EndTable();+ }+ }}// ============================================================================diff --git a/fincept-cpp/src/screens/settings/sections/storage_cache_section.h b/fincept-cpp/src/screens/settings/sections/storage_cache_section.hindex db1caa390..a6c5cd4f6 100644--- a/fincept-cpp/src/screens/settings/sections/storage_cache_section.h+++ b/fincept-cpp/src/screens/settings/sections/storage_cache_section.h@@ -21,6 +21,10 @@ private:int64_t cache_size_ = 0;int64_t cache_expired_ = 0;+ // Per-category stats+ struct CatStat { std::string name; int64_t count; int64_t size; };+ std::vector<CatStat> category_stats_;+// Database browserbool db_authenticated_ = false;char db_password_[128] = {};diff --git a/fincept-cpp/src/storage/cache_service.cpp b/fincept-cpp/src/storage/cache_service.cppnew file mode 100644index 000000000..b567dc5fd--- /dev/null+++ b/fincept-cpp/src/storage/cache_service.cpp@@ -0,0 +1,389 @@+#include "cache_service.h"+#include "database.h"+#include "core/logger.h"+#include <chrono>++namespace fincept {++// ============================================================================+// CacheCategories — default TTL lookup+// ============================================================================+int64_t CacheCategories::default_ttl_for(const std::string& category) {+ static const std::map<std::string, int64_t> defaults = {+ {"market-quotes", CacheTTL::FIVE_MIN},+ {"market-historical", CacheTTL::ONE_HOUR},+ {"news", CacheTTL::TEN_MIN},+ {"forum", CacheTTL::FIVE_MIN},+ {"economic", CacheTTL::ONE_HOUR},+ {"reference", CacheTTL::ONE_DAY},+ {"user-data", CacheTTL::THIRTY_DAYS},+ {"api-response", CacheTTL::FIFTEEN_MIN},+ {"system", CacheTTL::THIRTY_DAYS},+ };+ auto it = defaults.find(category);+ return (it != defaults.end()) ? it->second : CacheTTL::TEN_MIN;+}++// ============================================================================+// CacheService — Singleton+// ============================================================================+CacheService& CacheService::instance() {+ static CacheService svc;+ return svc;+}++CacheService::~CacheService() {+ shutdown();+}++// ============================================================================+// Lifecycle+// ============================================================================+bool CacheService::initialize() {+ if (initialized_.load()) return true;++ try {+ // Ensure cache database is initialized+ auto& cache_db = db::CacheDatabase::instance();+ if (!cache_db.initialize()) {+ LOG_ERROR("CacheService", "Failed to initialize cache database");+ return false;+ }++ // Check cache version — clear if mismatched+ check_version();++ // Start background cleanup+ start_background_cleanup();++ initialized_.store(true);+ LOG_INFO("CacheService", "Initialized (version %s)", CACHE_VERSION);+ return true;+ } catch (const std::exception& e) {+ LOG_ERROR("CacheService", "Initialization failed: %s", e.what());+ return false;+ }+}++void CacheService::shutdown() {+ stop_background_cleanup();+ initialized_.store(false);+}++void CacheService::check_version() {+ try {+ auto entry = db::ops::cache_get_with_stale(VERSION_KEY);+ if (!entry || entry->data != std::string("\"") + CACHE_VERSION + "\"") {+ LOG_INFO("CacheService", "Cache version mismatch, clearing cache");+ db::ops::cache_clear_all();+ // Store new version+ std::string version_data = std::string("\"") + CACHE_VERSION + "\"";+ db::ops::cache_set(VERSION_KEY, version_data, "system", CacheTTL::THIRTY_DAYS);+ }+ } catch (const std::exception& e) {+ LOG_WARN("CacheService", "Version check failed: %s", e.what());+ }+}++// ============================================================================+// Core Cache Operations+// ============================================================================+std::optional<std::string> CacheService::get(const std::string& key) {+ if (!initialized_.load()) return std::nullopt;++ try {+ auto entry = db::ops::cache_get(key);+ if (!entry) return std::nullopt;+ return entry->data;+ } catch (const std::exception& e) {+ LOG_ERROR("CacheService", "get error for '%s': %s", key.c_str(), e.what());+ return std::nullopt;+ }+}++std::optional<CacheService::StaleResult> CacheService::get_with_stale(const std::string& key) {+ if (!initialized_.load()) return std::nullopt;++ try {+ auto entry = db::ops::cache_get_with_stale(key);+ if (!entry) return std::nullopt;+ return StaleResult{entry->data, entry->is_expired};+ } catch (const std::exception& e) {+ LOG_ERROR("CacheService", "get_with_stale error for '%s': %s", key.c_str(), e.what());+ return std::nullopt;+ }+}++bool CacheService::set(const std::string& key, const std::string& data,+ const std::string& category, int64_t ttl) {+ if (!initialized_.load()) return false;++ try {+ // Check size limits before inserting+ ensure_cache_size();++ int64_t ttl_seconds = (ttl > 0) ? ttl : CacheCategories::default_ttl_for(category);+ db::ops::cache_set(key, data, category, ttl_seconds);+ return true;+ } catch (const std::exception& e) {+ LOG_ERROR("CacheService", "set error for '%s': %s", key.c_str(), e.what());+ return false;+ }+}++bool CacheService::remove(const std::string& key) {+ if (!initialized_.load()) return false;++ try {+ return db::ops::cache_delete(key);+ } catch (const std::exception& e) {+ LOG_ERROR("CacheService", "remove error for '%s': %s", key.c_str(), e.what());+ return false;+ }+}++std::map<std::string, std::string> CacheService::get_many(const std::vector<std::string>& keys) {+ std::map<std::string, std::string> result;+ if (!initialized_.load() || keys.empty()) return result;++ try {+ auto entries = db::ops::cache_get_many(keys);+ for (auto& entry : entries) {+ result[entry.cache_key] = std::move(entry.data);+ }+ } catch (const std::exception& e) {+ LOG_ERROR("CacheService", "get_many error: %s", e.what());+ }+ return result;+}++// ============================================================================+// Category & Pattern Operations+// ============================================================================+int64_t CacheService::invalidate_category(const std::string& category) {+ if (!initialized_.load()) return 0;++ try {+ return db::ops::cache_invalidate_category(category);+ } catch (const std::exception& e) {+ LOG_ERROR("CacheService", "invalidate_category error: %s", e.what());+ return 0;+ }+}++int64_t CacheService::invalidate_pattern(const std::string& pattern) {+ if (!initialized_.load()) return 0;++ try {+ return db::ops::cache_invalidate_pattern(pattern);+ } catch (const std::exception& e) {+ LOG_ERROR("CacheService", "invalidate_pattern error: %s", e.what());+ return 0;+ }+}++// ============================================================================+// Cleanup & Maintenance+// ============================================================================+int64_t CacheService::cleanup() {+ try {+ return db::ops::cache_cleanup();+ } catch (const std::exception& e) {+ LOG_ERROR("CacheService", "cleanup error: %s", e.what());+ return 0;+ }+}++int64_t CacheService::evict_lru(int64_t count) {+ try {+ return db::ops::cache_evict_lru(count);+ } catch (const std::exception& e) {+ LOG_ERROR("CacheService", "evict_lru error: %s", e.what());+ return 0;+ }+}++void CacheService::clear_all() {+ try {+ db::ops::cache_clear_all();+ // Restore version key+ std::string version_data = std::string("\"") + CACHE_VERSION + "\"";+ db::ops::cache_set(VERSION_KEY, version_data, "system", CacheTTL::THIRTY_DAYS);+ LOG_INFO("CacheService", "Cache cleared");+ } catch (const std::exception& e) {+ LOG_ERROR("CacheService", "clear_all error: %s", e.what());+ }+}++CacheService::Stats CacheService::get_stats() {+ Stats result{};+ try {+ auto db_stats = db::ops::cache_stats();+ result.total_entries = db_stats.total_entries;+ result.total_size_bytes = db_stats.total_size_bytes;+ result.expired_entries = db_stats.expired_entries;+ for (auto& cat : db_stats.categories) {+ result.categories.push_back({cat.category, cat.entry_count, cat.total_size});+ }+ } catch (const std::exception& e) {+ LOG_ERROR("CacheService", "get_stats error: %s", e.what());+ }+ return result;+}++// ============================================================================+// Size Management & LRU Eviction+// ============================================================================+void CacheService::ensure_cache_size() {+ try {+ auto stats = db::ops::cache_stats();++ int64_t max_size_bytes = MAX_CACHE_SIZE_MB * 1024 * 1024;+ bool size_exceeded = stats.total_size_bytes > (int64_t)(max_size_bytes * CLEANUP_THRESHOLD);+ bool count_exceeded = stats.total_entries > (int64_t)(MAX_CACHE_ENTRIES * CLEANUP_THRESHOLD);++ if (!size_exceeded && !count_exceeded) return;++ LOG_INFO("CacheService", "Cache cleanup triggered — Size: %.2f MB, Entries: %lld",+ (double)stats.total_size_bytes / (1024.0 * 1024.0),+ (long long)stats.total_entries);++ // First: remove expired entries+ int64_t expired_removed = db::ops::cache_cleanup();+ if (expired_removed > 0) {+ LOG_INFO("CacheService", "Removed %lld expired entries", (long long)expired_removed);+ }++ // Re-check after cleanup+ auto new_stats = db::ops::cache_stats();+ bool still_over_size = new_stats.total_size_bytes > (int64_t)(max_size_bytes * 0.8);+ bool still_over_count = new_stats.total_entries > (int64_t)(MAX_CACHE_ENTRIES * 0.8);++ if (still_over_size || still_over_count) {+ // LRU eviction — remove 20% of entries, minimum 100+ int64_t target = std::max((int64_t)(new_stats.total_entries * 0.2), (int64_t)100);+ int64_t evicted = db::ops::cache_evict_lru(target);+ LOG_INFO("CacheService", "LRU evicted %lld entries", (long long)evicted);+ }+ } catch (const std::exception& e) {+ LOG_ERROR("CacheService", "ensure_cache_size error: %s", e.what());+ }+}++// ============================================================================+// Tab Sessions+// ============================================================================+std::optional<std::string> CacheService::get_tab_session(const std::string& tab_id) {+ if (!initialized_.load()) return std::nullopt;++ try {+ auto session = db::ops::tab_session_get(tab_id);+ if (!session) return std::nullopt;+ return session->state;+ } catch (const std::exception& e) {+ LOG_ERROR("CacheService", "get_tab_session error: %s", e.what());+ return std::nullopt;+ }+}++bool CacheService::set_tab_session(const std::string& tab_id, const std::string& tab_name,+ const std::string& state, const std::string& scroll_position,+ const std::string& active_filters,+ const std::string& selected_items) {+ if (!initialized_.load()) return false;++ try {+ db::ops::tab_session_set(tab_id, tab_name, state, scroll_position,+ active_filters, selected_items);+ return true;+ } catch (const std::exception& e) {+ LOG_ERROR("CacheService", "set_tab_session error: %s", e.what());+ return false;+ }+}++bool CacheService::delete_tab_session(const std::string& tab_id) {+ if (!initialized_.load()) return false;++ try {+ db::ops::tab_session_delete(tab_id);+ return true;+ } catch (const std::exception& e) {+ LOG_ERROR("CacheService", "delete_tab_session error: %s", e.what());+ return false;+ }+}++int64_t CacheService::cleanup_tab_sessions(int64_t max_age_days) {+ try {+ return db::ops::tab_session_cleanup(max_age_days);+ } catch (const std::exception& e) {+ LOG_ERROR("CacheService", "cleanup_tab_sessions error: %s", e.what());+ return 0;+ }+}++// ============================================================================+// Background Cleanup Thread+// ============================================================================+void CacheService::start_background_cleanup(int interval_seconds) {+ stop_background_cleanup();++ cleanup_running_.store(true);+ cleanup_thread_ = std::thread([this, interval_seconds]() {+ LOG_INFO("CacheService", "Background cleanup started (interval: %ds)", interval_seconds);++ while (cleanup_running_.load()) {+ // Sleep in small increments so we can stop quickly+ for (int i = 0; i < interval_seconds && cleanup_running_.load(); i++) {+ std::this_thread::sleep_for(std::chrono::seconds(1));+ }++ if (!cleanup_running_.load()) break;++ try {+ int64_t expired = db::ops::cache_cleanup();+ if (expired > 0) {+ LOG_INFO("CacheService", "Background cleanup: removed %lld expired entries",+ (long long)expired);+ }++ // Also check size limits+ ensure_cache_size();++ // Cleanup old tab sessions (older than 30 days)+ db::ops::tab_session_cleanup(30);+ } catch (const std::exception& e) {+ LOG_ERROR("CacheService", "Background cleanup error: %s", e.what());+ }+ }++ LOG_INFO("CacheService", "Background cleanup stopped");+ });+}++void CacheService::stop_background_cleanup() {+ cleanup_running_.store(false);+ if (cleanup_thread_.joinable()) {+ cleanup_thread_.join();+ }+}++// ============================================================================+// Key Generation Helpers+// ============================================================================+std::string CacheService::make_key(const std::string& category, const std::string& part1) {+ return category + ":" + part1;+}++std::string CacheService::make_key(const std::string& category, const std::string& part1,+ const std::string& part2) {+ return category + ":" + part1 + ":" + part2;+}++std::string CacheService::make_key(const std::string& category, const std::string& part1,+ const std::string& part2, const std::string& part3) {+ return category + ":" + part1 + ":" + part2 + ":" + part3;+}++} // namespace finceptdiff --git a/fincept-cpp/src/storage/cache_service.h b/fincept-cpp/src/storage/cache_service.hnew file mode 100644index 000000000..471b582c8--- /dev/null+++ b/fincept-cpp/src/storage/cache_service.h@@ -0,0 +1,179 @@+#pragma once+// CacheService — High-level caching layer with TTL presets, size management,+// LRU eviction, background cleanup, and version-aware cache invalidation.+// Mirrors cacheService.ts from the Tauri project.+//+// Usage:+// auto& cache = fincept::CacheService::instance();+// cache.initialize();+// cache.set("market-quotes:AAPL", json_str, "market-quotes");+// auto result = cache.get("market-quotes:AAPL");++#include <string>+#include <vector>+#include <optional>+#include <map>+#include <mutex>+#include <thread>+#include <atomic>+#include <functional>+#include <cstdint>++namespace fincept {++// ============================================================================+// TTL Presets (seconds)+// ============================================================================+namespace CacheTTL {+ constexpr int64_t ONE_MIN = 60;+ constexpr int64_t FIVE_MIN = 300;+ constexpr int64_t TEN_MIN = 600;+ constexpr int64_t FIFTEEN_MIN = 900;+ constexpr int64_t THIRTY_MIN = 1800;+ constexpr int64_t ONE_HOUR = 3600;+ constexpr int64_t SIX_HOURS = 21600;+ constexpr int64_t TWELVE_HOURS = 43200;+ constexpr int64_t ONE_DAY = 86400;+ constexpr int64_t SEVEN_DAYS = 604800;+ constexpr int64_t THIRTY_DAYS = 2592000;++ // Backward compat aliases+ constexpr int64_t SHORT = ONE_MIN;+ constexpr int64_t MEDIUM = FIVE_MIN;+ constexpr int64_t LONG = TEN_MIN;+ constexpr int64_t HOUR = ONE_HOUR;+ constexpr int64_t DAY = ONE_DAY;+ constexpr int64_t WEEK = SEVEN_DAYS;+}++// ============================================================================+// Cache Categories with default TTLs+// ============================================================================+struct CacheCategoryInfo {+ const char* name;+ int64_t default_ttl;+};++namespace CacheCategories {+ constexpr CacheCategoryInfo MARKET_QUOTES = {"market-quotes", CacheTTL::FIVE_MIN};+ constexpr CacheCategoryInfo MARKET_HISTORICAL = {"market-historical", CacheTTL::ONE_HOUR};+ constexpr CacheCategoryInfo NEWS = {"news", CacheTTL::TEN_MIN};+ constexpr CacheCategoryInfo FORUM = {"forum", CacheTTL::FIVE_MIN};+ constexpr CacheCategoryInfo ECONOMIC = {"economic", CacheTTL::ONE_HOUR};+ constexpr CacheCategoryInfo REFERENCE = {"reference", CacheTTL::ONE_DAY};+ constexpr CacheCategoryInfo USER_DATA = {"user-data", CacheTTL::THIRTY_DAYS};+ constexpr CacheCategoryInfo API_RESPONSE = {"api-response", CacheTTL::FIFTEEN_MIN};+ constexpr CacheCategoryInfo SYSTEM = {"system", CacheTTL::THIRTY_DAYS};++ // Get default TTL for a category name, returns 600 (10 min) if unknown+ int64_t default_ttl_for(const std::string& category);+}++// ============================================================================+// CacheService — Singleton+// ============================================================================+class CacheService {+public:+ static CacheService& instance();++ // --- Lifecycle ---+ bool initialize();+ void shutdown();+ bool is_initialized() const { return initialized_.load(); }++ // --- Core Cache Operations ---++ // Get a cached value (returns nullopt if expired or not found)+ std::optional<std::string> get(const std::string& key);++ // Get cached value even if stale (for stale-while-revalidate pattern)+ struct StaleResult {+ std::string data;+ bool is_stale;+ };+ std::optional<StaleResult> get_with_stale(const std::string& key);++ // Set a cached value. If ttl == 0, uses the category's default TTL.+ bool set(const std::string& key, const std::string& data,+ const std::string& category, int64_t ttl = 0);++ // Delete a cached value+ bool remove(const std::string& key);++ // Get multiple cached values+ std::map<std::string, std::string> get_many(const std::vector<std::string>& keys);++ // --- Category & Pattern Operations ---+ int64_t invalidate_category(const std::string& category);+ int64_t invalidate_pattern(const std::string& pattern); // SQL LIKE pattern, use % wildcard++ // --- Cleanup & Maintenance ---+ int64_t cleanup(); // Remove expired entries+ int64_t evict_lru(int64_t count); // Remove N least recently used entries+ void clear_all(); // Clear entire cache (preserves version key)++ // --- Stats ---+ struct Stats {+ int64_t total_entries;+ int64_t total_size_bytes;+ int64_t expired_entries;+ struct Category {+ std::string name;+ int64_t entry_count;+ int64_t total_size;+ };+ std::vector<Category> categories;+ };+ Stats get_stats();++ // --- Tab Sessions ---+ std::optional<std::string> get_tab_session(const std::string& tab_id);+ bool set_tab_session(const std::string& tab_id, const std::string& tab_name,+ const std::string& state,+ const std::string& scroll_position = "",+ const std::string& active_filters = "",+ const std::string& selected_items = "");+ bool delete_tab_session(const std::string& tab_id);+ int64_t cleanup_tab_sessions(int64_t max_age_days = 30);++ // --- Background Cleanup ---+ void start_background_cleanup(int interval_seconds = 900); // default 15 min+ void stop_background_cleanup();++ // --- Key Generation Helpers ---+ static std::string make_key(const std::string& category, const std::string& part1);+ static std::string make_key(const std::string& category, const std::string& part1,+ const std::string& part2);+ static std::string make_key(const std::string& category, const std::string& part1,+ const std::string& part2, const std::string& part3);++ // --- Configuration ---+ static constexpr const char* CACHE_VERSION = "1.0.0";+ static constexpr int64_t MAX_CACHE_SIZE_MB = 100;+ static constexpr int64_t MAX_CACHE_ENTRIES = 10000;+ static constexpr double CLEANUP_THRESHOLD = 0.9;++ CacheService(const CacheService&) = delete;+ CacheService& operator=(const CacheService&) = delete;++private:+ CacheService() = default;+ ~CacheService();++ std::atomic<bool> initialized_{false};++ // Background cleanup thread+ std::thread cleanup_thread_;+ std::atomic<bool> cleanup_running_{false};+ std::mutex cleanup_mutex_;++ // Size management — evicts LRU entries when limits are approached+ void ensure_cache_size();++ // Version management+ void check_version();++ static constexpr const char* VERSION_KEY = "__cache_version__";+};++} // namespace finceptdiff --git a/fincept-cpp/src/storage/database.cpp b/fincept-cpp/src/storage/database.cppindex 2204dcfc9..23b16d903 100644--- a/fincept-cpp/src/storage/database.cpp+++ b/fincept-cpp/src/storage/database.cpp@@ -2,6 +2,7 @@// Thread-safe SQLite with WAL, performance PRAGMAs, domain operations#include "database.h"+#include "screens/algo_trading/algo_types.h"#include "core/logger.h"#include <sqlite3.h>#include <filesystem>@@ -443,7 +444,9 @@ void Database::create_schema() {UNIQUE(portfolio_id, symbol, side));CREATE INDEX IF NOT EXISTS idx_pt_positions_pid ON pt_positions(portfolio_id);+ )");+ exec(R"(CREATE TABLE IF NOT EXISTS pt_trades (id TEXT PRIMARY KEY,portfolio_id TEXT NOT NULL,@@ -523,6 +526,137 @@ void Database::create_schema() {CREATE INDEX IF NOT EXISTS idx_notes_priority ON notes(priority);CREATE INDEX IF NOT EXISTS idx_notes_favorite ON notes(is_favorite);CREATE INDEX IF NOT EXISTS idx_notes_archived ON notes(is_archived);++ -- Algo Trading: Strategies+ CREATE TABLE IF NOT EXISTS algo_strategies (+ id TEXT PRIMARY KEY,+ name TEXT NOT NULL,+ description TEXT DEFAULT '',+ symbols TEXT NOT NULL DEFAULT '[]',+ entry_conditions TEXT NOT NULL DEFAULT '[]',+ exit_conditions TEXT NOT NULL DEFAULT '[]',+ entry_logic TEXT NOT NULL DEFAULT 'AND',+ exit_logic TEXT NOT NULL DEFAULT 'AND',+ timeframe TEXT NOT NULL DEFAULT '5m',+ stop_loss REAL DEFAULT 0,+ take_profit REAL DEFAULT 0,+ trailing_stop REAL DEFAULT 0,+ position_size REAL DEFAULT 1,+ max_positions INTEGER DEFAULT 1,+ provider TEXT DEFAULT 'fyers',+ is_active INTEGER DEFAULT 1,+ created_at TEXT DEFAULT CURRENT_TIMESTAMP,+ updated_at TEXT DEFAULT CURRENT_TIMESTAMP+ );+ )");++ exec(R"(+ -- Algo Trading: Deployments+ CREATE TABLE IF NOT EXISTS algo_deployments (+ id TEXT PRIMARY KEY,+ strategy_id TEXT NOT NULL,+ strategy_name TEXT DEFAULT '',+ mode TEXT NOT NULL DEFAULT 'paper',+ status TEXT NOT NULL DEFAULT 'starting',+ pid INTEGER DEFAULT 0,+ portfolio_id TEXT DEFAULT '',+ started_at TEXT DEFAULT CURRENT_TIMESTAMP,+ stopped_at TEXT,+ error_message TEXT DEFAULT '',+ config TEXT DEFAULT '{}',+ FOREIGN KEY (strategy_id) REFERENCES algo_strategies(id)+ );+ CREATE INDEX IF NOT EXISTS idx_algo_deployments_strategy ON algo_deployments(strategy_id);+ CREATE INDEX IF NOT EXISTS idx_algo_deployments_status ON algo_deployments(status);++ -- Algo Trading: Metrics (per deployment)+ CREATE TABLE IF NOT EXISTS algo_metrics (+ deployment_id TEXT PRIMARY KEY,+ total_trades INTEGER DEFAULT 0,+ winning_trades INTEGER DEFAULT 0,+ losing_trades INTEGER DEFAULT 0,+ total_pnl REAL DEFAULT 0,+ max_drawdown REAL DEFAULT 0,+ win_rate REAL DEFAULT 0,+ avg_win REAL DEFAULT 0,+ avg_loss REAL DEFAULT 0,+ sharpe_ratio REAL DEFAULT 0,+ updated_at TEXT DEFAULT CURRENT_TIMESTAMP,+ FOREIGN KEY (deployment_id) REFERENCES algo_deployments(id) ON DELETE CASCADE+ );++ -- Algo Trading: Trades+ CREATE TABLE IF NOT EXISTS algo_trades (+ id TEXT PRIMARY KEY,+ deployment_id TEXT NOT NULL,+ symbol TEXT NOT NULL,+ side TEXT NOT NULL,+ quantity REAL NOT NULL,+ price REAL NOT NULL,+ pnl REAL DEFAULT 0,+ fees REAL DEFAULT 0,+ order_type TEXT DEFAULT 'market',+ status TEXT DEFAULT 'filled',+ executed_at TEXT DEFAULT CURRENT_TIMESTAMP,+ FOREIGN KEY (deployment_id) REFERENCES algo_deployments(id) ON DELETE CASCADE+ );+ CREATE INDEX IF NOT EXISTS idx_algo_trades_deployment ON algo_trades(deployment_id);++ -- Algo Trading: Order Signals (bridge between Python runner and order execution)+ CREATE TABLE IF NOT EXISTS algo_order_signals (+ id TEXT PRIMARY KEY,+ deployment_id TEXT NOT NULL,+ symbol TEXT NOT NULL,+ side TEXT NOT NULL,+ quantity REAL NOT NULL,+ order_type TEXT DEFAULT 'market',+ price REAL DEFAULT 0,+ stop_price REAL DEFAULT 0,+ status TEXT DEFAULT 'pending',+ created_at TEXT DEFAULT CURRENT_TIMESTAMP,+ executed_at TEXT,+ error TEXT DEFAULT '',+ 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);++ -- Algo Trading: Candle Cache+ CREATE TABLE IF NOT EXISTS candle_cache (+ id INTEGER PRIMARY KEY AUTOINCREMENT,+ symbol TEXT NOT NULL,+ timeframe TEXT NOT NULL,+ timestamp INTEGER NOT NULL,+ open REAL NOT NULL,+ high REAL NOT NULL,+ low REAL NOT NULL,+ close REAL NOT NULL,+ volume REAL DEFAULT 0,+ provider TEXT DEFAULT 'fyers',+ UNIQUE(symbol, timeframe, timestamp, provider)+ );+ CREATE INDEX IF NOT EXISTS idx_candle_cache_lookup ON candle_cache(symbol, timeframe, timestamp);++ -- Algo Trading: Custom Python Strategies+ CREATE TABLE IF NOT EXISTS custom_python_strategies (+ id TEXT PRIMARY KEY,+ name TEXT NOT NULL,+ description TEXT DEFAULT '',+ code TEXT NOT NULL,+ category TEXT DEFAULT 'custom',+ parameters TEXT DEFAULT '{}',+ created_at TEXT DEFAULT CURRENT_TIMESTAMP,+ updated_at TEXT DEFAULT CURRENT_TIMESTAMP+ );++ -- Algo Trading: Strategy Price Cache (live prices for deployed strategies)+ CREATE TABLE IF NOT EXISTS strategy_price_cache (+ symbol TEXT NOT NULL,+ price REAL NOT NULL,+ volume REAL DEFAULT 0,+ change_pct REAL DEFAULT 0,+ updated_at TEXT DEFAULT CURRENT_TIMESTAMP,+ PRIMARY KEY (symbol)+ );)");}@@ -1217,6 +1351,24 @@ void delete_ma_deal(const std::string& deal_id) {// ============================================================================// Operations — Cache (separate CacheDatabase)// ============================================================================++// Helper to parse a cache row from a SELECT statement+static CacheEntry parse_cache_row(Statement& stmt, int64_t now) {+ int64_t expires_at = stmt.col_int(5);+ return CacheEntry{+ stmt.col_text(0), // cache_key+ stmt.col_text(1), // category+ stmt.col_text(2), // data+ stmt.col_int(3), // ttl_seconds+ stmt.col_int(4), // created_at+ expires_at, // expires_at+ stmt.col_int(6), // last_accessed_at+ stmt.col_int(7), // hit_count+ stmt.col_int(8), // size_bytes+ now > expires_at // is_expired+ };+}+std::optional<CacheEntry> cache_get(const std::string& key) {auto& db = CacheDatabase::instance();std::lock_guard<std::recursive_mutex> lock(db.mutex());@@ -1224,18 +1376,13 @@ std::optional<CacheEntry> cache_get(const std::string& key) {auto stmt = db.prepare("SELECT cache_key, category, data, ttl_seconds, created_at, expires_at, "- "last_accessed_at, hit_count FROM unified_cache WHERE cache_key = ?1");+ "last_accessed_at, hit_count, size_bytes FROM unified_cache WHERE cache_key = ?1");stmt.bind_text(1, key);if (!stmt.step()) return std::nullopt;- int64_t expires_at = stmt.col_int(5);- bool expired = now > expires_at;-- CacheEntry entry{stmt.col_text(0), stmt.col_text(1), stmt.col_text(2),- stmt.col_int(3), stmt.col_int(4), expires_at,- stmt.col_int(7), expired};+ auto entry = parse_cache_row(stmt, now);- if (!expired) {+ if (!entry.is_expired) {auto upd = db.prepare("UPDATE unified_cache SET last_accessed_at = ?1, hit_count = hit_count + 1 WHERE cache_key = ?2");upd.bind_int(1, now);@@ -1246,6 +1393,51 @@ std::optional<CacheEntry> cache_get(const std::string& key) {return std::nullopt;}+std::optional<CacheEntry> cache_get_with_stale(const std::string& key) {+ auto& db = CacheDatabase::instance();+ std::lock_guard<std::recursive_mutex> lock(db.mutex());+ int64_t now = now_timestamp();++ auto stmt = db.prepare(+ "SELECT cache_key, category, data, ttl_seconds, created_at, expires_at, "+ "last_accessed_at, hit_count, size_bytes FROM unified_cache WHERE cache_key = ?1");+ stmt.bind_text(1, key);+ if (!stmt.step()) return std::nullopt;++ return parse_cache_row(stmt, now);+}++std::vector<CacheEntry> cache_get_many(const std::vector<std::string>& keys) {+ if (keys.empty()) return {};+ auto& db = CacheDatabase::instance();+ std::lock_guard<std::recursive_mutex> lock(db.mutex());+ int64_t now = now_timestamp();++ // Build query with placeholders+ std::string placeholders;+ for (size_t i = 0; i < keys.size(); i++) {+ if (i > 0) placeholders += ",";+ placeholders += "?" + std::to_string(i + 1);+ }+ std::string sql =+ "SELECT cache_key, category, data, ttl_seconds, created_at, expires_at, "+ "last_accessed_at, hit_count, size_bytes FROM unified_cache "+ "WHERE cache_key IN (" + placeholders + ") AND expires_at > ?" ++ std::to_string(keys.size() + 1);++ auto stmt = db.prepare(sql.c_str());+ for (size_t i = 0; i < keys.size(); i++) {+ stmt.bind_text(static_cast<int>(i + 1), keys[i]);+ }+ stmt.bind_int(static_cast<int>(keys.size() + 1), now);++ std::vector<CacheEntry> results;+ while (stmt.step()) {+ results.push_back(parse_cache_row(stmt, now));+ }+ return results;+}+void cache_set(const std::string& key, const std::string& data,const std::string& category, int64_t ttl_seconds) {auto& db = CacheDatabase::instance();@@ -1271,7 +1463,6 @@ void cache_set(const std::string& key, const std::string& data,bool cache_delete(const std::string& key) {auto& db = CacheDatabase::instance();std::lock_guard<std::recursive_mutex> lock(db.mutex());- // Check existence firstauto chk = db.prepare("SELECT 1 FROM unified_cache WHERE cache_key = ?1");chk.bind_text(1, key);bool existed = chk.step();@@ -1298,6 +1489,44 @@ int64_t cache_invalidate_category(const std::string& category) {return count;}+int64_t cache_invalidate_pattern(const std::string& pattern) {+ auto& db = CacheDatabase::instance();+ std::lock_guard<std::recursive_mutex> lock(db.mutex());+ int64_t count = 0;+ {+ auto cnt = db.prepare("SELECT COUNT(*) FROM unified_cache WHERE cache_key LIKE ?1");+ cnt.bind_text(1, pattern);+ if (cnt.step()) count = cnt.col_int(0);+ }+ auto stmt = db.prepare("DELETE FROM unified_cache WHERE cache_key LIKE ?1");+ stmt.bind_text(1, pattern);+ stmt.execute();+ return count;+}++int64_t cache_evict_lru(int64_t count) {+ auto& db = CacheDatabase::instance();+ std::lock_guard<std::recursive_mutex> lock(db.mutex());+ // Delete the N least recently accessed entries+ int64_t before = 0;+ {+ auto s = db.prepare("SELECT COUNT(*) FROM unified_cache");+ if (s.step()) before = s.col_int(0);+ }+ std::string sql =+ "DELETE FROM unified_cache WHERE cache_key IN ("+ "SELECT cache_key FROM unified_cache ORDER BY last_accessed_at ASC LIMIT ?1)";+ auto stmt = db.prepare(sql.c_str());+ stmt.bind_int(1, count);+ stmt.execute();+ int64_t after = 0;+ {+ auto s = db.prepare("SELECT COUNT(*) FROM unified_cache");+ if (s.step()) after = s.col_int(0);+ }+ return before - after;+}+int64_t cache_cleanup() {auto& db = CacheDatabase::instance();std::lock_guard<std::recursive_mutex> lock(db.mutex());@@ -1331,6 +1560,15 @@ CacheStats cache_stats() {s.bind_int(1, now_timestamp());if (s.step()) stats.expired_entries = s.col_int(0);}+ // Per-category breakdown+ {+ auto s = db.prepare(+ "SELECT category, COUNT(*), COALESCE(SUM(size_bytes), 0) "+ "FROM unified_cache GROUP BY category");+ while (s.step()) {+ stats.categories.push_back({s.col_text(0), s.col_int(1), s.col_int(2)});+ }+ }return stats;}@@ -1404,6 +1642,22 @@ std::vector<TabSession> tab_session_get_all() {return result;}+int64_t tab_session_cleanup(int64_t max_age_days) {+ auto& db = CacheDatabase::instance();+ std::lock_guard<std::recursive_mutex> lock(db.mutex());+ int64_t cutoff = now_timestamp() - (max_age_days * 24 * 60 * 60);+ int64_t count = 0;+ {+ auto cnt = db.prepare("SELECT COUNT(*) FROM tab_sessions WHERE updated_at < ?1");+ cnt.bind_int(1, cutoff);+ if (cnt.step()) count = cnt.col_int(0);+ }+ auto stmt = db.prepare("DELETE FROM tab_sessions WHERE updated_at < ?1");+ stmt.bind_int(1, cutoff);+ stmt.execute();+ return count;+}+// ============================================================================// Agent Configs// ============================================================================@@ -1740,5 +1994,537 @@ void ops::archive_note(int64_t id) {stmt.execute();}+// ============================================================================+// Algo Trading Operations+// ============================================================================++void ops::save_algo_strategy(const algo::AlgoStrategy& s) {+ auto& db = Database::instance();+ std::lock_guard<std::recursive_mutex> lock(db.mutex());+ auto stmt = db.prepare(R"(+ INSERT OR REPLACE INTO algo_strategies+ (id, name, description, symbols, entry_conditions, exit_conditions,+ entry_logic, exit_logic, timeframe, stop_loss, take_profit, trailing_stop,+ position_size, max_positions, provider, is_active, updated_at)+ VALUES (?1,?2,?3,?4,?5,?6,?7,?8,?9,?10,?11,?12,?13,?14,?15,?16,CURRENT_TIMESTAMP)+ )");+ stmt.bind_text(1, s.id);+ stmt.bind_text(2, s.name);+ stmt.bind_text(3, s.description);+ stmt.bind_text(4, s.symbols);+ stmt.bind_text(5, s.entry_conditions);+ stmt.bind_text(6, s.exit_conditions);+ stmt.bind_text(7, s.entry_logic);+ stmt.bind_text(8, s.exit_logic);+ stmt.bind_text(9, s.timeframe);+ stmt.bind_double(10, s.stop_loss);+ stmt.bind_double(11, s.take_profit);+ stmt.bind_double(12, s.trailing_stop);+ stmt.bind_double(13, s.position_size);+ stmt.bind_int(14, s.max_positions);+ stmt.bind_text(15, s.provider);+ stmt.bind_int(16, s.is_active ? 1 : 0);+ stmt.execute();+}++static algo::AlgoStrategy read_algo_strategy_row(Statement& stmt) {+ algo::AlgoStrategy s;+ s.id = stmt.col_text(0);+ s.name = stmt.col_text(1);+ s.description = stmt.col_text(2);+ s.symbols = stmt.col_text(3);+ s.entry_conditions = stmt.col_text(4);+ s.exit_conditions = stmt.col_text(5);+ s.entry_logic = stmt.col_text(6);+ s.exit_logic = stmt.col_text(7);+ s.timeframe = stmt.col_text(8);+ s.stop_loss = stmt.col_double(9);+ s.take_profit = stmt.col_double(10);+ s.trailing_stop = stmt.col_double(11);+ s.position_size = stmt.col_double(12);+ s.max_positions = (int)stmt.col_int(13);+ s.provider = stmt.col_text(14);+ s.is_active = stmt.col_bool(15);+ s.created_at = stmt.col_text(16);+ s.updated_at = stmt.col_text(17);+ return s;+}++std::vector<algo::AlgoStrategy> ops::list_algo_strategies() {+ auto& db = Database::instance();+ std::lock_guard<std::recursive_mutex> lock(db.mutex());+ auto stmt = db.prepare(+ "SELECT id, name, description, symbols, entry_conditions, exit_conditions, "+ "entry_logic, exit_logic, timeframe, stop_loss, take_profit, trailing_stop, "+ "position_size, max_positions, provider, is_active, created_at, updated_at "+ "FROM algo_strategies ORDER BY updated_at DESC");+ std::vector<algo::AlgoStrategy> result;+ while (stmt.step()) result.push_back(read_algo_strategy_row(stmt));+ return result;+}++std::optional<algo::AlgoStrategy> ops::get_algo_strategy(const std::string& id) {+ auto& db = Database::instance();+ std::lock_guard<std::recursive_mutex> lock(db.mutex());+ auto stmt = db.prepare(+ "SELECT id, name, description, symbols, entry_conditions, exit_conditions, "+ "entry_logic, exit_logic, timeframe, stop_loss, take_profit, trailing_stop, "+ "position_size, max_positions, provider, is_active, created_at, updated_at "+ "FROM algo_strategies WHERE id = ?1");+ stmt.bind_text(1, id);+ if (stmt.step()) return read_algo_strategy_row(stmt);+ return std::nullopt;+}++void ops::delete_algo_strategy(const std::string& id) {+ auto& db = Database::instance();+ std::lock_guard<std::recursive_mutex> lock(db.mutex());+ auto stmt = db.prepare("DELETE FROM algo_strategies WHERE id = ?1");+ stmt.bind_text(1, id);+ stmt.execute();+}++// --- Deployments ---++void ops::save_algo_deployment(const algo::AlgoDeployment& d) {+ auto& db = Database::instance();+ std::lock_guard<std::recursive_mutex> lock(db.mutex());+ auto stmt = db.prepare(R"(+ INSERT OR REPLACE INTO algo_deployments+ (id, strategy_id, strategy_name, mode, status, pid, portfolio_id,+ started_at, stopped_at, error_message, config)+ VALUES (?1,?2,?3,?4,?5,?6,?7,?8,?9,?10,?11)+ )");+ stmt.bind_text(1, d.id);+ stmt.bind_text(2, d.strategy_id);+ stmt.bind_text(3, d.strategy_name);+ stmt.bind_text(4, d.mode);+ stmt.bind_text(5, algo::deployment_status_str(d.status));+ stmt.bind_int(6, d.pid);+ stmt.bind_text(7, d.portfolio_id);+ stmt.bind_text(8, d.started_at);+ stmt.bind_text(9, d.stopped_at);+ stmt.bind_text(10, d.error_message);+ stmt.bind_text(11, d.config);+ stmt.execute();+}++static algo::AlgoDeployment read_algo_deployment_row(Statement& stmt) {+ algo::AlgoDeployment d;+ d.id = stmt.col_text(0);+ d.strategy_id = stmt.col_text(1);+ d.strategy_name = stmt.col_text(2);+ d.mode = stmt.col_text(3);+ d.status = algo::parse_deployment_status(stmt.col_text(4));+ d.pid = (int)stmt.col_int(5);+ d.portfolio_id = stmt.col_text(6);+ d.started_at = stmt.col_text(7);+ d.stopped_at = stmt.col_text(8);+ d.error_message = stmt.col_text(9);+ d.config = stmt.col_text(10);+ return d;+}++std::vector<algo::AlgoDeployment> ops::list_algo_deployments() {+ auto& db = Database::instance();+ std::lock_guard<std::recursive_mutex> lock(db.mutex());+ auto stmt = db.prepare(+ "SELECT id, strategy_id, strategy_name, mode, status, pid, portfolio_id, "+ "started_at, stopped_at, error_message, config "+ "FROM algo_deployments ORDER BY started_at DESC");+ std::vector<algo::AlgoDeployment> result;+ while (stmt.step()) result.push_back(read_algo_deployment_row(stmt));+ return result;+}++std::optional<algo::AlgoDeployment> ops::get_algo_deployment(const std::string& id) {+ auto& db = Database::instance();+ std::lock_guard<std::recursive_mutex> lock(db.mutex());+ auto stmt = db.prepare(+ "SELECT id, strategy_id, strategy_name, mode, status, pid, portfolio_id, "+ "started_at, stopped_at, error_message, config "+ "FROM algo_deployments WHERE id = ?1");+ stmt.bind_text(1, id);+ if (stmt.step()) return read_algo_deployment_row(stmt);+ return std::nullopt;+}++void ops::update_algo_deployment_status(const std::string& id, const std::string& status,+ const std::string& error) {+ auto& db = Database::instance();+ std::lock_guard<std::recursive_mutex> lock(db.mutex());+ if (status == "stopped" || status == "error" || status == "completed") {+ auto stmt = db.prepare(+ "UPDATE algo_deployments SET status = ?2, error_message = ?3, "+ "stopped_at = CURRENT_TIMESTAMP WHERE id = ?1");+ stmt.bind_text(1, id);+ stmt.bind_text(2, status);+ stmt.bind_text(3, error);+ stmt.execute();+ } else {+ auto stmt = db.prepare(+ "UPDATE algo_deployments SET status = ?2, error_message = ?3 WHERE id = ?1");+ stmt.bind_text(1, id);+ stmt.bind_text(2, status);+ stmt.bind_text(3, error);+ stmt.execute();+ }+}++void ops::delete_algo_deployment(const std::string& id) {+ auto& db = Database::instance();+ std::lock_guard<std::recursive_mutex> lock(db.mutex());+ // Cascade: delete trades, metrics, signals first+ auto s1 = db.prepare("DELETE FROM algo_trades WHERE deployment_id = ?1");+ s1.bind_text(1, id); s1.execute();+ auto s2 = db.prepare("DELETE FROM algo_metrics WHERE deployment_id = ?1");+ s2.bind_text(1, id); s2.execute();+ auto s3 = db.prepare("DELETE FROM algo_order_signals WHERE deployment_id = ?1");+ s3.bind_text(1, id); s3.execute();+ auto s4 = db.prepare("DELETE FROM algo_deployments WHERE id = ?1");+ s4.bind_text(1, id); s4.execute();+}++// --- Metrics ---++void ops::save_algo_metrics(const algo::AlgoMetrics& m) {+ auto& db = Database::instance();+ std::lock_guard<std::recursive_mutex> lock(db.mutex());+ auto stmt = db.prepare(R"(+ INSERT OR REPLACE INTO algo_metrics+ (deployment_id, total_trades, winning_trades, losing_trades, total_pnl,+ max_drawdown, win_rate, avg_win, avg_loss, sharpe_ratio, updated_at)+ VALUES (?1,?2,?3,?4,?5,?6,?7,?8,?9,?10,CURRENT_TIMESTAMP)+ )");+ stmt.bind_text(1, m.deployment_id);+ stmt.bind_int(2, m.total_trades);+ stmt.bind_int(3, m.winning_trades);+ stmt.bind_int(4, m.losing_trades);+ stmt.bind_double(5, m.total_pnl);+ stmt.bind_double(6, m.max_drawdown);+ stmt.bind_double(7, m.win_rate);+ stmt.bind_double(8, m.avg_win);+ stmt.bind_double(9, m.avg_loss);+ stmt.bind_double(10, m.sharpe_ratio);+ stmt.execute();+}++std::optional<algo::AlgoMetrics> ops::get_algo_metrics(const std::string& deployment_id) {+ auto& db = Database::instance();+ std::lock_guard<std::recursive_mutex> lock(db.mutex());+ auto stmt = db.prepare(+ "SELECT deployment_id, total_trades, winning_trades, losing_trades, total_pnl, "+ "max_drawdown, win_rate, avg_win, avg_loss, sharpe_ratio, updated_at "+ "FROM algo_metrics WHERE deployment_id = ?1");+ stmt.bind_text(1, deployment_id);+ if (!stmt.step()) return std::nullopt;+ algo::AlgoMetrics m;+ m.deployment_id = stmt.col_text(0);+ m.total_trades = (int)stmt.col_int(1);+ m.winning_trades = (int)stmt.col_int(2);+ m.losing_trades = (int)stmt.col_int(3);+ m.total_pnl = stmt.col_double(4);+ m.max_drawdown = stmt.col_double(5);+ m.win_rate = stmt.col_double(6);+ m.avg_win = stmt.col_double(7);+ m.avg_loss = stmt.col_double(8);+ m.sharpe_ratio = stmt.col_double(9);+ m.updated_at = stmt.col_text(10);+ return m;+}++// --- Trades ---++void ops::save_algo_trade(const algo::AlgoTrade& t) {+ auto& db = Database::instance();+ std::lock_guard<std::recursive_mutex> lock(db.mutex());+ auto stmt = db.prepare(R"(+ INSERT OR REPLACE INTO algo_trades+ (id, deployment_id, symbol, side, quantity, price, pnl, fees, order_type, status, executed_at)+ VALUES (?1,?2,?3,?4,?5,?6,?7,?8,?9,?10,?11)+ )");+ stmt.bind_text(1, t.id);+ stmt.bind_text(2, t.deployment_id);+ stmt.bind_text(3, t.symbol);+ stmt.bind_text(4, t.side);+ stmt.bind_double(5, t.quantity);+ stmt.bind_double(6, t.price);+ stmt.bind_double(7, t.pnl);+ stmt.bind_double(8, t.fees);+ stmt.bind_text(9, t.order_type);+ stmt.bind_text(10, t.status);+ stmt.bind_text(11, t.executed_at);+ stmt.execute();+}++std::vector<algo::AlgoTrade> ops::get_algo_trades(const std::string& deployment_id, int limit) {+ auto& db = Database::instance();+ std::lock_guard<std::recursive_mutex> lock(db.mutex());+ auto stmt = db.prepare(+ "SELECT id, deployment_id, symbol, side, quantity, price, pnl, fees, "+ "order_type, status, executed_at FROM algo_trades "+ "WHERE deployment_id = ?1 ORDER BY executed_at DESC LIMIT ?2");+ stmt.bind_text(1, deployment_id);+ stmt.bind_int(2, limit);+ std::vector<algo::AlgoTrade> result;+ while (stmt.step()) {+ algo::AlgoTrade t;+ t.id = stmt.col_text(0);+ t.deployment_id = stmt.col_text(1);+ t.symbol = stmt.col_text(2);+ t.side = stmt.col_text(3);+ t.quantity = stmt.col_double(4);+ t.price = stmt.col_double(5);+ t.pnl = stmt.col_double(6);+ t.fees = stmt.col_double(7);+ t.order_type = stmt.col_text(8);+ t.status = stmt.col_text(9);+ t.executed_at = stmt.col_text(10);+ result.push_back(t);+ }+ return result;+}++// --- Order Signals ---++void ops::save_algo_signal(const algo::AlgoOrderSignal& s) {+ auto& db = Database::instance();+ std::lock_guard<std::recursive_mutex> lock(db.mutex());+ auto stmt = db.prepare(R"(+ INSERT INTO algo_order_signals+ (id, deployment_id, symbol, side, quantity, order_type, price, stop_price, status)+ VALUES (?1,?2,?3,?4,?5,?6,?7,?8,?9)+ )");+ stmt.bind_text(1, s.id);+ stmt.bind_text(2, s.deployment_id);+ stmt.bind_text(3, s.symbol);+ stmt.bind_text(4, s.side);+ stmt.bind_double(5, s.quantity);+ stmt.bind_text(6, s.order_type);+ stmt.bind_double(7, s.price);+ stmt.bind_double(8, s.stop_price);+ stmt.bind_text(9, s.status);+ stmt.execute();+}++std::vector<algo::AlgoOrderSignal> ops::get_pending_signals() {+ auto& db = Database::instance();+ std::lock_guard<std::recursive_mutex> lock(db.mutex());+ auto stmt = db.prepare(+ "SELECT s.id, s.deployment_id, s.symbol, s.side, s.quantity, s.order_type, "+ "s.price, s.stop_price, s.status, s.created_at, s.executed_at, s.error "+ "FROM algo_order_signals s "+ "INNER JOIN algo_deployments d ON s.deployment_id = d.id "+ "WHERE s.status = 'pending' AND d.status = 'running' "+ "ORDER BY s.created_at ASC");+ std::vector<algo::AlgoOrderSignal> result;+ while (stmt.step()) {+ algo::AlgoOrderSignal sig;+ sig.id = stmt.col_text(0);+ sig.deployment_id = stmt.col_text(1);+ sig.symbol = stmt.col_text(2);+ sig.side = stmt.col_text(3);+ sig.quantity = stmt.col_double(4);+ sig.order_type = stmt.col_text(5);+ sig.price = stmt.col_double(6);+ sig.stop_price = stmt.col_double(7);+ sig.status = stmt.col_text(8);+ sig.created_at = stmt.col_text(9);+ sig.executed_at = stmt.col_text(10);+ sig.error = stmt.col_text(11);+ result.push_back(sig);+ }+ return result;+}++void ops::update_signal_status(const std::string& id, const std::string& status,+ const std::string& error) {+ auto& db = Database::instance();+ std::lock_guard<std::recursive_mutex> lock(db.mutex());+ auto stmt = db.prepare(+ "UPDATE algo_order_signals SET status = ?2, error = ?3, "+ "executed_at = CURRENT_TIMESTAMP WHERE id = ?1");+ stmt.bind_text(1, id);+ stmt.bind_text(2, status);+ stmt.bind_text(3, error);+ stmt.execute();+}++// --- Candle Cache ---++void ops::insert_candles(const std::vector<algo::CandleData>& candles) {+ auto& db = Database::instance();+ std::lock_guard<std::recursive_mutex> lock(db.mutex());+ db.begin_transaction();+ try {+ for (auto& c : candles) {+ auto stmt = db.prepare(R"(+ INSERT OR IGNORE INTO candle_cache+ (symbol, timeframe, timestamp, open, high, low, close, volume, provider)+ VALUES (?1,?2,?3,?4,?5,?6,?7,?8,?9)+ )");+ stmt.bind_text(1, c.symbol);+ stmt.bind_text(2, c.timeframe);+ stmt.bind_int(3, c.timestamp);+ stmt.bind_double(4, c.open);+ stmt.bind_double(5, c.high);+ stmt.bind_double(6, c.low);+ stmt.bind_double(7, c.close);+ stmt.bind_double(8, c.volume);+ stmt.bind_text(9, c.provider);+ stmt.execute();+ }+ db.commit();+ } catch (...) {+ db.rollback();+ throw;+ }+}++std::vector<algo::CandleData> ops::get_candle_cache(const std::string& symbol,+ const std::string& timeframe,+ int limit) {+ auto& db = Database::instance();+ std::lock_guard<std::recursive_mutex> lock(db.mutex());+ auto stmt = db.prepare(+ "SELECT symbol, timeframe, timestamp, open, high, low, close, volume, provider "+ "FROM candle_cache WHERE symbol = ?1 AND timeframe = ?2 "+ "ORDER BY timestamp DESC LIMIT ?3");+ stmt.bind_text(1, symbol);+ stmt.bind_text(2, timeframe);+ stmt.bind_int(3, limit);+ std::vector<algo::CandleData> result;+ while (stmt.step()) {+ algo::CandleData c;+ c.symbol = stmt.col_text(0);+ c.timeframe = stmt.col_text(1);+ c.timestamp = stmt.col_int(2);+ c.open = stmt.col_double(3);+ c.high = stmt.col_double(4);+ c.low = stmt.col_double(5);+ c.close = stmt.col_double(6);+ c.volume = stmt.col_double(7);+ c.provider = stmt.col_text(8);+ result.push_back(c);+ }+ return result;+}++int64_t ops::count_candles(const std::string& symbol, const std::string& timeframe) {+ auto& db = Database::instance();+ std::lock_guard<std::recursive_mutex> lock(db.mutex());+ auto stmt = db.prepare(+ "SELECT COUNT(*) FROM candle_cache WHERE symbol = ?1 AND timeframe = ?2");+ stmt.bind_text(1, symbol);+ stmt.bind_text(2, timeframe);+ if (stmt.step()) return stmt.col_int(0);+ return 0;+}++// --- Custom Python Strategies ---++void ops::save_custom_python_strategy(const algo::CustomPythonStrategy& s) {+ auto& db = Database::instance();+ std::lock_guard<std::recursive_mutex> lock(db.mutex());+ auto stmt = db.prepare(R"(+ INSERT OR REPLACE INTO custom_python_strategies+ (id, name, description, code, category, parameters, updated_at)+ VALUES (?1,?2,?3,?4,?5,?6,CURRENT_TIMESTAMP)+ )");+ stmt.bind_text(1, s.id);+ stmt.bind_text(2, s.name);+ stmt.bind_text(3, s.description);+ stmt.bind_text(4, s.code);+ stmt.bind_text(5, s.category);+ stmt.bind_text(6, s.parameters);+ stmt.execute();+}++std::vector<algo::CustomPythonStrategy> ops::list_custom_python_strategies() {+ auto& db = Database::instance();+ std::lock_guard<std::recursive_mutex> lock(db.mutex());+ auto stmt = db.prepare(+ "SELECT id, name, description, code, category, parameters, created_at, updated_at "+ "FROM custom_python_strategies ORDER BY updated_at DESC");+ std::vector<algo::CustomPythonStrategy> result;+ while (stmt.step()) {+ algo::CustomPythonStrategy s;+ s.id = stmt.col_text(0);+ s.name = stmt.col_text(1);+ s.description = stmt.col_text(2);+ s.code = stmt.col_text(3);+ s.category = stmt.col_text(4);+ s.parameters = stmt.col_text(5);+ s.created_at = stmt.col_text(6);+ s.updated_at = stmt.col_text(7);+ result.push_back(s);+ }+ return result;+}++std::optional<algo::CustomPythonStrategy> ops::get_custom_python_strategy(const std::string& id) {+ auto& db = Database::instance();+ std::lock_guard<std::recursive_mutex> lock(db.mutex());+ auto stmt = db.prepare(+ "SELECT id, name, description, code, category, parameters, created_at, updated_at "+ "FROM custom_python_strategies WHERE id = ?1");+ stmt.bind_text(1, id);+ if (!stmt.step()) return std::nullopt;+ algo::CustomPythonStrategy s;+ s.id = stmt.col_text(0);+ s.name = stmt.col_text(1);+ s.description = stmt.col_text(2);+ s.code = stmt.col_text(3);+ s.category = stmt.col_text(4);+ s.parameters = stmt.col_text(5);+ s.created_at = stmt.col_text(6);+ s.updated_at = stmt.col_text(7);+ return s;+}++void ops::delete_custom_python_strategy(const std::string& id) {+ auto& db = Database::instance();+ std::lock_guard<std::recursive_mutex> lock(db.mutex());+ auto stmt = db.prepare("DELETE FROM custom_python_strategies WHERE id = ?1");+ stmt.bind_text(1, id);+ stmt.execute();+}++// --- Price Cache ---++void ops::update_price_cache(const std::string& symbol, double price,+ double volume, double change_pct) {+ auto& db = Database::instance();+ std::lock_guard<std::recursive_mutex> lock(db.mutex());+ auto stmt = db.prepare(R"(+ INSERT OR REPLACE INTO strategy_price_cache+ (symbol, price, volume, change_pct, updated_at)+ VALUES (?1,?2,?3,?4,CURRENT_TIMESTAMP)+ )");+ stmt.bind_text(1, symbol);+ stmt.bind_double(2, price);+ stmt.bind_double(3, volume);+ stmt.bind_double(4, change_pct);+ stmt.execute();+}++std::vector<algo::PriceCacheEntry> ops::get_price_cache_entries() {+ auto& db = Database::instance();+ std::lock_guard<std::recursive_mutex> lock(db.mutex());+ auto stmt = db.prepare(+ "SELECT symbol, price, volume, change_pct, updated_at FROM strategy_price_cache");+ std::vector<algo::PriceCacheEntry> result;+ while (stmt.step()) {+ algo::PriceCacheEntry e;+ e.symbol = stmt.col_text(0);+ e.price = stmt.col_double(1);+ e.volume = stmt.col_double(2);+ e.change_pct = stmt.col_double(3);+ e.updated_at = stmt.col_text(4);+ result.push_back(e);+ }+ return result;+}+} // namespace ops} // namespace fincept::dbdiff --git a/fincept-cpp/src/storage/database.h b/fincept-cpp/src/storage/database.hindex aa05f4252..84b9d1125 100644--- a/fincept-cpp/src/storage/database.h+++ b/fincept-cpp/src/storage/database.h@@ -15,6 +15,18 @@#include <mutex>#include <cstdint>+// Forward declarations for algo trading types+namespace fincept::algo {+ struct AlgoStrategy;+ struct AlgoDeployment;+ struct AlgoMetrics;+ struct AlgoTrade;+ struct AlgoOrderSignal;+ struct CandleData;+ struct CustomPythonStrategy;+ struct PriceCacheEntry;+}+struct sqlite3;struct sqlite3_stmt;@@ -251,14 +263,23 @@ struct CacheEntry {int64_t ttl_seconds;int64_t created_at;int64_t expires_at;+ int64_t last_accessed_at;int64_t hit_count;+ int64_t size_bytes;bool is_expired;};+struct CategoryStats {+ std::string category;+ int64_t entry_count;+ int64_t total_size;+};+struct CacheStats {int64_t total_entries;int64_t total_size_bytes;int64_t expired_entries;+ std::vector<CategoryStats> categories;};struct TabSession {@@ -388,10 +409,14 @@ void delete_ma_deal(const std::string& deal_id);// --- Cache (uses CacheDatabase) ---std::optional<CacheEntry> cache_get(const std::string& key);+std::optional<CacheEntry> cache_get_with_stale(const std::string& key);+std::vector<CacheEntry> cache_get_many(const std::vector<std::string>& keys);void cache_set(const std::string& key, const std::string& data,const std::string& category, int64_t ttl_seconds);bool cache_delete(const std::string& key);int64_t cache_invalidate_category(const std::string& category);+int64_t cache_invalidate_pattern(const std::string& pattern);+int64_t cache_evict_lru(int64_t count);int64_t cache_cleanup();CacheStats cache_stats();void cache_clear_all();@@ -405,6 +430,7 @@ void tab_session_set(const std::string& tab_id, const std::string& tab_name,const std::string& selected_items = "");void tab_session_delete(const std::string& tab_id);std::vector<TabSession> tab_session_get_all();+int64_t tab_session_cleanup(int64_t max_age_days);// --- LLM Model Configs ---std::vector<LLMModelConfig> get_llm_model_configs();@@ -432,6 +458,52 @@ std::vector<Note> search_notes(const std::string& query);void toggle_note_favorite(int64_t id);void archive_note(int64_t id);+// --- Algo Trading: Strategies ---+void save_algo_strategy(const algo::AlgoStrategy& s);+std::vector<algo::AlgoStrategy> list_algo_strategies();+std::optional<algo::AlgoStrategy> get_algo_strategy(const std::string& id);+void delete_algo_strategy(const std::string& id);++// --- Algo Trading: Deployments ---+void save_algo_deployment(const algo::AlgoDeployment& d);+std::vector<algo::AlgoDeployment> list_algo_deployments();+std::optional<algo::AlgoDeployment> get_algo_deployment(const std::string& id);+void update_algo_deployment_status(const std::string& id, const std::string& status,+ const std::string& error = "");+void delete_algo_deployment(const std::string& id);++// --- Algo Trading: Metrics ---+void save_algo_metrics(const algo::AlgoMetrics& m);+std::optional<algo::AlgoMetrics> get_algo_metrics(const std::string& deployment_id);++// --- Algo Trading: Trades ---+void save_algo_trade(const algo::AlgoTrade& t);+std::vector<algo::AlgoTrade> get_algo_trades(const std::string& deployment_id, int limit = 100);++// --- Algo Trading: Order Signals ---+void save_algo_signal(const algo::AlgoOrderSignal& s);+std::vector<algo::AlgoOrderSignal> get_pending_signals();+void update_signal_status(const std::string& id, const std::string& status,+ const std::string& error = "");++// --- Algo Trading: Candle Cache ---+void insert_candles(const std::vector<algo::CandleData>& candles);+std::vector<algo::CandleData> get_candle_cache(const std::string& symbol,+ const std::string& timeframe,+ int limit = 500);+int64_t count_candles(const std::string& symbol, const std::string& timeframe);++// --- Algo Trading: Custom Python Strategies ---+void save_custom_python_strategy(const algo::CustomPythonStrategy& s);+std::vector<algo::CustomPythonStrategy> list_custom_python_strategies();+std::optional<algo::CustomPythonStrategy> get_custom_python_strategy(const std::string& id);+void delete_custom_python_strategy(const std::string& id);++// --- Algo Trading: Price Cache ---+void update_price_cache(const std::string& symbol, double price,+ double volume, double change_pct);+std::vector<algo::PriceCacheEntry> get_price_cache_entries();+} // namespace ops// ============================================================================diff --git a/fincept-cpp/src/trading/broker_interface.h b/fincept-cpp/src/trading/broker_interface.hnew file mode 100644index 000000000..085ee398a--- /dev/null+++ b/fincept-cpp/src/trading/broker_interface.h@@ -0,0 +1,61 @@+#pragma once+// Broker Interface — abstract base class for all 16 broker integrations+// Each broker implements auth, orders, portfolio, market data via HTTP REST APIs.++#include "broker_types.h"+#include <memory>++namespace fincept::trading {++class IBroker {+public:+ virtual ~IBroker() = default;++ // Identity+ virtual BrokerId id() const = 0;+ virtual const char* name() const = 0;+ virtual const char* base_url() const = 0;++ // --- Authentication ---+ virtual TokenExchangeResponse exchange_token(const std::string& api_key,+ const std::string& api_secret,+ const std::string& auth_code) = 0;++ // --- Orders ---+ virtual OrderPlaceResponse place_order(const BrokerCredentials& creds,+ const UnifiedOrder& order) = 0;+ virtual ApiResponse<json> modify_order(const BrokerCredentials& creds,+ const std::string& order_id,+ const json& modifications) = 0;+ virtual ApiResponse<json> cancel_order(const BrokerCredentials& creds,+ const std::string& order_id) = 0;+ virtual ApiResponse<std::vector<BrokerOrderInfo>> get_orders(const BrokerCredentials& creds) = 0;+ virtual ApiResponse<json> get_trade_book(const BrokerCredentials& creds) = 0;++ // --- Portfolio ---+ virtual ApiResponse<std::vector<BrokerPosition>> get_positions(const BrokerCredentials& creds) = 0;+ virtual ApiResponse<std::vector<BrokerHolding>> get_holdings(const BrokerCredentials& creds) = 0;+ virtual ApiResponse<BrokerFunds> get_funds(const BrokerCredentials& creds) = 0;++ // --- Market Data ---+ virtual ApiResponse<std::vector<BrokerQuote>> get_quotes(const BrokerCredentials& creds,+ const std::vector<std::string>& symbols) = 0;+ virtual ApiResponse<std::vector<BrokerCandle>> get_history(const BrokerCredentials& creds,+ const std::string& symbol,+ const std::string& resolution,+ const std::string& from_date,+ const std::string& to_date) = 0;++ // --- Credential helpers ---+ // Load credentials from DB for this broker+ BrokerCredentials load_credentials() const;+ void save_credentials(const BrokerCredentials& creds) const;++protected:+ // HTTP helper: build auth headers for this broker+ virtual std::map<std::string, std::string> auth_headers(const BrokerCredentials& creds) const = 0;+};++using BrokerPtr = std::unique_ptr<IBroker>;++} // namespace fincept::tradingdiff --git a/fincept-cpp/src/trading/broker_registry.cpp b/fincept-cpp/src/trading/broker_registry.cppnew file mode 100644index 000000000..5e65dcb4c--- /dev/null+++ b/fincept-cpp/src/trading/broker_registry.cpp@@ -0,0 +1,98 @@+#include "broker_registry.h"+#include "broker_interface.h"+#include "brokers/fyers_broker.h"+#include "brokers/generic_broker.h"+#include "storage/database.h"++namespace fincept::trading {++// ============================================================================+// IBroker credential helpers — load/save from existing DB credential system+// ============================================================================++BrokerCredentials IBroker::load_credentials() const {+ BrokerCredentials creds;+ creds.broker_id = broker_id_str(id());+ auto opt = db::ops::get_credential_by_service(creds.broker_id);+ if (opt) {+ creds.api_key = opt->api_key.value_or("");+ creds.api_secret = opt->api_secret.value_or("");+ creds.access_token = opt->password.value_or(""); // stored in password field+ creds.user_id = opt->username.value_or("");+ creds.additional_data = opt->additional_data.value_or("");+ }+ return creds;+}++void IBroker::save_credentials(const BrokerCredentials& creds) const {+ db::Credential c;+ c.service_name = creds.broker_id;+ c.api_key = creds.api_key;+ c.api_secret = creds.api_secret;+ c.password = creds.access_token; // store access_token in password field+ c.username = creds.user_id;+ c.additional_data = creds.additional_data;+ db::ops::save_credential(c);+}++// ============================================================================+// BrokerRegistry+// ============================================================================++BrokerRegistry& BrokerRegistry::instance() {+ static BrokerRegistry reg;+ return reg;+}++BrokerRegistry::BrokerRegistry() {+ register_all();+}++void BrokerRegistry::register_all() {+ // Fyers — fully implemented+ brokers_["fyers"] = std::make_unique<FyersBroker>();++ // Stub brokers — registered with GenericBroker defaults+ // Indian+ brokers_["zerodha"] = std::make_unique<ZerodhaBroker>();+ brokers_["upstox"] = std::make_unique<UpstoxBroker>();+ brokers_["dhan"] = std::make_unique<DhanBroker>();+ brokers_["kotak"] = std::make_unique<KotakBroker>();+ brokers_["groww"] = std::make_unique<GrowwBroker>();+ brokers_["aliceblue"] = std::make_unique<AliceBlueBroker>();+ brokers_["angelone"] = std::make_unique<AngelOneBroker>();+ brokers_["fivepaisa"] = std::make_unique<FivePaisaBroker>();+ brokers_["iifl"] = std::make_unique<IIFLBroker>();+ brokers_["motilal"] = std::make_unique<MotilalBroker>();+ brokers_["shoonya"] = std::make_unique<ShoonyaBroker>();++ // US+ brokers_["alpaca"] = std::make_unique<AlpacaBroker>();+ brokers_["ibkr"] = std::make_unique<IBKRBroker>();+ brokers_["tradier"] = std::make_unique<TradierBroker>();++ // EU+ brokers_["saxobank"] = std::make_unique<SaxoBankBroker>();+}++IBroker* BrokerRegistry::get(const std::string& broker_id) const {+ auto it = brokers_.find(broker_id);+ return it != brokers_.end() ? it->second.get() : nullptr;+}++IBroker* BrokerRegistry::get(BrokerId id) const {+ return get(broker_id_str(id));+}++std::vector<std::string> BrokerRegistry::list_brokers() const {+ std::vector<std::string> result;+ result.reserve(brokers_.size());+ for (auto& [key, _] : brokers_) result.push_back(key);+ return result;+}++bool BrokerRegistry::has(const std::string& broker_id) const {+ return brokers_.count(broker_id) > 0;+}++} // namespace fincept::tradingdiff --git a/fincept-cpp/src/trading/broker_registry.h b/fincept-cpp/src/trading/broker_registry.hnew file mode 100644index 000000000..cb977152b--- /dev/null+++ b/fincept-cpp/src/trading/broker_registry.h@@ -0,0 +1,42 @@+#pragma once+// Broker Registry — factory + lookup for all 16 broker implementations+// Usage:+// auto& reg = BrokerRegistry::instance();+// auto* broker = reg.get("fyers");+// auto result = broker->place_order(creds, order);++#include "broker_interface.h"+#include <unordered_map>+#include <memory>++namespace fincept::trading {++class BrokerRegistry {+public:+ static BrokerRegistry& instance();++ // Get a broker by string ID (returns nullptr if not registered)+ IBroker* get(const std::string& broker_id) const;++ // Get a broker by enum ID+ IBroker* get(BrokerId id) const;++ // Get all registered broker IDs+ std::vector<std::string> list_brokers() const;++ // Check if a broker is registered+ bool has(const std::string& broker_id) const;++ BrokerRegistry(const BrokerRegistry&) = delete;+ BrokerRegistry& operator=(const BrokerRegistry&) = delete;++private:+ BrokerRegistry();+ ~BrokerRegistry() = default;++ void register_all();++ std::unordered_map<std::string, BrokerPtr> brokers_;+};++} // namespace fincept::tradingdiff --git a/fincept-cpp/src/trading/broker_types.h b/fincept-cpp/src/trading/broker_types.hnew file mode 100644index 000000000..83e473941--- /dev/null+++ b/fincept-cpp/src/trading/broker_types.h@@ -0,0 +1,247 @@+#pragma once+// Broker Types — common types for all broker integrations+// Mirrors Tauri brokers/common.rs++#include <string>+#include <optional>+#include <vector>+#include <cstdint>+#include <nlohmann/json.hpp>++namespace fincept::trading {++using json = nlohmann::json;++// ============================================================================+// Common Response Types+// ============================================================================++template<typename T>+struct ApiResponse {+ bool success = false;+ std::optional<T> data;+ std::string error;+ int64_t timestamp = 0;+};++struct TokenExchangeResponse {+ bool success = false;+ std::string access_token;+ std::string user_id;+ std::string error;+};++struct OrderPlaceResponse {+ bool success = false;+ std::string order_id;+ std::string error;+};++// ============================================================================+// Broker Credentials (stored in DB via existing Credential system)+// ============================================================================++struct BrokerCredentials {+ std::string broker_id;+ std::string api_key;+ std::string api_secret;+ std::string access_token;+ std::string refresh_token;+ std::string user_id;+ std::string additional_data; // JSON string for broker-specific extras+};++// ============================================================================+// Order Types (unified across brokers)+// ============================================================================++enum class OrderSide { Buy, Sell };+enum class OrderType { Market, Limit, StopLoss, StopLossLimit };+enum class ProductType { Intraday, Delivery, Margin, CoverOrder, BracketOrder };++inline const char* order_side_str(OrderSide s) {+ return s == OrderSide::Buy ? "buy" : "sell";+}++inline const char* order_type_str(OrderType t) {+ switch (t) {+ case OrderType::Market: return "market";+ case OrderType::Limit: return "limit";+ case OrderType::StopLoss: return "stop_loss";+ case OrderType::StopLossLimit: return "stop_loss_limit";+ }+ return "market";+}++inline const char* product_type_str(ProductType p) {+ switch (p) {+ case ProductType::Intraday: return "intraday";+ case ProductType::Delivery: return "delivery";+ case ProductType::Margin: return "margin";+ case ProductType::CoverOrder: return "cover_order";+ case ProductType::BracketOrder: return "bracket_order";+ }+ return "intraday";+}++// ============================================================================+// Unified Order (broker-agnostic)+// ============================================================================++struct UnifiedOrder {+ std::string symbol;+ std::string exchange;+ OrderSide side = OrderSide::Buy;+ OrderType order_type = OrderType::Market;+ double quantity = 0;+ double price = 0; // for limit orders+ double stop_price = 0; // for stop-loss orders+ ProductType product_type = ProductType::Intraday;+ std::string validity = "DAY";+ double stop_loss = 0;+ double take_profit = 0;+};++// ============================================================================+// Position / Holding (returned from brokers)+// ============================================================================++struct BrokerPosition {+ std::string symbol;+ std::string exchange;+ std::string product_type;+ double quantity = 0;+ double avg_price = 0;+ double ltp = 0; // last traded price+ double pnl = 0;+ double day_pnl = 0;+ std::string side; // "buy" or "sell"+};++struct BrokerHolding {+ std::string symbol;+ std::string exchange;+ double quantity = 0;+ double avg_price = 0;+ double ltp = 0;+ double pnl = 0;+ double pnl_pct = 0;+ double invested_value = 0;+ double current_value = 0;+};++// ============================================================================+// Order Info (returned from broker order book)+// ============================================================================++struct BrokerOrderInfo {+ std::string order_id;+ std::string symbol;+ std::string exchange;+ std::string side;+ std::string order_type;+ std::string product_type;+ double quantity = 0;+ double price = 0;+ double trigger_price = 0;+ double filled_qty = 0;+ double avg_price = 0;+ std::string status; // "pending", "filled", "cancelled", "rejected"+ std::string timestamp;+ std::string message;+};++// ============================================================================+// Quote / Market Data+// ============================================================================++struct BrokerQuote {+ std::string symbol;+ double ltp = 0;+ double open = 0;+ double high = 0;+ double low = 0;+ double close = 0;+ double volume = 0;+ double change = 0;+ double change_pct = 0;+ double bid = 0;+ double ask = 0;+ int64_t timestamp = 0;+};++struct BrokerCandle {+ int64_t timestamp = 0;+ double open = 0;+ double high = 0;+ double low = 0;+ double close = 0;+ double volume = 0;+};++// ============================================================================+// Funds / Margin+// ============================================================================++struct BrokerFunds {+ double available_balance = 0;+ double used_margin = 0;+ double total_balance = 0;+ double collateral = 0;+ json raw_data; // broker-specific raw response+};++// ============================================================================+// Broker ID enum+// ============================================================================++enum class BrokerId {+ Fyers, Zerodha, Upstox, Dhan, Kotak, Groww, AliceBlue, AngelOne,+ FivePaisa, IIFL, Motilal, Shoonya, // Indian+ Alpaca, IBKR, Tradier, // US+ SaxoBank // EU+};++inline const char* broker_id_str(BrokerId id) {+ switch (id) {+ case BrokerId::Fyers: return "fyers";+ case BrokerId::Zerodha: return "zerodha";+ case BrokerId::Upstox: return "upstox";+ case BrokerId::Dhan: return "dhan";+ case BrokerId::Kotak: return "kotak";+ case BrokerId::Groww: return "groww";+ case BrokerId::AliceBlue: return "aliceblue";+ case BrokerId::AngelOne: return "angelone";+ case BrokerId::FivePaisa: return "fivepaisa";+ case BrokerId::IIFL: return "iifl";+ case BrokerId::Motilal: return "motilal";+ case BrokerId::Shoonya: return "shoonya";+ case BrokerId::Alpaca: return "alpaca";+ case BrokerId::IBKR: return "ibkr";+ case BrokerId::Tradier: return "tradier";+ case BrokerId::SaxoBank: return "saxobank";+ }+ return "unknown";+}++inline std::optional<BrokerId> parse_broker_id(const std::string& s) {+ if (s == "fyers") return BrokerId::Fyers;+ if (s == "zerodha") return BrokerId::Zerodha;+ if (s == "upstox") return BrokerId::Upstox;+ if (s == "dhan") return BrokerId::Dhan;+ if (s == "kotak") return BrokerId::Kotak;+ if (s == "groww") return BrokerId::Groww;+ if (s == "aliceblue") return BrokerId::AliceBlue;+ if (s == "angelone") return BrokerId::AngelOne;+ if (s == "fivepaisa") return BrokerId::FivePaisa;+ if (s == "iifl") return BrokerId::IIFL;+ if (s == "motilal") return BrokerId::Motilal;+ if (s == "shoonya") return BrokerId::Shoonya;+ if (s == "alpaca") return BrokerId::Alpaca;+ if (s == "ibkr") return BrokerId::IBKR;+ if (s == "tradier") return BrokerId::Tradier;+ if (s == "saxobank") return BrokerId::SaxoBank;+ return std::nullopt;+}++} // namespace fincept::tradingdiff --git a/fincept-cpp/src/trading/brokers/fyers_broker.cpp b/fincept-cpp/src/trading/brokers/fyers_broker.cppnew file mode 100644index 000000000..00cfa9a3f--- /dev/null+++ b/fincept-cpp/src/trading/brokers/fyers_broker.cpp@@ -0,0 +1,454 @@+#include "fyers_broker.h"+#include "http/http_client.h"+#include "core/logger.h"+#include <openssl/sha.h>+#include <sstream>+#include <iomanip>+#include <chrono>++namespace fincept::trading {++using namespace fincept::http;++// ============================================================================+// Auth headers: "Authorization: api_key:access_token"+// ============================================================================++std::map<std::string, std::string> FyersBroker::auth_headers(const BrokerCredentials& creds) const {+ return {+ {"Authorization", creds.api_key + ":" + creds.access_token},+ {"Content-Type", "application/json"},+ {"Accept", "application/json"}+ };+}++// ============================================================================+// Token Exchange — SHA256(api_key:api_secret) as appIdHash+// ============================================================================++TokenExchangeResponse FyersBroker::exchange_token(const std::string& api_key,+ const std::string& api_secret,+ const std::string& auth_code) {+ // Compute SHA256 hash of "api_key:api_secret"+ std::string input = api_key + ":" + api_secret;+ unsigned char hash[SHA256_DIGEST_LENGTH];+ SHA256(reinterpret_cast<const unsigned char*>(input.c_str()), input.size(), hash);++ std::ostringstream ss;+ for (int i = 0; i < SHA256_DIGEST_LENGTH; i++)+ ss << std::hex << std::setfill('0') << std::setw(2) << (int)hash[i];+ std::string app_id_hash = ss.str();++ json payload = {+ {"grant_type", "authorization_code"},+ {"appIdHash", app_id_hash},+ {"code", auth_code}+ };++ auto& client = HttpClient::instance();+ auto resp = client.post_json(std::string(base_url()) + "/api/v3/validate-authcode", payload,+ {{"Content-Type", "application/json"}, {"Accept", "application/json"}});++ TokenExchangeResponse result;+ if (!resp.success) {+ result.error = resp.error;+ return result;+ }++ auto body = resp.json_body();+ if (body.value("s", "") == "ok") {+ result.success = true;+ result.access_token = body.value("access_token", "");+ result.user_id = body.value("user_id", "");+ } else {+ result.error = body.value("message", "Token exchange failed");+ }+ return result;+}++// ============================================================================+// Order Type Mappings+// ============================================================================++int FyersBroker::fyers_order_type(OrderType t) {+ switch (t) {+ case OrderType::Limit: return 1;+ case OrderType::Market: return 2;+ case OrderType::StopLoss: return 3;+ case OrderType::StopLossLimit: return 4;+ }+ return 2;+}++int FyersBroker::fyers_side(OrderSide s) {+ return s == OrderSide::Buy ? 1 : -1;+}++std::string FyersBroker::fyers_product(ProductType p) {+ switch (p) {+ case ProductType::Intraday: return "INTRADAY";+ case ProductType::Delivery: return "CNC";+ case ProductType::Margin: return "MARGIN";+ case ProductType::CoverOrder: return "CO";+ case ProductType::BracketOrder: return "BO";+ }+ return "INTRADAY";+}++// ============================================================================+// Place Order+// ============================================================================++OrderPlaceResponse FyersBroker::place_order(const BrokerCredentials& creds,+ const UnifiedOrder& order) {+ auto headers = auth_headers(creds);+ json payload = {+ {"symbol", order.symbol},+ {"qty", (int)order.quantity},+ {"type", fyers_order_type(order.order_type)},+ {"side", fyers_side(order.side)},+ {"productType", fyers_product(order.product_type)},+ {"validity", order.validity},+ {"offlineOrder", false}+ };++ if (order.order_type == OrderType::Limit || order.order_type == OrderType::StopLossLimit)+ payload["limitPrice"] = order.price;+ if (order.order_type == OrderType::StopLoss || order.order_type == OrderType::StopLossLimit)+ payload["stopPrice"] = order.stop_price;+ if (order.stop_loss > 0) payload["stopLoss"] = order.stop_loss;+ if (order.take_profit > 0) payload["takeProfit"] = order.take_profit;++ auto& client = HttpClient::instance();+ auto resp = client.post_json(std::string(base_url()) + "/api/v3/orders", payload, headers);++ OrderPlaceResponse result;+ if (!resp.success) { result.error = resp.error; return result; }++ auto body = resp.json_body();+ if (body.value("s", "") == "ok") {+ result.success = true;+ result.order_id = body.value("id", "");+ } else {+ result.error = body.value("message", "Order placement failed");+ }+ return result;+}++// ============================================================================+// Modify Order+// ============================================================================++ApiResponse<json> FyersBroker::modify_order(const BrokerCredentials& creds,+ const std::string& order_id,+ const json& modifications) {+ auto headers = auth_headers(creds);+ json payload = modifications;+ payload["id"] = order_id;++ auto& client = HttpClient::instance();+ auto resp = client.put_json(std::string(base_url()) + "/api/v3/orders", payload, headers);++ auto now = std::chrono::system_clock::now().time_since_epoch();+ int64_t ts = std::chrono::duration_cast<std::chrono::seconds>(now).count();++ if (!resp.success)+ return {false, std::nullopt, resp.error, ts};++ auto body = resp.json_body();+ if (body.value("s", "") == "ok")+ return {true, body, "", ts};+ return {false, std::nullopt, body.value("message", "Order modification failed"), ts};+}++// ============================================================================+// Cancel Order+// ============================================================================++ApiResponse<json> FyersBroker::cancel_order(const BrokerCredentials& creds,+ const std::string& order_id) {+ auto headers = auth_headers(creds);+ json payload = {{"id", order_id}};++ auto& client = HttpClient::instance();+ auto resp = client.del(std::string(base_url()) + "/api/v3/orders", payload.dump(), headers);++ auto now = std::chrono::system_clock::now().time_since_epoch();+ int64_t ts = std::chrono::duration_cast<std::chrono::seconds>(now).count();++ if (!resp.success)+ return {false, std::nullopt, resp.error, ts};++ auto body = resp.json_body();+ if (body.value("s", "") == "ok")+ return {true, body, "", ts};+ return {false, std::nullopt, body.value("message", "Order cancellation failed"), ts};+}++// ============================================================================+// Get Orders (order book)+// ============================================================================++ApiResponse<std::vector<BrokerOrderInfo>> FyersBroker::get_orders(const BrokerCredentials& creds) {+ auto headers = auth_headers(creds);+ auto& client = HttpClient::instance();+ auto resp = client.get(std::string(base_url()) + "/api/v3/orders", headers);++ auto now = std::chrono::system_clock::now().time_since_epoch();+ int64_t ts = std::chrono::duration_cast<std::chrono::seconds>(now).count();++ if (!resp.success)+ return {false, std::nullopt, resp.error, ts};++ auto body = resp.json_body();+ if (body.value("s", "") != "ok")+ return {false, std::nullopt, body.value("message", "Failed to fetch orders"), ts};++ std::vector<BrokerOrderInfo> orders;+ auto arr = body.value("orderBook", json::array());+ for (auto& o : arr) {+ BrokerOrderInfo info;+ info.order_id = o.value("id", "");+ info.symbol = o.value("symbol", "");+ info.exchange = o.value("exchange", "");+ info.side = o.value("side", 0) == 1 ? "buy" : "sell";+ info.order_type = std::to_string(o.value("type", 0));+ info.product_type = o.value("productType", "");+ info.quantity = o.value("qty", 0.0);+ info.price = o.value("limitPrice", 0.0);+ info.trigger_price = o.value("stopPrice", 0.0);+ info.filled_qty = o.value("filledQty", 0.0);+ info.avg_price = o.value("tradedPrice", 0.0);+ info.status = std::to_string(o.value("status", 0));+ info.message = o.value("message", "");+ orders.push_back(info);+ }+ return {true, orders, "", ts};+}++// ============================================================================+// Get Trade Book+// ============================================================================++ApiResponse<json> FyersBroker::get_trade_book(const BrokerCredentials& creds) {+ auto headers = auth_headers(creds);+ auto& client = HttpClient::instance();+ auto resp = client.get(std::string(base_url()) + "/api/v3/tradebook", headers);++ auto now = std::chrono::system_clock::now().time_since_epoch();+ int64_t ts = std::chrono::duration_cast<std::chrono::seconds>(now).count();++ if (!resp.success)+ return {false, std::nullopt, resp.error, ts};++ auto body = resp.json_body();+ if (body.value("s", "") == "ok")+ return {true, body.value("tradeBook", json::array()), "", ts};+ return {false, std::nullopt, body.value("message", "Failed to fetch trade book"), ts};+}++// ============================================================================+// Positions+// ============================================================================++ApiResponse<std::vector<BrokerPosition>> FyersBroker::get_positions(const BrokerCredentials& creds) {+ auto headers = auth_headers(creds);+ auto& client = HttpClient::instance();+ auto resp = client.get(std::string(base_url()) + "/api/v3/positions", headers);++ auto now = std::chrono::system_clock::now().time_since_epoch();+ int64_t ts = std::chrono::duration_cast<std::chrono::seconds>(now).count();++ if (!resp.success)+ return {false, std::nullopt, resp.error, ts};++ auto body = resp.json_body();+ if (body.value("s", "") != "ok")+ return {false, std::nullopt, body.value("message", "Failed to fetch positions"), ts};++ std::vector<BrokerPosition> positions;+ auto arr = body.value("netPositions", json::array());+ for (auto& p : arr) {+ BrokerPosition pos;+ pos.symbol = p.value("symbol", "");+ pos.exchange = p.value("exchange", "");+ pos.product_type = p.value("productType", "");+ pos.quantity = p.value("netQty", 0.0);+ pos.avg_price = p.value("netAvg", 0.0);+ pos.ltp = p.value("ltp", 0.0);+ pos.pnl = p.value("pl", 0.0);+ pos.day_pnl = p.value("dayBuyValue", 0.0) - p.value("daySellValue", 0.0);+ pos.side = pos.quantity >= 0 ? "buy" : "sell";+ positions.push_back(pos);+ }+ return {true, positions, "", ts};+}++// ============================================================================+// Holdings+// ============================================================================++ApiResponse<std::vector<BrokerHolding>> FyersBroker::get_holdings(const BrokerCredentials& creds) {+ auto headers = auth_headers(creds);+ auto& client = HttpClient::instance();+ auto resp = client.get(std::string(base_url()) + "/api/v3/holdings", headers);++ auto now = std::chrono::system_clock::now().time_since_epoch();+ int64_t ts = std::chrono::duration_cast<std::chrono::seconds>(now).count();++ if (!resp.success)+ return {false, std::nullopt, resp.error, ts};++ auto body = resp.json_body();+ if (body.value("s", "") != "ok")+ return {false, std::nullopt, body.value("message", "Failed to fetch holdings"), ts};++ std::vector<BrokerHolding> holdings;+ auto arr = body.value("holdings", json::array());+ for (auto& h : arr) {+ BrokerHolding hold;+ hold.symbol = h.value("symbol", "");+ hold.exchange = h.value("exchange", "");+ hold.quantity = h.value("quantity", 0.0);+ hold.avg_price = h.value("costPrice", 0.0);+ hold.ltp = h.value("ltp", 0.0);+ hold.invested_value = hold.quantity * hold.avg_price;+ hold.current_value = hold.quantity * hold.ltp;+ hold.pnl = hold.current_value - hold.invested_value;+ hold.pnl_pct = hold.invested_value > 0 ? (hold.pnl / hold.invested_value) * 100 : 0;+ holdings.push_back(hold);+ }+ return {true, holdings, "", ts};+}++// ============================================================================+// Funds+// ============================================================================++ApiResponse<BrokerFunds> FyersBroker::get_funds(const BrokerCredentials& creds) {+ auto headers = auth_headers(creds);+ auto& client = HttpClient::instance();+ auto resp = client.get(std::string(base_url()) + "/api/v3/funds", headers);++ auto now = std::chrono::system_clock::now().time_since_epoch();+ int64_t ts = std::chrono::duration_cast<std::chrono::seconds>(now).count();++ if (!resp.success)+ return {false, std::nullopt, resp.error, ts};++ auto body = resp.json_body();+ if (body.value("s", "") != "ok")+ return {false, std::nullopt, body.value("message", "Failed to fetch funds"), ts};++ BrokerFunds funds;+ auto fl = body.value("fund_limit", json::array());+ for (auto& item : fl) {+ auto title = item.value("title", "");+ auto val = item.value("equityAmount", 0.0);+ if (title == "Total Balance") funds.total_balance = val;+ else if (title == "Available Balance") funds.available_balance = val;+ else if (title == "Used Margin") funds.used_margin = val;+ }+ funds.raw_data = body;+ return {true, funds, "", ts};+}++// ============================================================================+// Quotes+// ============================================================================++ApiResponse<std::vector<BrokerQuote>> FyersBroker::get_quotes(+ const BrokerCredentials& creds, const std::vector<std::string>& symbols) {+ auto headers = auth_headers(creds);+ std::string syms;+ for (size_t i = 0; i < symbols.size(); i++) {+ if (i > 0) syms += ",";+ syms += symbols[i];+ }++ auto& client = HttpClient::instance();+ auto resp = client.get(std::string(base_url()) + "/data/quotes?symbols=" + syms, headers);++ auto now = std::chrono::system_clock::now().time_since_epoch();+ int64_t ts = std::chrono::duration_cast<std::chrono::seconds>(now).count();++ if (!resp.success)+ return {false, std::nullopt, resp.error, ts};++ auto body = resp.json_body();+ if (body.value("s", "") != "ok")+ return {false, std::nullopt, body.value("message", "Failed to fetch quotes"), ts};++ std::vector<BrokerQuote> quotes;+ auto d_arr = body.value("d", json::array());+ for (auto& item : d_arr) {+ if (item.value("s", "") != "ok") continue;+ auto v = item.value("v", json::object());+ BrokerQuote q;+ q.symbol = v.value("symbol", "");+ q.ltp = v.value("lp", 0.0);+ q.open = v.value("open_price", 0.0);+ q.high = v.value("high_price", 0.0);+ q.low = v.value("low_price", 0.0);+ q.close = v.value("prev_close_price", 0.0);+ q.volume = v.value("volume", 0.0);+ q.change = v.value("ch", 0.0);+ q.change_pct = v.value("chp", 0.0);+ q.bid = v.value("bid", 0.0);+ q.ask = v.value("ask", 0.0);+ q.timestamp = v.value("tt", (int64_t)0);+ quotes.push_back(q);+ }+ return {true, quotes, "", ts};+}++// ============================================================================+// History (OHLCV)+// ============================================================================++ApiResponse<std::vector<BrokerCandle>> FyersBroker::get_history(+ const BrokerCredentials& creds,+ const std::string& symbol,+ const std::string& resolution,+ const std::string& from_date,+ const std::string& to_date) {+ auto headers = auth_headers(creds);++ std::string url = std::string(base_url()) + "/data/history"+ "?symbol=" + symbol ++ "&resolution=" + resolution ++ "&date_format=1" ++ "&range_from=" + from_date ++ "&range_to=" + to_date ++ "&cont_flag=1";++ auto& client = HttpClient::instance();+ auto resp = client.get(url, headers);++ auto now = std::chrono::system_clock::now().time_since_epoch();+ int64_t ts = std::chrono::duration_cast<std::chrono::seconds>(now).count();++ if (!resp.success)+ return {false, std::nullopt, resp.error, ts};++ auto body = resp.json_body();+ if (body.value("s", "") != "ok")+ return {false, std::nullopt, body.value("message", "Failed to fetch history"), ts};++ std::vector<BrokerCandle> candles;+ auto arr = body.value("candles", json::array());+ for (auto& c : arr) {+ if (!c.is_array() || c.size() < 6) continue;+ BrokerCandle candle;+ candle.timestamp = c[0].get<int64_t>();+ candle.open = c[1].get<double>();+ candle.high = c[2].get<double>();+ candle.low = c[3].get<double>();+ candle.close = c[4].get<double>();+ candle.volume = c[5].get<double>();+ candles.push_back(candle);+ }+ return {true, candles, "", ts};+}++} // namespace fincept::tradingdiff --git a/fincept-cpp/src/trading/brokers/fyers_broker.h b/fincept-cpp/src/trading/brokers/fyers_broker.hnew file mode 100644index 000000000..d163ef404--- /dev/null+++ b/fincept-cpp/src/trading/brokers/fyers_broker.h@@ -0,0 +1,54 @@+#pragma once+// Fyers Broker — Indian stock broker integration+// API Base: https://api-t1.fyers.in+// Auth: SHA256(api_key:api_secret) for token exchange, api_key:access_token for requests++#include "trading/broker_interface.h"++namespace fincept::trading {++class FyersBroker : public IBroker {+public:+ BrokerId id() const override { return BrokerId::Fyers; }+ const char* name() const override { return "Fyers"; }+ const char* base_url() const override { return "https://api-t1.fyers.in"; }++ TokenExchangeResponse exchange_token(const std::string& api_key,+ const std::string& api_secret,+ const std::string& auth_code) override;++ OrderPlaceResponse place_order(const BrokerCredentials& creds,+ const UnifiedOrder& order) override;+ ApiResponse<json> modify_order(const BrokerCredentials& creds,+ const std::string& order_id,+ const json& modifications) override;+ ApiResponse<json> cancel_order(const BrokerCredentials& creds,+ const std::string& order_id) override;+ ApiResponse<std::vector<BrokerOrderInfo>> get_orders(const BrokerCredentials& creds) override;+ ApiResponse<json> get_trade_book(const BrokerCredentials& creds) override;++ ApiResponse<std::vector<BrokerPosition>> get_positions(const BrokerCredentials& creds) override;+ ApiResponse<std::vector<BrokerHolding>> get_holdings(const BrokerCredentials& creds) override;+ ApiResponse<BrokerFunds> get_funds(const BrokerCredentials& creds) override;++ ApiResponse<std::vector<BrokerQuote>> get_quotes(const BrokerCredentials& creds,+ const std::vector<std::string>& symbols) override;+ ApiResponse<std::vector<BrokerCandle>> get_history(const BrokerCredentials& creds,+ const std::string& symbol,+ const std::string& resolution,+ const std::string& from_date,+ const std::string& to_date) override;++protected:+ std::map<std::string, std::string> auth_headers(const BrokerCredentials& creds) const override;++private:+ // Fyers order type mapping: Market=2, Limit=1, StopLoss=3, StopLossLimit=4+ static int fyers_order_type(OrderType t);+ // Fyers side mapping: Buy=1, Sell=-1+ static int fyers_side(OrderSide s);+ // Fyers product type mapping+ static std::string fyers_product(ProductType p);+};++} // namespace fincept::tradingdiff --git a/fincept-cpp/src/trading/brokers/generic_broker.h b/fincept-cpp/src/trading/brokers/generic_broker.hnew file mode 100644index 000000000..d435adc11--- /dev/null+++ b/fincept-cpp/src/trading/brokers/generic_broker.h@@ -0,0 +1,107 @@+#pragma once+// Generic Broker — base class with default "not implemented" for all operations+// Concrete brokers override only what they support.+// This lets us register all 16 brokers immediately.++#include "trading/broker_interface.h"+#include <chrono>++namespace fincept::trading {++class GenericBroker : public IBroker {+public:+ TokenExchangeResponse exchange_token(const std::string&, const std::string&,+ const std::string&) override {+ return {false, "", "", "Authentication not implemented for " + std::string(name())};+ }++ OrderPlaceResponse place_order(const BrokerCredentials&, const UnifiedOrder&) override {+ return {false, "", "Order placement not implemented for " + std::string(name())};+ }++ ApiResponse<json> modify_order(const BrokerCredentials&, const std::string&,+ const json&) override {+ return {false, std::nullopt, "Not implemented for " + std::string(name()), now_ts()};+ }++ ApiResponse<json> cancel_order(const BrokerCredentials&, const std::string&) override {+ return {false, std::nullopt, "Not implemented for " + std::string(name()), now_ts()};+ }++ ApiResponse<std::vector<BrokerOrderInfo>> get_orders(const BrokerCredentials&) override {+ return {false, std::nullopt, "Not implemented for " + std::string(name()), now_ts()};+ }++ ApiResponse<json> get_trade_book(const BrokerCredentials&) override {+ return {false, std::nullopt, "Not implemented for " + std::string(name()), now_ts()};+ }++ ApiResponse<std::vector<BrokerPosition>> get_positions(const BrokerCredentials&) override {+ return {false, std::nullopt, "Not implemented for " + std::string(name()), now_ts()};+ }++ ApiResponse<std::vector<BrokerHolding>> get_holdings(const BrokerCredentials&) override {+ return {false, std::nullopt, "Not implemented for " + std::string(name()), now_ts()};+ }++ ApiResponse<BrokerFunds> get_funds(const BrokerCredentials&) override {+ return {false, std::nullopt, "Not implemented for " + std::string(name()), now_ts()};+ }++ ApiResponse<std::vector<BrokerQuote>> get_quotes(const BrokerCredentials&,+ const std::vector<std::string>&) override {+ return {false, std::nullopt, "Not implemented for " + std::string(name()), now_ts()};+ }++ ApiResponse<std::vector<BrokerCandle>> get_history(const BrokerCredentials&,+ const std::string&, const std::string&,+ const std::string&, const std::string&) override {+ return {false, std::nullopt, "Not implemented for " + std::string(name()), now_ts()};+ }++protected:+ std::map<std::string, std::string> auth_headers(const BrokerCredentials&) const override {+ return {};+ }++ static int64_t now_ts() {+ auto now = std::chrono::system_clock::now().time_since_epoch();+ return std::chrono::duration_cast<std::chrono::seconds>(now).count();+ }+};++// ============================================================================+// Macro to define a stub broker in one line+// ============================================================================+#define DEFINE_STUB_BROKER(ClassName, BrokerIdVal, BrokerName, BaseUrl) \+ class ClassName : public GenericBroker { \+ public: \+ BrokerId id() const override { return BrokerIdVal; } \+ const char* name() const override { return BrokerName; } \+ const char* base_url() const override { return BaseUrl; } \+ };++// --- Indian Brokers ---+DEFINE_STUB_BROKER(ZerodhaBroker, BrokerId::Zerodha, "Zerodha", "https://api.kite.trade")+DEFINE_STUB_BROKER(UpstoxBroker, BrokerId::Upstox, "Upstox", "https://api.upstox.com/v2")+DEFINE_STUB_BROKER(DhanBroker, BrokerId::Dhan, "Dhan", "https://api.dhan.co/v2")+DEFINE_STUB_BROKER(KotakBroker, BrokerId::Kotak, "Kotak", "https://tradeapi.kotaksecurities.com")+DEFINE_STUB_BROKER(GrowwBroker, BrokerId::Groww, "Groww", "https://groww.in/api/v1")+DEFINE_STUB_BROKER(AliceBlueBroker, BrokerId::AliceBlue, "AliceBlue", "https://ant.aliceblueonline.com/rest/AliceBlueAPIService/api")+DEFINE_STUB_BROKER(AngelOneBroker, BrokerId::AngelOne, "AngelOne", "https://apiconnect.angelbroking.com")+DEFINE_STUB_BROKER(FivePaisaBroker, BrokerId::FivePaisa, "5Paisa", "https://openapi.5paisa.com")+DEFINE_STUB_BROKER(IIFLBroker, BrokerId::IIFL, "IIFL", "https://ttblaze.iifl.com/apimarketdata/instruments")+DEFINE_STUB_BROKER(MotilalBroker, BrokerId::Motilal, "Motilal", "https://openapi.motilaloswal.com/rest")+DEFINE_STUB_BROKER(ShoonyaBroker, BrokerId::Shoonya, "Shoonya", "https://api.shoonya.com/NorenWClientTP")++// --- US Brokers ---+DEFINE_STUB_BROKER(AlpacaBroker, BrokerId::Alpaca, "Alpaca", "https://paper-api.alpaca.markets/v2")+DEFINE_STUB_BROKER(IBKRBroker, BrokerId::IBKR, "IBKR", "https://localhost:5000/v1")+DEFINE_STUB_BROKER(TradierBroker, BrokerId::Tradier, "Tradier", "https://api.tradier.com/v1")++// --- EU Brokers ---+DEFINE_STUB_BROKER(SaxoBankBroker, BrokerId::SaxoBank, "Saxo Bank", "https://gateway.saxobank.com/openapi")++#undef DEFINE_STUB_BROKER++} // namespace fincept::tradingdiff --git a/fincept-cpp/src/trading/exchange_service.cpp b/fincept-cpp/src/trading/exchange_service.cppindex cda44995a..a366675ea 100644--- a/fincept-cpp/src/trading/exchange_service.cpp+++ b/fincept-cpp/src/trading/exchange_service.cpp@@ -27,6 +27,24 @@ namespace fincept::trading {static const char* TAG = "ExchangeService";+// Null-safe JSON accessors (used throughout; must appear before first use)+using json = nlohmann::json;+static double jdouble(const json& j, const char* key, double def = 0.0) {+ auto it = j.find(key);+ if (it == j.end() || it->is_null()) return def;+ return it->get<double>();+}+static int64_t jint64(const json& j, const char* key, int64_t def = 0) {+ auto it = j.find(key);+ if (it == j.end() || it->is_null()) return def;+ return it->get<int64_t>();+}+static std::string jstr(const json& j, const char* key, const std::string& def = "") {+ auto it = j.find(key);+ if (it == j.end() || it->is_null()) return def;+ return it->get<std::string>();+}+// ============================================================================// Singleton// ============================================================================@@ -365,6 +383,102 @@ json ExchangeService::cancel_order(const std::string& order_id, const std::strin{exchange, order_id, symbol});}+// ============================================================================+// New data fetches — trades, funding rate, open interest, etc.+// ============================================================================++std::vector<TradeData> ExchangeService::fetch_trades(const std::string& symbol, int limit) {+ std::string exchange = get_exchange();+ auto j = call_script("exchange/fetch_trades.py",+ {exchange, symbol, std::to_string(limit)});+ std::vector<TradeData> result;+ for (const auto& t : j["data"]["trades"]) {+ TradeData td;+ td.id = jstr(t, "id");+ td.symbol = symbol;+ td.side = jstr(t, "side");+ td.price = jdouble(t, "price");+ td.amount = jdouble(t, "amount");+ td.cost = jdouble(t, "cost");+ td.timestamp = jint64(t, "timestamp");+ result.push_back(td);+ }+ return result;+}++FundingRateData ExchangeService::fetch_funding_rate(const std::string& symbol) {+ std::string exchange = get_exchange();+ FundingRateData fr;+ try {+ auto j = call_script("exchange/fetch_funding_rate.py", {exchange, symbol});+ auto& d = j["data"];+ fr.symbol = symbol;+ fr.funding_rate = jdouble(d, "funding_rate");+ fr.mark_price = jdouble(d, "mark_price");+ fr.index_price = jdouble(d, "index_price");+ fr.funding_timestamp = jint64(d, "funding_timestamp");+ fr.next_funding_timestamp = jint64(d, "next_funding_timestamp");+ } catch (const std::exception& e) {+ LOG_DEBUG(TAG, "Funding rate not available for %s: %s", symbol.c_str(), e.what());+ }+ return fr;+}++OpenInterestData ExchangeService::fetch_open_interest(const std::string& symbol) {+ std::string exchange = get_exchange();+ OpenInterestData oi;+ try {+ auto j = call_script("exchange/fetch_open_interest.py", {exchange, symbol});+ auto& d = j["data"];+ oi.symbol = symbol;+ oi.open_interest = jdouble(d, "open_interest");+ oi.open_interest_value = jdouble(d, "open_interest_value");+ oi.timestamp = jint64(d, "timestamp");+ } catch (const std::exception& e) {+ LOG_DEBUG(TAG, "Open interest not available for %s: %s", symbol.c_str(), e.what());+ }+ return oi;+}++json ExchangeService::set_leverage(const std::string& symbol, int leverage) {+ std::string exchange = get_exchange();+ return call_script_with_credentials("exchange/set_leverage.py",+ {exchange, symbol, std::to_string(leverage)});+}++json ExchangeService::set_margin_mode(const std::string& symbol, const std::string& mode) {+ std::string exchange = get_exchange();+ return call_script_with_credentials("exchange/set_margin_mode.py",+ {exchange, symbol, mode});+}++json ExchangeService::fetch_positions_live(const std::string& symbol) {+ std::string exchange = get_exchange();+ std::vector<std::string> args = {exchange};+ if (!symbol.empty()) args.push_back(symbol);+ return call_script_with_credentials("exchange/fetch_positions.py", args);+}++json ExchangeService::fetch_open_orders_live(const std::string& symbol) {+ std::string exchange = get_exchange();+ std::vector<std::string> args = {exchange};+ if (!symbol.empty()) args.push_back(symbol);+ return call_script_with_credentials("exchange/fetch_open_orders.py", args);+}++json ExchangeService::fetch_my_trades_live(const std::string& symbol, int limit) {+ std::string exchange = get_exchange();+ return call_script_with_credentials("exchange/fetch_my_trades.py",+ {exchange, symbol, std::to_string(limit)});+}++json ExchangeService::fetch_trading_fees(const std::string& symbol) {+ std::string exchange = get_exchange();+ std::vector<std::string> args = {exchange};+ if (!symbol.empty()) args.push_back(symbol);+ return call_script("exchange/fetch_trading_fees.py", args);+}+// ============================================================================// Cache access// ============================================================================@@ -381,26 +495,9 @@ TickerData ExchangeService::get_cached_price(const std::string& symbol) const {}// ============================================================================-// JSON parsing+// JSON parsing (helpers defined at top of file)// ============================================================================-// Null-safe JSON accessors — j.value() throws on null, these return default instead-static double jdouble(const json& j, const char* key, double def = 0.0) {- auto it = j.find(key);- if (it == j.end() || it->is_null()) return def;- return it->get<double>();-}-static int64_t jint64(const json& j, const char* key, int64_t def = 0) {- auto it = j.find(key);- if (it == j.end() || it->is_null()) return def;- return it->get<int64_t>();-}-static std::string jstr(const json& j, const char* key, const std::string& def = "") {- auto it = j.find(key);- if (it == j.end() || it->is_null()) return def;- return it->get<std::string>();-}-TickerData ExchangeService::parse_ticker(const json& j) {TickerData t;t.symbol = jstr(j, "symbol");@@ -559,6 +656,18 @@ void ExchangeService::remove_candle_callback(int id) {candle_callbacks_.erase(id);}+int ExchangeService::on_trade_update(TradeCallback callback) {+ std::lock_guard<std::mutex> lock(mutex_);+ int id = next_callback_id_++;+ trade_callbacks_[id] = std::move(callback);+ return id;+}++void ExchangeService::remove_trade_callback(int id) {+ std::lock_guard<std::mutex> lock(mutex_);+ trade_callbacks_.erase(id);+}+// ============================================================================// WebSocket streaming — spawns ws_stream.py subprocess// ============================================================================@@ -570,6 +679,25 @@ void ExchangeService::start_ws_stream(const std::string& primary_symbol,stop_ws_stream();}+ // Save symbols for reconnection+ ws_primary_symbol_ = primary_symbol;+ ws_all_symbols_ = all_symbols;+ ws_reconnect_attempts_ = 0;++ ws_running_ = true;+ ws_connected_ = false;++ ws_spawn_subprocess();++ // Start reader thread+ ws_thread_ = std::thread([this]() {+ LOG_INFO(TAG, "WS reader thread started");+ ws_reader_loop();+ LOG_INFO(TAG, "WS reader thread exited");+ });+}++void ExchangeService::ws_spawn_subprocess() {// Resolve Python and script pathsauto python = python::resolve_python_path("exchange/ws_stream.py");if (python.empty()) {@@ -583,7 +711,6 @@ void ExchangeService::start_ws_stream(const std::string& primary_symbol,return;}- // Build command line: python -u -B ws_stream.py <exchange> <primary> [symbols...]std::string exchange;{std::lock_guard<std::mutex> lock(mutex_);@@ -591,13 +718,12 @@ void ExchangeService::start_ws_stream(const std::string& primary_symbol,}LOG_INFO(TAG, "Starting WS stream: exchange=%s primary=%s symbols=%zu",- exchange.c_str(), primary_symbol.c_str(), all_symbols.size());+ exchange.c_str(), ws_primary_symbol_.c_str(), ws_all_symbols_.size());#ifdef _WIN32- // Build command string- std::string cmd = "\"" + python.string() + "\" -u -B \"" + script.string() + "\" " + exchange + " " + primary_symbol;- for (const auto& s : all_symbols) {- if (s != primary_symbol) {+ std::string cmd = "\"" + python.string() + "\" -u -B \"" + script.string() + "\" " + exchange + " " + ws_primary_symbol_;+ for (const auto& s : ws_all_symbols_) {+ if (s != ws_primary_symbol_) {cmd += " " + s;}}@@ -606,7 +732,6 @@ void ExchangeService::start_ws_stream(const std::string& primary_symbol,sa.nLength = sizeof(sa);sa.bInheritHandle = TRUE;- // Create stdout pipeHANDLE hStdoutRead = nullptr, hStdoutWrite = nullptr;if (!CreatePipe(&hStdoutRead, &hStdoutWrite, &sa, 0)) {LOG_ERROR(TAG, "Failed to create WS stdout pipe");@@ -617,7 +742,7 @@ void ExchangeService::start_ws_stream(const std::string& primary_symbol,STARTUPINFOA si{};si.cb = sizeof(si);si.hStdOutput = hStdoutWrite;- si.hStdError = hStdoutWrite; // merge stderr into stdout for debugging+ si.hStdError = hStdoutWrite;si.dwFlags |= STARTF_USESTDHANDLES;PROCESS_INFORMATION pi{};@@ -627,7 +752,7 @@ void ExchangeService::start_ws_stream(const std::string& primary_symbol,CREATE_NO_WINDOW, nullptr, nullptr, &si, &pi);- CloseHandle(hStdoutWrite); // close write end in parent+ CloseHandle(hStdoutWrite);if (!ok) {LOG_ERROR(TAG, "Failed to spawn ws_stream.py subprocess");@@ -635,15 +760,13 @@ void ExchangeService::start_ws_stream(const std::string& primary_symbol,return;}- // Store handlesws_process_ = pi.hProcess;ws_stdout_rd_ = hStdoutRead;- CloseHandle(pi.hThread); // don't need thread handle+ CloseHandle(pi.hThread);LOG_INFO(TAG, "WS subprocess spawned (PID handle=%p)", ws_process_);#else- // Unix: fork + exec with pipeint pipefd[2];if (pipe(pipefd) < 0) {LOG_ERROR(TAG, "Failed to create WS pipe");@@ -659,13 +782,11 @@ void ExchangeService::start_ws_stream(const std::string& primary_symbol,}if (pid == 0) {- // Child process- close(pipefd[0]); // close read end+ close(pipefd[0]);dup2(pipefd[1], STDOUT_FILENO);dup2(pipefd[1], STDERR_FILENO);close(pipefd[1]);- // Build argvstd::vector<const char*> argv;std::string py_str = python.string();std::string sc_str = script.string();@@ -674,12 +795,11 @@ void ExchangeService::start_ws_stream(const std::string& primary_symbol,argv.push_back("-B");argv.push_back(sc_str.c_str());argv.push_back(exchange.c_str());- argv.push_back(primary_symbol.c_str());+ argv.push_back(ws_primary_symbol_.c_str());- // Store non-primary symbolsstd::vector<std::string> extra;- for (const auto& s : all_symbols) {- if (s != primary_symbol) extra.push_back(s);+ for (const auto& s : ws_all_symbols_) {+ if (s != ws_primary_symbol_) extra.push_back(s);}for (const auto& s : extra) {argv.push_back(s.c_str());@@ -690,23 +810,12 @@ void ExchangeService::start_ws_stream(const std::string& primary_symbol,_exit(1);}- // Parent- close(pipefd[1]); // close write end+ close(pipefd[1]);ws_pid_ = pid;ws_stdout_fd_ = pipefd[0];LOG_INFO(TAG, "WS subprocess spawned (PID=%d)", ws_pid_);#endif-- ws_running_ = true;- ws_connected_ = false;-- // Start reader thread- ws_thread_ = std::thread([this]() {- LOG_INFO(TAG, "WS reader thread started");- ws_reader_loop();- LOG_INFO(TAG, "WS reader thread exited");- });}void ExchangeService::stop_ws_stream() {@@ -817,6 +926,42 @@ void ExchangeService::ws_reader_loop() {#endifws_connected_ = false;++ // Auto-reconnect if WS is still supposed to be running+ if (ws_running_ && ws_reconnect_attempts_ < WS_MAX_RECONNECTS) {+ ws_reconnect_attempts_++;+ LOG_INFO(TAG, "WS disconnected, reconnecting (attempt %d/%d)...",+ ws_reconnect_attempts_.load(), WS_MAX_RECONNECTS);++ // Clean up old handles before respawning+#ifdef _WIN32+ if (ws_process_) {+ CloseHandle((HANDLE)ws_process_);+ ws_process_ = nullptr;+ }+ if (ws_stdout_rd_) {+ CloseHandle((HANDLE)ws_stdout_rd_);+ ws_stdout_rd_ = nullptr;+ }+#else+ if (ws_pid_ > 0) {+ int status;+ waitpid(ws_pid_, &status, WNOHANG);+ ws_pid_ = -1;+ }+ if (ws_stdout_fd_ >= 0) {+ close(ws_stdout_fd_);+ ws_stdout_fd_ = -1;+ }+#endif++ std::this_thread::sleep_for(std::chrono::seconds(5 * ws_reconnect_attempts_.load()));+ ws_spawn_subprocess();++ // Continue reading from the new subprocess+ ws_reader_loop();+ return;+ }}void ExchangeService::handle_ws_message(const json& msg) {@@ -909,6 +1054,49 @@ void ExchangeService::handle_ws_message(const json& msg) {return;}+ if (type == "trade") {+ TradeData td;+ td.id = jstr(msg, "id");+ td.symbol = jstr(msg, "symbol");+ td.side = jstr(msg, "side");+ td.price = jdouble(msg, "price");+ td.amount = jdouble(msg, "amount");+ td.cost = jdouble(msg, "cost");+ td.timestamp = jint64(msg, "timestamp");+ if (td.symbol.empty()) return;++ // Notify trade callbacks+ std::vector<TradeCallback> cbs;+ {+ std::lock_guard<std::mutex> lock(mutex_);+ for (const auto& [_, cb] : trade_callbacks_) cbs.push_back(cb);+ }+ for (const auto& cb : cbs) {+ try { cb(td.symbol, td); }+ catch (const std::exception& e) {+ LOG_ERROR(TAG, "WS trade callback error: %s", e.what());+ }+ }++ // Feed trade to OrderMatcher for more accurate paper fills+ PriceData pd;+ pd.last = td.price;+ pd.bid = (td.side == "sell") ? td.price : 0.0;+ pd.ask = (td.side == "buy") ? td.price : 0.0;+ pd.timestamp = td.timestamp;++ std::unordered_set<std::string> portfolios;+ {+ std::lock_guard<std::mutex> lock(mutex_);+ auto it = watched_.find(td.symbol);+ if (it != watched_.end()) portfolios = it->second;+ }+ for (const auto& pid : portfolios) {+ OrderMatcher::instance().check_orders(td.symbol, pd, pid);+ }+ return;+ }+if (type == "ohlcv") {auto candle_it = msg.find("candle");if (candle_it == msg.end()) return;diff --git a/fincept-cpp/src/trading/exchange_service.h b/fincept-cpp/src/trading/exchange_service.hindex 42f1392bf..c25ee9e5f 100644--- a/fincept-cpp/src/trading/exchange_service.h+++ b/fincept-cpp/src/trading/exchange_service.h@@ -88,6 +88,35 @@ struct ExchangeInfo {bool has_set_leverage = false;};+// Public trade+struct TradeData {+ std::string id;+ std::string symbol;+ std::string side; // "buy" | "sell"+ double price = 0.0;+ double amount = 0.0;+ double cost = 0.0;+ int64_t timestamp = 0;+};++// Funding rate info+struct FundingRateData {+ std::string symbol;+ double funding_rate = 0.0;+ double mark_price = 0.0;+ double index_price = 0.0;+ int64_t funding_timestamp = 0;+ int64_t next_funding_timestamp = 0;+};++// Open interest+struct OpenInterestData {+ std::string symbol;+ double open_interest = 0.0;+ double open_interest_value = 0.0;+ int64_t timestamp = 0;+};+// Credential set for authenticated operationsstruct ExchangeCredentials {std::string api_key;@@ -104,6 +133,9 @@ using OrderBookCallback = std::function<void(const std::string& symbol, const Or// Callback for candle updatesusing CandleCallback = std::function<void(const std::string& symbol, const Candle& candle)>;+// Callback for trade updates (Time & Sales)+using TradeCallback = std::function<void(const std::string& symbol, const TradeData& trade)>;+class ExchangeService {public:static ExchangeService& instance();@@ -127,6 +159,8 @@ public:void remove_orderbook_callback(int id);int on_candle_update(CandleCallback callback);void remove_candle_callback(int id);+ int on_trade_update(TradeCallback callback);+ void remove_trade_callback(int id);// --- WebSocket streaming (real-time via ws_stream.py subprocess) ---void start_ws_stream(const std::string& primary_symbol,@@ -143,6 +177,9 @@ public:int limit = 100);std::vector<MarketInfo> fetch_markets(const std::string& type = "");std::vector<ExchangeInfo> list_exchanges();+ std::vector<TradeData> fetch_trades(const std::string& symbol, int limit = 50);+ FundingRateData fetch_funding_rate(const std::string& symbol);+ OpenInterestData fetch_open_interest(const std::string& symbol);// --- Authenticated operations ---json fetch_balance();@@ -150,6 +187,12 @@ public:const std::string& type, double amount,double price = 0.0);json cancel_order(const std::string& order_id, const std::string& symbol);+ json set_leverage(const std::string& symbol, int leverage);+ json set_margin_mode(const std::string& symbol, const std::string& mode);+ json fetch_positions_live(const std::string& symbol = "");+ json fetch_open_orders_live(const std::string& symbol = "");+ json fetch_my_trades_live(const std::string& symbol, int limit = 50);+ json fetch_trading_fees(const std::string& symbol = "");// --- Cache ---const std::unordered_map<std::string, TickerData>& get_price_cache() const;@@ -190,6 +233,7 @@ private:std::unordered_map<int, PriceUpdateCallback> price_callbacks_;std::unordered_map<int, OrderBookCallback> orderbook_callbacks_;std::unordered_map<int, CandleCallback> candle_callbacks_;+ std::unordered_map<int, TradeCallback> trade_callbacks_;int next_callback_id_ = 1;// Feed thread (polling fallback)@@ -212,6 +256,13 @@ private:std::atomic<bool> ws_running_{false};std::atomic<bool> ws_connected_{false};+ // WS reconnection state+ std::atomic<int> ws_reconnect_attempts_{0};+ static constexpr int WS_MAX_RECONNECTS = 3;+ std::string ws_primary_symbol_;+ std::vector<std::string> ws_all_symbols_;+ void ws_spawn_subprocess(); // internal helper to (re)spawn WS subprocess+mutable std::mutex mutex_;};diff --git a/fincept-cpp/src/trading/unified_trading.cpp b/fincept-cpp/src/trading/unified_trading.cppnew file mode 100644index 000000000..d98c82d12--- /dev/null+++ b/fincept-cpp/src/trading/unified_trading.cpp@@ -0,0 +1,275 @@+#include "unified_trading.h"+#include "paper_trading.h"+#include "storage/database.h"+#include "screens/algo_trading/algo_types.h"+#include "core/logger.h"+#include <thread>+#include <chrono>+#include <unordered_set>++namespace fincept::trading {++UnifiedTrading& UnifiedTrading::instance() {+ static UnifiedTrading ut;+ return ut;+}++// ============================================================================+// Session Management+// ============================================================================++TradingSession UnifiedTrading::init_session(const std::string& broker,+ const std::string& mode,+ const std::string& paper_portfolio_id) {+ std::lock_guard lock(mutex_);++ TradingSession session;+ session.broker = broker;+ session.mode = (mode == "live") ? "live" : "paper";+ session.is_connected = false;++ // For paper mode, ensure portfolio exists or create one+ if (session.mode == "paper") {+ if (!paper_portfolio_id.empty()) {+ session.paper_portfolio_id = paper_portfolio_id;+ } else {+ // Create default paper portfolio+ auto portfolio = pt_create_portfolio(+ broker + " Paper Trading",+ 1000000.0, // 10 lakh INR+ "INR",+ 1.0,+ "cross",+ 0.0003 // 0.03% fee+ );+ session.paper_portfolio_id = portfolio.id;+ }+ }++ session_ = session;+ return session;+}++std::optional<TradingSession> UnifiedTrading::get_session() const {+ std::lock_guard lock(mutex_);+ return session_;+}++TradingSession UnifiedTrading::switch_mode(const std::string& mode) {+ std::lock_guard lock(mutex_);++ if (!session_) {+ // Auto-init if no session+ session_ = TradingSession{};+ session_->broker = "fyers";+ }++ session_->mode = (mode == "live") ? "live" : "paper";++ // Create paper portfolio if switching to paper and none exists+ if (session_->mode == "paper" && session_->paper_portfolio_id.empty()) {+ auto portfolio = pt_create_portfolio(+ session_->broker + " Paper Trading",+ 1000000.0, "INR", 1.0, "cross", 0.0003+ );+ session_->paper_portfolio_id = portfolio.id;+ }++ return *session_;+}++// ============================================================================+// Order Routing+// ============================================================================++UnifiedOrderResponse UnifiedTrading::place_order(const UnifiedOrder& order) {+ std::lock_guard lock(mutex_);++ if (!session_) {+ return {false, "", "No active trading session. Call init_session first.", ""};+ }++ if (session_->mode == "paper") {+ return place_paper_order(*session_, order);+ }+ return place_live_order(*session_, order);+}++UnifiedOrderResponse UnifiedTrading::place_paper_order(const TradingSession& session,+ const UnifiedOrder& order) {+ if (session.paper_portfolio_id.empty()) {+ return {false, "", "No paper portfolio configured", "paper"};+ }++ std::string symbol = order.exchange.empty() ? order.symbol+ : order.exchange + ":" + order.symbol;++ std::string side_str = order_side_str(order.side);+ std::string type_str = order_type_str(order.order_type);++ std::optional<double> price_opt;+ if (order.order_type == OrderType::Market) {+ price_opt = 1000.0; // placeholder for margin calc, filled at market+ } else if (order.price > 0) {+ price_opt = order.price;+ }++ std::optional<double> stop_opt;+ if (order.stop_price > 0) stop_opt = order.stop_price;++ try {+ auto paper_order = pt_place_order(+ session.paper_portfolio_id,+ symbol, side_str, type_str,+ order.quantity, price_opt, stop_opt, false+ );++ // Auto-fill market orders immediately+ if (order.order_type == OrderType::Market) {+ double fill_price = order.price > 0 ? order.price : 1000.0;+ pt_fill_order(paper_order.id, fill_price);+ }++ return {true, paper_order.id, "Paper order placed", "paper"};+ } catch (const std::exception& e) {+ return {false, "", std::string("Paper order failed: ") + e.what(), "paper"};+ }+}++UnifiedOrderResponse UnifiedTrading::place_live_order(const TradingSession& session,+ const UnifiedOrder& order) {+ auto* broker = BrokerRegistry::instance().get(session.broker);+ if (!broker) {+ return {false, "", "Broker not found: " + session.broker, "live"};+ }++ auto creds = broker->load_credentials();+ if (creds.access_token.empty()) {+ return {false, "", "No credentials for " + session.broker + ". Please authenticate.", "live"};+ }++ auto result = broker->place_order(creds, order);+ return {result.success, result.order_id, result.error, "live"};+}++UnifiedOrderResponse UnifiedTrading::cancel_order(const std::string& order_id) {+ std::lock_guard lock(mutex_);++ if (!session_) {+ return {false, "", "No active trading session", ""};+ }++ if (session_->mode == "paper") {+ try {+ pt_cancel_order(order_id);+ return {true, order_id, "Paper order cancelled", "paper"};+ } catch (const std::exception& e) {+ return {false, "", std::string("Cancel failed: ") + e.what(), "paper"};+ }+ }++ // Live cancel+ auto* broker = BrokerRegistry::instance().get(session_->broker);+ if (!broker) return {false, "", "Broker not found", "live"};++ auto creds = broker->load_credentials();+ auto result = broker->cancel_order(creds, order_id);+ return {result.success, order_id, result.error, "live"};+}++// ============================================================================+// Order Bridge — polls pending algo signals and executes them+// ============================================================================++void UnifiedTrading::start_order_bridge() {+ if (bridge_running_.exchange(true)) return; // already running++ bridge_thread_ = std::thread([this]() { bridge_loop(); });+ bridge_thread_.detach();+ LOG_INFO("UnifiedTrading", "Order signal bridge started");+}++void UnifiedTrading::stop_order_bridge() {+ bridge_running_.store(false);+ LOG_INFO("UnifiedTrading", "Order signal bridge stopping");+}++bool UnifiedTrading::is_bridge_running() const {+ return bridge_running_.load();+}++void UnifiedTrading::bridge_loop() {+ while (bridge_running_.load()) {+ try {+ int count = poll_and_execute_signals();+ if (count > 0) {+ LOG_INFO("UnifiedTrading", "Executed %d order signal(s)", count);+ }+ } catch (const std::exception& e) {+ LOG_ERROR("UnifiedTrading", "Bridge error: %s", e.what());+ }+ std::this_thread::sleep_for(std::chrono::seconds(1));+ }+ bridge_running_.store(false);+}++int UnifiedTrading::poll_and_execute_signals() {+ // Get pending signals from DB (only from running deployments)+ auto signals = db::ops::get_pending_signals();+ if (signals.empty()) return 0;++ // Mark as processing+ for (auto& sig : signals) {+ db::ops::update_signal_status(sig.id, "processing");+ }++ std::unordered_set<std::string> processing_symbols;+ int executed = 0;++ for (auto& sig : signals) {+ if (sig.quantity <= 0) continue;++ // Concurrency check: skip duplicate symbols in same batch+ std::string clean_sym = sig.symbol;+ auto colon = clean_sym.find(':');+ if (colon != std::string::npos)+ clean_sym = clean_sym.substr(colon + 1);+ if (!processing_symbols.insert(clean_sym).second) {+ // Reset to pending for next cycle+ db::ops::update_signal_status(sig.id, "pending");+ continue;+ }++ // Parse exchange from symbol+ std::string exchange = "NSE";+ std::string symbol = sig.symbol;+ if (auto pos = sig.symbol.find(':'); pos != std::string::npos) {+ exchange = sig.symbol.substr(0, pos);+ symbol = sig.symbol.substr(pos + 1);+ }++ // Build order+ UnifiedOrder order;+ order.symbol = symbol;+ order.exchange = exchange;+ order.side = (sig.side == "buy") ? OrderSide::Buy : OrderSide::Sell;+ order.order_type = (sig.order_type == "limit") ? OrderType::Limit : OrderType::Market;+ order.quantity = sig.quantity;+ order.price = sig.price;+ order.stop_price = sig.stop_price;+ order.product_type = ProductType::Intraday;++ // Execute via unified trading+ auto result = place_order(order);++ std::string status = result.success ? "filled" : "failed";+ std::string error = result.success ? "" : result.message;+ db::ops::update_signal_status(sig.id, status, error);++ if (result.success) executed++;+ }++ return executed;+}++} // namespace fincept::tradingdiff --git a/fincept-cpp/src/trading/unified_trading.h b/fincept-cpp/src/trading/unified_trading.hnew file mode 100644index 000000000..ca46ddbdc--- /dev/null+++ b/fincept-cpp/src/trading/unified_trading.h@@ -0,0 +1,82 @@+#pragma once+// Unified Trading — routes orders to live broker or paper trading engine+// Mirrors: unified_trading.rs from the Tauri app+//+// Usage:+// auto& ut = UnifiedTrading::instance();+// ut.init_session("fyers", "paper");+// auto result = ut.place_order(order);++#include "broker_types.h"+#include "broker_registry.h"+#include <mutex>+#include <optional>+#include <atomic>++namespace fincept::trading {++// ============================================================================+// Trading Session+// ============================================================================++struct TradingSession {+ std::string broker;+ std::string mode; // "live" or "paper"+ std::string paper_portfolio_id;+ bool is_connected = false;+};++struct UnifiedOrderResponse {+ bool success = false;+ std::string order_id;+ std::string message;+ std::string mode; // "live" or "paper"+};++// ============================================================================+// Unified Trading Service+// ============================================================================++class UnifiedTrading {+public:+ static UnifiedTrading& instance();++ // Session management+ TradingSession init_session(const std::string& broker, const std::string& mode,+ const std::string& paper_portfolio_id = "");+ std::optional<TradingSession> get_session() const;+ TradingSession switch_mode(const std::string& mode);++ // Order routing — dispatches to paper or live broker+ UnifiedOrderResponse place_order(const UnifiedOrder& order);+ UnifiedOrderResponse cancel_order(const std::string& order_id);++ // Order bridge for algo trading — polls pending signals and executes+ void start_order_bridge();+ void stop_order_bridge();+ bool is_bridge_running() const;++ UnifiedTrading(const UnifiedTrading&) = delete;+ UnifiedTrading& operator=(const UnifiedTrading&) = delete;++private:+ UnifiedTrading() = default;++ UnifiedOrderResponse place_paper_order(const TradingSession& session,+ const UnifiedOrder& order);+ UnifiedOrderResponse place_live_order(const TradingSession& session,+ const UnifiedOrder& order);++ // Order bridge loop+ void bridge_loop();+ int poll_and_execute_signals();++ std::optional<TradingSession> session_;+ mutable std::mutex mutex_;++ // Order bridge+ std::atomic<bool> bridge_running_{false};+ std::thread bridge_thread_;+};++} // namespace fincept::tradingdiff --git a/fincept-cpp/vcpkg.json b/fincept-cpp/vcpkg.jsonindex d3d24262b..a98a2f019 100644--- a/fincept-cpp/vcpkg.json+++ b/fincept-cpp/vcpkg.json@@ -10,7 +10,7 @@"openssl",{"name": "imgui",- "features": ["glfw-binding", "opengl3-binding", "docking-experimental"]+ "features": ["glfw-binding", "opengl3-binding", "docking-experimental", "freetype", "wchar32"]},"yoga","stb",