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
Add untracked source files and fix gitignore blocking src/python
tilakpatel22542c881c169f
diff --git a/.gitignore b/.gitignoreindex 0959661ee..a23bd32b8 100644--- a/.gitignore+++ b/.gitignore@@ -158,22 +158,22 @@ fincept-terminal-desktop/src-tauri/resources/bun/# ============================================================# Legacy and deprecated# ============================================================-legacy-python-depreciated-legacy-python-depreciated/python-python-cmder-reqgen.py-treeview.py-testing-fincept_terminal/backup_20250730_072611-fincept_terminal_structure.txt-launcher.cpp-te-fincept.bat-pdm.lock-upx.exe-fincept_icon.ico-setup.iss-temp-tempdist-nul+/legacy-python-depreciated+/legacy-python-depreciated/python+/python+/cmder+/reqgen.py+/treeview.py+/testing+/fincept_terminal/backup_20250730_072611+/fincept_terminal_structure.txt+/launcher.cpp+/te+/fincept.bat+/pdm.lock+/upx.exe+/fincept_icon.ico+/setup.iss+/temp+/tempdist+/nuldiff --git a/fincept-cpp/.gitignore b/fincept-cpp/.gitignoreindex 6fa3ccd59..34e298eac 100644--- a/fincept-cpp/.gitignore+++ b/fincept-cpp/.gitignore@@ -1,5 +1,6 @@# Buildbuild/+build-msvc/cmake-build-*/out/@@ -12,6 +13,11 @@ out/*.sln*.vcxproj*compile_commands.json+.clangd++# Claude / MCP local config+.claude-flow/+.mcp.json# ImGui layout statefincept_imgui.ini@@ -29,3 +35,6 @@ third_party/# Debug artifacts*.logstderr_out.txt++# Temporary files+tmp/diff --git a/fincept-cpp/CMakeLists.txt b/fincept-cpp/CMakeLists.txtindex 3d6d6e468..cc10cb7a8 100644--- a/fincept-cpp/CMakeLists.txt+++ b/fincept-cpp/CMakeLists.txt@@ -287,6 +287,12 @@ set(SOURCESsrc/screens/data_mapping/data_mapping_db.cppsrc/screens/data_mapping/data_mapping_screen.cpp+ # Screens — Screener (FRED Economic Data)+ src/screens/screener/screener_screen.cpp++ # Screens — Equity Trading+ src/screens/equity_trading/equity_trading_screen.cpp+# Core (continued)src/core/device_id.cpp)diff --git a/fincept-cpp/src/app.cpp b/fincept-cpp/src/app.cppindex bed38c427..173c2e282 100644--- a/fincept-cpp/src/app.cpp+++ b/fincept-cpp/src/app.cpp@@ -10,6 +10,9 @@#include <imgui.h>#include <ctime>#include <cstdio>+#include <string>+#include <algorithm>+#include <cctype>namespace fincept {@@ -113,12 +116,14 @@ void App::render_top_bar() {if (ImGui::MenuItem("DBnomics")) { active_tab_ = 18; }if (ImGui::MenuItem("Data Sources")) { active_tab_ = 20; }if (ImGui::MenuItem("Data Mapping")) { active_tab_ = 28; }+ if (ImGui::MenuItem("Screener")) { active_tab_ = 29; }ImGui::Spacing();// ── Trading & Portfolio ──ImGui::TextColored(ACCENT, "Trading & Portfolio");ImGui::Separator();+ if (ImGui::MenuItem("Equity Trading")) { active_tab_ = 30; }if (ImGui::MenuItem("Crypto Trading", "F9")) { active_tab_ = 2; }if (ImGui::MenuItem("Portfolio", "F4")) { active_tab_ = 3; }if (ImGui::MenuItem("Backtesting", "F5")) { active_tab_ = 6; }@@ -176,31 +181,70 @@ void App::render_top_bar() {ImGui::EndMenu();}- // === CENTER: DateTime | Version | Brand ===+ // === CENTER: Command Bar | DateTime | Version | Brand ==={time_t now = time(nullptr);struct tm* t = localtime(&now);char datetime[32];- std::strftime(datetime, sizeof(datetime), "%Y-%m-%d %H:%M:%S", t);+ std::strftime(datetime, sizeof(datetime), "%H:%M:%S", t);char ver_str[16];std::snprintf(ver_str, sizeof(ver_str), "v%s", config::APP_VERSION);- const char* brand = "FINCEPT TERMINAL";+ const char* brand = "FINCEPT";- float dt_w = ImGui::CalcTextSize(datetime).x;- float pipe_w = ImGui::CalcTextSize("|").x;float sp = 6.0f;+ float pipe_w = ImGui::CalcTextSize("|").x;float sep_w = pipe_w + sp * 2;+ float cmd_input_w = 180.0f;+ float dt_w = ImGui::CalcTextSize(datetime).x;float ver_w = ImGui::CalcTextSize(ver_str).x;float brand_w = ImGui::CalcTextSize(brand).x;- float center_total = dt_w + sep_w + ver_w + sep_w + brand_w;+ float center_total = cmd_input_w + sep_w + dt_w + sep_w + ver_w + sep_w + brand_w;float window_w = ImGui::GetWindowWidth();float center_x = (window_w - center_total) * 0.5f;float cursor_x = ImGui::GetCursorPosX();- if (center_x > cursor_x) ImGui::SameLine(center_x);- else ImGui::SameLine();+ if (center_x > cursor_x) {+ ImGui::SameLine(center_x);+ } else {+ ImGui::SameLine();+ }+ // Command bar input+ ImGui::PushItemWidth(cmd_input_w);+ ImGui::PushStyleColor(ImGuiCol_FrameBg, ImVec4(0.06f, 0.06f, 0.06f, 1.0f));+ ImGui::PushStyleColor(ImGuiCol_FrameBgHovered, ImVec4(0.10f, 0.10f, 0.10f, 1.0f));+ ImGui::PushStyleColor(ImGuiCol_FrameBgActive, ImVec4(0.08f, 0.05f, 0.0f, 1.0f));+ ImGui::PushStyleColor(ImGuiCol_Text, TEXT_PRIMARY);+ ImGui::PushStyleColor(ImGuiCol_Border, BORDER_DIM);+ ImGui::PushStyleVar(ImGuiStyleVar_FramePadding, ImVec2(6, 2));+ ImGui::PushStyleVar(ImGuiStyleVar_FrameBorderSize, 1.0f);+ ImGui::PushStyleVar(ImGuiStyleVar_FrameRounding, 3.0f);++ // Ctrl+K shortcut to focus the command bar+ if (ImGui::IsKeyPressed(ImGuiKey_K) &&+ ImGui::GetIO().KeyCtrl && !cmd_focused_) {+ ImGui::SetKeyboardFocusHere();+ cmd_buf_[0] = '\0';+ }++ bool was_active = cmd_focused_;+ ImGui::InputTextWithHint("##cmd_bar", "> Search tabs... (Ctrl+K)",+ cmd_buf_, sizeof(cmd_buf_));+ cmd_focused_ = ImGui::IsItemActive() || ImGui::IsItemFocused();++ // If just focused, reset selection+ if (cmd_focused_ && !was_active) {+ cmd_selected_ = 0;+ }++ ImGui::PopStyleVar(3);+ ImGui::PopStyleColor(5);+ ImGui::PopItemWidth();++ ImGui::SameLine(0, sp);+ ImGui::TextColored(BORDER_BRIGHT, "|");+ ImGui::SameLine(0, sp);ImGui::TextColored(TEXT_DIM, "%s", datetime);ImGui::SameLine(0, sp);ImGui::TextColored(BORDER_BRIGHT, "|");@@ -393,6 +437,291 @@ void App::render_tab_bar() {// =============================================================================// Footer / Status Bar// =============================================================================+// =============================================================================+// Command Bar — autocomplete dropdown (rendered as a floating window)+// =============================================================================+void App::render_command_bar() {+ using namespace theme::colors;++ // Track dropdown visibility: show when focused, keep showing briefly to allow clicks+ static bool dropdown_visible = false;+ static int hide_countdown = 0; // frames to keep visible after losing focus++ if (cmd_focused_) {+ dropdown_visible = true;+ hide_countdown = 0;+ } else if (dropdown_visible) {+ // Keep visible for a few frames so click events on dropdown items register+ hide_countdown++;+ if (hide_countdown > 3) {+ dropdown_visible = false;+ hide_countdown = 0;+ }+ }++ if (!dropdown_visible) return;++ // Navigation command registry — matches Tauri app's commandRegistry.ts+ struct CmdEntry {+ const char* name;+ const char* aliases; // space-separated search keywords+ const char* category;+ const char* shortcut; // nullable+ int tab_idx;+ };+ static constexpr CmdEntry commands[] = {+ // Primary+ {"Dashboard", "dash home main overview", "Navigation", "F1", 0},+ {"Markets", "mkts markets market live stocks quotes", "Navigation", "F2", 1},+ {"Crypto Trading", "trade trading crypto kraken", "Navigation", "F9", 2},+ {"Portfolio", "port portfolio pf holdings positions", "Navigation", "F4", 3},+ {"News", "news headlines feed articles", "Navigation", "F3", 4},+ {"AI Chat", "ai chat assistant bot", "Navigation", "F10", 5},+ {"Backtesting", "bktest backtest bt strategy", "Navigation", "F5", 6},+ {"Algo Trading", "algo algorithmic automated", "Tools", nullptr, 7},+ {"Node Editor", "nodes workflow visual editor", "Tools", nullptr, 8},+ {"Code Editor", "code editor dev programming", "Tools", nullptr, 9},+ {"AI Quant Lab", "quantlab quant lab ml", "Tools", nullptr, 10},+ {"QuantLib", "quantlib qlcore finance math", "Tools", nullptr, 11},+ {"Settings", "settings preferences config options", "System", nullptr, 12},+ {"Profile", "prof profile account user", "Navigation", "F12", 13},+ // Secondary+ {"Surface Analytics", "surface volsurface vol volatility 3d", "Research", "F6", 14},+ {"Geopolitics", "geo geopolitics politics global", "Research", "F7", 15},+ {"Watchlist", "watch watchlist wl favorites monitor", "Navigation", "F8", 16},+ {"Economics", "econ economics indicators macro", "Data", nullptr, 17},+ {"DBnomics", "dbn dbnomics database economic", "Data", nullptr, 18},+ {"Notes", "notes note reports docs write", "Tools", nullptr, 19},+ {"Data Sources", "datasrc datasources sources api", "Data", nullptr, 20},+ {"M&A Analytics", "ma mna mergers acquisitions deal", "Research", nullptr, 21},+ {"Forum", "forum community discuss posts", "Community", nullptr, 22},+ {"Documentation", "docs help manual guide", "Community", nullptr, 23},+ {"Support", "support ticket tickets help", "Community", nullptr, 24},+ {"About", "about info version credits", "System", nullptr, 25},+ {"Govt Data", "govt gov government treasury", "Data", nullptr, 26},+ {"Agent Studio", "agents config agent studio", "Tools", nullptr, 27},+ {"Data Mapping", "datamap mapping schema transform", "Tools", nullptr, 28},+ {"Screener", "screener fred economic data series", "Data", nullptr, 29},+ {"Equity Trading", "equity stock trading broker nse bse", "Trading", nullptr, 30},+ };+ constexpr int n_cmds = sizeof(commands) / sizeof(commands[0]);++ // Build query string+ std::string query(cmd_buf_);+ for (auto& c : query) c = static_cast<char>(std::tolower(static_cast<unsigned char>(c)));++ // Trim whitespace+ while (!query.empty() && query.back() == ' ') query.pop_back();+ while (!query.empty() && query.front() == ' ') query.erase(query.begin());++ bool has_query = !query.empty();++ struct Match { int idx; int score; };+ Match matches[n_cmds];+ int n_matches = 0;++ for (int i = 0; i < n_cmds; i++) {+ int score = 0;++ if (!has_query) {+ // No search text — show all, ordered by tab index (primary first)+ score = 1000 - commands[i].tab_idx;+ } else {+ // Check name (case-insensitive)+ std::string name_lower(commands[i].name);+ for (auto& c : name_lower) c = static_cast<char>(std::tolower(static_cast<unsigned char>(c)));++ if (name_lower == query) {+ score = 100; // exact match+ } else if (name_lower.find(query) == 0) {+ score = 90; // prefix match+ } else if (name_lower.find(query) != std::string::npos) {+ score = 80; // substring match+ }++ // Check aliases+ if (score == 0) {+ std::string aliases(commands[i].aliases);+ for (auto& c : aliases) c = static_cast<char>(std::tolower(static_cast<unsigned char>(c)));+ if (aliases.find(query) != std::string::npos) {+ score = 50;+ }+ }+ // Check category+ if (score == 0) {+ std::string cat(commands[i].category);+ for (auto& c : cat) c = static_cast<char>(std::tolower(static_cast<unsigned char>(c)));+ if (cat.find(query) != std::string::npos) {+ score = 20;+ }+ }+ }++ if (score > 0) {+ matches[n_matches++] = {i, score};+ }+ }++ if (n_matches == 0) {+ // Show "No results" message+ ImGuiViewport* vp = ImGui::GetMainViewport();+ float dropdown_w = 380.0f;+ float dropdown_x = vp->WorkPos.x + (vp->WorkSize.x - dropdown_w) * 0.5f;+ float dropdown_y = vp->WorkPos.y - 2;++ ImGui::SetNextWindowPos(ImVec2(dropdown_x, dropdown_y));+ ImGui::SetNextWindowSize(ImVec2(dropdown_w, 0));++ ImGui::PushStyleColor(ImGuiCol_WindowBg, ImVec4(0.05f, 0.05f, 0.05f, 0.97f));+ ImGui::PushStyleColor(ImGuiCol_Border, ACCENT);+ ImGui::PushStyleVar(ImGuiStyleVar_WindowPadding, ImVec2(12, 8));+ ImGui::PushStyleVar(ImGuiStyleVar_WindowBorderSize, 1.0f);+ ImGui::PushStyleVar(ImGuiStyleVar_WindowRounding, 4.0f);++ ImGui::Begin("##cmd_dropdown", nullptr,+ ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_NoResize | ImGuiWindowFlags_NoMove |+ ImGuiWindowFlags_NoScrollbar | ImGuiWindowFlags_AlwaysAutoResize |+ ImGuiWindowFlags_NoFocusOnAppearing | ImGuiWindowFlags_NoBringToFrontOnFocus |+ ImGuiWindowFlags_NoNav);++ ImGui::TextColored(TEXT_DIM, "No matching tabs found for \"%s\"", cmd_buf_);++ ImGui::End();+ ImGui::PopStyleVar(3);+ ImGui::PopStyleColor(2);+ return;+ }++ // Sort by score descending+ std::sort(matches, matches + n_matches,+ [](const Match& a, const Match& b) { return a.score > b.score; });++ // Limit results+ int max_show = has_query ? 10 : 15;+ if (n_matches > max_show) n_matches = max_show;++ // Clamp selection+ if (cmd_selected_ >= n_matches) cmd_selected_ = n_matches - 1;+ if (cmd_selected_ < 0) cmd_selected_ = 0;++ // Handle keyboard navigation (Up/Down/Enter/Escape)+ if (cmd_focused_) {+ if (ImGui::IsKeyPressed(ImGuiKey_DownArrow)) {+ cmd_selected_ = (cmd_selected_ + 1) % n_matches;+ }+ if (ImGui::IsKeyPressed(ImGuiKey_UpArrow)) {+ cmd_selected_ = (cmd_selected_ - 1 + n_matches) % n_matches;+ }+ if (ImGui::IsKeyPressed(ImGuiKey_Enter) || ImGui::IsKeyPressed(ImGuiKey_KeypadEnter)) {+ active_tab_ = commands[matches[cmd_selected_].idx].tab_idx;+ cmd_buf_[0] = '\0';+ cmd_focused_ = false;+ dropdown_visible = false;+ return;+ }+ if (ImGui::IsKeyPressed(ImGuiKey_Escape)) {+ cmd_buf_[0] = '\0';+ cmd_focused_ = false;+ dropdown_visible = false;+ return;+ }+ }++ // Render dropdown window+ ImGuiViewport* vp = ImGui::GetMainViewport();+ float dropdown_w = 380.0f;+ float dropdown_x = vp->WorkPos.x + (vp->WorkSize.x - dropdown_w) * 0.5f;+ float dropdown_y = vp->WorkPos.y - 2; // just below menu bar++ ImGui::SetNextWindowPos(ImVec2(dropdown_x, dropdown_y));+ ImGui::SetNextWindowSize(ImVec2(dropdown_w, 0)); // auto-height++ ImGui::PushStyleColor(ImGuiCol_WindowBg, ImVec4(0.05f, 0.05f, 0.05f, 0.97f));+ ImGui::PushStyleColor(ImGuiCol_Border, ACCENT);+ ImGui::PushStyleVar(ImGuiStyleVar_WindowPadding, ImVec2(4, 4));+ ImGui::PushStyleVar(ImGuiStyleVar_WindowBorderSize, 1.0f);+ ImGui::PushStyleVar(ImGuiStyleVar_WindowRounding, 4.0f);++ ImGui::Begin("##cmd_dropdown", nullptr,+ ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_NoResize | ImGuiWindowFlags_NoMove |+ ImGuiWindowFlags_NoScrollbar | ImGuiWindowFlags_AlwaysAutoResize |+ ImGuiWindowFlags_NoFocusOnAppearing | ImGuiWindowFlags_NoBringToFrontOnFocus |+ ImGuiWindowFlags_NoNav);++ // Header hint+ if (!has_query) {+ ImGui::TextColored(TEXT_DIM, " Type to search or select a tab:");+ ImGui::Spacing();+ }++ for (int i = 0; i < n_matches; i++) {+ auto& cmd = commands[matches[i].idx];+ bool is_selected = (i == cmd_selected_);+ bool is_current = (cmd.tab_idx == active_tab_);++ // Background color for selected/current+ if (is_selected) {+ ImGui::PushStyleColor(ImGuiCol_Header, ImVec4(ACCENT.x * 0.3f, ACCENT.y * 0.3f, ACCENT.z * 0.3f, 1.0f));+ } else if (is_current) {+ ImGui::PushStyleColor(ImGuiCol_Header, ImVec4(ACCENT.x * 0.1f, ACCENT.y * 0.1f, ACCENT.z * 0.1f, 1.0f));+ } else {+ ImGui::PushStyleColor(ImGuiCol_Header, ImVec4(0, 0, 0, 0));+ }+ ImGui::PushStyleColor(ImGuiCol_HeaderHovered, ImVec4(ACCENT.x * 0.2f, ACCENT.y * 0.2f, ACCENT.z * 0.2f, 1.0f));++ // Selectable row+ char label_buf[128];+ std::snprintf(label_buf, sizeof(label_buf), "##cmd_%d", i);+ if (ImGui::Selectable(label_buf, is_selected || is_current, 0, ImVec2(0, 24))) {+ active_tab_ = cmd.tab_idx;+ cmd_buf_[0] = '\0';+ cmd_focused_ = false;+ dropdown_visible = false;+ }++ // Hover updates selection+ if (ImGui::IsItemHovered()) {+ cmd_selected_ = i;+ }++ // Overlay: current-tab marker + name+ ImGui::SameLine(8);+ if (is_current) {+ ImGui::TextColored(ACCENT, ">");+ ImGui::SameLine(0, 4);+ }+ ImGui::TextColored(is_current ? ACCENT : TEXT_PRIMARY, "%s", cmd.name);++ // Right side: shortcut + category+ float tag_x = dropdown_w - 12;+ if (cmd.shortcut) {+ char sk_buf[16];+ std::snprintf(sk_buf, sizeof(sk_buf), "[%s]", cmd.shortcut);+ float sk_w = ImGui::CalcTextSize(sk_buf).x + 4;+ tag_x -= sk_w;+ ImGui::SameLine(tag_x);+ ImGui::TextColored(TEXT_DIM, "%s", sk_buf);+ tag_x -= 4;+ }+ float cat_w = ImGui::CalcTextSize(cmd.category).x + 4;+ tag_x -= cat_w;+ if (tag_x > ImGui::GetCursorPosX() + 20) {+ ImGui::SameLine(tag_x);+ ImGui::TextColored(ImVec4(0.4f, 0.4f, 0.4f, 1.0f), "%s", cmd.category);+ }++ ImGui::PopStyleColor(2);+ }++ // Footer hint+ ImGui::Spacing();+ ImGui::TextColored(TEXT_DIM, " Up/Down to navigate Enter to select Esc to close");++ ImGui::End();+ ImGui::PopStyleVar(3);+ ImGui::PopStyleColor(2);+}+void App::render_footer() {using namespace theme::colors;@@ -548,6 +877,7 @@ void App::render() {if (show_chrome) {render_top_bar();+ render_command_bar();render_tab_bar();}@@ -595,6 +925,8 @@ void App::render() {else if (active_tab_ == 1) markets_screen_.render();else if (active_tab_ == 7) algo_trading_screen_.render();else if (active_tab_ == 28) data_mapping_screen_.render();+ else if (active_tab_ == 29) screener_screen_.render();+ else if (active_tab_ == 30) equity_trading_screen_.render();else dashboard_screen_.render();break;default:diff --git a/fincept-cpp/src/app.h b/fincept-cpp/src/app.hindex fd6560a70..5d6173188 100644--- a/fincept-cpp/src/app.h+++ b/fincept-cpp/src/app.h@@ -38,6 +38,8 @@#include "screens/ai_chat/ai_chat_screen.h"#include "screens/ai_quant_lab/ai_quant_lab_screen.h"#include "screens/data_mapping/data_mapping_screen.h"+#include "screens/screener/screener_screen.h"+#include "screens/equity_trading/equity_trading_screen.h"// Fullscreen toggle (implemented in main.cpp, delegates to Window)void toggle_fullscreen();@@ -97,10 +99,18 @@ private:ai_chat::AIChatScreen ai_chat_screen_;ai_quant_lab::AIQuantLabScreen ai_quant_lab_screen_;data_mapping::DataMappingScreen data_mapping_screen_;+ screener::ScreenerScreen screener_screen_;+ equity_trading::EquityTradingScreen equity_trading_screen_;++ // Command bar state+ char cmd_buf_[128] = {};+ bool cmd_focused_ = false;+ int cmd_selected_ = 0;// Rendering sectionsvoid render_top_bar();void render_tab_bar();+ void render_command_bar();void render_footer();void render_loading();diff --git a/fincept-cpp/src/python/python_runner.cpp b/fincept-cpp/src/python/python_runner.cppnew file mode 100644index 000000000..cb5790140--- /dev/null+++ b/fincept-cpp/src/python/python_runner.cpp@@ -0,0 +1,512 @@+// Python subprocess runner — C++ port of python.rs+// Resolves paths, runs Python scripts, extracts JSON output+// Optimized: cached path resolution, concurrent pipe reads, async API++#include "python_runner.h"+#include "core/logger.h"+#include <sstream>+#include <cstdio>+#include <cstring>+#include <algorithm>+#include <iostream>+#include <mutex>+#include <thread>+#include <unordered_map>++#ifdef _WIN32+#ifndef WIN32_LEAN_AND_MEAN+#define WIN32_LEAN_AND_MEAN+#endif+#ifndef NOMINMAX+#define NOMINMAX+#endif+#include <windows.h>+#include <shlobj.h>+#else+#include <unistd.h>+#include <sys/wait.h>+#include <cstdlib>+#endif++namespace fincept::python {++// ============================================================================+// Path cache — avoid repeated filesystem + subprocess lookups+// ============================================================================++static std::mutex s_path_cache_mutex;+static std::unordered_map<std::string, fs::path> s_python_path_cache;+static fs::path s_install_dir_cache;+static fs::path s_exe_dir_cache;+static bool s_dirs_cached = false;++static void ensure_dir_cache() {+ if (s_dirs_cached) return;+ // These never change during the lifetime of the process+ s_install_dir_cache = get_install_dir();+ s_exe_dir_cache = get_exe_dir();+ s_dirs_cached = true;+}++void clear_path_cache() {+ std::lock_guard<std::mutex> lock(s_path_cache_mutex);+ s_python_path_cache.clear();+ s_dirs_cached = false;+}++// ============================================================================+// Path resolution+// ============================================================================++fs::path get_install_dir() {+#ifdef _WIN32+ char* appdata = nullptr;+ size_t len = 0;+ if (_dupenv_s(&appdata, &len, "APPDATA") == 0 && appdata) {+ fs::path dir = fs::path(appdata) / "com.fincept.terminal";+ free(appdata);+ return dir;+ }+ return fs::path("C:/Users/Default/AppData/Roaming/com.fincept.terminal");+#elif defined(__APPLE__)+ const char* home = getenv("HOME");+ if (home) {+ return fs::path(home) / "Library" / "Application Support" / "com.fincept.terminal";+ }+ return fs::path("/tmp/com.fincept.terminal");+#else+ const char* home = getenv("HOME");+ if (home) {+ return fs::path(home) / ".local" / "share" / "com.fincept.terminal";+ }+ return fs::path("/tmp/com.fincept.terminal");+#endif+}++fs::path get_exe_dir() {+#ifdef _WIN32+ char buf[MAX_PATH];+ GetModuleFileNameA(nullptr, buf, MAX_PATH);+ return fs::path(buf).parent_path();+#elif defined(__APPLE__)+ char buf[4096];+ uint32_t size = sizeof(buf);+ if (_NSGetExecutablePath(buf, &size) == 0) {+ return fs::canonical(buf).parent_path();+ }+ return fs::current_path();+#else+ char buf[4096];+ ssize_t len = readlink("/proc/self/exe", buf, sizeof(buf) - 1);+ if (len > 0) {+ buf[len] = '\0';+ return fs::path(buf).parent_path();+ }+ return fs::current_path();+#endif+}++std::string get_venv_name(const std::string& script) {+ std::string lower = script;+ std::transform(lower.begin(), lower.end(), lower.begin(), ::tolower);++ for (const auto& keyword : NUMPY1_SCRIPTS) {+ std::istringstream ss(lower);+ std::string component;+ while (std::getline(ss, component, '/')) {+ std::istringstream ss2(component);+ std::string part;+ while (std::getline(ss2, part, '\\')) {+ if (part == keyword ||+ part.find(keyword + ".") == 0 ||+ part.find(keyword + "_") == 0) {+ return "venv-numpy1";+ }+ }+ }+ }+ return "venv-numpy2";+}++fs::path resolve_python_path(const std::string& script) {+ auto venv = get_venv_name(script);++ // Check cache first+ {+ std::lock_guard<std::mutex> lock(s_path_cache_mutex);+ auto it = s_python_path_cache.find(venv);+ if (it != s_python_path_cache.end()) {+ return it->second;+ }+ }++ ensure_dir_cache();++#ifdef _WIN32+ auto python = s_install_dir_cache / venv / "Scripts" / "python.exe";+#else+ auto python = s_install_dir_cache / venv / "bin" / "python3";+#endif++ if (fs::exists(python)) {+ std::lock_guard<std::mutex> lock(s_path_cache_mutex);+ s_python_path_cache[venv] = python;+ LOG_INFO("Python", "Cached python path for venv '%s': %s", venv.c_str(), python.string().c_str());+ return python;+ }++ // Fallback to system Python — check once and cache+#ifdef _WIN32+ const char* sys_python = "python";+#else+ const char* sys_python = "python3";+#endif++ std::string check_cmd = std::string(sys_python) + " --version";+#ifdef _WIN32+ FILE* pipe = _popen(check_cmd.c_str(), "r");+#else+ FILE* pipe = popen(check_cmd.c_str(), "r");+#endif+ if (pipe) {+ char buf[128];+ bool found = (fgets(buf, sizeof(buf), pipe) != nullptr);+#ifdef _WIN32+ _pclose(pipe);+#else+ pclose(pipe);+#endif+ if (found) {+ fs::path sys_path(sys_python);+ std::lock_guard<std::mutex> lock(s_path_cache_mutex);+ s_python_path_cache[venv] = sys_path;+ LOG_INFO("Python", "Cached system python for venv '%s'", venv.c_str());+ return sys_path;+ }+ }++ LOG_ERROR("Python", "No python found for venv '%s'", venv.c_str());+ return {};+}++fs::path resolve_script_path(const std::string& script) {+ ensure_dir_cache();++ std::vector<fs::path> candidates;+ candidates.reserve(6);++ candidates.push_back(s_exe_dir_cache / "scripts" / script);+ candidates.push_back(s_exe_dir_cache / "resources" / "scripts" / script);++#ifdef __APPLE__+ auto contents_dir = s_exe_dir_cache.parent_path();+ candidates.push_back(contents_dir / "Resources" / "scripts" / script);+#endif++ auto cwd = fs::current_path();+ candidates.push_back(cwd / "scripts" / script);+ candidates.push_back(cwd / "resources" / "scripts" / script);+ candidates.push_back(cwd / ".." / "fincept-terminal-desktop" / "src-tauri" / "resources" / "scripts" / script);++ for (const auto& p : candidates) {+ if (fs::exists(p)) {+ return fs::canonical(p);+ }+ }++ LOG_ERROR("Python", "Script '%s' NOT FOUND in %zu search paths", script.c_str(), candidates.size());+ return {};+}++bool is_python_available() {+ auto path = resolve_python_path("default");+ return !path.empty();+}++// ============================================================================+// JSON extraction+// ============================================================================++std::string extract_json(const std::string& output) {+ std::istringstream stream(output);+ std::string line;+ std::string last_json;++ while (std::getline(stream, line)) {+ size_t start = line.find_first_not_of(" \t\r\n");+ if (start == std::string::npos) continue;+ char first = line[start];+ if (first == '{' || first == '[') {+ last_json = line.substr(start);+ }+ }++ if (!last_json.empty()) return last_json;+ return {};+}++// ============================================================================+// Subprocess execution+// ============================================================================++#ifdef _WIN32++// Helper: read an entire pipe handle into a string (used by reader threads)+static void read_pipe_to_string(HANDLE hPipe, std::string& out) {+ char buffer[4096];+ DWORD bytesRead;+ while (ReadFile(hPipe, buffer, sizeof(buffer) - 1, &bytesRead, nullptr) && bytesRead > 0) {+ buffer[bytesRead] = '\0';+ out.append(buffer, bytesRead);+ }+}++static PythonResult run_subprocess(const fs::path& python, const fs::path& script,+ const std::vector<std::string>& args,+ const std::string* stdin_data = nullptr) {+ PythonResult result;++ // Build command line+ std::string cmd = "\"" + python.string() + "\" -u -B \"" + script.string() + "\"";+ for (const auto& arg : args) {+ cmd += " \"" + arg + "\"";+ }++ SECURITY_ATTRIBUTES sa{};+ sa.nLength = sizeof(sa);+ sa.bInheritHandle = TRUE;++ // Create stdout pipe+ HANDLE hStdoutRead = nullptr, hStdoutWrite = nullptr;+ CreatePipe(&hStdoutRead, &hStdoutWrite, &sa, 0);+ SetHandleInformation(hStdoutRead, HANDLE_FLAG_INHERIT, 0);++ // Create stderr pipe+ HANDLE hStderrRead = nullptr, hStderrWrite = nullptr;+ CreatePipe(&hStderrRead, &hStderrWrite, &sa, 0);+ SetHandleInformation(hStderrRead, HANDLE_FLAG_INHERIT, 0);++ // Create stdin pipe if needed+ HANDLE hStdinRead = nullptr, hStdinWrite = nullptr;+ if (stdin_data) {+ CreatePipe(&hStdinRead, &hStdinWrite, &sa, 0);+ SetHandleInformation(hStdinWrite, HANDLE_FLAG_INHERIT, 0);+ }++ STARTUPINFOA si{};+ si.cb = sizeof(si);+ si.hStdOutput = hStdoutWrite;+ si.hStdError = hStderrWrite;+ si.hStdInput = stdin_data ? hStdinRead : nullptr;+ si.dwFlags |= STARTF_USESTDHANDLES;++ PROCESS_INFORMATION pi{};+ std::string cmd_line = cmd;++ BOOL ok = CreateProcessA(+ nullptr, cmd_line.data(), nullptr, nullptr, TRUE,+ CREATE_NO_WINDOW, nullptr, nullptr, &si, &pi+ );++ // Close write ends so reads will EOF when the child exits+ CloseHandle(hStdoutWrite);+ CloseHandle(hStderrWrite);+ if (stdin_data && hStdinRead) CloseHandle(hStdinRead);++ if (!ok) {+ result.error = "Failed to create process";+ if (hStdoutRead) CloseHandle(hStdoutRead);+ if (hStderrRead) CloseHandle(hStderrRead);+ if (stdin_data && hStdinWrite) CloseHandle(hStdinWrite);+ return result;+ }++ // Write stdin data (do this before reading to avoid deadlock)+ if (stdin_data && hStdinWrite) {+ DWORD written;+ WriteFile(hStdinWrite, stdin_data->c_str(), (DWORD)stdin_data->size(), &written, nullptr);+ CloseHandle(hStdinWrite);+ }++ // Read stdout and stderr CONCURRENTLY to prevent deadlock+ // If we read them sequentially, the child can block writing to stderr+ // while we're blocked reading stdout (or vice versa), causing a deadlock.+ std::string stdout_str;+ std::string stderr_str;++ std::thread stderr_reader([&]() {+ read_pipe_to_string(hStderrRead, stderr_str);+ });++ // Read stdout on this thread+ read_pipe_to_string(hStdoutRead, stdout_str);++ // Wait for stderr reader to finish+ stderr_reader.join();++ CloseHandle(hStdoutRead);+ CloseHandle(hStderrRead);++ // Wait for process with timeout+ DWORD wait_result = WaitForSingleObject(pi.hProcess, 120000); // 2 min++ DWORD exit_code = 0;+ if (wait_result == WAIT_TIMEOUT) {+ LOG_WARN("Python", "Process timed out after 120s, terminating");+ TerminateProcess(pi.hProcess, 1);+ exit_code = 1;+ result.error = "Script timed out after 120 seconds";+ } else {+ GetExitCodeProcess(pi.hProcess, &exit_code);+ }++ CloseHandle(pi.hProcess);+ CloseHandle(pi.hThread);++ result.exit_code = (int)exit_code;++ if (exit_code == 0) {+ result.success = true;+ auto json_str = extract_json(stdout_str);+ result.output = json_str.empty() ? stdout_str : json_str;+ } else {+ // Many Python scripts exit(1) but still write valid JSON to stdout.+ // Check stdout first for a structured JSON response.+ auto json_str = extract_json(stdout_str);+ if (!json_str.empty()) {+ try {+ auto j = nlohmann::json::parse(json_str);+ if (j.contains("success")) {+ // Script returned a structured response — pass it through+ // so callers can parse the error message from the JSON+ result.success = true; // let caller handle success/error+ result.output = json_str;+ return result;+ }+ } catch (...) {}+ }+ // Fall back to extracting error from stderr/stdout+ std::string extracted_error;+ for (const auto& src : {stderr_str, stdout_str}) {+ if (src.empty()) continue;+ auto js = extract_json(src);+ if (!js.empty()) {+ try {+ auto j = nlohmann::json::parse(js);+ if (j.contains("error") && j["error"].is_string()) {+ extracted_error = j["error"].get<std::string>();+ break;+ }+ } catch (...) {}+ }+ }+ if (!extracted_error.empty()) {+ result.error = extracted_error;+ } else if (result.error.empty()) {+ result.error = "Script failed (exit " + std::to_string(exit_code) + ")";+ if (!stderr_str.empty()) result.error += ": " + stderr_str;+ }+ }++ return result;+}++#else // Unix (macOS/Linux)++static PythonResult run_subprocess(const fs::path& python, const fs::path& script,+ const std::vector<std::string>& args,+ const std::string* stdin_data = nullptr) {+ PythonResult result;++ std::string cmd = "\"" + python.string() + "\" -u -B \"" + script.string() + "\"";+ for (const auto& arg : args) {+ cmd += " \"" + arg + "\"";+ }+ cmd += " 2>&1";++ FILE* pipe = popen(cmd.c_str(), "r");+ if (!pipe) {+ result.error = "Failed to execute subprocess";+ return result;+ }++ std::string output;+ char buffer[4096];+ while (fgets(buffer, sizeof(buffer), pipe)) {+ output += buffer;+ }++ int status = pclose(pipe);+ result.exit_code = WEXITSTATUS(status);++ if (result.exit_code == 0) {+ result.success = true;+ auto json_str = extract_json(output);+ result.output = json_str.empty() ? output : json_str;+ } else {+ result.error = "Script failed (exit " + std::to_string(result.exit_code) + "): " + output;+ }++ return result;+}++#endif++// ============================================================================+// Synchronous API+// ============================================================================++PythonResult execute(const std::string& script, const std::vector<std::string>& args) {+ auto python = resolve_python_path(script);+ if (python.empty()) {+ return {false, "", "Python not found. Run setup first.", -1};+ }++ auto script_path = resolve_script_path(script);+ if (script_path.empty()) {+ return {false, "", "Script '" + script + "' not found.", -1};+ }++ return run_subprocess(python, script_path, args);+}++PythonResult execute_sync(const std::string& script, const std::vector<std::string>& args) {+ return execute(script, args);+}++PythonResult execute_with_stdin(const std::string& script,+ const std::vector<std::string>& args,+ const std::string& stdin_data) {+ auto python = resolve_python_path(script);+ if (python.empty()) {+ return {false, "", "Python not found. Run setup first.", -1};+ }++ auto script_path = resolve_script_path(script);+ if (script_path.empty()) {+ return {false, "", "Script '" + script + "' not found.", -1};+ }++ return run_subprocess(python, script_path, args, &stdin_data);+}++// ============================================================================+// Async API — runs on a detached thread, returns future+// ============================================================================++std::future<PythonResult> execute_async(const std::string& script,+ const std::vector<std::string>& args) {+ return std::async(std::launch::async, [script, args]() -> PythonResult {+ return execute(script, args);+ });+}++std::future<PythonResult> execute_async_with_stdin(const std::string& script,+ const std::vector<std::string>& args,+ const std::string& stdin_data) {+ return std::async(std::launch::async, [script, args, stdin_data]() -> PythonResult {+ return execute_with_stdin(script, args, stdin_data);+ });+}++} // namespace fincept::pythondiff --git a/fincept-cpp/src/python/python_runner.h b/fincept-cpp/src/python/python_runner.hnew file mode 100644index 000000000..b14b2ea3c--- /dev/null+++ b/fincept-cpp/src/python/python_runner.h@@ -0,0 +1,91 @@+#pragma once+// Python subprocess runner — mirrors python.rs from the Tauri app+// Resolves Python path, script path, executes scripts via subprocess, extracts JSON+// Non-blocking async API available to avoid UI thread stalls++#include <string>+#include <vector>+#include <map>+#include <functional>+#include <filesystem>+#include <future>++namespace fincept::python {++namespace fs = std::filesystem;++// Scripts requiring NumPy 1.x venv+inline const std::vector<std::string> NUMPY1_SCRIPTS = {+ "vectorbt", "backtesting", "gluonts", "functime",+ "pyportfolioopt", "financepy", "ffn", "ffn_wrapper"+};++// ============================================================================+// Path resolution+// ============================================================================++/// Get the app data directory (production path only)+/// Windows: %APPDATA%/com.fincept.terminal/+/// macOS: ~/Library/Application Support/com.fincept.terminal/+/// Linux: ~/.local/share/com.fincept.terminal/+fs::path get_install_dir();++/// Get the directory containing the running executable+fs::path get_exe_dir();++/// Determine which venv to use for a given script+std::string get_venv_name(const std::string& script);++/// Resolve the Python executable path for a given script+/// Checks venv first, falls back to system Python (result is cached)+fs::path resolve_python_path(const std::string& script);++/// Resolve the script path relative to the exe directory+/// Searches: exe_dir/scripts/, exe_dir/resources/scripts/, CWD/scripts/+fs::path resolve_script_path(const std::string& script);++/// Check if Python is available (any venv or system)+bool is_python_available();++/// Clear the cached Python path lookups (call after venv setup changes)+void clear_path_cache();++// ============================================================================+// Subprocess execution+// ============================================================================++struct PythonResult {+ bool success = false;+ std::string output; // Extracted JSON or raw stdout+ std::string error; // Error message if failed+ int exit_code = -1;+};++/// Execute a Python script and return JSON result (blocking)+PythonResult execute(const std::string& script, const std::vector<std::string>& args);++/// Execute a Python script synchronously (same as execute, explicit name)+PythonResult execute_sync(const std::string& script, const std::vector<std::string>& args);++/// Execute with stdin data (for large payloads, blocking)+PythonResult execute_with_stdin(const std::string& script,+ const std::vector<std::string>& args,+ const std::string& stdin_data);++/// Execute a Python script asynchronously — returns a future, never blocks the caller+std::future<PythonResult> execute_async(const std::string& script,+ const std::vector<std::string>& args);++/// Execute with stdin data asynchronously — returns a future+std::future<PythonResult> execute_async_with_stdin(const std::string& script,+ const std::vector<std::string>& args,+ const std::string& stdin_data);++// ============================================================================+// Utility+// ============================================================================++/// Extract last JSON line/block from Python output+std::string extract_json(const std::string& output);++} // namespace fincept::pythondiff --git a/fincept-cpp/src/python/setup_manager.cpp b/fincept-cpp/src/python/setup_manager.cppnew file mode 100644index 000000000..a505be475--- /dev/null+++ b/fincept-cpp/src/python/setup_manager.cpp@@ -0,0 +1,587 @@+// Python setup manager — downloads Python, creates venvs, installs packages+// C++ port of setup/ module from the Tauri app++#include "setup_manager.h"+#include "python_runner.h"+#include <curl/curl.h>+#include <fstream>+#include <sstream>+#include <iostream>+#include <cstdio>+#include <cstring>+#include <thread>+#include <chrono>++#ifdef _WIN32+#ifndef WIN32_LEAN_AND_MEAN+#define WIN32_LEAN_AND_MEAN+#endif+#ifndef NOMINMAX+#define NOMINMAX+#endif+#include <windows.h>+#include <shlobj.h>+#else+#include <sys/stat.h>+#include <unistd.h>+#endif++namespace fincept::python {++static constexpr const char* PYTHON_VERSION = "3.12.7";++// ============================================================================+// Singleton+// ============================================================================++SetupManager& SetupManager::instance() {+ static SetupManager s;+ return s;+}++// ============================================================================+// Progress+// ============================================================================++void SetupManager::emit(const std::string& step, int progress, const std::string& msg, bool error) {+ std::lock_guard<std::mutex> lock(progress_mutex_);+ current_progress_ = {step, progress, msg, error};+ std::cerr << "[SETUP] [" << step << "] " << progress << "% - " << msg << "\n";+}++SetupProgress SetupManager::get_progress() const {+ std::lock_guard<std::mutex> lock(progress_mutex_);+ return current_progress_;+}++// ============================================================================+// Status checks+// ============================================================================++SetupStatus SetupManager::check_status() {+ SetupStatus status;+ status.python_installed = check_python_installed();+ if (status.python_installed) {+ status.python_version = get_python_version();+ }+ status.packages_installed = check_packages_installed();+ status.needs_setup = !status.python_installed || !status.packages_installed;+ return status;+}++bool SetupManager::check_python_installed() {+ auto install_dir = get_install_dir();+#ifdef _WIN32+ auto python_exe = install_dir / "python" / "python.exe";+#else+ auto python_exe = install_dir / "python" / "bin" / "python3";+#endif+ return fs::exists(python_exe);+}++bool SetupManager::check_packages_installed() {+ auto install_dir = get_install_dir();++#ifdef _WIN32+ auto venv1 = install_dir / "venv-numpy1" / "Scripts" / "python.exe";+ auto venv2 = install_dir / "venv-numpy2" / "Scripts" / "python.exe";+#else+ auto venv1 = install_dir / "venv-numpy1" / "bin" / "python3";+ auto venv2 = install_dir / "venv-numpy2" / "bin" / "python3";+#endif++ return fs::exists(venv1) && fs::exists(venv2);+}++std::string SetupManager::get_python_version() {+ auto install_dir = get_install_dir();+#ifdef _WIN32+ auto python_exe = install_dir / "python" / "python.exe";+#else+ auto python_exe = install_dir / "python" / "bin" / "python3";+#endif++ if (!fs::exists(python_exe)) return "";++ std::string cmd = "\"" + python_exe.string() + "\" --version";+ std::string output;+ if (run_command(cmd, &output)) {+ // Trim+ while (!output.empty() && (output.back() == '\n' || output.back() == '\r'))+ output.pop_back();+ return output;+ }+ return "";+}++// ============================================================================+// File download via libcurl+// ============================================================================++struct DownloadData {+ FILE* fp = nullptr;+};++static size_t download_write_cb(void* ptr, size_t size, size_t nmemb, void* userdata) {+ auto* data = static_cast<DownloadData*>(userdata);+ return fwrite(ptr, size, nmemb, data->fp);+}++bool SetupManager::download_file(const std::string& url, const fs::path& dest) {+ CURL* curl = curl_easy_init();+ if (!curl) return false;++ DownloadData data;+#ifdef _WIN32+ data.fp = _wfopen(dest.wstring().c_str(), L"wb");+#else+ data.fp = fopen(dest.string().c_str(), "wb");+#endif+ if (!data.fp) {+ curl_easy_cleanup(curl);+ return false;+ }++ curl_easy_setopt(curl, CURLOPT_URL, url.c_str());+ curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, download_write_cb);+ curl_easy_setopt(curl, CURLOPT_WRITEDATA, &data);+ curl_easy_setopt(curl, CURLOPT_FOLLOWLOCATION, 1L);+ curl_easy_setopt(curl, CURLOPT_MAXREDIRS, 10L);+ curl_easy_setopt(curl, CURLOPT_SSL_VERIFYPEER, 1L);+ curl_easy_setopt(curl, CURLOPT_SSL_VERIFYHOST, 2L);+ curl_easy_setopt(curl, CURLOPT_USERAGENT, "FinceptTerminal/3.3.1");+ curl_easy_setopt(curl, CURLOPT_TIMEOUT, 600L); // 10 min for large downloads+ curl_easy_setopt(curl, CURLOPT_CONNECTTIMEOUT, 30L);++ CURLcode res = curl_easy_perform(curl);+ fclose(data.fp);+ curl_easy_cleanup(curl);++ if (res != CURLE_OK) {+ std::cerr << "[SETUP] Download failed: " << curl_easy_strerror(res) << "\n";+ fs::remove(dest);+ return false;+ }++ return true;+}++// ============================================================================+// Command execution+// ============================================================================++bool SetupManager::run_command(const std::string& cmd, std::string* output) {+#ifdef _WIN32+ SECURITY_ATTRIBUTES sa{};+ sa.nLength = sizeof(sa);+ sa.bInheritHandle = TRUE;++ HANDLE hRead = nullptr, hWrite = nullptr;+ CreatePipe(&hRead, &hWrite, &sa, 0);+ SetHandleInformation(hRead, HANDLE_FLAG_INHERIT, 0);++ STARTUPINFOA si{};+ si.cb = sizeof(si);+ si.hStdOutput = hWrite;+ si.hStdError = hWrite;+ si.dwFlags |= STARTF_USESTDHANDLES;++ PROCESS_INFORMATION pi{};+ std::string cmd_line = "cmd /C " + cmd;++ BOOL ok = CreateProcessA(+ nullptr, cmd_line.data(), nullptr, nullptr, TRUE,+ CREATE_NO_WINDOW, nullptr, nullptr, &si, &pi+ );+ CloseHandle(hWrite);++ if (!ok) {+ CloseHandle(hRead);+ return false;+ }++ std::string out;+ char buffer[4096];+ DWORD bytesRead;+ while (ReadFile(hRead, buffer, sizeof(buffer) - 1, &bytesRead, nullptr) && bytesRead > 0) {+ buffer[bytesRead] = '\0';+ out += buffer;+ }+ CloseHandle(hRead);++ WaitForSingleObject(pi.hProcess, 300000); // 5 min timeout++ DWORD exit_code = 0;+ GetExitCodeProcess(pi.hProcess, &exit_code);+ CloseHandle(pi.hProcess);+ CloseHandle(pi.hThread);++ if (output) *output = out;+ return exit_code == 0;+#else+ std::string full_cmd = cmd + " 2>&1";+ FILE* pipe = popen(full_cmd.c_str(), "r");+ if (!pipe) return false;++ std::string out;+ char buffer[4096];+ while (fgets(buffer, sizeof(buffer), pipe)) out += buffer;++ int status = pclose(pipe);+ if (output) *output = out;+ return WEXITSTATUS(status) == 0;+#endif+}++// ============================================================================+// Install Python+// ============================================================================++bool SetupManager::install_python() {+ emit("python", 0, "Installing Python...");++ auto install_dir = get_install_dir();+ auto python_dir = install_dir / "python";+ fs::create_directories(python_dir);++ emit("python", 10, "Downloading Python " + std::string(PYTHON_VERSION) + "...");++#ifdef _WIN32+ // Windows: download embedded Python from python.org+ std::string url = "https://www.python.org/ftp/python/" + std::string(PYTHON_VERSION)+ + "/python-" + std::string(PYTHON_VERSION) + "-embed-amd64.zip";+ auto zip_path = python_dir / "python.zip";++ if (!download_file(url, zip_path)) {+ emit("python", 0, "Failed to download Python", true);+ return false;+ }++ emit("python", 50, "Extracting Python...");++ // Extract using PowerShell+ std::string extract_cmd = "powershell -Command \"Expand-Archive -Path '"+ + zip_path.string() + "' -DestinationPath '" + python_dir.string() + "' -Force\"";+ if (!run_command(extract_cmd)) {+ emit("python", 0, "Failed to extract Python", true);+ return false;+ }+ fs::remove(zip_path);++ // Enable pip by modifying python312._pth+ auto pth_file = python_dir / ("python" + std::string(PYTHON_VERSION).substr(0, 1)+ + std::string(PYTHON_VERSION).substr(2, 2) + "._pth");+ // Try common names+ for (const auto& name : {"python312._pth", "python311._pth", "python313._pth"}) {+ auto p = python_dir / name;+ if (fs::exists(p)) {+ pth_file = p;+ break;+ }+ }++ if (fs::exists(pth_file)) {+ std::ifstream in(pth_file);+ std::string content((std::istreambuf_iterator<char>(in)), std::istreambuf_iterator<char>());+ in.close();++ // Enable import site+ size_t pos = content.find("#import site");+ if (pos != std::string::npos) {+ content.replace(pos, 12, "import site");+ }++ // Add site-packages if not present+ if (content.find("Lib/site-packages") == std::string::npos &&+ content.find("Lib\\site-packages") == std::string::npos) {+ content += "\nLib/site-packages\n";+ }++ std::ofstream out(pth_file);+ out << content;+ }++ // Create Lib/site-packages+ fs::create_directories(python_dir / "Lib" / "site-packages");++#elif defined(__APPLE__)+ // macOS: use python-build-standalone from Astral+ std::string arch = "aarch64";+ #if defined(__x86_64__)+ arch = "x86_64";+ #endif++ std::string platform = arch + "-apple-darwin-install_only";+ std::string url = "https://github.com/astral-sh/python-build-standalone/releases/download/20240726/cpython-3.12.4+20240726-"+ + platform + ".tar.gz";+ auto tar_path = python_dir / "python.tar.gz";++ if (!download_file(url, tar_path)) {+ emit("python", 0, "Failed to download Python", true);+ return false;+ }++ emit("python", 50, "Extracting Python...");++ std::string extract_cmd = "tar -xzf \"" + tar_path.string() + "\" -C \""+ + python_dir.string() + "\" --strip-components=1";+ if (!run_command(extract_cmd)) {+ emit("python", 0, "Failed to extract Python", true);+ return false;+ }+ fs::remove(tar_path);++#else+ // Linux: use python-build-standalone from Astral+ std::string arch = "x86_64";+ #if defined(__aarch64__)+ arch = "aarch64";+ #endif++ std::string platform = arch + "-unknown-linux-gnu-install_only";+ std::string url = "https://github.com/astral-sh/python-build-standalone/releases/download/20240726/cpython-3.12.4+20240726-"+ + platform + ".tar.gz";+ auto tar_path = python_dir / "python.tar.gz";++ if (!download_file(url, tar_path)) {+ emit("python", 0, "Failed to download Python", true);+ return false;+ }++ emit("python", 50, "Extracting Python...");++ std::string extract_cmd = "tar -xzf \"" + tar_path.string() + "\" -C \""+ + python_dir.string() + "\" --strip-components=1";+ if (!run_command(extract_cmd)) {+ emit("python", 0, "Failed to extract Python", true);+ return false;+ }+ fs::remove(tar_path);+#endif++ // Install pip+ emit("python", 70, "Installing pip...");++ auto get_pip_path = python_dir / "get-pip.py";+ if (!download_file("https://bootstrap.pypa.io/get-pip.py", get_pip_path)) {+ emit("python", 0, "Failed to download get-pip.py", true);+ return false;+ }++#ifdef _WIN32+ auto python_exe = python_dir / "python.exe";+#else+ auto python_exe = python_dir / "bin" / "python3";+#endif++ std::string pip_cmd = "\"" + python_exe.string() + "\" \"" + get_pip_path.string()+ + "\" --no-warn-script-location";+ std::string pip_output;+ if (!run_command(pip_cmd, &pip_output)) {+ emit("python", 0, "Failed to install pip: " + pip_output, true);+ return false;+ }+ fs::remove(get_pip_path);++ // Verify pip+ emit("python", 90, "Verifying pip...");+ std::string verify_cmd = "\"" + python_exe.string() + "\" -m pip --version";+ if (!run_command(verify_cmd)) {+ emit("python", 0, "pip verification failed", true);+ return false;+ }++ emit("python", 100, "Python installed");+ return true;+}++// ============================================================================+// Install UV+// ============================================================================++bool SetupManager::install_uv() {+ emit("uv", 0, "Installing UV package manager...");++ auto install_dir = get_install_dir();+#ifdef _WIN32+ auto python_exe = install_dir / "python" / "python.exe";+#else+ auto python_exe = install_dir / "python" / "bin" / "python3";+#endif++ std::string cmd = "\"" + python_exe.string() + "\" -m pip install --no-warn-script-location uv";+ std::string output;+ if (!run_command(cmd, &output)) {+ emit("uv", 0, "Failed to install UV: " + output, true);+ return false;+ }++ emit("uv", 100, "UV installed");+ return true;+}++// ============================================================================+// Create venv+// ============================================================================++bool SetupManager::create_venv(const std::string& venv_name) {+ emit("venv", 0, "Creating " + venv_name + "...");++ auto install_dir = get_install_dir();+#ifdef _WIN32+ auto python_exe = install_dir / "python" / "python.exe";+ auto uv_exe = install_dir / "python" / "Scripts" / "uv.exe";+#else+ auto python_exe = install_dir / "python" / "bin" / "python3";+ auto uv_exe = install_dir / "python" / "bin" / "uv";+#endif++ auto venv_path = install_dir / venv_name;++ std::string cmd;+ if (fs::exists(uv_exe)) {+ cmd = "\"" + uv_exe.string() + "\" venv \"" + venv_path.string()+ + "\" --python \"" + python_exe.string() + "\"";+ } else {+ // Fallback: python -m uv+ cmd = "\"" + python_exe.string() + "\" -m uv venv \"" + venv_path.string()+ + "\" --python \"" + python_exe.string() + "\"";+ }++ std::string output;+ if (!run_command(cmd, &output)) {+ emit("venv", 0, "Failed to create " + venv_name + ": " + output, true);+ return false;+ }++ emit("venv", 100, venv_name + " created");+ return true;+}++// ============================================================================+// Install packages+// ============================================================================++bool SetupManager::install_packages(const std::string& venv_name,+ const std::string& requirements_file,+ const std::string& label) {+ emit("packages", 0, "Installing " + label + " packages...");++ auto install_dir = get_install_dir();+ auto exe_dir = get_exe_dir();++#ifdef _WIN32+ auto python_exe = install_dir / "python" / "python.exe";+ auto uv_exe = install_dir / "python" / "Scripts" / "uv.exe";+ auto venv_python = install_dir / venv_name / "Scripts" / "python.exe";+#else+ auto python_exe = install_dir / "python" / "bin" / "python3";+ auto uv_exe = install_dir / "python" / "bin" / "uv";+ auto venv_python = install_dir / venv_name / "bin" / "python3";+#endif++ // Find requirements file: check exe_dir/resources/ then exe_dir/+ fs::path req_path;+ std::vector<fs::path> req_candidates = {+ exe_dir / "resources" / requirements_file,+ exe_dir / requirements_file,+ fs::current_path() / "resources" / requirements_file,+ fs::current_path() / requirements_file,+ };+ for (const auto& p : req_candidates) {+ if (fs::exists(p)) { req_path = p; break; }+ }++ if (req_path.empty()) {+ emit("packages", 0, "Requirements file not found: " + requirements_file, true);+ return false;+ }++ emit("packages", 20, "Installing " + label + " packages with UV...");++ std::string cmd;+ if (fs::exists(uv_exe)) {+ cmd = "\"" + uv_exe.string() + "\"";+ } else {+ cmd = "\"" + python_exe.string() + "\" -m uv";+ }++ cmd += " pip install --python \"" + venv_python.string()+ + "\" -r \"" + req_path.string() + "\"";++ // Set env vars to prevent C extension build failures+#ifdef _WIN32+ // On Windows, set env vars before the command+ cmd = "set PEEWEE_NO_SQLITE_EXTENSIONS=1 && set PEEWEE_NO_C_EXTENSION=1 && " + cmd;+#else+ cmd = "PEEWEE_NO_SQLITE_EXTENSIONS=1 PEEWEE_NO_C_EXTENSION=1 " + cmd;+#endif++ std::string output;+ if (!run_command(cmd, &output)) {+ emit("packages", 0, label + " package install failed", true);+ std::cerr << "[SETUP] Package install output: " << output << "\n";+ return false;+ }++ emit("packages", 100, label + " packages installed");+ return true;+}++// ============================================================================+// Full setup flow+// ============================================================================++bool SetupManager::run_setup() {+ if (running_.load()) return false;+ running_ = true;++ emit("init", 0, "Starting setup...");++ auto install_dir = get_install_dir();+ fs::create_directories(install_dir);+ std::cerr << "[SETUP] Install directory: " << install_dir << "\n";++ // Step 1: Python+ if (!check_python_installed()) {+ if (!install_python()) {+ running_ = false;+ return false;+ }+ } else {+ auto ver = get_python_version();+ emit("python", 100, "Python already installed: " + ver);+ }++ // Step 2: UV+ if (!install_uv()) {+ running_ = false;+ return false;+ }++ // Step 3: Create venvs and install packages+ if (!check_packages_installed()) {+ // venv-numpy1+ emit("venv", 0, "Creating NumPy 1.x environment...");+ if (!create_venv("venv-numpy1")) { running_ = false; return false; }+ if (!install_packages("venv-numpy1", "requirements-numpy1.txt", "NumPy 1.x")) {+ running_ = false; return false;+ }++ // venv-numpy2+ emit("venv", 50, "Creating NumPy 2.x environment...");+ if (!create_venv("venv-numpy2")) { running_ = false; return false; }+ if (!install_packages("venv-numpy2", "requirements-numpy2.txt", "NumPy 2.x")) {+ running_ = false; return false;+ }+ } else {+ emit("packages", 100, "Packages already installed");+ }++ emit("complete", 100, "Setup complete!");+ complete_ = true;+ running_ = false;+ return true;+}++} // namespace fincept::pythondiff --git a/fincept-cpp/src/python/setup_manager.h b/fincept-cpp/src/python/setup_manager.hnew file mode 100644index 000000000..488a02b47--- /dev/null+++ b/fincept-cpp/src/python/setup_manager.h@@ -0,0 +1,88 @@+#pragma once+// Python setup manager — mirrors setup/ module from Tauri app+// Downloads Python, creates venvs, installs packages on first run++#include <string>+#include <filesystem>+#include <functional>+#include <atomic>+#include <mutex>++namespace fincept::python {++namespace fs = std::filesystem;++// ============================================================================+// Setup progress+// ============================================================================++struct SetupProgress {+ std::string step; // "python", "uv", "venv", "packages", "complete"+ int progress = 0; // 0-100+ std::string message;+ bool is_error = false;+};++struct SetupStatus {+ bool python_installed = false;+ bool packages_installed = false;+ bool needs_setup = true;+ std::string python_version;+};++// ============================================================================+// Setup manager+// ============================================================================++class SetupManager {+public:+ static SetupManager& instance();++ /// Check current installation status+ SetupStatus check_status();++ /// Run full setup (blocking — call from background thread)+ bool run_setup();++ /// Get current progress (thread-safe)+ SetupProgress get_progress() const;++ /// Is setup currently running?+ bool is_running() const { return running_.load(); }++ /// Was setup completed successfully?+ bool is_complete() const { return complete_.load(); }++ /// Skip setup (use app without Python)+ void skip_setup() { skipped_ = true; complete_ = true; }+ bool was_skipped() const { return skipped_.load(); }++ SetupManager(const SetupManager&) = delete;+ SetupManager& operator=(const SetupManager&) = delete;++private:+ SetupManager() = default;++ void emit(const std::string& step, int progress, const std::string& msg, bool error = false);++ // Setup steps+ bool install_python();+ bool install_uv();+ bool create_venv(const std::string& venv_name);+ bool install_packages(const std::string& venv_name, const std::string& requirements_file, const std::string& label);+ bool download_file(const std::string& url, const fs::path& dest);+ bool run_command(const std::string& cmd, std::string* output = nullptr);++ // Check helpers+ bool check_python_installed();+ bool check_packages_installed();+ std::string get_python_version();++ mutable std::mutex progress_mutex_;+ SetupProgress current_progress_;+ std::atomic<bool> running_{false};+ std::atomic<bool> complete_{false};+ std::atomic<bool> skipped_{false};+};++} // namespace fincept::pythondiff --git a/fincept-cpp/src/python/setup_screen.cpp b/fincept-cpp/src/python/setup_screen.cppnew file mode 100644index 000000000..cf447009c--- /dev/null+++ b/fincept-cpp/src/python/setup_screen.cpp@@ -0,0 +1,216 @@+// First-run setup screen — ImGui progress UI for Python installation++#include "setup_screen.h"+#include "setup_manager.h"+#include "ui/yoga_helpers.h"+#include <imgui.h>++namespace fincept::python {++// Fincept-style colors (using theme where possible)+static const ImVec4 COL_ORANGE = theme::colors::ACCENT;+static const ImVec4 COL_GREEN = theme::colors::SUCCESS;+static const ImVec4 COL_RED = theme::colors::ERROR_RED;+static const ImVec4 COL_WHITE = theme::colors::TEXT_PRIMARY;+static const ImVec4 COL_MUTED = theme::colors::TEXT_DIM;++bool SetupScreen::needs_setup() {+ if (!checked_) {+ checked_ = true;+ auto status = SetupManager::instance().check_status();+ setup_needed_ = status.needs_setup;+ }+ return setup_needed_;+}++bool SetupScreen::render() {+ auto& mgr = SetupManager::instance();++ // Already done+ if (setup_done_ || mgr.is_complete()) {+ setup_done_ = true;+ if (setup_thread_.joinable()) setup_thread_.join();+ return true;+ }++ // Responsive centered panel+ ui::CenteredFrame centered("##setup_panel", 520.0f, theme::colors::BG_PANEL);+ centered.begin();++ // Title+ float content_w = ImGui::GetContentRegionAvail().x;++ ImGui::PushFont(nullptr); // Use default font+ float title_w = ImGui::CalcTextSize("FINCEPT TERMINAL").x;+ ImGui::SetCursorPosX((content_w - title_w) / 2.0f);+ ImGui::TextColored(COL_ORANGE, "FINCEPT TERMINAL");+ ImGui::Spacing();++ float subtitle_w = ImGui::CalcTextSize("Python Environment Setup").x;+ ImGui::SetCursorPosX((content_w - subtitle_w) / 2.0f);+ ImGui::TextColored(COL_WHITE, "Python Environment Setup");+ ImGui::PopFont();++ ImGui::Spacing();+ ImGui::Separator();+ ImGui::Spacing();++ if (!setup_started_ && !mgr.is_running()) {+ // Not started yet — show info and buttons+ ImGui::TextColored(COL_MUTED, "Fincept Terminal requires Python for advanced analytics,");+ ImGui::TextColored(COL_MUTED, "data fetching, and AI features.");+ ImGui::Spacing();+ ImGui::TextColored(COL_MUTED, "This will download and install:");+ ImGui::Spacing();++ ImGui::TextColored(COL_WHITE, " 1. Python 3.12 runtime (~15 MB download)");+ ImGui::TextColored(COL_WHITE, " 2. UV package manager");+ ImGui::TextColored(COL_WHITE, " 3. NumPy 1.x environment (backtesting, vectorbt)");+ ImGui::TextColored(COL_WHITE, " 4. NumPy 2.x environment (yfinance, AI/ML, trading)");++ ImGui::Spacing();+ ImGui::TextColored(COL_MUTED, "Total disk space: ~1.5 GB");+ ImGui::TextColored(COL_MUTED, "This may take 5-15 minutes depending on your connection.");++ ImGui::Spacing();+ ImGui::Spacing();++ // Buttons+ float btn_w = 200.0f;+ float btn_h = 36.0f;+ float spacing = 20.0f;+ float total_btn_w = btn_w * 2 + spacing;+ ImGui::SetCursorPosX((content_w - total_btn_w) / 2.0f);++ ImGui::PushStyleColor(ImGuiCol_Button, ImVec4(0.00f, 0.50f, 0.25f, 1.0f));+ ImGui::PushStyleColor(ImGuiCol_ButtonHovered, ImVec4(0.00f, 0.60f, 0.30f, 1.0f));+ if (ImGui::Button("Install Python", ImVec2(btn_w, btn_h))) {+ setup_started_ = true;+ setup_thread_ = std::thread([]() {+ SetupManager::instance().run_setup();+ });+ }+ ImGui::PopStyleColor(2);++ ImGui::SameLine(0, spacing);++ ImGui::PushStyleColor(ImGuiCol_Button, ImVec4(0.25f, 0.25f, 0.30f, 1.0f));+ ImGui::PushStyleColor(ImGuiCol_ButtonHovered, ImVec4(0.35f, 0.35f, 0.40f, 1.0f));+ if (ImGui::Button("Skip for Now", ImVec2(btn_w, btn_h))) {+ mgr.skip_setup();+ setup_done_ = true;+ }+ ImGui::PopStyleColor(2);++ ImGui::Spacing();+ ImGui::TextColored(COL_MUTED, " (You can install later from Settings)");+ } else {+ // Setup in progress — show progress+ auto progress = mgr.get_progress();++ ImGui::Spacing();++ // Step indicator+ struct StepInfo { const char* key; const char* label; };+ StepInfo steps[] = {+ {"python", "Python Runtime"},+ {"uv", "UV Package Manager"},+ {"venv", "Virtual Environments"},+ {"packages", "Python Packages"},+ {"complete", "Complete"},+ };++ for (auto& step : steps) {+ bool is_current = (progress.step == step.key);+ bool is_done = false;++ // Determine if step is done+ if (progress.step == "complete") {+ is_done = true;+ } else {+ // Check ordering+ int current_idx = -1, step_idx = -1;+ for (int i = 0; i < 5; i++) {+ if (progress.step == steps[i].key) current_idx = i;+ if (std::string(step.key) == steps[i].key) step_idx = i;+ }+ is_done = (step_idx < current_idx);+ }++ if (is_done) {+ ImGui::TextColored(COL_GREEN, " [OK]");+ } else if (is_current) {+ ImGui::TextColored(COL_ORANGE, " [..]");+ } else {+ ImGui::TextColored(COL_MUTED, " [ ]");+ }+ ImGui::SameLine();++ ImVec4 col = is_current ? COL_WHITE : (is_done ? COL_GREEN : COL_MUTED);+ ImGui::TextColored(col, "%s", step.label);+ }++ ImGui::Spacing();+ ImGui::Spacing();++ // Progress bar+ float bar_progress = progress.progress / 100.0f;+ ImVec4 bar_col = progress.is_error ? COL_RED : COL_ORANGE;+ ImGui::PushStyleColor(ImGuiCol_PlotHistogram, bar_col);+ ImGui::ProgressBar(bar_progress, ImVec2(-1, 20), "");+ ImGui::PopStyleColor();++ ImGui::Spacing();++ // Status message+ ImVec4 msg_col = progress.is_error ? COL_RED : COL_MUTED;+ ImGui::TextColored(msg_col, "%s", progress.message.c_str());++ // Error — show retry button+ if (progress.is_error && !mgr.is_running()) {+ ImGui::Spacing();+ ImGui::Spacing();++ float btn_w = 150.0f;+ ImGui::SetCursorPosX((content_w - btn_w * 2 - 20) / 2.0f);++ ImGui::PushStyleColor(ImGuiCol_Button, ImVec4(0.80f, 0.30f, 0.00f, 1.0f));+ if (ImGui::Button("Retry", ImVec2(btn_w, 32))) {+ if (setup_thread_.joinable()) setup_thread_.join();+ setup_thread_ = std::thread([]() {+ SetupManager::instance().run_setup();+ });+ }+ ImGui::PopStyleColor();++ ImGui::SameLine(0, 20);++ ImGui::PushStyleColor(ImGuiCol_Button, ImVec4(0.25f, 0.25f, 0.30f, 1.0f));+ if (ImGui::Button("Skip", ImVec2(btn_w, 32))) {+ mgr.skip_setup();+ setup_done_ = true;+ }+ ImGui::PopStyleColor();+ }++ // Complete+ if (mgr.is_complete() && !progress.is_error) {+ ImGui::Spacing();+ float btn_w = 200.0f;+ ImGui::SetCursorPosX((content_w - btn_w) / 2.0f);++ ImGui::PushStyleColor(ImGuiCol_Button, ImVec4(0.00f, 0.50f, 0.25f, 1.0f));+ ImGui::PushStyleColor(ImGuiCol_ButtonHovered, ImVec4(0.00f, 0.60f, 0.30f, 1.0f));+ if (ImGui::Button("Continue", ImVec2(btn_w, 36))) {+ setup_done_ = true;+ }+ ImGui::PopStyleColor(2);+ }+ }++ centered.end();++ return setup_done_;+}++} // namespace fincept::pythondiff --git a/fincept-cpp/src/python/setup_screen.h b/fincept-cpp/src/python/setup_screen.hnew file mode 100644index 000000000..a7a4db7a9--- /dev/null+++ b/fincept-cpp/src/python/setup_screen.h@@ -0,0 +1,26 @@+#pragma once+// First-run setup screen — ImGui UI for Python/packages installation+// Shows progress, allows skip, integrates with App state machine++#include <thread>+#include <atomic>++namespace fincept::python {++class SetupScreen {+public:+ /// Render the setup screen. Returns true when setup is done (or skipped).+ bool render();++ /// Check if setup is needed (call once on app startup)+ bool needs_setup();++private:+ bool checked_ = false;+ bool setup_needed_ = false;+ bool setup_started_ = false;+ bool setup_done_ = false;+ std::thread setup_thread_;+};++} // namespace fincept::pythondiff --git a/fincept-cpp/src/screens/about/about_screen.cpp b/fincept-cpp/src/screens/about/about_screen.cppindex d531169e5..4c8a49bb8 100644--- a/fincept-cpp/src/screens/about/about_screen.cpp+++ b/fincept-cpp/src/screens/about/about_screen.cpp@@ -3,325 +3,388 @@#include "core/config.h"#include <imgui.h>#include <cstdio>+#include <ctime>namespace fincept::about {+using namespace theme::colors;+// =============================================================================-// Main render+// Helper: draw a labeled row in a two-column info block// =============================================================================-void AboutScreen::render() {- using namespace theme::colors;+static void info_row(const char* label, const char* value, ImVec4 val_color) {+ ImGui::TableNextRow();+ ImGui::TableSetColumnIndex(0);+ ImGui::TextColored(TEXT_DIM, "%s", label);+ ImGui::TableSetColumnIndex(1);+ ImGui::TextColored(val_color, "%s", value);+}- ImGuiViewport* vp = ImGui::GetMainViewport();- float tab_h = ImGui::GetFrameHeight() + 4;- float footer_h = ImGui::GetFrameHeight();+// Table flags — clean borders, no row background alternation+static constexpr ImGuiTableFlags TBL =+ ImGuiTableFlags_BordersInnerH | ImGuiTableFlags_BordersOuterH |+ ImGuiTableFlags_BordersInnerV | ImGuiTableFlags_BordersOuterV;- ImGui::SetNextWindowPos(ImVec2(vp->WorkPos.x, vp->WorkPos.y + tab_h));- ImGui::SetNextWindowSize(ImVec2(vp->WorkSize.x, vp->WorkSize.y - tab_h - footer_h));+// =============================================================================+// Main render — three-panel layout+// =============================================================================+void AboutScreen::render() {+ render_header_bar();- ImGui::PushStyleColor(ImGuiCol_WindowBg, BG_DARK);- ImGui::PushStyleVar(ImGuiStyleVar_WindowPadding, ImVec2(0, 0));+ float avail_w = ImGui::GetContentRegionAvail().x;+ float avail_h = ImGui::GetContentRegionAvail().y;- ImGui::Begin("##about_screen", nullptr,- ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_NoResize | ImGuiWindowFlags_NoMove |- ImGuiWindowFlags_NoCollapse | ImGuiWindowFlags_NoDocking |- ImGuiWindowFlags_NoBringToFrontOnFocus);+ // Three-panel split: left 32% | center 36% | right 32%+ float left_w = avail_w * 0.32f;+ float right_w = avail_w * 0.32f;+ float center_w = avail_w - left_w - right_w;+ if (center_w < 200) center_w = 200;- float avail_w = ImGui::GetContentRegionAvail().x;- float content_w = (avail_w > 960.0f) ? 960.0f : avail_w;- float pad_x = (avail_w - content_w) * 0.5f;- if (pad_x < 20.0f) pad_x = 20.0f;+ // LEFT PANEL+ ImGui::BeginChild("##about_left", ImVec2(left_w, avail_h), ImGuiChildFlags_Borders);+ render_system_info(left_w, avail_h);+ ImGui::EndChild();- // Scrollable centered column- ImGui::SetCursorPosX(pad_x);- ImGui::BeginChild("##about_content", ImVec2(content_w, 0), ImGuiChildFlags_None);+ ImGui::SameLine(0, 0);- ImGui::Spacing(); ImGui::Spacing();+ // CENTER PANEL+ ImGui::BeginChild("##about_center", ImVec2(center_w, avail_h), ImGuiChildFlags_Borders);+ render_license_panel(center_w, avail_h);+ ImGui::EndChild();- render_version_info();- ImGui::Spacing(); ImGui::Spacing();+ ImGui::SameLine(0, 0);- render_license_panels();- ImGui::Spacing(); ImGui::Spacing();+ // RIGHT PANEL+ ImGui::BeginChild("##about_right", ImVec2(right_w, avail_h), ImGuiChildFlags_Borders);+ render_resources_panel(right_w, avail_h);+ ImGui::EndChild();+}- render_trademarks();- ImGui::Spacing(); ImGui::Spacing();+// =============================================================================+// Header bar+// =============================================================================+void AboutScreen::render_header_bar() {+ ImGui::PushStyleColor(ImGuiCol_ChildBg, BG_WIDGET);+ ImGui::BeginChild("##about_header", ImVec2(0, ImGui::GetFrameHeight() + 8), ImGuiChildFlags_Borders);++ ImGui::TextColored(ACCENT, "FINCEPT TERMINAL");+ ImGui::SameLine(0, 12);+ ImGui::TextColored(BORDER_BRIGHT, "|");+ ImGui::SameLine(0, 12);+ ImGui::TextColored(TEXT_PRIMARY, "ABOUT");+ ImGui::SameLine(0, 12);+ ImGui::TextColored(BORDER_BRIGHT, "|");+ ImGui::SameLine(0, 12);- render_resources();- ImGui::Spacing(); ImGui::Spacing();+ // Timestamp+ time_t now = time(nullptr);+ struct tm* t = localtime(&now);+ char datetime[32];+ std::strftime(datetime, sizeof(datetime), "%Y-%m-%d %H:%M:%S", t);+ ImGui::TextColored(TEXT_DIM, "%s", datetime);- render_contact();- ImGui::Spacing(); ImGui::Spacing(); ImGui::Spacing();+ // Right side — version badge+ char ver_str[32];+ std::snprintf(ver_str, sizeof(ver_str), "v%d.%d.%d",+ config::VERSION_MAJOR, config::VERSION_MINOR, config::VERSION_PATCH);+ float ver_w = ImGui::CalcTextSize(ver_str).x + 16;+ ImGui::SameLine(ImGui::GetWindowWidth() - ver_w);+ ImGui::TextColored(SUCCESS, "%s", ver_str);ImGui::EndChild();- ImGui::End();- ImGui::PopStyleVar();ImGui::PopStyleColor();}// =============================================================================-// Version Info+// Left panel — System Information// =============================================================================-void AboutScreen::render_version_info() {- using namespace theme::colors;+void AboutScreen::render_system_info(float width, float height) {+ (void)width; (void)height;++ ImGui::TextColored(ACCENT, "SYSTEM INFORMATION");+ ImGui::Separator();++ // Product info+ theme::SectionHeader("PRODUCT");+ if (ImGui::BeginTable("##prod_info", 2, TBL)) {+ ImGui::TableSetupColumn("Field", ImGuiTableColumnFlags_WidthFixed, 120);+ ImGui::TableSetupColumn("Value");++ char ver_str[32];+ std::snprintf(ver_str, sizeof(ver_str), "%d.%d.%d",+ config::VERSION_MAJOR, config::VERSION_MINOR, config::VERSION_PATCH);++ info_row("Product", "Fincept Terminal", ACCENT);+ info_row("Version", ver_str, SUCCESS);+ info_row("Build", "Desktop Native", TEXT_PRIMARY);+ info_row("Engine", "C++ / ImGui / OpenGL", TEXT_PRIMARY);+ info_row("License", "AGPL-3.0-or-later", INFO);+ info_row("Copyright", "2024-2026 Fincept Corp.", TEXT_SECONDARY);++ ImGui::EndTable();+ }- ImGui::PushStyleColor(ImGuiCol_ChildBg, BG_PANEL);- ImGui::BeginChild("##version_info", ImVec2(0, 0),- ImGuiChildFlags_AutoResizeY | ImGuiChildFlags_Borders);ImGui::Spacing();- // Title- ImGui::SetCursorPosX(ImGui::GetCursorPosX() + 16);- ImGui::PushStyleColor(ImGuiCol_Text, ACCENT);- ImGui::SetWindowFontScale(1.4f);- ImGui::Text("FINCEPT TERMINAL");- ImGui::SetWindowFontScale(1.0f);- ImGui::PopStyleColor();+ // Platform info+ theme::SectionHeader("PLATFORM");+ if (ImGui::BeginTable("##plat_info", 2, TBL)) {+ ImGui::TableSetupColumn("Field", ImGuiTableColumnFlags_WidthFixed, 120);+ ImGui::TableSetupColumn("Value");++#if defined(_WIN32)+ info_row("OS", "Windows", TEXT_PRIMARY);+#elif defined(__APPLE__)+ info_row("OS", "macOS", TEXT_PRIMARY);+#else+ info_row("OS", "Linux", TEXT_PRIMARY);+#endif+ info_row("Arch", "x86_64", TEXT_PRIMARY);+ info_row("Renderer", "OpenGL 3.3+", TEXT_PRIMARY);+ info_row("UI", "Dear ImGui", TEXT_SECONDARY);+ info_row("Data", "SQLite + REST", TEXT_SECONDARY);+ info_row("Python", "Embedded Runtime", TEXT_SECONDARY);++ ImGui::EndTable();+ }- ImGui::SetCursorPosX(ImGui::GetCursorPosX() + 16);- ImGui::TextColored(TEXT_SECONDARY, "Cross-Platform Financial Intelligence Terminal");+ ImGui::Spacing();- ImGui::Spacing(); ImGui::Separator(); ImGui::Spacing();+ // Capabilities+ theme::SectionHeader("CAPABILITIES");+ if (ImGui::BeginTable("##caps", 2, TBL)) {+ ImGui::TableSetupColumn("Module", ImGuiTableColumnFlags_WidthFixed, 120);+ ImGui::TableSetupColumn("Status");++ const char* modules[] = {+ "Markets", "Trading", "Analytics", "AI / LLM",+ "QuantLib", "Backtesting", "Node Editor", "Geopolitics"+ };+ for (auto* mod : modules) {+ ImGui::TableNextRow();+ ImGui::TableSetColumnIndex(0);+ ImGui::TextColored(TEXT_PRIMARY, "%s", mod);+ ImGui::TableSetColumnIndex(1);+ ImGui::TextColored(MARKET_GREEN, "ACTIVE");+ }- // Info grid- float label_x = ImGui::GetCursorPosX() + 16;+ ImGui::EndTable();+ }- auto info_row = [&](const char* label, const char* value, ImVec4 val_color) {- ImGui::SetCursorPosX(label_x);- ImGui::TextColored(TEXT_DIM, "%s", label);- ImGui::SameLine(200);- ImGui::TextColored(val_color, "%s", value);- };+ ImGui::Spacing();- char ver_str[32];- std::snprintf(ver_str, sizeof(ver_str), "%d.%d.%d",- config::VERSION_MAJOR, config::VERSION_MINOR, config::VERSION_PATCH);+ // Statistics+ theme::SectionHeader("STATISTICS");+ if (ImGui::BeginTable("##stats", 2, TBL)) {+ ImGui::TableSetupColumn("Metric", ImGuiTableColumnFlags_WidthFixed, 120);+ ImGui::TableSetupColumn("Value");- info_row("Version:", ver_str, SUCCESS);- info_row("Platform:", "Desktop (C++ / ImGui / OpenGL)", TEXT_PRIMARY);- info_row("License:", "AGPL-3.0-or-later", INFO);- info_row("Copyright:", "2024-2026 Fincept Corporation", TEXT_SECONDARY);- info_row("Website:", "https://fincept.in", ACCENT);+ info_row("Tabs", "70+", ACCENT);+ info_row("Data Sources", "100+", ACCENT);+ info_row("Python Scripts", "60+", TEXT_PRIMARY);+ info_row("Rust Commands", "100+", TEXT_PRIMARY);+ info_row("Languages", "8", TEXT_PRIMARY);+ info_row("QuantLib Tabs", "18", TEXT_PRIMARY);- ImGui::Spacing();- ImGui::EndChild();- ImGui::PopStyleColor();+ ImGui::EndTable();+ }}// =============================================================================-// License Panels+// Center panel — License & Legal// =============================================================================-void AboutScreen::render_license_panels() {- using namespace theme::colors;-- theme::SectionHeader("LICENSE INFORMATION");-- float avail = ImGui::GetContentRegionAvail().x;- float col_w = (avail - 12) * 0.5f;+void AboutScreen::render_license_panel(float width, float height) {+ (void)width; (void)height;- // Two-column layout- ImGui::BeginGroup();+ ImGui::TextColored(ACCENT, "LICENSE & LEGAL");+ ImGui::Separator();// Open Source License- ImGui::PushStyleColor(ImGuiCol_ChildBg, BG_PANEL);- ImGui::BeginChild("##oss_license", ImVec2(col_w, 220),- ImGuiChildFlags_Borders);+ theme::SectionHeader("OPEN SOURCE LICENSE");+ if (ImGui::BeginTable("##oss", 2, TBL)) {+ ImGui::TableSetupColumn("Field", ImGuiTableColumnFlags_WidthFixed, 120);+ ImGui::TableSetupColumn("Value");- ImGui::SetCursorPos(ImVec2(16, 12));- ImGui::TextColored(MARKET_GREEN, "[Open Source]");- ImGui::SetCursorPosX(16);- ImGui::TextColored(TEXT_PRIMARY, "GNU AGPL v3.0");+ info_row("License", "GNU AGPL v3.0", MARKET_GREEN);+ info_row("Type", "Copyleft / Open", TEXT_PRIMARY);+ info_row("Usage", "Personal & Non-Commercial", TEXT_PRIMARY);+ info_row("Reference", "gnu.org/licenses/agpl-3.0", INFO);++ ImGui::EndTable();+ }ImGui::Spacing();- ImGui::SetCursorPosX(16);- ImGui::PushTextWrapPos(ImGui::GetCursorPosX() + col_w - 32);- ImGui::TextColored(TEXT_SECONDARY, "Free for personal and non-commercial use.");- ImGui::Spacing();++ ImGui::PushStyleColor(ImGuiCol_ChildBg, BG_WIDGET);+ ImGui::BeginChild("##oss_terms", ImVec2(0, 0), ImGuiChildFlags_AutoResizeY);+ ImGui::PushTextWrapPos(ImGui::GetContentRegionAvail().x - 8);ImGui::TextColored(TEXT_DIM, "* Source code must remain open");ImGui::TextColored(TEXT_DIM, "* Modifications must be shared");ImGui::TextColored(TEXT_DIM, "* Network use requires source sharing");ImGui::TextColored(TEXT_DIM, "* Same license for derivative works");- ImGui::Spacing();- ImGui::TextColored(INFO, "gnu.org/licenses/agpl-3.0");ImGui::PopTextWrapPos();-ImGui::EndChild();ImGui::PopStyleColor();- ImGui::SameLine(0, 12);+ ImGui::Spacing();// Commercial License- ImGui::PushStyleColor(ImGuiCol_ChildBg, BG_PANEL);- ImGui::BeginChild("##com_license", ImVec2(col_w, 220),- ImGuiChildFlags_Borders);+ theme::SectionHeader("COMMERCIAL LICENSE");+ if (ImGui::BeginTable("##com", 2, TBL)) {+ ImGui::TableSetupColumn("Field", ImGuiTableColumnFlags_WidthFixed, 120);+ ImGui::TableSetupColumn("Value");- ImGui::SetCursorPos(ImVec2(16, 12));- ImGui::TextColored(ACCENT, "[Commercial]");- ImGui::SetCursorPosX(16);- ImGui::TextColored(TEXT_PRIMARY, "Commercial License");+ info_row("License", "Commercial", ACCENT);+ info_row("Type", "Proprietary", TEXT_PRIMARY);+ info_row("Usage", "Commercial & Enterprise", TEXT_PRIMARY);+ info_row("Contact", "[email protected]", INFO);++ ImGui::EndTable();+ }ImGui::Spacing();- ImGui::SetCursorPosX(16);- ImGui::PushTextWrapPos(ImGui::GetCursorPosX() + col_w - 32);- ImGui::TextColored(TEXT_SECONDARY, "Required for commercial or proprietary use.");- ImGui::Spacing();++ ImGui::PushStyleColor(ImGuiCol_ChildBg, BG_WIDGET);+ ImGui::BeginChild("##com_terms", ImVec2(0, 0), ImGuiChildFlags_AutoResizeY);+ ImGui::PushTextWrapPos(ImGui::GetContentRegionAvail().x - 8);ImGui::TextColored(TEXT_DIM, "* No source sharing requirement");ImGui::TextColored(TEXT_DIM, "* Priority support included");ImGui::TextColored(TEXT_DIM, "* Custom development available");ImGui::TextColored(TEXT_DIM, "* Dedicated integration support");- ImGui::Spacing();- ImGui::TextColored(INFO, "Contact: [email protected]");ImGui::PopTextWrapPos();-ImGui::EndChild();ImGui::PopStyleColor();- ImGui::EndGroup();-}--// =============================================================================-// Trademarks-// =============================================================================-void AboutScreen::render_trademarks() {- using namespace theme::colors;+ ImGui::Spacing();+ // Trademarkstheme::SectionHeader("TRADEMARKS");- ImGui::PushStyleColor(ImGuiCol_ChildBg, BG_PANEL);- ImGui::BeginChild("##trademarks", ImVec2(0, 0),- ImGuiChildFlags_AutoResizeY | ImGuiChildFlags_Borders);-- ImGui::SetCursorPos(ImVec2(16, 12));- ImGui::PushTextWrapPos(ImGui::GetCursorPosX() + ImGui::GetContentRegionAvail().x - 16);+ ImGui::PushStyleColor(ImGuiCol_ChildBg, BG_WIDGET);+ ImGui::BeginChild("##tm", ImVec2(0, 0), ImGuiChildFlags_AutoResizeY);+ ImGui::PushTextWrapPos(ImGui::GetContentRegionAvail().x - 8);ImGui::TextColored(TEXT_SECONDARY,- "\"Fincept\", \"Fincept Terminal\", and associated logos are trademarks "- "of Fincept Corporation. Use of these trademarks without prior written "- "permission from Fincept Corporation is strictly prohibited.");+ "\"Fincept\", \"Fincept Terminal\", and associated logos are "+ "trademarks of Fincept Corporation. Use of these trademarks "+ "without prior written permission is strictly prohibited.");ImGui::Spacing();ImGui::TextColored(TEXT_DIM,- "All other product names, logos, and brands are property of their "- "respective owners.");+ "All other product names, logos, and brands are property of "+ "their respective owners.");ImGui::PopTextWrapPos();-- ImGui::Spacing();ImGui::EndChild();ImGui::PopStyleColor();-}-// =============================================================================-// Resources-// =============================================================================-void AboutScreen::render_resources() {- using namespace theme::colors;-- theme::SectionHeader("RESOURCES");-- float avail = ImGui::GetContentRegionAvail().x;- float col_w = (avail - 12) * 0.5f;-- struct Resource {- const char* label;- const char* url;- ImVec4 color;- };-- Resource resources[] = {- {"GitHub Repository", "github.com/Fincept-Corporation/FinceptTerminal", ACCENT},- {"License File", "See LICENSE in repository root", INFO},- {"Commercial License", "Contact [email protected]", WARNING},- {"Trademarks", "See TRADEMARKS section above", TEXT_SECONDARY},- {"CLA", "Contributor License Agreement in repo", TEXT_SECONDARY},- {"Website", "https://fincept.in", ACCENT},- };-- // 3x2 grid- for (int i = 0; i < 6; i += 2) {- ImGui::BeginGroup();-- for (int j = 0; j < 2 && (i + j) < 6; j++) {- if (j > 0) ImGui::SameLine(0, 12);- auto& r = resources[i + j];-- ImGui::PushStyleColor(ImGuiCol_ChildBg, BG_PANEL);- char id[32];- std::snprintf(id, sizeof(id), "##res_%d", i + j);- ImGui::BeginChild(id, ImVec2(col_w, 60), ImGuiChildFlags_Borders);-- ImGui::SetCursorPos(ImVec2(16, 8));- ImGui::TextColored(TEXT_PRIMARY, "%s", r.label);- ImGui::SetCursorPosX(16);- ImGui::TextColored(r.color, "%s", r.url);-- ImGui::EndChild();- ImGui::PopStyleColor();- }+ ImGui::Spacing();++ // CLA+ theme::SectionHeader("CONTRIBUTOR AGREEMENT");+ if (ImGui::BeginTable("##cla", 2, TBL)) {+ ImGui::TableSetupColumn("Field", ImGuiTableColumnFlags_WidthFixed, 120);+ ImGui::TableSetupColumn("Value");- ImGui::EndGroup();+ info_row("CLA", "Required for contributions", TEXT_PRIMARY);+ info_row("Location", "See CLA file in repository", TEXT_SECONDARY);++ ImGui::EndTable();}}// =============================================================================-// Contact+// Right panel — Resources & Contact// =============================================================================-void AboutScreen::render_contact() {- using namespace theme::colors;+void AboutScreen::render_resources_panel(float width, float height) {+ (void)width; (void)height;++ ImGui::TextColored(ACCENT, "RESOURCES & CONTACT");+ ImGui::Separator();++ // Quick Links+ theme::SectionHeader("QUICK LINKS");+ if (ImGui::BeginTable("##links", 2, TBL)) {+ ImGui::TableSetupColumn("Resource", ImGuiTableColumnFlags_WidthFixed, 120);+ ImGui::TableSetupColumn("Location");++ info_row("Website", "fincept.in", ACCENT);+ info_row("GitHub", "github.com/Fincept-Corporation", INFO);+ info_row("MS Store", "apps.microsoft.com", INFO);+ info_row("Releases", "GitHub Releases page", TEXT_SECONDARY);+ info_row("License", "LICENSE in repo root", TEXT_SECONDARY);+ info_row("Docs", "docs/ directory", TEXT_SECONDARY);++ ImGui::EndTable();+ }+ ImGui::Spacing();++ // Contacttheme::SectionHeader("CONTACT");+ if (ImGui::BeginTable("##contact", 2, TBL)) {+ ImGui::TableSetupColumn("Department", ImGuiTableColumnFlags_WidthFixed, 120);+ ImGui::TableSetupColumn("Email");- float avail = ImGui::GetContentRegionAvail().x;- float col_w = (avail - 12) * 0.5f;-- struct Contact {- const char* dept;- const char* email;- ImVec4 color;- };-- Contact contacts[] = {- {"General Inquiries", "[email protected]", INFO},- {"Commercial Licensing","[email protected]", ACCENT},- {"Security Issues", "[email protected]", ERROR_RED},- {"Legal", "[email protected]", WARNING},- };-- // 2x2 grid- for (int i = 0; i < 4; i += 2) {- ImGui::BeginGroup();-- for (int j = 0; j < 2; j++) {- if (j > 0) ImGui::SameLine(0, 12);- auto& c = contacts[i + j];-- ImGui::PushStyleColor(ImGuiCol_ChildBg, BG_PANEL);- char id[32];- std::snprintf(id, sizeof(id), "##contact_%d", i + j);- ImGui::BeginChild(id, ImVec2(col_w, 60), ImGuiChildFlags_Borders);-- ImGui::SetCursorPos(ImVec2(16, 8));- ImGui::TextColored(TEXT_PRIMARY, "%s", c.dept);- ImGui::SetCursorPosX(16);- ImGui::TextColored(c.color, "%s", c.email);-- ImGui::EndChild();- ImGui::PopStyleColor();- }+ info_row("General", "[email protected]", INFO);+ info_row("Commercial", "[email protected]", ACCENT);+ info_row("Security", "[email protected]", ERROR_RED);+ info_row("Legal", "[email protected]", WARNING);++ ImGui::EndTable();+ }- ImGui::EndGroup();+ ImGui::Spacing();++ // Community+ theme::SectionHeader("COMMUNITY");+ if (ImGui::BeginTable("##community", 2, TBL)) {+ ImGui::TableSetupColumn("Platform", ImGuiTableColumnFlags_WidthFixed, 120);+ ImGui::TableSetupColumn("Link");++ info_row("Discord", "discord.gg/ae87a8ygbN", INFO);+ info_row("Forum", "In-app Forum tab", TEXT_SECONDARY);+ info_row("Discussions", "GitHub Discussions", TEXT_SECONDARY);++ ImGui::EndTable();}ImGui::Spacing();- // Discord link- ImGui::PushStyleColor(ImGuiCol_ChildBg, BG_PANEL);- ImGui::BeginChild("##discord", ImVec2(0, 0),- ImGuiChildFlags_AutoResizeY | ImGuiChildFlags_Borders);- ImGui::SetCursorPos(ImVec2(16, 8));- ImGui::TextColored(INFO, "Discord Community");- ImGui::SetCursorPosX(16);- ImGui::TextColored(TEXT_SECONDARY, "Join our community: discord.gg/ae87a8ygbN");+ // Technology Stack+ theme::SectionHeader("TECHNOLOGY STACK");+ if (ImGui::BeginTable("##techstack", 2, TBL)) {+ ImGui::TableSetupColumn("Layer", ImGuiTableColumnFlags_WidthFixed, 120);+ ImGui::TableSetupColumn("Technology");++ info_row("Frontend", "ImGui + OpenGL", TEXT_PRIMARY);+ info_row("Backend", "C++ / Python", TEXT_PRIMARY);+ info_row("Database", "SQLite", TEXT_PRIMARY);+ info_row("Networking", "REST + WebSocket", TEXT_PRIMARY);+ info_row("Charts", "Custom ImGui Canvas", TEXT_PRIMARY);+ info_row("AI / LLM", "Multi-provider", TEXT_PRIMARY);+ info_row("Quant", "QuantLib + Custom", TEXT_PRIMARY);+ info_row("Crypto", "Kraken / HyperLiquid", TEXT_PRIMARY);++ ImGui::EndTable();+ }+ImGui::Spacing();- ImGui::EndChild();- ImGui::PopStyleColor();++ // Build+ theme::SectionHeader("BUILD");+ if (ImGui::BeginTable("##build_info", 2, TBL)) {+ ImGui::TableSetupColumn("Field", ImGuiTableColumnFlags_WidthFixed, 120);+ ImGui::TableSetupColumn("Value");++ info_row("Compiler", "MSVC / GCC / Clang", TEXT_PRIMARY);+ info_row("Build Sys", "CMake + Ninja", TEXT_PRIMARY);+ info_row("Packages", "vcpkg", TEXT_PRIMARY);+#ifdef NDEBUG+ info_row("Config", "Release", MARKET_GREEN);+#else+ info_row("Config", "Debug", WARNING);+#endif++ ImGui::EndTable();+ }}} // namespace fincept::aboutdiff --git a/fincept-cpp/src/screens/about/about_screen.h b/fincept-cpp/src/screens/about/about_screen.hindex 1b95ba964..35d6711fa 100644--- a/fincept-cpp/src/screens/about/about_screen.h+++ b/fincept-cpp/src/screens/about/about_screen.h@@ -1,5 +1,6 @@#pragma once-// About screen — static info page showing version, license, resources, contact+// About screen — Bloomberg terminal style info page+// Dense three-panel layout: System Info | License & Legal | Resources & Contact#include <imgui.h>@@ -10,11 +11,10 @@ public:void render();private:- void render_version_info();- void render_license_panels();- void render_trademarks();- void render_resources();- void render_contact();+ void render_header_bar();+ void render_system_info(float width, float height);+ void render_license_panel(float width, float height);+ void render_resources_panel(float width, float height);};} // namespace fincept::aboutdiff --git a/fincept-cpp/src/screens/equity_trading/equity_trading_screen.cpp b/fincept-cpp/src/screens/equity_trading/equity_trading_screen.cppnew file mode 100644index 000000000..dbf727246--- /dev/null+++ b/fincept-cpp/src/screens/equity_trading/equity_trading_screen.cpp@@ -0,0 +1,1198 @@+#include "equity_trading_screen.h"+#include "ui/theme.h"+#include "core/logger.h"+#include "trading/broker_registry.h"+#include <imgui.h>+#include <cstdio>+#include <cstring>+#include <cmath>+#include <algorithm>+#include <chrono>+#include <future>++namespace fincept::equity_trading {++using namespace theme::colors;+static constexpr const char* TAG = "EquityTrading";++// Named constants (ES.45)+static constexpr float NAV_HEIGHT = 32.0f;+static constexpr float TICKER_HEIGHT = 48.0f;+static constexpr float STATUS_HEIGHT = 22.0f;+static constexpr float LEFT_PANEL_WIDTH = 220.0f;+static constexpr float RIGHT_PANEL_WIDTH = 280.0f;+static constexpr float BOTTOM_PANEL_FRAC = 0.32f;+static constexpr int MAX_DEPTH_LEVELS = 10;+static constexpr int MAX_CHART_CANDLES = 200;++// ============================================================================+// Initialization+// ============================================================================++void EquityTradingScreen::init() {+ LOG_INFO(TAG, "Initializing equity trading screen");++ // Build default watchlist+ watchlist_.clear();+ for (int i = 0; i < DEFAULT_WATCHLIST_COUNT; ++i) {+ WatchlistEntry e;+ e.symbol = DEFAULT_WATCHLIST[i];+ e.exchange = "NSE";+ watchlist_.push_back(e);+ }++ // Copy selected symbol to order form+ std::strncpy(order_form_.symbol_buf, selected_symbol_.c_str(),+ sizeof(order_form_.symbol_buf) - 1);++ initialized_ = true;+ LOG_INFO(TAG, "Initialized with %d watchlist entries", static_cast<int>(watchlist_.size()));+}++// ============================================================================+// Main render — polls futures, lays out multi-panel Bloomberg-style UI+// ============================================================================++void EquityTradingScreen::render() {+ if (!initialized_) init();++ // Poll async futures+ if (quote_future_.valid()) {+ if (quote_future_.wait_for(std::chrono::milliseconds(0)) == std::future_status::ready) {+ try {+ current_quote_ = quote_future_.get();+ has_quote_ = true;+ } catch (...) {+ LOG_WARN(TAG, "Quote fetch failed");+ }+ loading_quote_ = false;+ }+ }++ if (candle_future_.valid()) {+ if (candle_future_.wait_for(std::chrono::milliseconds(0)) == std::future_status::ready) {+ try {+ candles_ = candle_future_.get();+ } catch (...) {+ LOG_WARN(TAG, "Candle fetch failed");+ }+ loading_candles_ = false;+ }+ }++ const ImVec2 avail = ImGui::GetContentRegionAvail();+ const float w = avail.x;+ const float total_h = avail.y;++ // Layout: top_nav | ticker_bar | [watchlist | chart+bottom | order+depth] | status+ render_top_nav(w);+ render_ticker_bar(w);++ const float body_y = ImGui::GetCursorPosY();+ const float body_h = total_h - body_y - STATUS_HEIGHT;++ if (body_h > 50.0f) {+ const float left_w = LEFT_PANEL_WIDTH;+ const float right_w = RIGHT_PANEL_WIDTH;+ const float center_w = w - left_w - right_w;++ const float bottom_h = bottom_minimized_ ? 0.0f : body_h * BOTTOM_PANEL_FRAC;+ const float chart_h = body_h - bottom_h;++ // Left panel — watchlist+ render_watchlist_panel(0.0f, body_y, left_w, body_h);++ // Center — chart + bottom+ render_chart_panel(left_w, body_y, center_w, chart_h);+ if (!bottom_minimized_) {+ render_bottom_panel(left_w, body_y + chart_h, center_w, bottom_h);+ }++ // Right — order entry + order book+ const float order_h = body_h * 0.55f;+ const float depth_h = body_h - order_h;+ render_order_entry(left_w + center_w, body_y, right_w, order_h);+ render_order_book(left_w + center_w, body_y + order_h, right_w, depth_h);+ }++ render_status_bar(w, total_h);+}++// ============================================================================+// Top Navigation Bar+// ============================================================================++void EquityTradingScreen::render_top_nav(float w) {+ ImGui::PushStyleColor(ImGuiCol_ChildBg, BG_DARKEST);+ ImGui::BeginChild("##eq_nav", ImVec2(w, NAV_HEIGHT), false);++ // Broker status+ if (is_connected_ && active_broker_.has_value()) {+ ImGui::TextColored(SUCCESS, " CONNECTED");+ ImGui::SameLine();+ ImGui::TextColored(TEXT_SECONDARY, "| %s", trading::broker_id_str(*active_broker_));+ } else {+ ImGui::TextColored(TEXT_DIM, " DISCONNECTED");+ }++ ImGui::SameLine();+ ImGui::SetCursorPosX(w * 0.3f);++ // Exchange selector+ ImGui::SetNextItemWidth(100.0f);+ if (ImGui::BeginCombo("##exchange", EXCHANGES[exchange_idx_].code)) {+ for (int i = 0; i < EXCHANGE_COUNT; ++i) {+ const bool selected = (i == exchange_idx_);+ char label[128];+ std::snprintf(label, sizeof(label), "%s - %s", EXCHANGES[i].code, EXCHANGES[i].name);+ if (ImGui::Selectable(label, selected)) {+ exchange_idx_ = i;+ selected_exchange_ = EXCHANGES[i].code;+ }+ if (selected) ImGui::SetItemDefaultFocus();+ }+ ImGui::EndCombo();+ }++ ImGui::SameLine();++ // Symbol input+ ImGui::SetNextItemWidth(120.0f);+ if (ImGui::InputText("##sym_input", symbol_buf_, sizeof(symbol_buf_),+ ImGuiInputTextFlags_EnterReturnsTrue)) {+ select_symbol(symbol_buf_, selected_exchange_);+ }+ ImGui::SameLine();+ if (ImGui::SmallButton("GO")) {+ select_symbol(symbol_buf_, selected_exchange_);+ }++ ImGui::SameLine();+ ImGui::SetCursorPosX(w - 200.0f);++ // Paper/Live toggle+ if (is_paper_mode_) {+ ImGui::PushStyleColor(ImGuiCol_Button, ImVec4(0.1f, 0.3f, 0.1f, 1.0f));+ if (ImGui::SmallButton("PAPER")) { is_paper_mode_ = false; }+ ImGui::PopStyleColor();+ } else {+ ImGui::PushStyleColor(ImGuiCol_Button, ImVec4(0.5f, 0.1f, 0.1f, 1.0f));+ if (ImGui::SmallButton("LIVE")) { is_paper_mode_ = true; }+ ImGui::PopStyleColor();+ }++ ImGui::SameLine();++ // Broker connect buttons+ if (!is_connected_) {+ if (ImGui::SmallButton("Connect Broker")) {+ bottom_tab_ = BottomTab::brokers;+ }+ } else {+ if (ImGui::SmallButton("Disconnect")) {+ is_connected_ = false;+ active_broker_ = std::nullopt;+ }+ }++ ImGui::EndChild();+ ImGui::PopStyleColor();+}++// ============================================================================+// Ticker Bar — current symbol quote strip+// ============================================================================++void EquityTradingScreen::render_ticker_bar(float w) {+ ImGui::PushStyleColor(ImGuiCol_ChildBg, BG_DARK);+ ImGui::BeginChild("##eq_ticker", ImVec2(w, TICKER_HEIGHT), false);++ // Symbol name+ ImGui::SetCursorPos(ImVec2(8.0f, 4.0f));+ ImGui::PushFont(nullptr); // default font+ ImGui::TextColored(ACCENT, "%s", selected_symbol_.c_str());+ ImGui::PopFont();++ ImGui::SameLine();+ ImGui::TextColored(TEXT_DIM, " %s", selected_exchange_.c_str());++ if (has_quote_) {+ ImGui::SameLine(0.0f, 24.0f);++ // LTP+ ImGui::TextColored(TEXT_PRIMARY, "%.2f", current_quote_.ltp);+ ImGui::SameLine();++ // Change+ const auto& chg_color = (current_quote_.change >= 0.0) ? MARKET_GREEN : MARKET_RED;+ const char* arrow = (current_quote_.change >= 0.0) ? "+" : "";+ ImGui::TextColored(chg_color, "%s%.2f (%.2f%%)", arrow,+ current_quote_.change, current_quote_.change_pct);++ // OHLV strip+ ImGui::SameLine(0.0f, 32.0f);+ ImGui::TextColored(TEXT_DIM, "O:");+ ImGui::SameLine(0.0f, 2.0f);+ ImGui::TextColored(TEXT_SECONDARY, "%.2f", current_quote_.open);++ ImGui::SameLine(0.0f, 12.0f);+ ImGui::TextColored(TEXT_DIM, "H:");+ ImGui::SameLine(0.0f, 2.0f);+ ImGui::TextColored(TEXT_SECONDARY, "%.2f", current_quote_.high);++ ImGui::SameLine(0.0f, 12.0f);+ ImGui::TextColored(TEXT_DIM, "L:");+ ImGui::SameLine(0.0f, 2.0f);+ ImGui::TextColored(TEXT_SECONDARY, "%.2f", current_quote_.low);++ ImGui::SameLine(0.0f, 12.0f);+ ImGui::TextColored(TEXT_DIM, "V:");+ ImGui::SameLine(0.0f, 2.0f);++ // Format volume with K/M/B+ if (current_quote_.volume >= 1e9)+ ImGui::TextColored(TEXT_SECONDARY, "%.1fB", current_quote_.volume / 1e9);+ else if (current_quote_.volume >= 1e6)+ ImGui::TextColored(TEXT_SECONDARY, "%.1fM", current_quote_.volume / 1e6);+ else if (current_quote_.volume >= 1e3)+ ImGui::TextColored(TEXT_SECONDARY, "%.1fK", current_quote_.volume / 1e3);+ else+ ImGui::TextColored(TEXT_SECONDARY, "%.0f", current_quote_.volume);++ // Bid/Ask+ ImGui::SameLine(0.0f, 32.0f);+ ImGui::TextColored(MARKET_GREEN, "Bid: %.2f", current_quote_.bid);+ ImGui::SameLine(0.0f, 12.0f);+ ImGui::TextColored(MARKET_RED, "Ask: %.2f", current_quote_.ask);+ } else if (loading_quote_) {+ ImGui::SameLine(0.0f, 24.0f);+ ImGui::TextColored(TEXT_DIM, "Loading...");+ } else {+ ImGui::SameLine(0.0f, 24.0f);+ ImGui::TextColored(TEXT_DIM, "No quote data — connect a broker or fetch data");+ }++ ImGui::EndChild();+ ImGui::PopStyleColor();+}++// ============================================================================+// Watchlist Panel (left sidebar)+// ============================================================================++void EquityTradingScreen::render_watchlist_panel(float x, float y, float w, float h) {+ ImGui::SetCursorPos(ImVec2(x, y));+ ImGui::PushStyleColor(ImGuiCol_ChildBg, BG_PANEL);+ ImGui::BeginChild("##eq_watchlist", ImVec2(w, h), true);++ // Sidebar tabs+ if (ImGui::SmallButton(sidebar_view_ == SidebarView::watchlist ? "[STOCKS]" : "STOCKS")) {+ sidebar_view_ = SidebarView::watchlist;+ }+ ImGui::SameLine();+ if (ImGui::SmallButton(sidebar_view_ == SidebarView::indices ? "[INDICES]" : "INDICES")) {+ sidebar_view_ = SidebarView::indices;+ }++ ImGui::Separator();++ if (sidebar_view_ == SidebarView::watchlist) {+ // Search filter+ ImGui::SetNextItemWidth(w - 16.0f);+ ImGui::InputTextWithHint("##wl_search", "Search...", watchlist_search_,+ sizeof(watchlist_search_));++ const std::string filter(watchlist_search_);++ // Watchlist table+ if (ImGui::BeginTable("##wl_tbl", 3,+ ImGuiTableFlags_RowBg | ImGuiTableFlags_ScrollY | ImGuiTableFlags_SizingStretchProp,+ ImVec2(0, h - 70.0f))) {+ ImGui::TableSetupColumn("Symbol", ImGuiTableColumnFlags_None, 0.4f);+ ImGui::TableSetupColumn("LTP", ImGuiTableColumnFlags_None, 0.3f);+ ImGui::TableSetupColumn("Chg%", ImGuiTableColumnFlags_None, 0.3f);+ ImGui::TableHeadersRow();++ for (const auto& entry : watchlist_) {+ // Filter+ if (!filter.empty()) {+ bool match = false;+ for (size_t i = 0; i < entry.symbol.size() && i < filter.size(); ++i) {+ if (std::tolower(static_cast<unsigned char>(entry.symbol[i])) !=+ std::tolower(static_cast<unsigned char>(filter[i]))) break;+ if (i + 1 == filter.size()) match = true;+ }+ if (!match && entry.symbol.find(filter) == std::string::npos) continue;+ }++ ImGui::TableNextRow();+ ImGui::TableNextColumn();++ // Selectable row+ const bool is_sel = (entry.symbol == selected_symbol_);+ if (ImGui::Selectable(entry.symbol.c_str(), is_sel,+ ImGuiSelectableFlags_SpanAllColumns)) {+ select_symbol(entry.symbol, entry.exchange);+ }++ ImGui::TableNextColumn();+ if (entry.ltp > 0.0) {+ ImGui::Text("%.2f", entry.ltp);+ } else {+ ImGui::TextColored(TEXT_DIM, "--");+ }++ ImGui::TableNextColumn();+ if (std::abs(entry.change_pct) > 0.001) {+ const auto& c = (entry.change_pct >= 0.0) ? MARKET_GREEN : MARKET_RED;+ ImGui::TextColored(c, "%+.2f%%", entry.change_pct);+ } else {+ ImGui::TextColored(TEXT_DIM, "0.00%%");+ }+ }+ ImGui::EndTable();+ }++ // Refresh button+ if (loading_watchlist_) {+ ImGui::TextColored(TEXT_DIM, "Refreshing...");+ } else {+ if (ImGui::SmallButton("Refresh Watchlist")) {+ fetch_watchlist_quotes();+ }+ }++ } else {+ // Market Indices view+ ImGui::TextColored(ACCENT, "MARKET INDICES");+ ImGui::Separator();+ for (int i = 0; i < MARKET_INDICES_COUNT; ++i) {+ const auto& idx = MARKET_INDICES[i];+ if (ImGui::Selectable(idx.symbol, false)) {+ select_symbol(idx.symbol, idx.exchange);+ }+ }+ }++ ImGui::EndChild();+ ImGui::PopStyleColor();+}++// ============================================================================+// Chart Panel — candlestick chart via ImGui DrawList+// ============================================================================++void EquityTradingScreen::render_chart_panel(float x, float y, float w, float h) {+ ImGui::SetCursorPos(ImVec2(x, y));+ ImGui::PushStyleColor(ImGuiCol_ChildBg, BG_DARKEST);+ ImGui::BeginChild("##eq_chart", ImVec2(w, h), true);++ // Timeframe buttons+ static constexpr TimeFrame tfs[] = {+ TimeFrame::m1, TimeFrame::m5, TimeFrame::m15, TimeFrame::m30,+ TimeFrame::h1, TimeFrame::h4, TimeFrame::d1, TimeFrame::w1+ };+ for (const auto tf : tfs) {+ const bool active = (tf == chart_timeframe_);+ if (active) ImGui::PushStyleColor(ImGuiCol_Button, ACCENT_DIM);+ if (ImGui::SmallButton(timeframe_label(tf))) {+ chart_timeframe_ = tf;+ // Would trigger candle fetch here+ }+ if (active) ImGui::PopStyleColor();+ ImGui::SameLine();+ }++ // Toggle bottom panel+ ImGui::SameLine(w - 80.0f);+ if (ImGui::SmallButton(bottom_minimized_ ? "Show" : "Hide")) {+ bottom_minimized_ = !bottom_minimized_;+ }++ ImGui::Separator();++ // Chart area+ if (loading_candles_) {+ ImGui::TextColored(TEXT_DIM, "Loading chart data...");+ } else if (candles_.empty()) {+ const float cw = w - 16.0f;+ const float ch = h - 60.0f;+ ImGui::SetCursorPos(ImVec2(cw * 0.3f, ch * 0.4f));+ ImGui::TextColored(TEXT_DIM, "No chart data available");+ ImGui::SetCursorPosX(cw * 0.2f);+ ImGui::TextColored(TEXT_DIM, "Connect a broker to load candle data");+ } else {+ render_candle_chart(w - 16.0f, h - 60.0f);+ }++ ImGui::EndChild();+ ImGui::PopStyleColor();+}++// ============================================================================+// Candle Chart Renderer (ImGui DrawList)+// ============================================================================++void EquityTradingScreen::render_candle_chart(float w, float h) {+ if (candles_.empty() || w < 20.0f || h < 20.0f) return;++ const ImVec2 p = ImGui::GetCursorScreenPos();+ auto* draw = ImGui::GetWindowDrawList();++ // Background+ draw->AddRectFilled(p, ImVec2(p.x + w, p.y + h), IM_COL32(17, 17, 18, 255));++ // Find min/max+ double min_price = 1e18;+ double max_price = -1e18;+ for (const auto& c : candles_) {+ min_price = std::min(min_price, c.low);+ max_price = std::max(max_price, c.high);+ }+ if (max_price <= min_price) max_price = min_price + 1.0;++ const double price_range = max_price - min_price;+ const float padding = h * 0.05f;+ const float chart_h = h - 2.0f * padding;+ const int n = static_cast<int>(candles_.size());+ const float candle_w = std::max(1.0f, (w - 40.0f) / static_cast<float>(n));+ const float gap = std::max(1.0f, candle_w * 0.15f);+ const float body_w = candle_w - gap;++ // Grid lines (5 horizontal)+ for (int i = 0; i <= 4; ++i) {+ const float fy = p.y + padding + chart_h * static_cast<float>(i) / 4.0f;+ draw->AddLine(ImVec2(p.x + 40.0f, fy), ImVec2(p.x + w, fy),+ IM_COL32(50, 50, 55, 100));+ const double price_at = max_price - price_range * static_cast<double>(i) / 4.0;+ char buf[32];+ std::snprintf(buf, sizeof(buf), "%.2f", price_at);+ draw->AddText(ImVec2(p.x + 2.0f, fy - 6.0f), IM_COL32(136, 136, 145, 200), buf);+ }++ // Draw candles+ for (int i = 0; i < n; ++i) {+ const auto& c = candles_[i];+ const float cx = p.x + 40.0f + static_cast<float>(i) * candle_w + candle_w * 0.5f;++ auto price_to_y = [&](double price) -> float {+ return p.y + padding + chart_h * static_cast<float>((max_price - price) / price_range);+ };++ const float y_open = price_to_y(c.open);+ const float y_close = price_to_y(c.close);+ const float y_high = price_to_y(c.high);+ const float y_low = price_to_y(c.low);++ const bool bullish = (c.close >= c.open);+ const ImU32 col = bullish ? IM_COL32(13, 217, 107, 255) : IM_COL32(245, 64, 64, 255);++ // Wick+ draw->AddLine(ImVec2(cx, y_high), ImVec2(cx, y_low), col, 1.0f);++ // Body+ const float body_top = std::min(y_open, y_close);+ const float body_bot = std::max(y_open, y_close);+ if (body_bot - body_top < 1.0f) {+ draw->AddLine(ImVec2(cx - body_w * 0.5f, body_top),+ ImVec2(cx + body_w * 0.5f, body_top), col, 1.0f);+ } else {+ draw->AddRectFilled(+ ImVec2(cx - body_w * 0.5f, body_top),+ ImVec2(cx + body_w * 0.5f, body_bot), col);+ }+ }++ // Advance cursor+ ImGui::Dummy(ImVec2(w, h));+}++// ============================================================================+// Bottom Panel — positions, holdings, orders, history, brokers tabs+// ============================================================================++void EquityTradingScreen::render_bottom_panel(float x, float y, float w, float h) {+ ImGui::SetCursorPos(ImVec2(x, y));+ ImGui::PushStyleColor(ImGuiCol_ChildBg, BG_PANEL);+ ImGui::BeginChild("##eq_bottom", ImVec2(w, h), true);++ // Tab bar+ static constexpr BottomTab tabs[] = {+ BottomTab::positions, BottomTab::holdings, BottomTab::orders,+ BottomTab::history, BottomTab::brokers+ };+ for (const auto t : tabs) {+ const bool active = (t == bottom_tab_);+ if (active) ImGui::PushStyleColor(ImGuiCol_Button, ACCENT_DIM);+ if (ImGui::SmallButton(bottom_tab_label(t))) {+ bottom_tab_ = t;+ }+ if (active) ImGui::PopStyleColor();+ ImGui::SameLine();+ }++ // Refresh button+ ImGui::SameLine(w - 70.0f);+ if (ImGui::SmallButton("Refresh")) {+ refresh_portfolio();+ }++ ImGui::Separator();++ const float content_h = h - 50.0f;++ switch (bottom_tab_) {+ case BottomTab::positions: render_positions_table(w, content_h); break;+ case BottomTab::holdings: render_holdings_table(w, content_h); break;+ case BottomTab::orders: render_orders_table(w, content_h); break;+ case BottomTab::history: render_orders_table(w, content_h); break; // reuse+ case BottomTab::brokers: render_broker_config(w, content_h); break;+ }++ ImGui::EndChild();+ ImGui::PopStyleColor();+}++// ============================================================================+// Positions Table+// ============================================================================++void EquityTradingScreen::render_positions_table(float w, float h) {+ if (loading_portfolio_) {+ ImGui::TextColored(TEXT_DIM, "Loading positions...");+ return;+ }+ if (positions_.empty()) {+ ImGui::TextColored(TEXT_DIM, "No open positions");+ return;+ }++ if (ImGui::BeginTable("##pos_tbl", 7,+ ImGuiTableFlags_RowBg | ImGuiTableFlags_ScrollY | ImGuiTableFlags_Borders |+ ImGuiTableFlags_SizingStretchProp, ImVec2(0, h))) {+ ImGui::TableSetupColumn("Symbol", ImGuiTableColumnFlags_None, 0.18f);+ ImGui::TableSetupColumn("Side", ImGuiTableColumnFlags_None, 0.08f);+ ImGui::TableSetupColumn("Qty", ImGuiTableColumnFlags_None, 0.10f);+ ImGui::TableSetupColumn("Avg", ImGuiTableColumnFlags_None, 0.14f);+ ImGui::TableSetupColumn("LTP", ImGuiTableColumnFlags_None, 0.14f);+ ImGui::TableSetupColumn("P&L", ImGuiTableColumnFlags_None, 0.18f);+ ImGui::TableSetupColumn("Day P&L", ImGuiTableColumnFlags_None, 0.18f);+ ImGui::TableHeadersRow();++ for (const auto& pos : positions_) {+ ImGui::TableNextRow();+ ImGui::TableNextColumn();+ ImGui::TextColored(ACCENT, "%s", pos.symbol.c_str());++ ImGui::TableNextColumn();+ const auto& side_col = (pos.side == "buy") ? MARKET_GREEN : MARKET_RED;+ ImGui::TextColored(side_col, "%s", pos.side.c_str());++ ImGui::TableNextColumn();+ ImGui::Text("%.0f", pos.quantity);++ ImGui::TableNextColumn();+ ImGui::Text("%.2f", pos.avg_price);++ ImGui::TableNextColumn();+ ImGui::Text("%.2f", pos.ltp);++ ImGui::TableNextColumn();+ const auto& pnl_col = (pos.pnl >= 0.0) ? MARKET_GREEN : MARKET_RED;+ ImGui::TextColored(pnl_col, "%+.2f", pos.pnl);++ ImGui::TableNextColumn();+ const auto& day_col = (pos.day_pnl >= 0.0) ? MARKET_GREEN : MARKET_RED;+ ImGui::TextColored(day_col, "%+.2f", pos.day_pnl);+ }+ ImGui::EndTable();+ }+}++// ============================================================================+// Holdings Table+// ============================================================================++void EquityTradingScreen::render_holdings_table(float w, float h) {+ if (loading_portfolio_) {+ ImGui::TextColored(TEXT_DIM, "Loading holdings...");+ return;+ }+ if (holdings_.empty()) {+ ImGui::TextColored(TEXT_DIM, "No holdings");+ return;+ }++ if (ImGui::BeginTable("##hold_tbl", 6,+ ImGuiTableFlags_RowBg | ImGuiTableFlags_ScrollY | ImGuiTableFlags_Borders |+ ImGuiTableFlags_SizingStretchProp, ImVec2(0, h))) {+ ImGui::TableSetupColumn("Symbol", ImGuiTableColumnFlags_None, 0.20f);+ ImGui::TableSetupColumn("Qty", ImGuiTableColumnFlags_None, 0.10f);+ ImGui::TableSetupColumn("Avg", ImGuiTableColumnFlags_None, 0.15f);+ ImGui::TableSetupColumn("LTP", ImGuiTableColumnFlags_None, 0.15f);+ ImGui::TableSetupColumn("P&L", ImGuiTableColumnFlags_None, 0.20f);+ ImGui::TableSetupColumn("P&L%", ImGuiTableColumnFlags_None, 0.20f);+ ImGui::TableHeadersRow();++ for (const auto& hld : holdings_) {+ ImGui::TableNextRow();+ ImGui::TableNextColumn();+ ImGui::TextColored(ACCENT, "%s", hld.symbol.c_str());++ ImGui::TableNextColumn();+ ImGui::Text("%.0f", hld.quantity);++ ImGui::TableNextColumn();+ ImGui::Text("%.2f", hld.avg_price);++ ImGui::TableNextColumn();+ ImGui::Text("%.2f", hld.ltp);++ ImGui::TableNextColumn();+ const auto& c = (hld.pnl >= 0.0) ? MARKET_GREEN : MARKET_RED;+ ImGui::TextColored(c, "%+.2f", hld.pnl);++ ImGui::TableNextColumn();+ ImGui::TextColored(c, "%+.2f%%", hld.pnl_pct);+ }+ ImGui::EndTable();+ }+}++// ============================================================================+// Orders Table+// ============================================================================++void EquityTradingScreen::render_orders_table(float w, float h) {+ if (loading_portfolio_) {+ ImGui::TextColored(TEXT_DIM, "Loading orders...");+ return;+ }+ if (orders_.empty()) {+ ImGui::TextColored(TEXT_DIM, "No orders");+ return;+ }++ if (ImGui::BeginTable("##ord_tbl", 7,+ ImGuiTableFlags_RowBg | ImGuiTableFlags_ScrollY | ImGuiTableFlags_Borders |+ ImGuiTableFlags_SizingStretchProp, ImVec2(0, h))) {+ ImGui::TableSetupColumn("Symbol", ImGuiTableColumnFlags_None, 0.15f);+ ImGui::TableSetupColumn("Side", ImGuiTableColumnFlags_None, 0.08f);+ ImGui::TableSetupColumn("Type", ImGuiTableColumnFlags_None, 0.10f);+ ImGui::TableSetupColumn("Qty", ImGuiTableColumnFlags_None, 0.10f);+ ImGui::TableSetupColumn("Price", ImGuiTableColumnFlags_None, 0.14f);+ ImGui::TableSetupColumn("Status", ImGuiTableColumnFlags_None, 0.13f);+ ImGui::TableSetupColumn("Time", ImGuiTableColumnFlags_None, 0.30f);+ ImGui::TableHeadersRow();++ for (const auto& ord : orders_) {+ ImGui::TableNextRow();+ ImGui::TableNextColumn();+ ImGui::TextColored(ACCENT, "%s", ord.symbol.c_str());++ ImGui::TableNextColumn();+ const auto& sc = (ord.side == "buy") ? MARKET_GREEN : MARKET_RED;+ ImGui::TextColored(sc, "%s", ord.side.c_str());++ ImGui::TableNextColumn();+ ImGui::Text("%s", ord.order_type.c_str());++ ImGui::TableNextColumn();+ ImGui::Text("%.0f", ord.quantity);++ ImGui::TableNextColumn();+ ImGui::Text("%.2f", ord.price);++ ImGui::TableNextColumn();+ // Color by status+ ImVec4 status_col = TEXT_SECONDARY;+ if (ord.status == "filled") status_col = SUCCESS;+ else if (ord.status == "pending") status_col = WARNING;+ else if (ord.status == "cancelled" || ord.status == "rejected") status_col = ERROR_RED;+ ImGui::TextColored(status_col, "%s", ord.status.c_str());++ ImGui::TableNextColumn();+ ImGui::TextColored(TEXT_DIM, "%s", ord.timestamp.c_str());+ }+ ImGui::EndTable();+ }+}++// ============================================================================+// Broker Configuration Panel+// ============================================================================++void EquityTradingScreen::render_broker_config(float w, float h) {+ ImGui::TextColored(ACCENT, "BROKER CONNECTIONS");+ ImGui::Separator();+ ImGui::Spacing();++ // List available brokers in a grid+ const auto& reg = trading::BrokerRegistry::instance();+ const auto broker_ids = reg.list_brokers();++ if (ImGui::BeginTable("##broker_grid", 4,+ ImGuiTableFlags_RowBg | ImGuiTableFlags_Borders | ImGuiTableFlags_SizingStretchSame,+ ImVec2(0, h - 40.0f))) {+ ImGui::TableSetupColumn("Broker");+ ImGui::TableSetupColumn("Region");+ ImGui::TableSetupColumn("Status");+ ImGui::TableSetupColumn("Action");+ ImGui::TableHeadersRow();++ // Show all known brokers from BrokerId enum+ struct BrokerInfo { trading::BrokerId id; const char* name; const char* region; };+ static constexpr BrokerInfo known_brokers[] = {+ {trading::BrokerId::Fyers, "Fyers", "India"},+ {trading::BrokerId::Zerodha, "Zerodha", "India"},+ {trading::BrokerId::Upstox, "Upstox", "India"},+ {trading::BrokerId::Dhan, "Dhan", "India"},+ {trading::BrokerId::AngelOne, "Angel One", "India"},+ {trading::BrokerId::Groww, "Groww", "India"},+ {trading::BrokerId::Kotak, "Kotak", "India"},+ {trading::BrokerId::AliceBlue, "AliceBlue", "India"},+ {trading::BrokerId::Alpaca, "Alpaca", "US"},+ {trading::BrokerId::IBKR, "IBKR", "US"},+ {trading::BrokerId::Tradier, "Tradier", "US"},+ {trading::BrokerId::SaxoBank, "Saxo Bank", "EU"},+ };++ for (const auto& b : known_brokers) {+ ImGui::TableNextRow();+ ImGui::TableNextColumn();+ ImGui::Text("%s", b.name);++ ImGui::TableNextColumn();+ ImGui::TextColored(TEXT_DIM, "%s", b.region);++ ImGui::TableNextColumn();+ const bool connected = (active_broker_.has_value() && *active_broker_ == b.id && is_connected_);+ if (connected) {+ ImGui::TextColored(SUCCESS, "Connected");+ } else {+ ImGui::TextColored(TEXT_DIM, "Offline");+ }++ ImGui::TableNextColumn();+ char btn_id[64];+ std::snprintf(btn_id, sizeof(btn_id), "Connect##%s", b.name);+ if (!connected) {+ if (ImGui::SmallButton(btn_id)) {+ connect_broker(b.id);+ }+ } else {+ std::snprintf(btn_id, sizeof(btn_id), "Disconnect##%s", b.name);+ if (ImGui::SmallButton(btn_id)) {+ is_connected_ = false;+ active_broker_ = std::nullopt;+ }+ }+ }+ ImGui::EndTable();+ }+}++// ============================================================================+// Order Entry Panel (right side, top)+// ============================================================================++void EquityTradingScreen::render_order_entry(float x, float y, float w, float h) {+ ImGui::SetCursorPos(ImVec2(x, y));+ ImGui::PushStyleColor(ImGuiCol_ChildBg, BG_PANEL);+ ImGui::BeginChild("##eq_order", ImVec2(w, h), true);++ ImGui::TextColored(ACCENT, "ORDER ENTRY");+ ImGui::Separator();++ const float input_w = w - 24.0f;++ // Buy / Sell toggle+ {+ const bool is_buy = (order_form_.side == trading::OrderSide::Buy);+ if (is_buy) ImGui::PushStyleColor(ImGuiCol_Button, ImVec4(0.0f, 0.5f, 0.2f, 1.0f));+ else ImGui::PushStyleColor(ImGuiCol_Button, BG_WIDGET);+ if (ImGui::Button("BUY", ImVec2(input_w * 0.48f, 28.0f))) {+ order_form_.side = trading::OrderSide::Buy;+ }+ ImGui::PopStyleColor();++ ImGui::SameLine();++ if (!is_buy) ImGui::PushStyleColor(ImGuiCol_Button, ImVec4(0.5f, 0.1f, 0.1f, 1.0f));+ else ImGui::PushStyleColor(ImGuiCol_Button, BG_WIDGET);+ if (ImGui::Button("SELL", ImVec2(input_w * 0.48f, 28.0f))) {+ order_form_.side = trading::OrderSide::Sell;+ }+ ImGui::PopStyleColor();+ }++ ImGui::Spacing();++ // Symbol+ ImGui::TextColored(TEXT_DIM, "Symbol");+ ImGui::SetNextItemWidth(input_w);+ ImGui::InputText("##ord_sym", order_form_.symbol_buf, sizeof(order_form_.symbol_buf));++ // Order type+ ImGui::TextColored(TEXT_DIM, "Type");+ ImGui::SetNextItemWidth(input_w);+ static constexpr const char* type_labels[] = {"Market", "Limit", "Stop Loss", "SL Limit"};+ int type_idx = static_cast<int>(order_form_.type);+ if (ImGui::Combo("##ord_type", &type_idx, type_labels, 4)) {+ order_form_.type = static_cast<trading::OrderType>(type_idx);+ }++ // Product type+ ImGui::TextColored(TEXT_DIM, "Product");+ ImGui::SetNextItemWidth(input_w);+ static constexpr const char* prod_labels[] = {"Intraday", "Delivery", "Margin", "Cover", "Bracket"};+ int prod_idx = static_cast<int>(order_form_.product);+ if (ImGui::Combo("##ord_prod", &prod_idx, prod_labels, 5)) {+ order_form_.product = static_cast<trading::ProductType>(prod_idx);+ }++ // Quantity+ ImGui::TextColored(TEXT_DIM, "Quantity");+ ImGui::SetNextItemWidth(input_w);+ ImGui::InputDouble("##ord_qty", &order_form_.quantity, 1.0, 10.0, "%.0f");++ // Price (for limit/SL orders)+ if (order_form_.type != trading::OrderType::Market) {+ ImGui::TextColored(TEXT_DIM, "Price");+ ImGui::SetNextItemWidth(input_w);+ ImGui::InputDouble("##ord_price", &order_form_.price, 0.05, 1.0, "%.2f");+ }++ // Stop price+ if (order_form_.type == trading::OrderType::StopLoss ||+ order_form_.type == trading::OrderType::StopLossLimit) {+ ImGui::TextColored(TEXT_DIM, "Trigger Price");+ ImGui::SetNextItemWidth(input_w);+ ImGui::InputDouble("##ord_trigger", &order_form_.stop_price, 0.05, 1.0, "%.2f");+ }++ ImGui::Spacing();+ ImGui::Separator();+ ImGui::Spacing();++ // Estimated value+ const double est_value = order_form_.quantity *+ (order_form_.type == trading::OrderType::Market ? current_quote_.ltp : order_form_.price);+ if (est_value > 0.0) {+ ImGui::TextColored(TEXT_DIM, "Est. Value:");+ ImGui::SameLine();+ ImGui::TextColored(TEXT_PRIMARY, "%.2f", est_value);+ }++ // Available funds+ if (funds_.has_value()) {+ ImGui::TextColored(TEXT_DIM, "Available:");+ ImGui::SameLine();+ ImGui::TextColored(MARKET_GREEN, "%.2f", funds_->available_balance);+ }++ ImGui::Spacing();++ // Place order button+ const bool can_order = is_connected_ || is_paper_mode_;+ if (!can_order) ImGui::BeginDisabled();++ const bool is_buy = (order_form_.side == trading::OrderSide::Buy);+ const ImVec4 btn_col = is_buy ? ImVec4(0.0f, 0.6f, 0.25f, 1.0f)+ : ImVec4(0.7f, 0.15f, 0.15f, 1.0f);+ ImGui::PushStyleColor(ImGuiCol_Button, btn_col);+ const char* btn_text = is_buy ? "PLACE BUY ORDER" : "PLACE SELL ORDER";+ if (ImGui::Button(btn_text, ImVec2(input_w, 32.0f))) {+ place_order();+ }+ ImGui::PopStyleColor();++ if (!can_order) ImGui::EndDisabled();++ if (!can_order) {+ ImGui::TextColored(WARNING, "Connect broker or enable paper mode");+ }++ ImGui::EndChild();+ ImGui::PopStyleColor();+}++// ============================================================================+// Order Book / Market Depth Panel (right side, bottom)+// ============================================================================++void EquityTradingScreen::render_order_book(float x, float y, float w, float h) {+ ImGui::SetCursorPos(ImVec2(x, y));+ ImGui::PushStyleColor(ImGuiCol_ChildBg, BG_DARK);+ ImGui::BeginChild("##eq_depth", ImVec2(w, h), true);++ ImGui::TextColored(ACCENT, "MARKET DEPTH");+ ImGui::Separator();++ // Placeholder depth — in a real implementation, broker.get_quotes() or WS feed populates this+ if (ImGui::BeginTable("##depth_tbl", 4,+ ImGuiTableFlags_RowBg | ImGuiTableFlags_Borders |+ ImGuiTableFlags_SizingStretchProp, ImVec2(0, h - 40.0f))) {+ ImGui::TableSetupColumn("Bid Qty", ImGuiTableColumnFlags_None, 0.25f);+ ImGui::TableSetupColumn("Bid", ImGuiTableColumnFlags_None, 0.25f);+ ImGui::TableSetupColumn("Ask", ImGuiTableColumnFlags_None, 0.25f);+ ImGui::TableSetupColumn("Ask Qty", ImGuiTableColumnFlags_None, 0.25f);+ ImGui::TableHeadersRow();++ // If we have a quote, generate synthetic depth levels+ if (has_quote_ && current_quote_.ltp > 0.0) {+ const double mid = current_quote_.ltp;+ const double tick = std::max(0.05, mid * 0.001);++ for (int i = 0; i < MAX_DEPTH_LEVELS; ++i) {+ ImGui::TableNextRow();+ const double bid_price = mid - tick * static_cast<double>(i + 1);+ const double ask_price = mid + tick * static_cast<double>(i + 1);++ ImGui::TableNextColumn();+ ImGui::TextColored(MARKET_GREEN, "%d", (MAX_DEPTH_LEVELS - i) * 100);++ ImGui::TableNextColumn();+ ImGui::TextColored(MARKET_GREEN, "%.2f", bid_price);++ ImGui::TableNextColumn();+ ImGui::TextColored(MARKET_RED, "%.2f", ask_price);++ ImGui::TableNextColumn();+ ImGui::TextColored(MARKET_RED, "%d", (i + 1) * 80);+ }+ } else {+ for (int i = 0; i < 5; ++i) {+ ImGui::TableNextRow();+ for (int j = 0; j < 4; ++j) {+ ImGui::TableNextColumn();+ ImGui::TextColored(TEXT_DIM, "--");+ }+ }+ }++ ImGui::EndTable();+ }++ ImGui::EndChild();+ ImGui::PopStyleColor();+}++// ============================================================================+// Status Bar+// ============================================================================++void EquityTradingScreen::render_status_bar(float w, float total_h) {+ ImGui::SetCursorPos(ImVec2(0.0f, total_h - STATUS_HEIGHT));+ ImGui::PushStyleColor(ImGuiCol_ChildBg, BG_DARKEST);+ ImGui::BeginChild("##eq_status", ImVec2(w, STATUS_HEIGHT), false);++ ImGui::SetCursorPos(ImVec2(8.0f, 2.0f));++ // Connection status+ if (is_connected_ && active_broker_.has_value()) {+ ImGui::TextColored(SUCCESS, "CONNECTED");+ ImGui::SameLine();+ ImGui::TextColored(TEXT_DIM, "| %s", trading::broker_id_str(*active_broker_));+ } else {+ ImGui::TextColored(TEXT_DIM, "DISCONNECTED");+ }++ ImGui::SameLine(0.0f, 20.0f);++ // Mode+ if (is_paper_mode_) {+ ImGui::TextColored(WARNING, "PAPER MODE");+ } else {+ ImGui::TextColored(MARKET_RED, "LIVE MODE");+ }++ ImGui::SameLine(0.0f, 20.0f);+ ImGui::TextColored(TEXT_DIM, "%s:%s",+ selected_exchange_.c_str(), selected_symbol_.c_str());++ // Funds on the right+ if (funds_.has_value()) {+ ImGui::SameLine(w - 200.0f);+ ImGui::TextColored(TEXT_DIM, "Balance:");+ ImGui::SameLine();+ ImGui::TextColored(MARKET_GREEN, "%.2f", funds_->available_balance);+ }++ ImGui::EndChild();+ ImGui::PopStyleColor();+}++// ============================================================================+// Actions+// ============================================================================++void EquityTradingScreen::select_symbol(const std::string& symbol, const std::string& exchange) {+ selected_symbol_ = symbol;+ selected_exchange_ = exchange;+ std::strncpy(symbol_buf_, symbol.c_str(), sizeof(symbol_buf_) - 1);+ std::strncpy(order_form_.symbol_buf, symbol.c_str(), sizeof(order_form_.symbol_buf) - 1);+ has_quote_ = false;+ candles_.clear();++ LOG_INFO(TAG, "Selected %s:%s", exchange.c_str(), symbol.c_str());++ // Fetch quote if broker connected+ if (is_connected_) {+ fetch_quote();+ }+}++void EquityTradingScreen::fetch_quote() {+ if (!active_broker_.has_value() || loading_quote_) return;++ auto* broker = trading::BrokerRegistry::instance().get(*active_broker_);+ if (!broker) return;++ loading_quote_ = true;+ const auto creds = active_creds_;+ const auto sym = selected_symbol_;++ quote_future_ = std::async(std::launch::async, [broker, creds, sym]() {+ auto resp = broker->get_quotes(creds, {sym});+ if (resp.success && resp.data.has_value() && !resp.data->empty()) {+ return resp.data->front();+ }+ return trading::BrokerQuote{};+ });+}++void EquityTradingScreen::fetch_watchlist_quotes() {+ if (!active_broker_.has_value() || loading_watchlist_) return;++ auto* broker = trading::BrokerRegistry::instance().get(*active_broker_);+ if (!broker) return;++ loading_watchlist_ = true;+ const auto creds = active_creds_;+ std::vector<std::string> symbols;+ symbols.reserve(watchlist_.size());+ for (const auto& e : watchlist_) symbols.push_back(e.symbol);++ // Fire async — results polled next frame+ std::thread([this, broker, creds, symbols]() {+ auto resp = broker->get_quotes(creds, symbols);+ if (resp.success && resp.data.has_value()) {+ for (const auto& q : *resp.data) {+ for (auto& e : watchlist_) {+ if (e.symbol == q.symbol) {+ e.ltp = q.ltp;+ e.change = q.change;+ e.change_pct = q.change_pct;+ e.volume = q.volume;+ break;+ }+ }+ }+ }+ loading_watchlist_ = false;+ }).detach();+}++void EquityTradingScreen::place_order() {+ if (!is_connected_ && !is_paper_mode_) return;++ trading::UnifiedOrder order;+ order.symbol = order_form_.symbol_buf;+ order.exchange = selected_exchange_;+ order.side = order_form_.side;+ order.order_type = order_form_.type;+ order.quantity = order_form_.quantity;+ order.price = order_form_.price;+ order.stop_price = order_form_.stop_price;+ order.product_type = order_form_.product;+ order.stop_loss = order_form_.stop_loss;+ order.take_profit = order_form_.take_profit;++ LOG_INFO(TAG, "Placing %s %s order: %s x%.0f @ %.2f",+ trading::order_side_str(order.side),+ trading::order_type_str(order.order_type),+ order.symbol.c_str(), order.quantity, order.price);++ if (is_paper_mode_) {+ // Paper mode — just log it (paper engine integration would go here)+ LOG_INFO(TAG, "Paper order placed (not connected to paper engine)");+ return;+ }++ if (!active_broker_.has_value()) return;+ auto* broker = trading::BrokerRegistry::instance().get(*active_broker_);+ if (!broker) return;++ const auto creds = active_creds_;+ std::thread([broker, creds, order]() {+ auto resp = broker->place_order(creds, order);+ if (resp.success) {+ LOG_INFO(TAG, "Order placed: %s", resp.order_id.c_str());+ } else {+ LOG_WARN(TAG, "Order failed: %s", resp.error.c_str());+ }+ }).detach();+}++void EquityTradingScreen::connect_broker(trading::BrokerId broker_id) {+ LOG_INFO(TAG, "Connecting to broker: %s", trading::broker_id_str(broker_id));++ auto* broker = trading::BrokerRegistry::instance().get(broker_id);+ if (!broker) {+ LOG_WARN(TAG, "Broker not found in registry");+ return;+ }++ // Load credentials from DB+ active_creds_ = broker->load_credentials();+ if (active_creds_.api_key.empty()) {+ LOG_WARN(TAG, "No credentials found for %s — configure in Settings",+ trading::broker_id_str(broker_id));+ return;+ }++ active_broker_ = broker_id;+ is_connected_ = true;+ LOG_INFO(TAG, "Connected to %s", trading::broker_id_str(broker_id));++ // Fetch initial data+ fetch_quote();+ refresh_portfolio();+}++void EquityTradingScreen::refresh_portfolio() {+ if (!active_broker_.has_value() || loading_portfolio_) return;++ auto* broker = trading::BrokerRegistry::instance().get(*active_broker_);+ if (!broker) return;++ loading_portfolio_ = true;+ const auto creds = active_creds_;++ std::thread([this, broker, creds]() {+ auto pos_resp = broker->get_positions(creds);+ if (pos_resp.success && pos_resp.data.has_value()) {+ positions_ = *pos_resp.data;+ }++ auto hold_resp = broker->get_holdings(creds);+ if (hold_resp.success && hold_resp.data.has_value()) {+ holdings_ = *hold_resp.data;+ }++ auto ord_resp = broker->get_orders(creds);+ if (ord_resp.success && ord_resp.data.has_value()) {+ orders_ = *ord_resp.data;+ }++ auto funds_resp = broker->get_funds(creds);+ if (funds_resp.success && funds_resp.data.has_value()) {+ funds_ = *funds_resp.data;+ }++ loading_portfolio_ = false;+ }).detach();+}++} // namespace fincept::equity_tradingdiff --git a/fincept-cpp/src/screens/equity_trading/equity_trading_screen.h b/fincept-cpp/src/screens/equity_trading/equity_trading_screen.hnew file mode 100644index 000000000..0f11b2226--- /dev/null+++ b/fincept-cpp/src/screens/equity_trading/equity_trading_screen.h@@ -0,0 +1,95 @@+#pragma once+// Equity Trading Screen — Bloomberg Terminal-style stock trading interface.+// Multi-panel layout: watchlist | chart + bottom panel | order entry + depth++#include "equity_trading_types.h"+#include "trading/broker_registry.h"+#include "trading/broker_interface.h"+#include <string>+#include <vector>+#include <future>+#include <optional>++namespace fincept::equity_trading {++class EquityTradingScreen {+public:+ void render();++private:+ void init();++ // Panel renderers+ void render_top_nav(float w);+ void render_ticker_bar(float w);+ void render_watchlist_panel(float x, float y, float w, float h);+ void render_chart_panel(float x, float y, float w, float h);+ void render_bottom_panel(float x, float y, float w, float h);+ void render_order_entry(float x, float y, float w, float h);+ void render_order_book(float x, float y, float w, float h);+ void render_status_bar(float w, float total_h);++ // Sub-renderers+ void render_positions_table(float w, float h);+ void render_holdings_table(float w, float h);+ void render_orders_table(float w, float h);+ void render_broker_config(float w, float h);+ void render_candle_chart(float w, float h);++ // Actions+ void select_symbol(const std::string& symbol, const std::string& exchange);+ void fetch_quote();+ void fetch_watchlist_quotes();+ void place_order();+ void connect_broker(trading::BrokerId broker_id);+ void refresh_portfolio();++ // State+ bool initialized_ = false;++ // Broker connection+ std::optional<trading::BrokerId> active_broker_;+ trading::BrokerCredentials active_creds_;+ bool is_connected_ = false;+ bool is_paper_mode_ = true;++ // Selected symbol+ char symbol_buf_[64] = "RELIANCE";+ std::string selected_symbol_ = "RELIANCE";+ std::string selected_exchange_ = "NSE";+ int exchange_idx_ = 0;++ // Quote data+ trading::BrokerQuote current_quote_;+ bool has_quote_ = false;+ bool loading_quote_ = false;+ std::future<trading::BrokerQuote> quote_future_;++ // Watchlist+ std::vector<WatchlistEntry> watchlist_;+ bool loading_watchlist_ = false;++ // Candle data+ std::vector<trading::BrokerCandle> candles_;+ TimeFrame chart_timeframe_ = TimeFrame::d1;+ bool loading_candles_ = false;+ std::future<std::vector<trading::BrokerCandle>> candle_future_;++ // Portfolio data+ std::vector<trading::BrokerPosition> positions_;+ std::vector<trading::BrokerHolding> holdings_;+ std::vector<trading::BrokerOrderInfo> orders_;+ std::optional<trading::BrokerFunds> funds_;+ bool loading_portfolio_ = false;++ // Order form+ OrderFormState order_form_;++ // UI state+ BottomTab bottom_tab_ = BottomTab::positions;+ SidebarView sidebar_view_ = SidebarView::watchlist;+ bool bottom_minimized_ = false;+ char watchlist_search_[64] = {};+};++} // namespace fincept::equity_tradingdiff --git a/fincept-cpp/src/screens/equity_trading/equity_trading_types.h b/fincept-cpp/src/screens/equity_trading/equity_trading_types.hnew file mode 100644index 000000000..2b6b6b455--- /dev/null+++ b/fincept-cpp/src/screens/equity_trading/equity_trading_types.h@@ -0,0 +1,134 @@+#pragma once+// Equity Trading Types — UI state types and constants for equity trading screen.++#include "trading/broker_types.h"+#include <string>+#include <vector>++namespace fincept::equity_trading {++// Bottom panel tabs+enum class BottomTab { positions, holdings, orders, history, brokers };++inline const char* bottom_tab_label(BottomTab t) {+ switch (t) {+ case BottomTab::positions: return "POSITIONS";+ case BottomTab::holdings: return "HOLDINGS";+ case BottomTab::orders: return "ORDERS";+ case BottomTab::history: return "HISTORY";+ case BottomTab::brokers: return "BROKERS";+ }+ return "POSITIONS";+}++// Left sidebar view+enum class SidebarView { watchlist, indices };++// Chart time frame+enum class TimeFrame {+ m1, m5, m15, m30, h1, h4, d1, w1+};++inline const char* timeframe_label(TimeFrame tf) {+ switch (tf) {+ case TimeFrame::m1: return "1M";+ case TimeFrame::m5: return "5M";+ case TimeFrame::m15: return "15M";+ case TimeFrame::m30: return "30M";+ case TimeFrame::h1: return "1H";+ case TimeFrame::h4: return "4H";+ case TimeFrame::d1: return "1D";+ case TimeFrame::w1: return "1W";+ }+ return "5M";+}++inline const char* timeframe_resolution(TimeFrame tf) {+ switch (tf) {+ case TimeFrame::m1: return "1";+ case TimeFrame::m5: return "5";+ case TimeFrame::m15: return "15";+ case TimeFrame::m30: return "30";+ case TimeFrame::h1: return "60";+ case TimeFrame::h4: return "240";+ case TimeFrame::d1: return "D";+ case TimeFrame::w1: return "W";+ }+ return "5";+}++// Watchlist entry with cached quote data+struct WatchlistEntry {+ std::string symbol;+ std::string exchange = "NSE";+ double ltp = 0.0;+ double change = 0.0;+ double change_pct = 0.0;+ double volume = 0.0;+};++// Order form state+struct OrderFormState {+ trading::OrderSide side = trading::OrderSide::Buy;+ trading::OrderType type = trading::OrderType::Market;+ trading::ProductType product = trading::ProductType::Intraday;+ char symbol_buf[64] = {};+ double quantity = 1;+ double price = 0.0;+ double stop_price = 0.0;+ double stop_loss = 0.0;+ double take_profit = 0.0;+};++// Stock exchange list+struct ExchangeDef {+ const char* code;+ const char* name;+ const char* currency;+ const char* region;+};++inline constexpr ExchangeDef EXCHANGES[] = {+ {"NSE", "National Stock Exchange", "INR", "India"},+ {"BSE", "Bombay Stock Exchange", "INR", "India"},+ {"NFO", "NSE F&O", "INR", "India"},+ {"MCX", "Multi Commodity Exchange", "INR", "India"},+ {"NYSE", "New York Stock Exchange", "USD", "US"},+ {"NASDAQ", "NASDAQ", "USD", "US"},+ {"LSE", "London Stock Exchange", "GBP", "UK"},+ {"XETRA", "Deutsche Borse", "EUR", "EU"},+ {"TSE", "Tokyo Stock Exchange", "JPY", "Japan"},+ {"HKEX", "Hong Kong Exchange", "HKD", "HK"},+};+inline constexpr int EXCHANGE_COUNT = sizeof(EXCHANGES) / sizeof(EXCHANGES[0]);++// Default NIFTY 50 watchlist+inline const char* DEFAULT_WATCHLIST[] = {+ "HDFCBANK", "ICICIBANK", "SBIN", "KOTAKBANK", "AXISBANK",+ "BAJFINANCE", "BAJAJFINSV", "HDFCLIFE", "SBILIFE", "INDUSINDBK",+ "TCS", "INFY", "WIPRO", "HCLTECH", "TECHM",+ "RELIANCE", "ONGC", "NTPC", "POWERGRID", "ADANIPORTS",+ "MARUTI", "TATAMOTORS", "M&M", "BAJAJ-AUTO", "HEROMOTOCO",+ "HINDUNILVR", "ITC", "NESTLEIND", "BRITANNIA", "TATACONSUM",+ "TATASTEEL", "JSWSTEEL", "HINDALCO", "COALINDIA",+ "SUNPHARMA", "DRREDDY", "CIPLA", "APOLLOHOSP",+ "LT", "BHARTIARTL", "ULTRACEMCO", "GRASIM", "TITAN",+ "ASIANPAINT", "BPCL", "SHRIRAMFIN", "TRENT",+};+inline constexpr int DEFAULT_WATCHLIST_COUNT = 47;++// Market indices+struct IndexDef {+ const char* symbol;+ const char* exchange;+};++inline constexpr IndexDef MARKET_INDICES[] = {+ {"NIFTY 50", "NSE"},+ {"SENSEX", "BSE"},+ {"BANKNIFTY", "NSE"},+ {"NIFTYIT", "NSE"},+};+inline constexpr int MARKET_INDICES_COUNT = 4;++} // namespace fincept::equity_tradingdiff --git a/fincept-cpp/src/screens/forum/forum_screen.cpp b/fincept-cpp/src/screens/forum/forum_screen.cppindex ac09dbe50..5052d6189 100644--- a/fincept-cpp/src/screens/forum/forum_screen.cpp+++ b/fincept-cpp/src/screens/forum/forum_screen.cpp@@ -41,7 +41,6 @@ void ForumScreen::render() {// Initializeif (!data_loaded_) {- top_contributors_ = get_top_contributors();data_loaded_ = true;load_data();}@@ -615,7 +614,7 @@ void ForumScreen::render_post_detail() {auto headers = auth::AuthApi::instance().get_auth_headers(auth::AuthManager::instance().session().api_key);json body;- body["vote_type"] = "like";+ body["vote_type"] = "up";std::string url = std::string(BASE_URL) + "/forum/posts/" + selected_post_.id + "/vote";load_future_ = std::async(std::launch::async, [url, body, headers]() {try { http::HttpClient::instance().post_json(url, body, headers); } catch (...) {}@@ -631,7 +630,7 @@ void ForumScreen::render_post_detail() {auto headers = auth::AuthApi::instance().get_auth_headers(auth::AuthManager::instance().session().api_key);json body;- body["vote_type"] = "dislike";+ body["vote_type"] = "down";std::string url = std::string(BASE_URL) + "/forum/posts/" + selected_post_.id + "/vote";load_future_ = std::async(std::launch::async, [url, body, headers]() {try { http::HttpClient::instance().post_json(url, body, headers); } catch (...) {}@@ -1005,8 +1004,9 @@ void ForumScreen::load_data() {status_message_ = "Error loading forum data";}- // Load posts separately+ // Load posts and generate derived dataload_posts();+ top_contributors_ = generate_top_contributors(posts_);generate_trending();generate_activity();});@@ -1027,21 +1027,16 @@ void ForumScreen::load_posts() {BASE_URL, active_category_id_, sort.c_str());url = buf;} else {- // Load from first category or all- if (!categories_.empty()) {- char buf[256];- std::snprintf(buf, sizeof(buf),- "%s/forum/categories/%d/posts?sort_by=%s&limit=50",- BASE_URL, categories_[0].id, sort.c_str());- url = buf;- } else {- return;- }+ // Load all posts across categories+ char buf[256];+ std::snprintf(buf, sizeof(buf),+ "%s/forum/posts?sort_by=%s&limit=50",+ BASE_URL, sort.c_str());+ url = buf;}auto& cache = CacheService::instance();- int cat_id = active_category_id_ > 0 ? active_category_id_ :- (!categories_.empty() ? categories_[0].id : 0);+ int cat_id = active_category_id_ > 0 ? active_category_id_ : 0;std::string posts_ck = CacheService::make_key("api-response", "forum-posts",std::to_string(cat_id) + "_" + sort);@@ -1066,10 +1061,10 @@ void ForumScreen::load_posts() {posts_.clear();for (auto& item : posts_arr) {ForumPost p;- p.id = item.value("id", item.value("uuid", ""));+ p.id = item.value("post_uuid", item.value("uuid", item.value("id", "")));p.title = item.value("title", "");p.content = item.value("content", "");- p.author = item.value("author", item.value("username", "anonymous"));+ p.author = item.value("author_display_name", item.value("author", item.value("username", "anonymous")));p.time = item.value("created_at", "");p.category = item.value("category_name", active_category_);p.category_id = item.value("category_id", 0);@@ -1077,7 +1072,7 @@ void ForumScreen::load_posts() {p.replies = item.value("reply_count", item.value("replies", 0));p.likes = item.value("likes", item.value("upvotes", 0));p.dislikes = item.value("dislikes", item.value("downvotes", 0));- p.verified = item.value("verified", false);+ p.verified = item.value("is_pinned", item.value("verified", false));// Derive sentiment from likes/dislikesif (p.likes > p.dislikes * 2) p.sentiment = "bullish";@@ -1139,8 +1134,8 @@ void ForumScreen::load_post_detail(const std::string& post_id) {if (post_data.contains("comments") && post_data["comments"].is_array()) {for (auto& c : post_data["comments"]) {ForumComment comment;- comment.id = c.value("id", c.value("uuid", ""));- comment.author = c.value("author", c.value("username", "anonymous"));+ comment.id = c.value("comment_uuid", c.value("uuid", c.value("id", "")));+ comment.author = c.value("author_display_name", c.value("author", c.value("username", "anonymous")));comment.content = c.value("content", "");comment.time = c.value("created_at", "");comment.likes = c.value("likes", c.value("upvotes", 0));@@ -1193,15 +1188,19 @@ void ForumScreen::generate_trending() {trending_.push_back(t);}- // Fallback if no tags+ // If no tags found in posts, generate from post titlesif (trending_.empty()) {- trending_ = {- {"markets", 24, "bullish"},- {"fed", 18, "bearish"},- {"earnings", 15, "neutral"},- {"AI", 12, "bullish"},- {"crypto", 10, "neutral"},- };+ for (const auto& p : posts_) {+ if (trending_.size() >= 5) break;+ if (!p.title.empty()) {+ TrendingTopic t;+ t.topic = p.title.substr(0, 25);+ if (p.title.size() > 25) t.topic += "...";+ t.mentions = p.views + p.replies;+ t.sentiment = p.sentiment.empty() ? "neutral" : p.sentiment;+ trending_.push_back(t);+ }+ }}}@@ -1219,14 +1218,7 @@ void ForumScreen::generate_activity() {recent_activity_.push_back(a);}- // Fallback- if (recent_activity_.empty()) {- recent_activity_ = {- {"quanttrader", "posted", "Market Analysis Update", "2 min ago"},- {"alphaseeker", "commented on", "Fed Decision Impact", "5 min ago"},- {"datadriven", "liked", "Crypto Portfolio Strategy", "12 min ago"},- };- }+ // No fallback — empty activity is fine when there are no posts}void ForumScreen::do_search() {@@ -1265,10 +1257,10 @@ void ForumScreen::do_search() {if (results.is_array()) {for (auto& item : results) {ForumPost p;- p.id = item.value("id", item.value("uuid", ""));+ p.id = item.value("post_uuid", item.value("uuid", item.value("id", "")));p.title = item.value("title", "");p.content = item.value("content", "");- p.author = item.value("author", item.value("username", "anonymous"));+ p.author = item.value("author_display_name", item.value("author", item.value("username", "anonymous")));p.time = item.value("created_at", "");p.views = item.value("views", 0);p.replies = item.value("reply_count", 0);diff --git a/fincept-cpp/src/screens/forum/forum_types.h b/fincept-cpp/src/screens/forum/forum_types.hindex 3304c6137..8245a3cfc 100644--- a/fincept-cpp/src/screens/forum/forum_types.h+++ b/fincept-cpp/src/screens/forum/forum_types.h@@ -4,6 +4,8 @@#include <imgui.h>#include <string>#include <vector>+#include <map>+#include <algorithm>namespace fincept::forum {@@ -75,16 +77,31 @@ struct RecentActivity {enum class ForumView { Posts, PostDetail, CreatePost, Search };enum class SortMode { Latest, Popular, Views };-// Top contributors (static data like Tauri)-inline std::vector<ForumUser> get_top_contributors() {- return {- {"quanttrader", 2847, 156, "2024-01-15", "online"},- {"marketwizard", 2156, 132, "2024-02-20", "offline"},- {"alphaseeker", 1923, 98, "2024-03-01", "online"},- {"riskmaster", 1567, 87, "2024-01-28", "offline"},- {"datadriven", 1234, 76, "2024-04-10", "online"},- {"techanalyst", 1089, 65, "2024-02-15", "offline"},- };+// Generate top contributors from actual post data+inline std::vector<ForumUser> generate_top_contributors(const std::vector<ForumPost>& posts) {+ std::map<std::string, int> author_posts;+ std::map<std::string, int> author_rep;+ for (const auto& p : posts) {+ if (p.author.empty() || p.author == "anonymous") continue;+ author_posts[p.author]++;+ author_rep[p.author] += p.likes + p.views / 10 + p.replies;+ }++ std::vector<ForumUser> contributors;+ for (const auto& [name, count] : author_posts) {+ ForumUser u;+ u.username = name;+ u.posts = count;+ u.reputation = author_rep[name];+ u.status = (contributors.size() % 2 == 0) ? "online" : "offline";+ contributors.push_back(std::move(u));+ }++ std::sort(contributors.begin(), contributors.end(),+ [](const ForumUser& a, const ForumUser& b) { return a.reputation > b.reputation; });++ if (contributors.size() > 6) contributors.resize(6);+ return contributors;}// Helpersdiff --git a/fincept-cpp/src/screens/screener/screener_screen.cpp b/fincept-cpp/src/screens/screener/screener_screen.cppnew file mode 100644index 000000000..f016dda39--- /dev/null+++ b/fincept-cpp/src/screens/screener/screener_screen.cpp@@ -0,0 +1,1195 @@+// Screener Screen — FRED Economic Data Screener+// Bloomberg Terminal-style dense data layout with FRED API integration++#include "screener_screen.h"+#include "ui/theme.h"+#include "storage/database.h"+#include "http/http_client.h"+#include "core/logger.h"+#include <imgui.h>+#include <nlohmann/json.hpp>+#include <algorithm>+#include <cstring>+#include <chrono>+#include <ctime>+#include <cstdio>+#include <sstream>+#include <set>++namespace fincept::screener {++using json = nlohmann::json;+using namespace theme::colors;++// Bloomberg-style colors+static constexpr ImVec4 BB_BG = {0.055f, 0.055f, 0.060f, 1.0f};+static constexpr ImVec4 BB_PANEL = {0.075f, 0.075f, 0.082f, 1.0f};+static constexpr ImVec4 BB_ROW_ALT = {0.082f, 0.082f, 0.090f, 1.0f};+static constexpr ImVec4 BB_HEADER_BG = {0.090f, 0.090f, 0.098f, 1.0f};+static constexpr ImVec4 BB_AMBER = {1.0f, 0.65f, 0.0f, 1.0f};+static constexpr ImVec4 BB_CYAN = {0.0f, 0.84f, 0.44f, 1.0f};+static constexpr ImVec4 BB_GREEN = {0.18f, 0.80f, 0.44f, 1.0f};+static constexpr ImVec4 BB_RED = {0.95f, 0.30f, 0.25f, 1.0f};+static constexpr ImVec4 BB_BLUE = {0.30f, 0.55f, 0.95f, 1.0f};+static constexpr ImVec4 BB_DIM = {0.45f, 0.45f, 0.48f, 1.0f};+static constexpr ImVec4 BB_TEXT = {0.85f, 0.85f, 0.87f, 1.0f};++static constexpr ImVec4 CHART_IMCOLORS[] = {+ {0.92f, 0.35f, 0.05f, 1.0f}, // orange+ {0.13f, 0.77f, 0.37f, 1.0f}, // green+ {0.23f, 0.51f, 0.96f, 1.0f}, // blue+ {0.92f, 0.70f, 0.03f, 1.0f}, // yellow+ {0.94f, 0.27f, 0.27f, 1.0f}, // red+};++// ============================================================================+// Initialization+// ============================================================================++void ScreenerScreen::init() {+ if (initialized_) return;+ initialized_ = true;++ // Set default end date to today+ const time_t now = time(nullptr);+ const struct tm* t = localtime(&now);+ std::snprintf(end_date_buf_, sizeof(end_date_buf_), "%04d-%02d-%02d",+ t->tm_year + 1900, t->tm_mon + 1, t->tm_mday);++ category_path_.push_back({0, "All Categories"});+ check_api_key();+ parse_selected_ids();+}++// ============================================================================+// API Key+// ============================================================================++void ScreenerScreen::check_api_key() {+ const auto key = get_fred_api_key();+ api_key_configured_ = !key.empty();+}++std::string ScreenerScreen::get_fred_api_key() const {+ const auto cred = db::ops::get_credential_by_service("fred_api_key");+ if (cred && cred->api_key) return *cred->api_key;+ return "";+}++// ============================================================================+// Selected IDs parsing+// ============================================================================++void ScreenerScreen::parse_selected_ids() {+ selected_ids_.clear();+ std::string ids(series_ids_buf_);+ std::istringstream ss(ids);+ std::string token;+ while (std::getline(ss, token, ',')) {+ // Trim whitespace+ const auto start = token.find_first_not_of(" \t");+ if (start == std::string::npos) continue;+ const auto end = token.find_last_not_of(" \t");+ selected_ids_.insert(token.substr(start, end - start + 1));+ }+}++void ScreenerScreen::toggle_series(const std::string& series_id) {+ parse_selected_ids();+ if (selected_ids_.count(series_id)) {+ selected_ids_.erase(series_id);+ } else {+ selected_ids_.insert(series_id);+ }+ // Rebuild buffer+ std::string result;+ for (const auto& id : selected_ids_) {+ if (!result.empty()) result += ",";+ result += id;+ }+ std::strncpy(series_ids_buf_, result.c_str(), sizeof(series_ids_buf_) - 1);+ series_ids_buf_[sizeof(series_ids_buf_) - 1] = '\0';+}++// ============================================================================+// FRED API helpers+// ============================================================================++FREDSeries ScreenerScreen::fetch_single_series(+ const std::string& series_id, const std::string& start_date,+ const std::string& end_date, const std::string& api_key) {++ FREDSeries result;+ result.series_id = series_id;++ auto& client = http::HttpClient::instance();++ // 1. Fetch series info+ const std::string info_url =+ "https://api.stlouisfed.org/fred/series?series_id=" + series_id ++ "&api_key=" + api_key + "&file_type=json";+ const auto info_resp = client.get(info_url);+ if (info_resp.success) {+ try {+ const auto j = json::parse(info_resp.body);+ if (j.contains("seriess") && j["seriess"].is_array() && !j["seriess"].empty()) {+ const auto& s = j["seriess"][0];+ result.title = s.value("title", "");+ result.units = s.value("units", "");+ result.frequency = s.value("frequency", "");+ result.seasonal_adjustment = s.value("seasonal_adjustment", "");+ result.last_updated = s.value("last_updated", "");+ }+ } catch (...) {}+ }++ // 2. Fetch observations+ const std::string obs_url =+ "https://api.stlouisfed.org/fred/series/observations?series_id=" + series_id ++ "&observation_start=" + start_date + "&observation_end=" + end_date ++ "&api_key=" + api_key + "&file_type=json";+ const auto obs_resp = client.get(obs_url);+ if (obs_resp.success) {+ try {+ const auto j = json::parse(obs_resp.body);+ if (j.contains("observations") && j["observations"].is_array()) {+ for (const auto& obs : j["observations"]) {+ const std::string date = obs.value("date", "");+ const std::string val_str = obs.value("value", ".");+ if (val_str != "." && !val_str.empty()) {+ try {+ const double val = std::stod(val_str);+ result.observations.push_back({date, val});+ } catch (...) {}+ }+ }+ }+ result.observation_count = static_cast<int>(result.observations.size());+ } catch (const std::exception& e) {+ result.error = e.what();+ }+ } else {+ result.error = "HTTP error: " + obs_resp.error;+ }++ return result;+}++std::vector<SearchResult> ScreenerScreen::search_fred(+ const std::string& query, const std::string& api_key, int limit) {++ std::vector<SearchResult> results;+ auto& client = http::HttpClient::instance();++ // URL-encode query (simple: replace spaces with +)+ std::string encoded_query;+ for (char c : query) {+ if (c == ' ') encoded_query += '+';+ else encoded_query += c;+ }++ const std::string url =+ "https://api.stlouisfed.org/fred/series/search?search_text=" + encoded_query ++ "&limit=" + std::to_string(limit) ++ "&api_key=" + api_key + "&file_type=json";++ const auto resp = client.get(url);+ if (resp.success) {+ try {+ const auto j = json::parse(resp.body);+ if (j.contains("seriess") && j["seriess"].is_array()) {+ for (const auto& s : j["seriess"]) {+ SearchResult sr;+ sr.id = s.value("id", "");+ sr.title = s.value("title", "");+ sr.frequency = s.value("frequency", "");+ sr.units = s.value("units", "");+ sr.seasonal_adjustment = s.value("seasonal_adjustment", "");+ sr.last_updated = s.value("last_updated", "");+ sr.popularity = s.value("popularity", 0);+ results.push_back(std::move(sr));+ }+ }+ } catch (...) {}+ }+ return results;+}++std::vector<Category> ScreenerScreen::fetch_categories(+ int parent_id, const std::string& api_key) {++ std::vector<Category> results;+ auto& client = http::HttpClient::instance();++ const std::string url =+ "https://api.stlouisfed.org/fred/category/children?category_id=" ++ std::to_string(parent_id) + "&api_key=" + api_key + "&file_type=json";++ const auto resp = client.get(url);+ if (resp.success) {+ try {+ const auto j = json::parse(resp.body);+ if (j.contains("categories") && j["categories"].is_array()) {+ for (const auto& c : j["categories"]) {+ Category cat;+ cat.id = c.value("id", 0);+ cat.name = c.value("name", "");+ cat.parent_id = c.value("parent_id", 0);+ results.push_back(std::move(cat));+ }+ }+ } catch (...) {}+ }+ return results;+}++std::vector<SearchResult> ScreenerScreen::fetch_category_series(+ int cat_id, const std::string& api_key, int limit) {++ std::vector<SearchResult> results;+ auto& client = http::HttpClient::instance();++ const std::string url =+ "https://api.stlouisfed.org/fred/category/series?category_id=" ++ std::to_string(cat_id) + "&limit=" + std::to_string(limit) ++ "&api_key=" + api_key + "&file_type=json";++ const auto resp = client.get(url);+ if (resp.success) {+ try {+ const auto j = json::parse(resp.body);+ if (j.contains("seriess") && j["seriess"].is_array()) {+ for (const auto& s : j["seriess"]) {+ SearchResult sr;+ sr.id = s.value("id", "");+ sr.title = s.value("title", "");+ sr.frequency = s.value("frequency", "");+ sr.units = s.value("units", "");+ sr.popularity = s.value("popularity", 0);+ sr.last_updated = s.value("last_updated", "");+ results.push_back(std::move(sr));+ }+ }+ } catch (...) {}+ }+ return results;+}++// ============================================================================+// Actions+// ============================================================================++void ScreenerScreen::fetch_data() {+ const auto api_key = get_fred_api_key();+ if (api_key.empty()) {+ error_ = "FRED API key not configured. Add it in Settings > Credentials.";+ api_key_configured_ = false;+ return;+ }++ parse_selected_ids();+ if (selected_ids_.empty()) {+ error_ = "Please enter at least one series ID.";+ return;+ }++ loading_ = true;+ error_.clear();+ loading_message_ = "Fetching " + std::to_string(selected_ids_.size()) + " series from FRED...";++ // Copy state for the async lambda+ const std::set<std::string> ids = selected_ids_;+ const std::string start = start_date_buf_;+ const std::string end = end_date_buf_;+ const std::string key = api_key;++ fetch_future_ = std::async(std::launch::async, [this, ids, start, end, key]() {+ std::vector<FREDSeries> results;+ for (const auto& id : ids) {+ results.push_back(fetch_single_series(id, start, end, key));+ }+ return results;+ });+}++void ScreenerScreen::search_series(const std::string& query) {+ const auto api_key = get_fred_api_key();+ if (api_key.empty()) return;++ search_loading_ = true;+ const std::string q = query;+ const std::string key = api_key;++ search_future_ = std::async(std::launch::async, [this, q, key]() {+ return search_fred(q, key, 50);+ });+}++void ScreenerScreen::load_categories(int category_id) {+ const auto api_key = get_fred_api_key();+ if (api_key.empty()) return;++ category_loading_ = true;+ const std::string key = api_key;++ category_future_ = std::async(std::launch::async, [this, category_id, key]() {+ return fetch_categories(category_id, key);+ });+}++void ScreenerScreen::load_category_series(int category_id) {+ const auto api_key = get_fred_api_key();+ if (api_key.empty()) return;++ category_series_loading_ = true;+ const std::string key = api_key;++ cat_series_future_ = std::async(std::launch::async, [this, category_id, key]() {+ return fetch_category_series(category_id, key, 50);+ });+}++void ScreenerScreen::export_csv() {+ if (data_.empty()) return;++ // Build date set+ std::set<std::string> all_dates;+ for (const auto& series : data_) {+ for (const auto& obs : series.observations) {+ all_dates.insert(obs.date);+ }+ }++ std::ostringstream csv;+ // Header+ csv << "Date";+ for (const auto& series : data_) {+ csv << "," << series.series_id;+ }+ csv << "\n";++ // Rows+ for (const auto& date : all_dates) {+ csv << date;+ for (const auto& series : data_) {+ const auto it = std::find_if(series.observations.begin(), series.observations.end(),+ [&](const Observation& o) { return o.date == date; });+ if (it != series.observations.end()) {+ char val_buf[32];+ std::snprintf(val_buf, sizeof(val_buf), "%.4f", it->value);+ csv << "," << val_buf;+ } else {+ csv << ",";+ }+ }+ csv << "\n";+ }++ // Write to file (desktop export)+ const time_t now = time(nullptr);+ const struct tm* t = localtime(&now);+ char filename[128];+ std::snprintf(filename, sizeof(filename), "fred_data_%04d-%02d-%02d.csv",+ t->tm_year + 1900, t->tm_mon + 1, t->tm_mday);++ FILE* f = fopen(filename, "w");+ if (f) {+ const std::string content = csv.str();+ fwrite(content.data(), 1, content.size(), f);+ fclose(f);+ LOG_INFO("Screener", "Exported CSV: %s", filename);+ }+}++// ============================================================================+// Main render+// ============================================================================++void ScreenerScreen::render() {+ init();++ // Check async results+ if (fetch_future_.valid()) {+ if (fetch_future_.wait_for(std::chrono::milliseconds(0)) == std::future_status::ready) {+ data_ = fetch_future_.get();+ loading_ = false;+ loading_message_.clear();+ // Check for errors in any series+ for (const auto& s : data_) {+ if (!s.error.empty()) {+ error_ = "Error fetching " + s.series_id + ": " + s.error;+ break;+ }+ }+ }+ }+ if (search_future_.valid()) {+ if (search_future_.wait_for(std::chrono::milliseconds(0)) == std::future_status::ready) {+ search_results_ = search_future_.get();+ search_loading_ = false;+ }+ }+ if (category_future_.valid()) {+ if (category_future_.wait_for(std::chrono::milliseconds(0)) == std::future_status::ready) {+ categories_ = category_future_.get();+ category_loading_ = false;+ }+ }+ if (cat_series_future_.valid()) {+ if (cat_series_future_.wait_for(std::chrono::milliseconds(0)) == std::future_status::ready) {+ category_series_ = cat_series_future_.get();+ category_series_loading_ = false;+ }+ }++ ImGuiViewport* vp = ImGui::GetMainViewport();+ const float tab_h = ImGui::GetFrameHeight() + 6;+ const float footer_h = ImGui::GetFrameHeight() + 4;+ const float x = vp->WorkPos.x;+ const float y = vp->WorkPos.y + tab_h;+ const float w = vp->WorkSize.x;+ const float total_h = vp->WorkSize.y - tab_h;++ ImGui::SetNextWindowPos(ImVec2(x, y));+ ImGui::SetNextWindowSize(ImVec2(w, total_h));++ ImGui::PushStyleColor(ImGuiCol_WindowBg, BB_BG);+ ImGui::PushStyleVar(ImGuiStyleVar_WindowPadding, ImVec2(0, 0));++ ImGui::Begin("##screener", nullptr,+ ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_NoResize |+ ImGuiWindowFlags_NoMove | ImGuiWindowFlags_NoCollapse |+ ImGuiWindowFlags_NoDocking | ImGuiWindowFlags_NoBringToFrontOnFocus);++ // Header bar+ render_header(w);++ // API key warning (if not configured)+ if (!api_key_configured_) {+ render_api_key_warning(w);+ }++ // Query panel (series IDs, dates, fetch button, quick-add)+ render_query_panel(w);++ // Main content area: chart (left 2/3) + data tables (right 1/3)+ const float content_y = ImGui::GetCursorPosY();+ const float available_h = total_h - content_y - footer_h;+ const float chart_w = w * 0.65f;+ const float table_w = w - chart_w - 4;++ render_chart_panel(0, content_y, chart_w, available_h);+ render_data_tables(chart_w + 4, content_y, table_w, available_h);++ // Footer+ render_footer(w, total_h);++ ImGui::End();+ ImGui::PopStyleVar();+ ImGui::PopStyleColor();++ // Browser modal (rendered on top)+ if (show_browser_) {+ render_browser_modal();+ }+}++// ============================================================================+// Header+// ============================================================================++void ScreenerScreen::render_header(float w) {+ ImGui::PushStyleColor(ImGuiCol_ChildBg, BB_PANEL);+ ImGui::BeginChild("##scr_header", ImVec2(w, 32), false);++ ImGui::SetCursorPos(ImVec2(12, 6));+ ImGui::TextColored(BB_AMBER, "ECONOMIC DATA SCREENER");++ // Right side: chart type + normalize + export buttons+ const float btn_x = w - 280;+ ImGui::SameLine(btn_x);++ ImGui::PushStyleColor(ImGuiCol_Button, ImVec4(0.08f, 0.08f, 0.09f, 1.0f));+ ImGui::PushStyleColor(ImGuiCol_ButtonHovered, ImVec4(0.12f, 0.12f, 0.14f, 1.0f));+ ImGui::PushStyleColor(ImGuiCol_Text, BB_AMBER);++ if (ImGui::SmallButton(chart_type_ == ChartType::line ? "AREA" : "LINE")) {+ chart_type_ = (chart_type_ == ChartType::line) ? ChartType::area : ChartType::line;+ }+ ImGui::SameLine();++ if (data_.size() > 1) {+ ImGui::PushStyleColor(ImGuiCol_Text, normalize_data_ ? BB_GREEN : BB_DIM);+ if (ImGui::SmallButton(normalize_data_ ? "[NORM]" : "NORM")) {+ normalize_data_ = !normalize_data_;+ }+ ImGui::PopStyleColor();+ } else {+ ImGui::TextColored(BB_DIM, "NORM");+ }+ ImGui::SameLine();++ ImGui::PushStyleColor(ImGuiCol_Text, data_.empty() ? BB_DIM : BB_GREEN);+ if (ImGui::SmallButton("CSV") && !data_.empty()) {+ export_csv();+ }+ ImGui::PopStyleColor();++ ImGui::PopStyleColor(3);++ ImGui::EndChild();+ ImGui::PopStyleColor();+}++// ============================================================================+// API Key Warning+// ============================================================================++void ScreenerScreen::render_api_key_warning(float w) {+ ImGui::PushStyleColor(ImGuiCol_ChildBg, ImVec4(0.15f, 0.12f, 0.02f, 1.0f));+ ImGui::BeginChild("##scr_apikey_warn", ImVec2(w, 70), false);++ ImGui::SetCursorPos(ImVec2(16, 8));+ ImGui::TextColored(BB_AMBER, "FRED API Key Required");++ ImGui::SetCursorPos(ImVec2(16, 26));+ ImGui::TextColored(BB_TEXT, "Configure your FRED API key in Settings > Credentials to access economic data.");++ ImGui::SetCursorPos(ImVec2(16, 44));+ ImGui::TextColored(BB_DIM, "1. Get free key at research.stlouisfed.org ");+ ImGui::SameLine();+ ImGui::TextColored(BB_DIM, "2. Add to Settings > Credentials > FRED_API_KEY ");+ ImGui::SameLine();+ ImGui::TextColored(BB_DIM, "3. Reload this tab");++ ImGui::EndChild();+ ImGui::PopStyleColor();+}++// ============================================================================+// Query Panel+// ============================================================================++void ScreenerScreen::render_query_panel(float w) {+ ImGui::PushStyleColor(ImGuiCol_ChildBg, BB_PANEL);+ ImGui::BeginChild("##scr_query", ImVec2(w, 80), false);++ const float pad = 12.0f;+ ImGui::SetCursorPos(ImVec2(pad, 6));++ // Row 1: Series IDs input + dates + fetch button+ ImGui::TextColored(BB_DIM, "SERIES IDS (comma-separated)");+ ImGui::SameLine(0, 8);+ ImGui::PushItemWidth(w * 0.35f);+ ImGui::PushStyleColor(ImGuiCol_FrameBg, ImVec4(0.04f, 0.04f, 0.05f, 1.0f));+ ImGui::PushStyleColor(ImGuiCol_Text, BB_TEXT);+ if (ImGui::InputText("##series_ids", series_ids_buf_, sizeof(series_ids_buf_))) {+ parse_selected_ids();+ }+ ImGui::PopStyleColor(2);+ ImGui::PopItemWidth();++ ImGui::SameLine(0, 16);+ ImGui::TextColored(BB_DIM, "FROM");+ ImGui::SameLine(0, 4);+ ImGui::PushItemWidth(90);+ ImGui::PushStyleColor(ImGuiCol_FrameBg, ImVec4(0.04f, 0.04f, 0.05f, 1.0f));+ ImGui::PushStyleColor(ImGuiCol_Text, BB_TEXT);+ ImGui::InputText("##start_date", start_date_buf_, sizeof(start_date_buf_));+ ImGui::PopStyleColor(2);+ ImGui::PopItemWidth();++ ImGui::SameLine(0, 8);+ ImGui::TextColored(BB_DIM, "TO");+ ImGui::SameLine(0, 4);+ ImGui::PushItemWidth(90);+ ImGui::PushStyleColor(ImGuiCol_FrameBg, ImVec4(0.04f, 0.04f, 0.05f, 1.0f));+ ImGui::PushStyleColor(ImGuiCol_Text, BB_TEXT);+ ImGui::InputText("##end_date", end_date_buf_, sizeof(end_date_buf_));+ ImGui::PopStyleColor(2);+ ImGui::PopItemWidth();++ ImGui::SameLine(0, 12);+ ImGui::PushStyleColor(ImGuiCol_Button, loading_ ? ImVec4(0.1f, 0.1f, 0.1f, 1.0f) : ImVec4(0.0f, 0.55f, 0.30f, 1.0f));+ ImGui::PushStyleColor(ImGuiCol_ButtonHovered, ImVec4(0.0f, 0.65f, 0.35f, 1.0f));+ ImGui::PushStyleColor(ImGuiCol_Text, ImVec4(1, 1, 1, 1));+ if (ImGui::Button(loading_ ? "LOADING..." : "FETCH", ImVec2(80, 0)) && !loading_) {+ fetch_data();+ }+ ImGui::PopStyleColor(3);++ ImGui::SameLine(0, 16);+ ImGui::PushStyleColor(ImGuiCol_Button, ImVec4(0.08f, 0.08f, 0.10f, 1.0f));+ ImGui::PushStyleColor(ImGuiCol_ButtonHovered, ImVec4(0.12f, 0.12f, 0.15f, 1.0f));+ ImGui::PushStyleColor(ImGuiCol_Text, BB_AMBER);+ if (ImGui::Button("BROWSE", ImVec2(70, 0)) && api_key_configured_) {+ show_browser_ = true;+ if (categories_.empty()) {+ load_categories(0);+ }+ }+ ImGui::PopStyleColor(3);++ // Row 2: Quick-add buttons+ ImGui::SetCursorPos(ImVec2(pad, 46));+ ImGui::TextColored(BB_DIM, "QUICK ADD");+ ImGui::SameLine(0, 8);++ for (int i = 0; i < POPULAR_SERIES_COUNT; i++) {+ const bool is_selected = selected_ids_.count(POPULAR_SERIES[i].id) > 0;+ if (is_selected) {+ ImGui::PushStyleColor(ImGuiCol_Button, ImVec4(0.0f, 0.3f, 0.15f, 1.0f));+ ImGui::PushStyleColor(ImGuiCol_Text, BB_GREEN);+ } else {+ ImGui::PushStyleColor(ImGuiCol_Button, ImVec4(0.06f, 0.06f, 0.07f, 1.0f));+ ImGui::PushStyleColor(ImGuiCol_Text, BB_DIM);+ }+ ImGui::PushStyleColor(ImGuiCol_ButtonHovered, ImVec4(0.1f, 0.1f, 0.12f, 1.0f));++ if (ImGui::SmallButton(POPULAR_SERIES[i].id)) {+ toggle_series(POPULAR_SERIES[i].id);+ }+ ImGui::PopStyleColor(3);++ if (i < POPULAR_SERIES_COUNT - 1) ImGui::SameLine(0, 4);+ }++ ImGui::EndChild();+ ImGui::PopStyleColor();+}++// ============================================================================+// Chart Panel+// ============================================================================++void ScreenerScreen::render_chart_panel(float x, float y, float w, float h) {+ ImGui::SetCursorPos(ImVec2(x, y));+ ImGui::PushStyleColor(ImGuiCol_ChildBg, BB_PANEL);+ ImGui::BeginChild("##scr_chart", ImVec2(w, h), false);++ const float pad = 12.0f;+ ImGui::SetCursorPos(ImVec2(pad, 8));+ ImGui::TextColored(BB_AMBER, "TIME SERIES CHART");++ if (loading_) {+ const float center_y = h * 0.4f;+ ImGui::SetCursorPos(ImVec2(w * 0.35f, center_y));+ ImGui::TextColored(BB_AMBER, "%s", loading_message_.c_str());+ ImGui::SetCursorPos(ImVec2(w * 0.35f, center_y + 20));+ ImGui::TextColored(BB_DIM, "Please wait...");+ } else if (!error_.empty()) {+ ImGui::SetCursorPos(ImVec2(pad, 40));+ ImGui::TextColored(BB_RED, "Error: %s", error_.c_str());+ } else if (data_.empty()) {+ const float center_y = h * 0.4f;+ ImGui::SetCursorPos(ImVec2(w * 0.3f, center_y));+ ImGui::TextColored(BB_DIM, "No data to display");+ ImGui::SetCursorPos(ImVec2(w * 0.25f, center_y + 20));+ ImGui::TextColored(BB_DIM, "Enter series IDs and click FETCH to load data");+ } else {+ // Render stacked line charts using ImGui DrawList+ const float chart_x = pad;+ const float chart_y = 30.0f;+ const float chart_w = w - pad * 2;+ const float chart_h = h - chart_y - 30.0f;++ if (chart_w > 50 && chart_h > 50) {+ ImDrawList* draw = ImGui::GetWindowDrawList();+ const ImVec2 origin = ImGui::GetWindowPos();+ const ImVec2 p0(origin.x + chart_x, origin.y + chart_y);+ const ImVec2 p1(origin.x + chart_x + chart_w, origin.y + chart_y + chart_h);++ // Background+ draw->AddRectFilled(p0, p1, IM_COL32(10, 10, 12, 255));+ draw->AddRect(p0, p1, IM_COL32(60, 60, 65, 255));++ // Grid lines+ for (int gi = 1; gi < 5; gi++) {+ const float gy = p0.y + chart_h * gi / 5.0f;+ draw->AddLine(ImVec2(p0.x, gy), ImVec2(p1.x, gy), IM_COL32(40, 40, 45, 255));+ }++ // Find global min/max for normalization+ for (int si = 0; si < static_cast<int>(data_.size()); si++) {+ const auto& series = data_[si];+ if (series.observations.empty()) continue;++ double min_val = series.observations[0].value;+ double max_val = series.observations[0].value;+ for (const auto& obs : series.observations) {+ min_val = std::min(min_val, obs.value);+ max_val = std::max(max_val, obs.value);+ }++ if (normalize_data_) {+ min_val = 0.0;+ max_val = 100.0;+ }++ const double range = (max_val - min_val);+ const double safe_range = (range > 0.0) ? range : 1.0;+ const int n = static_cast<int>(series.observations.size());+ const int color_idx = si % 5;+ const ImU32 color = ImColor(CHART_IMCOLORS[color_idx]);++ auto normalize_val = [&](double v) -> double {+ if (normalize_data_ && range > 0.0) {+ return ((v - series.observations[0].value) /+ (max_val - min_val)) * 100.0; // 0-100 scale+ }+ return v;+ };++ // Draw the line+ for (int i = 1; i < n; i++) {+ const double v0 = normalize_data_ ? normalize_val(series.observations[i-1].value)+ : series.observations[i-1].value;+ const double v1 = normalize_data_ ? normalize_val(series.observations[i].value)+ : series.observations[i].value;++ const float x0 = p0.x + chart_w * (i - 1) / static_cast<float>(n - 1);+ const float x1 = p0.x + chart_w * i / static_cast<float>(n - 1);+ const float y0 = p1.y - chart_h * static_cast<float>((v0 - min_val) / safe_range);+ const float y1 = p1.y - chart_h * static_cast<float>((v1 - min_val) / safe_range);++ draw->AddLine(ImVec2(x0, y0), ImVec2(x1, y1), color, 1.5f);++ // Fill for area chart+ if (chart_type_ == ChartType::area) {+ const ImU32 fill = (color & 0x00FFFFFF) | 0x30000000; // 20% opacity+ draw->AddQuadFilled(+ ImVec2(x0, y0), ImVec2(x1, y1),+ ImVec2(x1, p1.y), ImVec2(x0, p1.y), fill);+ }+ }++ // Y-axis labels (min/max)+ if (si == 0) {+ char min_str[32], max_str[32];+ std::snprintf(min_str, sizeof(min_str), "%.2f", min_val);+ std::snprintf(max_str, sizeof(max_str), "%.2f", max_val);+ draw->AddText(ImVec2(p0.x + 4, p1.y - 14), IM_COL32(120, 120, 130, 255), min_str);+ draw->AddText(ImVec2(p0.x + 4, p0.y + 2), IM_COL32(120, 120, 130, 255), max_str);+ }+ }++ // Legend+ float legend_x = p0.x + 8;+ const float legend_y = p1.y + 4;+ for (int si = 0; si < static_cast<int>(data_.size()); si++) {+ const int ci = si % 5;+ const ImU32 lc = ImColor(CHART_IMCOLORS[ci]);+ draw->AddRectFilled(ImVec2(legend_x, legend_y + 2),+ ImVec2(legend_x + 10, legend_y + 10), lc);+ legend_x += 14;+ draw->AddText(ImVec2(legend_x, legend_y),+ IM_COL32(180, 180, 185, 255), data_[si].series_id.c_str());+ legend_x += ImGui::CalcTextSize(data_[si].series_id.c_str()).x + 16;+ }+ }+ }++ ImGui::EndChild();+ ImGui::PopStyleColor();+}++// ============================================================================+// Data Tables (right panel — scrollable series cards)+// ============================================================================++void ScreenerScreen::render_data_tables(float x, float y, float w, float h) {+ ImGui::SetCursorPos(ImVec2(x, y));+ ImGui::PushStyleColor(ImGuiCol_ChildBg, BB_BG);+ ImGui::BeginChild("##scr_tables", ImVec2(w, h), false);++ for (const auto& series : data_) {+ render_series_table(series, w - 8);+ ImGui::Spacing();+ }++ if (data_.empty()) {+ ImGui::SetCursorPos(ImVec2(16, h * 0.3f));+ ImGui::TextColored(BB_DIM, "Series data will appear here");+ }++ ImGui::EndChild();+ ImGui::PopStyleColor();+}++void ScreenerScreen::render_series_table(const FREDSeries& series, float w) {+ ImGui::PushStyleColor(ImGuiCol_ChildBg, BB_PANEL);+ const std::string id = "##srt_" + series.series_id;+ ImGui::BeginChild(id.c_str(), ImVec2(w, 220), true);++ // Header+ ImGui::TextColored(BB_AMBER, "%s", series.series_id.c_str());+ ImGui::TextColored(BB_TEXT, "%s", series.title.c_str());++ ImGui::Spacing();++ // Metadata grid+ ImGui::TextColored(BB_DIM, "Units: %s", series.units.c_str());+ ImGui::SameLine(w * 0.5f);+ ImGui::TextColored(BB_DIM, "Freq: %s", series.frequency.c_str());++ ImGui::TextColored(BB_DIM, "Obs: %d", series.observation_count);+ ImGui::SameLine(w * 0.5f);+ const std::string updated_short = series.last_updated.substr(0,+ std::min(series.last_updated.size(), static_cast<size_t>(10)));+ ImGui::TextColored(BB_DIM, "Updated: %s", updated_short.c_str());++ ImGui::Separator();++ // Recent observations table (last 15, reversed)+ if (ImGui::BeginTable("##obs", 2, ImGuiTableFlags_ScrollY | ImGuiTableFlags_RowBg,+ ImVec2(0, 130))) {+ ImGui::TableSetupScrollFreeze(0, 1);+ ImGui::TableSetupColumn("Date", ImGuiTableColumnFlags_WidthStretch);+ ImGui::TableSetupColumn("Value", ImGuiTableColumnFlags_WidthStretch);++ ImGui::PushStyleColor(ImGuiCol_TableHeaderBg, BB_HEADER_BG);+ ImGui::TableHeadersRow();+ ImGui::PopStyleColor();++ const int n = static_cast<int>(series.observations.size());+ const int start = std::max(0, n - 15);+ for (int i = n - 1; i >= start; i--) {+ ImGui::TableNextRow();+ ImGui::TableNextColumn();+ ImGui::TextColored(BB_DIM, "%s", series.observations[i].date.c_str());+ ImGui::TableNextColumn();++ char val_buf[32];+ std::snprintf(val_buf, sizeof(val_buf), "%.4f", series.observations[i].value);+ ImGui::TextColored(BB_TEXT, "%s", val_buf);+ }+ ImGui::EndTable();+ }++ ImGui::EndChild();+ ImGui::PopStyleColor();+}++// ============================================================================+// Footer+// ============================================================================++void ScreenerScreen::render_footer(float w, float total_h) {+ const float footer_h = ImGui::GetFrameHeight() + 4;+ ImGui::SetCursorPos(ImVec2(0, total_h - footer_h));++ ImGui::PushStyleColor(ImGuiCol_ChildBg, BB_PANEL);+ ImGui::BeginChild("##scr_footer", ImVec2(w, footer_h), false);++ ImGui::SetCursorPos(ImVec2(12, 3));+ ImGui::TextColored(BB_AMBER, "ECONOMIC SCREENER");+ ImGui::SameLine(0, 16);+ ImGui::TextColored(BB_DIM, "FRED Economic Data | Federal Reserve Bank of St. Louis");++ if (!data_.empty()) {+ int total_obs = 0;+ for (const auto& s : data_) total_obs += s.observation_count;++ char stats[64];+ std::snprintf(stats, sizeof(stats), "%d series | %d observations",+ static_cast<int>(data_.size()), total_obs);+ const float stats_w = ImGui::CalcTextSize(stats).x;+ ImGui::SameLine(w - stats_w - 16);+ ImGui::TextColored(BB_AMBER, "%s", stats);+ }++ ImGui::EndChild();+ ImGui::PopStyleColor();+}++// ============================================================================+// Browser Modal+// ============================================================================++void ScreenerScreen::render_browser_modal() {+ ImGuiViewport* vp = ImGui::GetMainViewport();+ const float modal_w = vp->WorkSize.x * 0.85f;+ const float modal_h = vp->WorkSize.y * 0.8f;+ const float modal_x = vp->WorkPos.x + (vp->WorkSize.x - modal_w) * 0.5f;+ const float modal_y = vp->WorkPos.y + (vp->WorkSize.y - modal_h) * 0.5f;++ // Dim background+ ImGui::GetForegroundDrawList()->AddRectFilled(+ vp->WorkPos, ImVec2(vp->WorkPos.x + vp->WorkSize.x, vp->WorkPos.y + vp->WorkSize.y),+ IM_COL32(0, 0, 0, 200));++ ImGui::SetNextWindowPos(ImVec2(modal_x, modal_y));+ ImGui::SetNextWindowSize(ImVec2(modal_w, modal_h));+ ImGui::PushStyleColor(ImGuiCol_WindowBg, BB_BG);+ ImGui::PushStyleColor(ImGuiCol_Border, BB_AMBER);+ ImGui::PushStyleVar(ImGuiStyleVar_WindowBorderSize, 1.0f);+ ImGui::PushStyleVar(ImGuiStyleVar_WindowPadding, ImVec2(0, 0));++ ImGui::Begin("##fred_browser", nullptr,+ ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_NoResize |+ ImGuiWindowFlags_NoMove | ImGuiWindowFlags_NoCollapse |+ ImGuiWindowFlags_NoDocking);++ // Modal header+ {+ ImGui::PushStyleColor(ImGuiCol_ChildBg, BB_PANEL);+ ImGui::BeginChild("##browser_hdr", ImVec2(modal_w, 36), false);++ ImGui::SetCursorPos(ImVec2(16, 8));+ ImGui::TextColored(BB_AMBER, "FRED SERIES BROWSER");++ // Close button+ ImGui::SameLine(modal_w - 60);+ ImGui::PushStyleColor(ImGuiCol_Button, ImVec4(0, 0, 0, 0));+ ImGui::PushStyleColor(ImGuiCol_Text, BB_DIM);+ if (ImGui::SmallButton("[X] CLOSE")) {+ show_browser_ = false;+ }+ ImGui::PopStyleColor(2);++ ImGui::EndChild();+ ImGui::PopStyleColor();+ }++ // Search bar+ {+ ImGui::PushStyleColor(ImGuiCol_ChildBg, ImVec4(0.06f, 0.06f, 0.07f, 1.0f));+ ImGui::BeginChild("##browser_search", ImVec2(modal_w, 36), false);++ ImGui::SetCursorPos(ImVec2(16, 6));+ ImGui::PushItemWidth(modal_w - 40);+ ImGui::PushStyleColor(ImGuiCol_FrameBg, ImVec4(0.04f, 0.04f, 0.05f, 1.0f));+ ImGui::PushStyleColor(ImGuiCol_Text, BB_TEXT);+ if (ImGui::InputTextWithHint("##browser_q", "Search FRED series (e.g. unemployment, inflation, GDP)...",+ browser_search_buf_, sizeof(browser_search_buf_),+ ImGuiInputTextFlags_EnterReturnsTrue)) {+ if (std::strlen(browser_search_buf_) > 0) {+ search_series(browser_search_buf_);+ }+ }+ ImGui::PopStyleColor(2);+ ImGui::PopItemWidth();++ ImGui::EndChild();+ ImGui::PopStyleColor();+ }++ // Content: left categories (if no search) + right results+ const float content_h = modal_h - 36 - 36 - 30; // header + search + footer+ const bool has_search = std::strlen(browser_search_buf_) > 0;+ const float cat_w = has_search ? 0 : 280;+ const float results_w = modal_w - cat_w;++ if (!has_search) {+ // Categories panel (left)+ ImGui::PushStyleColor(ImGuiCol_ChildBg, ImVec4(0.05f, 0.05f, 0.055f, 1.0f));+ ImGui::BeginChild("##browser_cats", ImVec2(cat_w, content_h), true);+ render_browser_categories();+ ImGui::EndChild();+ ImGui::PopStyleColor();++ ImGui::SameLine(0, 0);+ }++ // Results panel (right)+ ImGui::PushStyleColor(ImGuiCol_ChildBg, BB_BG);+ ImGui::BeginChild("##browser_results", ImVec2(results_w, content_h), false);++ if (has_search) {+ render_browser_search_results();+ } else {+ render_browser_series_list();+ }++ ImGui::EndChild();+ ImGui::PopStyleColor();++ // Modal footer+ {+ ImGui::PushStyleColor(ImGuiCol_ChildBg, BB_PANEL);+ ImGui::BeginChild("##browser_ftr", ImVec2(modal_w, 30), false);+ ImGui::SetCursorPos(ImVec2(16, 6));+ ImGui::TextColored(BB_DIM, "Federal Reserve Economic Data (FRED) | 800,000+ series available");++ ImGui::SameLine(modal_w - 80);+ ImGui::PushStyleColor(ImGuiCol_Button, ImVec4(0.0f, 0.55f, 0.30f, 1.0f));+ ImGui::PushStyleColor(ImGuiCol_Text, ImVec4(1, 1, 1, 1));+ if (ImGui::SmallButton("DONE")) {+ show_browser_ = false;+ }+ ImGui::PopStyleColor(2);++ ImGui::EndChild();+ ImGui::PopStyleColor();+ }++ ImGui::End();+ ImGui::PopStyleVar(2);+ ImGui::PopStyleColor(2);+}++// ============================================================================+// Browser sub-panels+// ============================================================================++void ScreenerScreen::render_browser_categories() {+ const float w = ImGui::GetContentRegionAvail().x;++ // Breadcrumb + back button+ if (category_path_.size() > 1) {+ ImGui::PushStyleColor(ImGuiCol_Button, ImVec4(0.08f, 0.08f, 0.1f, 1.0f));+ ImGui::PushStyleColor(ImGuiCol_Text, BB_AMBER);+ if (ImGui::SmallButton("<< BACK")) {+ category_path_.pop_back();+ const int parent_id = category_path_.back().id;+ current_category_ = parent_id;+ load_categories(parent_id);+ }+ ImGui::PopStyleColor(2);+ }++ // Breadcrumb text+ std::string path_str;+ for (size_t i = 0; i < category_path_.size(); i++) {+ if (i > 0) path_str += " > ";+ path_str += category_path_[i].name;+ }+ ImGui::TextColored(BB_DIM, "%s", path_str.c_str());+ ImGui::Separator();++ // Popular categories (only at root)+ if (current_category_ == 0) {+ ImGui::TextColored(BB_AMBER, "POPULAR CATEGORIES");+ ImGui::Spacing();++ for (int i = 0; i < POPULAR_CATEGORIES_COUNT; i++) {+ ImGui::PushStyleColor(ImGuiCol_Button, ImVec4(0.06f, 0.06f, 0.07f, 1.0f));+ ImGui::PushStyleColor(ImGuiCol_ButtonHovered, ImVec4(0.1f, 0.1f, 0.12f, 1.0f));+ ImGui::PushStyleColor(ImGuiCol_Text, BB_TEXT);+ if (ImGui::Button(POPULAR_CATEGORIES[i].name, ImVec2(w - 8, 0))) {+ category_path_.push_back({POPULAR_CATEGORIES[i].id, POPULAR_CATEGORIES[i].name});+ current_category_ = POPULAR_CATEGORIES[i].id;+ load_categories(POPULAR_CATEGORIES[i].id);+ load_category_series(POPULAR_CATEGORIES[i].id);+ }+ ImGui::PopStyleColor(3);+ }++ ImGui::Separator();+ }++ // Subcategories list+ if (category_loading_) {+ ImGui::TextColored(BB_DIM, "Loading categories...");+ } else {+ char lbl[64];+ std::snprintf(lbl, sizeof(lbl), "SUBCATEGORIES (%d)", static_cast<int>(categories_.size()));+ ImGui::TextColored(BB_DIM, "%s", lbl);+ ImGui::Spacing();++ for (const auto& cat : categories_) {+ ImGui::PushStyleColor(ImGuiCol_Button, ImVec4(0.06f, 0.06f, 0.07f, 1.0f));+ ImGui::PushStyleColor(ImGuiCol_ButtonHovered, ImVec4(0.1f, 0.1f, 0.12f, 1.0f));+ ImGui::PushStyleColor(ImGuiCol_Text, BB_TEXT);+ const std::string cat_btn = cat.name + " >##cat" + std::to_string(cat.id);+ if (ImGui::Button(cat_btn.c_str(), ImVec2(w - 8, 0))) {+ category_path_.push_back({cat.id, cat.name});+ current_category_ = cat.id;+ load_categories(cat.id);+ load_category_series(cat.id);+ }+ ImGui::PopStyleColor(3);+ }+ }+}++void ScreenerScreen::render_browser_search_results() {+ if (search_loading_) {+ ImGui::SetCursorPos(ImVec2(16, 16));+ ImGui::TextColored(BB_AMBER, "Searching FRED...");+ return;+ }++ char hdr[64];+ std::snprintf(hdr, sizeof(hdr), "SEARCH RESULTS (%d)", static_cast<int>(search_results_.size()));+ ImGui::SetCursorPos(ImVec2(16, 8));+ ImGui::TextColored(BB_AMBER, "%s", hdr);++ if (search_results_.empty()) {+ ImGui::SetCursorPos(ImVec2(16, 30));+ ImGui::TextColored(BB_DIM, "No results found");+ return;+ }++ ImGui::SetCursorPosY(28);+ for (const auto& sr : search_results_) {+ render_search_result_row(sr);+ }+}++void ScreenerScreen::render_browser_series_list() {+ if (category_series_loading_) {+ ImGui::SetCursorPos(ImVec2(16, 16));+ ImGui::TextColored(BB_AMBER, "Loading series...");+ return;+ }++ if (category_series_.empty()) {+ ImGui::SetCursorPos(ImVec2(16, 40));+ ImGui::TextColored(BB_DIM, "Search or browse categories to find series");+ return;+ }++ char hdr[64];+ std::snprintf(hdr, sizeof(hdr), "SERIES IN CATEGORY (%d)", static_cast<int>(category_series_.size()));+ ImGui::SetCursorPos(ImVec2(16, 8));+ ImGui::TextColored(BB_AMBER, "%s", hdr);++ ImGui::SetCursorPosY(28);+ for (const auto& sr : category_series_) {+ render_search_result_row(sr);+ }+}++void ScreenerScreen::render_search_result_row(const SearchResult& result) {+ parse_selected_ids();+ const bool is_added = selected_ids_.count(result.id) > 0;++ ImGui::PushStyleColor(ImGuiCol_ChildBg, BB_PANEL);+ const std::string child_id = "##sr_" + result.id;+ ImGui::BeginChild(child_id.c_str(), ImVec2(ImGui::GetContentRegionAvail().x - 16, 60), true);++ ImGui::SetCursorPos(ImVec2(8, 4));+ ImGui::TextColored(BB_AMBER, "%s", result.id.c_str());+ ImGui::SameLine(0, 12);+ ImGui::TextColored(BB_DIM, "Pop: %d", result.popularity);++ // Add button (right side)+ const float btn_x = ImGui::GetContentRegionAvail().x - 50;+ ImGui::SameLine(btn_x);+ if (is_added) {+ ImGui::TextColored(BB_GREEN, "ADDED");+ } else {+ ImGui::PushStyleColor(ImGuiCol_Button, ImVec4(0.0f, 0.55f, 0.30f, 1.0f));+ ImGui::PushStyleColor(ImGuiCol_Text, ImVec4(1, 1, 1, 1));+ const std::string btn_id = "+ADD##add_" + result.id;+ if (ImGui::SmallButton(btn_id.c_str())) {+ toggle_series(result.id);+ }+ ImGui::PopStyleColor(2);+ }++ ImGui::SetCursorPos(ImVec2(8, 22));+ ImGui::TextColored(BB_TEXT, "%s", result.title.c_str());++ ImGui::SetCursorPos(ImVec2(8, 40));+ ImGui::TextColored(BB_DIM, "Freq: %s | Units: %s | Updated: %s",+ result.frequency.c_str(), result.units.c_str(),+ result.last_updated.substr(0, 10).c_str());++ ImGui::EndChild();+ ImGui::PopStyleColor();+ ImGui::Spacing();+}++} // namespace fincept::screenerdiff --git a/fincept-cpp/src/screens/screener/screener_screen.h b/fincept-cpp/src/screens/screener/screener_screen.hnew file mode 100644index 000000000..bc2e73cc2--- /dev/null+++ b/fincept-cpp/src/screens/screener/screener_screen.h@@ -0,0 +1,100 @@+#pragma once+// Screener Screen — FRED Economic Data Screener with Bloomberg Terminal UI.+// Fetch, chart, and browse 800,000+ economic time series from FRED API.++#include "screener_types.h"+#include <string>+#include <vector>+#include <future>+#include <set>++namespace fincept::screener {++class ScreenerScreen {+public:+ void render();++private:+ void init();++ // Panel renderers+ void render_header(float w);+ void render_api_key_warning(float w);+ void render_query_panel(float w);+ void render_chart_panel(float x, float y, float w, float h);+ void render_data_tables(float x, float y, float w, float h);+ void render_series_table(const FREDSeries& series, float w);+ void render_footer(float w, float total_h);++ // Browser modal+ void render_browser_modal();+ void render_browser_search_results();+ void render_browser_categories();+ void render_browser_series_list();+ void render_search_result_row(const SearchResult& result);++ // Simple line chart (ImGui DrawList)+ void render_line_chart(const FREDSeries& series, float w, float h, int color_idx);++ // Actions+ void fetch_data();+ void search_series(const std::string& query);+ void load_categories(int category_id);+ void load_category_series(int category_id);+ void check_api_key();+ void toggle_series(const std::string& series_id);+ void export_csv();++ // FRED API helpers+ std::string get_fred_api_key() const;+ FREDSeries fetch_single_series(const std::string& series_id,+ const std::string& start_date,+ const std::string& end_date,+ const std::string& api_key);+ std::vector<SearchResult> search_fred(const std::string& query,+ const std::string& api_key, int limit);+ std::vector<Category> fetch_categories(int parent_id, const std::string& api_key);+ std::vector<SearchResult> fetch_category_series(int cat_id,+ const std::string& api_key, int limit);++ // State+ bool initialized_ = false;+ bool api_key_configured_ = false;++ // Form buffers+ char series_ids_buf_[512] = "GDP";+ char start_date_buf_[16] = "2000-01-01";+ char end_date_buf_[16] = {};+ ChartType chart_type_ = ChartType::line;+ bool normalize_data_ = false;++ // Loaded data+ std::vector<FREDSeries> data_;+ bool loading_ = false;+ std::string loading_message_;+ std::string error_;+ std::future<std::vector<FREDSeries>> fetch_future_;++ // Search+ std::vector<SearchResult> search_results_;+ bool search_loading_ = false;+ std::future<std::vector<SearchResult>> search_future_;++ // Browser modal+ bool show_browser_ = false;+ char browser_search_buf_[256] = {};+ std::vector<Category> categories_;+ std::vector<SearchResult> category_series_;+ bool category_loading_ = false;+ bool category_series_loading_ = false;+ int current_category_ = 0;+ std::vector<CategoryPath> category_path_;+ std::future<std::vector<Category>> category_future_;+ std::future<std::vector<SearchResult>> cat_series_future_;++ // Selected series IDs (for quick-add highlighting)+ std::set<std::string> selected_ids_;+ void parse_selected_ids();+};++} // namespace fincept::screenerdiff --git a/fincept-cpp/src/screens/screener/screener_types.h b/fincept-cpp/src/screens/screener/screener_types.hnew file mode 100644index 000000000..090ff87c4--- /dev/null+++ b/fincept-cpp/src/screens/screener/screener_types.h@@ -0,0 +1,106 @@+#pragma once+// Screener Types — FRED Economic Data series, search results, categories.++#include <string>+#include <vector>+#include <optional>++namespace fincept::screener {++// A single observation (date + value)+struct Observation {+ std::string date;+ double value = 0.0;+};++// A FRED time series with metadata + observations+struct FREDSeries {+ std::string series_id;+ std::string title;+ std::string units;+ std::string frequency;+ std::string seasonal_adjustment;+ std::string last_updated;+ std::vector<Observation> observations;+ int observation_count = 0;+ std::string error;+};++// Search result from FRED series search+struct SearchResult {+ std::string id;+ std::string title;+ std::string frequency;+ std::string units;+ std::string seasonal_adjustment;+ std::string last_updated;+ int popularity = 0;+};++// FRED category+struct Category {+ int id = 0;+ std::string name;+ int parent_id = 0;+};++// Breadcrumb path element+struct CategoryPath {+ int id = 0;+ std::string name;+};++// Popular preset series for quick-add+struct PopularSeries {+ const char* id;+ const char* name;+ const char* category;+};++// Popular preset categories+struct PopularCategory {+ int id;+ const char* name;+ const char* desc;+};++// Chart display mode+enum class ChartType { line, area };++// ============================================================================+// Constants+// ============================================================================++inline constexpr PopularSeries POPULAR_SERIES[] = {+ {"GDP", "Gross Domestic Product", "Economic"},+ {"UNRATE", "Unemployment Rate", "Labor"},+ {"CPIAUCSL", "Consumer Price Index", "Inflation"},+ {"FEDFUNDS", "Federal Funds Rate", "Interest Rates"},+ {"DGS10", "10-Year Treasury Rate", "Bonds"},+ {"DEXUSEU", "USD/EUR Exchange Rate", "Forex"},+ {"DCOILWTICO", "WTI Crude Oil Price", "Commodities"},+ {"GOLDAMGBD228NLBM", "Gold Price", "Commodities"},+};+inline constexpr int POPULAR_SERIES_COUNT = sizeof(POPULAR_SERIES) / sizeof(POPULAR_SERIES[0]);++inline constexpr PopularCategory POPULAR_CATEGORIES[] = {+ {32991, "Money, Banking, & Finance", "Money supply, interest rates, banking data"},+ {10, "Population, Employment, Labor", "Employment, unemployment, labor statistics"},+ {32455, "Prices", "Inflation, CPI, PPI, commodity prices"},+ {1, "Production & Business", "Industrial production, capacity utilization"},+ {32263, "International Data", "Trade, exchange rates, foreign markets"},+ {33060, "U.S. Regional Data", "State and metro area statistics"},+};+inline constexpr int POPULAR_CATEGORIES_COUNT = sizeof(POPULAR_CATEGORIES) / sizeof(POPULAR_CATEGORIES[0]);++// Chart colors (matching desktop)+inline constexpr unsigned int CHART_COLORS[] = {+ 0xFF0C58EA, // #ea580c orange (ABGR for ImGui)+ 0xFF55C522, // #22c55e green+ 0xFFF6823B, // #3b82f6 blue+ 0xFF08B3EA, // #eab308 yellow+ 0xFF4444EF, // #ef4444 red+};+inline constexpr int CHART_COLORS_COUNT = sizeof(CHART_COLORS) / sizeof(CHART_COLORS[0]);++} // namespace fincept::screener