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
refactor(aql+data-mapping): split two 2000-line screens into focused files
tilakpatel2233aee196a68d
diff --git a/fincept-cpp/CMakeLists.txt b/fincept-cpp/CMakeLists.txtindex 407030bd2..586adf094 100644--- a/fincept-cpp/CMakeLists.txt+++ b/fincept-cpp/CMakeLists.txt@@ -327,6 +327,9 @@ set(SOURCES# Screens — AI Quant Labsrc/screens/ai_quant_lab/ai_quant_lab_api.cppsrc/screens/ai_quant_lab/ai_quant_lab_screen.cpp+ src/screens/ai_quant_lab/aql_screen.cpp+ src/screens/ai_quant_lab/aql_panels_1.cpp+ src/screens/ai_quant_lab/aql_panels_2.cpp# Screens — Code Editorsrc/screens/code_editor/notebook_io.cpp@@ -368,6 +371,8 @@ set(SOURCESsrc/screens/data_mapping/data_mapping_engine.cppsrc/screens/data_mapping/data_mapping_db.cppsrc/screens/data_mapping/data_mapping_screen.cpp+ src/screens/data_mapping/dm_screen.cpp+ src/screens/data_mapping/dm_create.cpp# Screens — Screener (FRED Economic Data)src/screens/screener/screener_screen.cppdiff --git a/fincept-cpp/src/screens/ai_quant_lab/ai_quant_lab_screen.cpp b/fincept-cpp/src/screens/ai_quant_lab/ai_quant_lab_screen.cppindex 443aa62a8..2e0f992d1 100644--- a/fincept-cpp/src/screens/ai_quant_lab/ai_quant_lab_screen.cpp+++ b/fincept-cpp/src/screens/ai_quant_lab/ai_quant_lab_screen.cpp@@ -1,2044 +1,7 @@-// AI Quant Lab Screen — 18-module quantitative research platform-// Three-panel layout: [Sidebar | Content | Status]-// Mirrors the Tauri AIQuantLabTab with all sub-panels--#include "ai_quant_lab_screen.h"-#include "ui/theme.h"-#include "core/logger.h"-#include <imgui.h>-#include <implot.h>-#include <cstring>-#include <cstdio>-#include <cmath>-#include <algorithm>-#include <ctime>--namespace fincept::ai_quant_lab {--// ============================================================================-// Module theme colors (per-panel accent)-// ============================================================================-namespace panel_colors {- constexpr ImVec4 PURPLE = {0.55f, 0.26f, 0.87f, 1.0f}; // Factor Discovery, RL Trading- constexpr ImVec4 BLUE = {0.18f, 0.53f, 0.96f, 1.0f}; // Model Library- constexpr ImVec4 GREEN = {0.05f, 0.85f, 0.42f, 1.0f}; // Live Signals- constexpr ImVec4 CYAN = {0.00f, 0.79f, 0.89f, 1.0f}; // Rolling Retraining- constexpr ImVec4 RED = {0.96f, 0.25f, 0.25f, 1.0f}; // HFT- constexpr ImVec4 MAGENTA = {0.87f, 0.26f, 0.55f, 1.0f}; // Meta Learning- constexpr ImVec4 YELLOW = {1.0f, 0.78f, 0.08f, 1.0f}; // Online Learning- constexpr ImVec4 TEAL = {0.00f, 0.79f, 0.65f, 1.0f}; // Statsmodels- constexpr ImVec4 GLUON_BLUE = {0.00f, 0.63f, 0.89f, 1.0f}; // GluonTS- constexpr ImVec4 GS_PURPLE = {0.44f, 0.26f, 0.76f, 1.0f}; // GS Quant- constexpr ImVec4 ORANGE = {1.0f, 0.45f, 0.05f, 1.0f}; // Default / Accent-}--// ============================================================================-// Init-// ============================================================================-void AIQuantLabScreen::init() {- if (initialized_) return;- modules_ = get_modules();- expanded_categories_ = {ModuleCategory::Core, ModuleCategory::AIML};- initialized_ = true;- log_status("AI Quant Lab initialized", theme::colors::SUCCESS);- LOG_INFO("AIQuantLab", "Initialized with %zu modules", modules_.size());-}--void AIQuantLabScreen::log_status(const std::string& msg, ImVec4 color) {- status_log_.push_back({ImGui::GetTime(), msg, color});- if (status_log_.size() > 100) status_log_.erase(status_log_.begin());-}--// ============================================================================-// Main render-// ============================================================================-void AIQuantLabScreen::render() {- init();- using namespace theme::colors;-- ImGuiViewport* vp = ImGui::GetMainViewport();- float tab_bar_h = ImGui::GetFrameHeight() + 4;- float footer_h = ImGui::GetFrameHeight();-- float x = vp->WorkPos.x;- float y = vp->WorkPos.y + tab_bar_h;- float w = vp->WorkSize.x;- float h = vp->WorkSize.y - tab_bar_h - footer_h;-- ImGui::SetNextWindowPos(ImVec2(x, y));- ImGui::SetNextWindowSize(ImVec2(w, h));-- ImGui::PushStyleColor(ImGuiCol_WindowBg, BG_DARK);- ImGui::PushStyleVar(ImGuiStyleVar_WindowPadding, ImVec2(0, 0));-- ImGui::Begin("##ai_quant_lab", nullptr,- ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_NoResize |- ImGuiWindowFlags_NoMove | ImGuiWindowFlags_NoScrollbar |- ImGuiWindowFlags_NoDocking);-- float sidebar_w = left_panel_visible_ ? 220.0f : 0.0f;- float status_w = right_panel_visible_ ? 260.0f : 0.0f;- float content_w = w - sidebar_w - status_w - 4;-- // Left sidebar- if (left_panel_visible_) {- ImGui::BeginChild("##aql_sidebar", ImVec2(sidebar_w, h), true);- render_sidebar(h);- ImGui::EndChild();- ImGui::SameLine();- }-- // Center content- ImGui::BeginChild("##aql_content", ImVec2(content_w, h), false);- render_content(content_w, h);- ImGui::EndChild();-- // Right status panel- if (right_panel_visible_) {- ImGui::SameLine();- ImGui::BeginChild("##aql_status", ImVec2(status_w, h), true);- render_status_panel(h);- ImGui::EndChild();- }-- ImGui::End();- ImGui::PopStyleVar();- ImGui::PopStyleColor();-}--// ============================================================================-// Sidebar — Module navigation grouped by category-// ============================================================================-void AIQuantLabScreen::render_sidebar(float /*height*/) {- using namespace theme::colors;-- // Header- ImGui::PushStyleColor(ImGuiCol_ChildBg, BG_DARKEST);- ImGui::BeginChild("##aql_header", ImVec2(-1, 50), false);- ImGui::SetCursorPos(ImVec2(12, 8));- ImGui::TextColored(panel_colors::ORANGE, "AI QUANT LAB");- ImGui::SetCursorPos(ImVec2(12, 28));- ImGui::TextColored(TEXT_DIM, "18 MODULES | QUANT RESEARCH");- ImGui::EndChild();- ImGui::PopStyleColor();-- // Accent line- ImVec2 p = ImGui::GetCursorScreenPos();- ImGui::GetWindowDrawList()->AddRectFilled(p,- ImVec2(p.x + ImGui::GetContentRegionAvail().x, p.y + 2),- IM_COL32(255, 115, 13, 255));- ImGui::Dummy(ImVec2(0, 4));-- // Toggle buttons- ImGui::PushStyleVar(ImGuiStyleVar_FramePadding, ImVec2(6, 2));- if (ImGui::SmallButton(right_panel_visible_ ? "Hide Status >>" : "<< Show Status")) {- right_panel_visible_ = !right_panel_visible_;- }- ImGui::PopStyleVar();- ImGui::Dummy(ImVec2(0, 4));-- // Category groups- ModuleCategory categories[] = {- ModuleCategory::Core, ModuleCategory::AIML,- ModuleCategory::Advanced, ModuleCategory::Analytics- };-- for (auto cat : categories) {- bool expanded = expanded_categories_.count(cat) > 0;- ImVec4 cat_color;- switch (cat) {- case ModuleCategory::Core: cat_color = panel_colors::BLUE; break;- case ModuleCategory::AIML: cat_color = panel_colors::PURPLE; break;- case ModuleCategory::Advanced: cat_color = panel_colors::RED; break;- case ModuleCategory::Analytics: cat_color = panel_colors::TEAL; break;- }-- char cat_label[64];- std::snprintf(cat_label, sizeof(cat_label), "%s %s",- expanded ? "v" : ">", category_label(cat));-- ImGui::PushStyleColor(ImGuiCol_Header, ImVec4(cat_color.x, cat_color.y, cat_color.z, 0.08f));- ImGui::PushStyleColor(ImGuiCol_HeaderHovered, BG_HOVER);-- if (ImGui::Selectable(cat_label, false, ImGuiSelectableFlags_None, ImVec2(0, 22))) {- if (expanded) expanded_categories_.erase(cat);- else expanded_categories_.insert(cat);- }- ImGui::PopStyleColor(2);-- if (!expanded) continue;-- ImGui::Indent(12);- for (auto& mod : modules_) {- if (mod.category != cat) continue;- bool is_active = (mod.view == active_view_);-- if (is_active) {- ImGui::PushStyleColor(ImGuiCol_Header, ImVec4(cat_color.x, cat_color.y, cat_color.z, 0.15f));- ImGui::PushStyleColor(ImGuiCol_Text, cat_color);- } else {- ImGui::PushStyleColor(ImGuiCol_Header, ImVec4(0, 0, 0, 0));- ImGui::PushStyleColor(ImGuiCol_Text, TEXT_SECONDARY);- }-- if (ImGui::Selectable(mod.label, is_active, ImGuiSelectableFlags_None, ImVec2(0, 20))) {- active_view_ = mod.view;- log_status(std::string("Switched to ") + mod.label, cat_color);- }- ImGui::PopStyleColor(2);-- if (ImGui::IsItemHovered()) {- ImGui::SetTooltip("%s", mod.description);- }- }- ImGui::Unindent(12);- ImGui::Dummy(ImVec2(0, 2));- }-}--// ============================================================================-// Content — dispatches to the active panel-// ============================================================================-void AIQuantLabScreen::render_content(float width, float height) {- using namespace theme::colors;- (void)width; (void)height;-- ImGui::PushStyleVar(ImGuiStyleVar_WindowPadding, ImVec2(12, 8));-- // Panel toggle for left sidebar- ImGui::PushStyleVar(ImGuiStyleVar_FramePadding, ImVec2(4, 2));- if (ImGui::SmallButton(left_panel_visible_ ? "<< Hide" : ">> Show")) {- left_panel_visible_ = !left_panel_visible_;- }- ImGui::SameLine();-- // Current module title- for (auto& mod : modules_) {- if (mod.view == active_view_) {- ImGui::TextColored(ACCENT, "%s", mod.label);- ImGui::SameLine();- ImGui::TextColored(TEXT_DIM, "- %s", mod.description);- break;- }- }- ImGui::PopStyleVar();- ImGui::Separator();- ImGui::Dummy(ImVec2(0, 4));-- // Dispatch to panel- switch (active_view_) {- case ViewMode::FactorDiscovery: render_factor_discovery(); break;- case ViewMode::ModelLibrary: render_model_library(); break;- case ViewMode::Backtesting: render_backtesting(); break;- case ViewMode::LiveSignals: render_live_signals(); break;- case ViewMode::Functime: render_functime(); break;- case ViewMode::Fortitudo: render_fortitudo(); break;- case ViewMode::Statsmodels: render_statsmodels(); break;- case ViewMode::CFAQuant: render_cfa_quant(); break;- case ViewMode::DeepAgent: render_deep_agent(); break;- case ViewMode::RLTrading: render_rl_trading(); break;- case ViewMode::OnlineLearning: render_online_learning(); break;- case ViewMode::HFT: render_hft(); break;- case ViewMode::MetaLearning: render_meta_learning(); break;- case ViewMode::RollingRetraining: render_rolling_retraining(); break;- case ViewMode::AdvancedModels: render_advanced_models(); break;- case ViewMode::GluonTS: render_gluonts(); break;- case ViewMode::GSQuant: render_gs_quant(); break;- case ViewMode::PatternIntelligence: render_pattern_intelligence(); break;- }-- ImGui::PopStyleVar();-}--// ============================================================================-// Status Panel (Right) — System status + activity log-// ============================================================================-void AIQuantLabScreen::render_status_panel(float /*height*/) {- using namespace theme::colors;-- ImGui::PushStyleColor(ImGuiCol_ChildBg, BG_DARKEST);- ImGui::BeginChild("##status_header", ImVec2(-1, 40), false);- ImGui::SetCursorPos(ImVec2(8, 8));- ImGui::TextColored(TEXT_DIM, "SYSTEM STATUS");- ImGui::EndChild();- ImGui::PopStyleColor();-- ImVec2 p = ImGui::GetCursorScreenPos();- ImGui::GetWindowDrawList()->AddRectFilled(p,- ImVec2(p.x + ImGui::GetContentRegionAvail().x, p.y + 1),- IM_COL32(88, 88, 97, 255));- ImGui::Dummy(ImVec2(0, 4));-- // Service status indicators- theme::StatusIndicator("Qlib Engine", true);- theme::StatusIndicator("RD-Agent", true);- theme::StatusIndicator("Deep Agent", true);- theme::StatusIndicator("Python Runtime", true);- ImGui::Dummy(ImVec2(0, 8));-- // Active module- ImGui::TextColored(TEXT_DIM, "Active Module:");- for (auto& mod : modules_) {- if (mod.view == active_view_) {- ImGui::TextColored(ACCENT, " %s", mod.label);- break;- }- }- ImGui::Dummy(ImVec2(0, 8));-- // Activity log- ImGui::TextColored(TEXT_DIM, "ACTIVITY LOG");- ImGui::Separator();-- ImGui::BeginChild("##log_scroll", ImVec2(-1, -1), false);- for (int i = (int)status_log_.size() - 1; i >= 0; i--) {- auto& entry = status_log_[i];- double age = ImGui::GetTime() - entry.time;- char time_buf[16];- if (age < 60) std::snprintf(time_buf, sizeof(time_buf), "%.0fs ago", age);- else if (age < 3600) std::snprintf(time_buf, sizeof(time_buf), "%.0fm ago", age / 60);- else std::snprintf(time_buf, sizeof(time_buf), "%.0fh ago", age / 3600);-- ImGui::TextColored(TEXT_DISABLED, "%s", time_buf);- ImGui::SameLine();- ImGui::TextColored(entry.color, "%s", entry.msg.c_str());- }- ImGui::EndChild();-}--// ============================================================================-// UI Helpers-// ============================================================================-void AIQuantLabScreen::metric_card(const char* label, const char* value, ImVec4 color) {- using namespace theme::colors;- ImGui::BeginGroup();- ImGui::PushStyleColor(ImGuiCol_ChildBg, BG_WIDGET);- ImGui::BeginChild(ImGui::GetID(label), ImVec2(140, 56), true);- ImGui::TextColored(TEXT_DIM, "%s", label);- ImGui::TextColored(color, "%s", value);- ImGui::EndChild();- ImGui::PopStyleColor();- ImGui::EndGroup();-}--void AIQuantLabScreen::metric_card(const char* label, double value, const char* fmt, ImVec4 color) {- char buf[64];- std::snprintf(buf, sizeof(buf), fmt, value);- metric_card(label, buf, color);-}--void AIQuantLabScreen::progress_bar(float fraction, const char* label) {- using namespace theme::colors;- ImGui::PushStyleColor(ImGuiCol_PlotHistogram, ACCENT);- ImGui::PushStyleColor(ImGuiCol_FrameBg, BG_INPUT);- if (label)- ImGui::ProgressBar(fraction, ImVec2(-1, 18), label);- else- ImGui::ProgressBar(fraction, ImVec2(-1, 18));- ImGui::PopStyleColor(2);-}--bool AIQuantLabScreen::config_input_text(const char* label, char* buf, int buf_size, float width) {- ImGui::TextColored(theme::colors::TEXT_DIM, "%s", label);- ImGui::SameLine(width);- char id[128];- std::snprintf(id, sizeof(id), "##%s", label);- ImGui::SetNextItemWidth(ImGui::GetContentRegionAvail().x);- return ImGui::InputText(id, buf, buf_size);-}--bool AIQuantLabScreen::config_input_float(const char* label, float* val, float width) {- ImGui::TextColored(theme::colors::TEXT_DIM, "%s", label);- ImGui::SameLine(width);- char id[128];- std::snprintf(id, sizeof(id), "##%s", label);- ImGui::SetNextItemWidth(ImGui::GetContentRegionAvail().x);- return ImGui::InputFloat(id, val, 0, 0, "%.4f");-}--bool AIQuantLabScreen::config_input_int(const char* label, int* val, float width) {- ImGui::TextColored(theme::colors::TEXT_DIM, "%s", label);- ImGui::SameLine(width);- char id[128];- std::snprintf(id, sizeof(id), "##%s", label);- ImGui::SetNextItemWidth(ImGui::GetContentRegionAvail().x);- return ImGui::InputInt(id, val);-}--bool AIQuantLabScreen::config_combo(const char* label, int* current, const char* const* items, int count, float width) {- ImGui::TextColored(theme::colors::TEXT_DIM, "%s", label);- ImGui::SameLine(width);- char id[128];- std::snprintf(id, sizeof(id), "##%s", label);- ImGui::SetNextItemWidth(ImGui::GetContentRegionAvail().x);- return ImGui::Combo(id, current, items, count);-}--void AIQuantLabScreen::section_header(const char* title, ImVec4 color) {- ImGui::PushStyleColor(ImGuiCol_Text, color);- ImGui::SeparatorText(title);- ImGui::PopStyleColor();-}--void AIQuantLabScreen::status_badge(const char* text, ImVec4 bg_color, ImVec4 text_color) {- ImVec2 p = ImGui::GetCursorScreenPos();- ImVec2 sz = ImGui::CalcTextSize(text);- ImGui::GetWindowDrawList()->AddRectFilled(p,- ImVec2(p.x + sz.x + 12, p.y + sz.y + 6),- ImGui::ColorConvertFloat4ToU32(bg_color), 3.0f);- ImGui::SetCursorPosX(ImGui::GetCursorPosX() + 6);- ImGui::TextColored(text_color, "%s", text);- ImGui::Dummy(ImVec2(sz.x + 16, sz.y + 8));-}--// ============================================================================-// PANEL 1: Factor Discovery (RD-Agent) — PURPLE THEME-// ============================================================================-void AIQuantLabScreen::render_factor_discovery() {- using namespace theme::colors;- section_header("FACTOR DISCOVERY", panel_colors::PURPLE);- ImGui::TextColored(TEXT_DIM, "RD-Agent automated alpha factor mining with AI-driven research");- ImGui::Dummy(ImVec2(0, 8));-- // Config- static const char* markets[] = {"US", "CN", "CRYPTO"};- config_input_text("Task Description", fd_task_desc_, sizeof(fd_task_desc_), 130);- config_input_text("API Key", fd_api_key_, sizeof(fd_api_key_), 130);- config_combo("Target Market", &fd_market_idx_, markets, 3, 130);- config_input_int("Budget", &fd_budget_, 130);-- ImGui::Dummy(ImVec2(0, 8));-- // Start button- bool is_running = fd_op_.loading.load() || fd_polling_;- if (is_running) {- theme::LoadingSpinner("Mining factors...");- progress_bar(0.5f, "Searching for alpha...");-- // Poll status every 5 seconds- if (fd_polling_ && !fd_task_id_.empty()) {- double now = ImGui::GetTime();- if (now - fd_last_poll_ > 5.0) {- fd_last_poll_ = now;- // Check status- auto status_future = QuantLabApi::instance().rdagent_get_status(fd_task_id_);- if (status_future.wait_for(std::chrono::milliseconds(0)) == std::future_status::ready) {- auto r = status_future.get();- if (r.success && r.data.value("status", "") == "completed") {- fd_polling_ = false;- // Fetch factors- auto fac_future = QuantLabApi::instance().rdagent_get_factors(fd_task_id_);- // Will be picked up next frame- }- }- }- }- } else {- if (theme::AccentButton("Start Factor Mining")) {- json config = {- {"task_description", fd_task_desc_},- {"api_key", fd_api_key_},- {"target_market", markets[fd_market_idx_]},- {"budget", fd_budget_},- };- fd_op_.loading.store(true);- log_status("Starting factor mining...", panel_colors::PURPLE);-- std::thread([this, config]() {- auto result = QuantLabApi::instance().rdagent_start_mining(config).get();- if (result.success) {- fd_task_id_ = result.data.value("task_id", "");- fd_polling_ = true;- fd_last_poll_ = 0;- log_status("Factor mining started: " + fd_task_id_, SUCCESS);- } else {- fd_op_.set_error(result.error);- log_status("Factor mining failed: " + result.error, ERROR_RED);- }- fd_op_.loading.store(false);- }).detach();- }- }-- // Display discovered factors- if (!fd_factors_.empty()) {- ImGui::Dummy(ImVec2(0, 12));- section_header("DISCOVERED FACTORS", panel_colors::PURPLE);-- for (size_t i = 0; i < fd_factors_.size(); i++) {- auto& f = fd_factors_[i];- ImGui::PushID((int)i);-- ImGui::PushStyleColor(ImGuiCol_ChildBg, BG_WIDGET);- ImGui::BeginChild("##factor", ImVec2(-1, 0), ImGuiChildFlags_AutoResizeY | ImGuiChildFlags_Borders);-- ImGui::TextColored(panel_colors::PURPLE, "%s", f.name.c_str());- ImGui::TextColored(TEXT_DIM, "%s", f.description.c_str());-- // Metrics row- metric_card("IC", f.ic, "%.4f", f.ic > 0.03 ? MARKET_GREEN : TEXT_SECONDARY);- ImGui::SameLine();- metric_card("Sharpe", f.sharpe, "%.2f", f.sharpe > 1.0 ? MARKET_GREEN : TEXT_SECONDARY);- ImGui::SameLine();- metric_card("Annual Return", f.annual_return, "%.2f%%", f.annual_return > 0 ? MARKET_GREEN : MARKET_RED);-- // Code display- if (ImGui::CollapsingHeader("Factor Code")) {- ImGui::PushStyleColor(ImGuiCol_ChildBg, BG_DARKEST);- ImGui::BeginChild("##code", ImVec2(-1, 100));- ImGui::TextWrapped("%s", f.code.c_str());- ImGui::EndChild();- ImGui::PopStyleColor();-- if (ImGui::SmallButton("Copy Code")) {- ImGui::SetClipboardText(f.code.c_str());- log_status("Factor code copied", SUCCESS);- }- }-- ImGui::EndChild();- ImGui::PopStyleColor();- ImGui::PopID();- ImGui::Dummy(ImVec2(0, 4));- }- }-- // Error display- if (!fd_op_.error.empty()) {- theme::ErrorMessage(fd_op_.error.c_str());- }-}--// ============================================================================-// PANEL 2: Model Library (Qlib) — BLUE THEME-// ============================================================================-void AIQuantLabScreen::render_model_library() {- using namespace theme::colors;- section_header("MODEL LIBRARY", panel_colors::BLUE);- ImGui::TextColored(TEXT_DIM, "Microsoft Qlib ML models for financial prediction");- ImGui::Dummy(ImVec2(0, 8));-- // Filter- static const char* filters[] = {"All", "Tree-Based", "Neural Network", "Linear", "Ensemble"};- config_combo("Filter", &ml_filter_idx_, filters, 5, 100);-- // Load models button- if (!ml_list_op_.loading.load()) {- if (theme::SecondaryButton("Refresh Models")) {- ml_list_op_.loading.store(true);- std::thread([this]() {- auto result = QuantLabApi::instance().qlib_list_models().get();- if (result.success) {- std::lock_guard<std::mutex> lock(ml_list_op_.mutex);- ml_models_.clear();- if (result.data.is_array()) {- for (auto& m : result.data) {- QlibModel model;- model.name = m.value("name", "");- model.type = m.value("type", "");- model.description = m.value("description", "");- ml_models_.push_back(model);- }- }- ml_list_op_.set_result(result.data);- } else {- ml_list_op_.set_error(result.error);- }- }).detach();- }- } else {- theme::LoadingSpinner("Loading models...");- }-- ImGui::Dummy(ImVec2(0, 8));-- // Model list- if (ml_models_.empty() && !ml_list_op_.has_result) {- // Show default models- static const struct { const char* name; const char* type; const char* desc; } defaults[] = {- {"LightGBM", "tree_based", "Gradient boosting framework with high efficiency"},- {"XGBoost", "tree_based", "Extreme gradient boosting for structured data"},- {"CatBoost", "tree_based", "Gradient boosting with native categorical support"},- {"LSTM", "neural_network", "Long Short-Term Memory recurrent network"},- {"GRU", "neural_network", "Gated Recurrent Unit network"},- {"Transformer", "neural_network", "Attention-based architecture for sequences"},- {"Linear", "linear", "Linear regression with regularization"},- {"Ridge", "linear", "L2-regularized linear regression"},- {"RandomForest","ensemble", "Bagged decision tree ensemble"},- {"AdaBoost", "ensemble", "Adaptive boosting ensemble method"},- };-- for (auto& d : defaults) {- if (ml_filter_idx_ > 0) {- const char* filter_types[] = {"", "tree_based", "neural_network", "linear", "ensemble"};- if (std::strcmp(d.type, filter_types[ml_filter_idx_]) != 0) continue;- }-- bool selected = false;- ImGui::PushStyleColor(ImGuiCol_Header, ImVec4(panel_colors::BLUE.x, panel_colors::BLUE.y, panel_colors::BLUE.z, 0.1f));- if (ImGui::Selectable(d.name, &selected, ImGuiSelectableFlags_None, ImVec2(0, 28))) {- // Select model- }- ImGui::PopStyleColor();- ImGui::SameLine(200);- ImGui::TextColored(TEXT_DIM, "[%s]", d.type);- ImGui::SameLine(350);- ImGui::TextColored(TEXT_SECONDARY, "%s", d.desc);- }- }-- ImGui::Dummy(ImVec2(0, 12));-- // Train config- section_header("TRAIN MODEL", panel_colors::BLUE);- config_input_text("Instruments", ml_instruments_, sizeof(ml_instruments_), 120);- config_input_text("Start Date", ml_start_date_, sizeof(ml_start_date_), 120);- config_input_text("End Date", ml_end_date_, sizeof(ml_end_date_), 120);-- if (!ml_train_op_.loading.load()) {- if (theme::AccentButton("Train Model")) {- ml_train_op_.loading.store(true);- json config = {- {"instruments", ml_instruments_},- {"start_date", ml_start_date_},- {"end_date", ml_end_date_},- };- log_status("Training model...", panel_colors::BLUE);- std::thread([this, config]() {- auto result = QuantLabApi::instance().qlib_train_model(config).get();- if (result.success) {- ml_train_op_.set_result(result.data);- log_status("Model training completed", SUCCESS);- } else {- ml_train_op_.set_error(result.error);- log_status("Training failed: " + result.error, ERROR_RED);- }- }).detach();- }- } else {- theme::LoadingSpinner("Training...");- }-- if (!ml_train_op_.error.empty()) theme::ErrorMessage(ml_train_op_.error.c_str());-}--// ============================================================================-// PANEL 3: Backtesting (Qlib)-// ============================================================================-void AIQuantLabScreen::render_backtesting() {- using namespace theme::colors;- section_header("STRATEGY BACKTESTING", ACCENT);- ImGui::TextColored(TEXT_DIM, "Qlib-powered strategy backtesting engine");- ImGui::Dummy(ImVec2(0, 8));-- static const char* strategies[] = {"TopK Dropout", "Weight Base", "Enhanced Indexing"};- config_combo("Strategy", &bt_strategy_idx_, strategies, 3, 120);- config_input_text("Instruments", bt_instruments_, sizeof(bt_instruments_), 120);- config_input_text("Start Date", bt_start_, sizeof(bt_start_), 120);- config_input_text("End Date", bt_end_, sizeof(bt_end_), 120);- config_input_float("Initial Capital", &bt_capital_, 120);- config_input_text("Benchmark", bt_benchmark_, sizeof(bt_benchmark_), 120);- config_input_float("Commission", &bt_commission_, 120);- config_input_float("Slippage", &bt_slippage_, 120);-- ImGui::Dummy(ImVec2(0, 8));-- if (!bt_op_.loading.load()) {- if (theme::AccentButton("Run Backtest")) {- static const char* strat_keys[] = {"topk_dropout", "weight_base", "enhanced_indexing"};- json config = {- {"strategy", strat_keys[bt_strategy_idx_]},- {"instruments", bt_instruments_},- {"start_date", bt_start_},- {"end_date", bt_end_},- {"initial_capital", bt_capital_},- {"benchmark", bt_benchmark_},- {"commission", bt_commission_},- {"slippage", bt_slippage_},- };- bt_op_.loading.store(true);- log_status("Running backtest...", ACCENT);- std::thread([this, config]() {- auto result = QuantLabApi::instance().qlib_run_backtest(config).get();- if (result.success) {- bt_op_.set_result(result.data);- log_status("Backtest completed", SUCCESS);- } else {- bt_op_.set_error(result.error);- log_status("Backtest failed: " + result.error, ERROR_RED);- }- }).detach();- }- } else {- theme::LoadingSpinner("Running backtest...");- }-- // Results- if (bt_op_.has_result) {- ImGui::Dummy(ImVec2(0, 12));- section_header("BACKTEST RESULTS", SUCCESS);-- std::lock_guard<std::mutex> lock(bt_op_.mutex);- auto& d = bt_op_.result;-- double ann_ret = d.value("annual_return", 0.0);- double sharpe = d.value("sharpe_ratio", 0.0);- double max_dd = d.value("max_drawdown", 0.0);- double win_rate = d.value("win_rate", 0.0);- int trades = d.value("total_trades", 0);- double pf = d.value("profit_factor", 0.0);-- metric_card("Annual Return", ann_ret * 100, "%.2f%%", ann_ret > 0 ? MARKET_GREEN : MARKET_RED);- ImGui::SameLine();- metric_card("Sharpe Ratio", sharpe, "%.2f", sharpe > 1 ? MARKET_GREEN : WARNING);- ImGui::SameLine();- metric_card("Max Drawdown", max_dd * 100, "%.2f%%", MARKET_RED);-- metric_card("Win Rate", win_rate * 100, "%.1f%%", win_rate > 0.5 ? MARKET_GREEN : WARNING);- ImGui::SameLine();- char trades_buf[32];- std::snprintf(trades_buf, sizeof(trades_buf), "%d", trades);- metric_card("Total Trades", trades_buf, TEXT_PRIMARY);- ImGui::SameLine();- metric_card("Profit Factor", pf, "%.2f", pf > 1 ? MARKET_GREEN : MARKET_RED);- }-- if (!bt_op_.error.empty()) theme::ErrorMessage(bt_op_.error.c_str());-}--// ============================================================================-// PANEL 4: Live Signals — GREEN THEME-// ============================================================================-void AIQuantLabScreen::render_live_signals() {- using namespace theme::colors;- section_header("LIVE SIGNALS", panel_colors::GREEN);- ImGui::TextColored(TEXT_DIM, "Real-time model predictions & trading signals");- ImGui::Dummy(ImVec2(0, 8));-- static const char* models[] = {"LightGBM", "XGBoost", "LSTM", "Transformer"};- config_combo("Model", &ls_model_idx_, models, 4, 120);- config_input_int("Refresh (sec)", &ls_refresh_sec_, 120);-- static const char* signal_filters[] = {"ALL", "BUY", "SELL"};- config_combo("Filter", &ls_filter_idx_, signal_filters, 3, 120);-- ImGui::Dummy(ImVec2(0, 8));-- // Stream toggle- if (ls_streaming_) {- ImGui::PushStyleColor(ImGuiCol_Button, ImVec4(panel_colors::GREEN.x, panel_colors::GREEN.y, panel_colors::GREEN.z, 0.3f));- if (ImGui::Button("Stop Streaming")) {- ls_streaming_ = false;- log_status("Signal streaming stopped", WARNING);- }- ImGui::PopStyleColor();- ImGui::SameLine();- theme::LoadingSpinner("Streaming...");-- // Auto-refresh- double now = ImGui::GetTime();- if (now - ls_last_refresh_ > ls_refresh_sec_ && !ls_op_.loading.load()) {- ls_last_refresh_ = now;- ls_op_.loading.store(true);- json config = {{"model", models[ls_model_idx_]}};- std::thread([this, config]() {- auto result = QuantLabApi::instance().qlib_get_live_predictions(config).get();- if (result.success) {- std::lock_guard<std::mutex> lock(ls_op_.mutex);- ls_signals_.clear();- if (result.data.is_array()) {- for (auto& s : result.data) {- SignalEntry sig;- sig.symbol = s.value("symbol", "");- sig.signal = s.value("signal", "HOLD");- sig.score = s.value("score", 0.0);- sig.price = s.value("price", 0.0);- sig.confidence = s.value("confidence", 0.0);- sig.model = s.value("model", "");- sig.timestamp = s.value("timestamp", "");- ls_signals_.push_back(sig);- }- }- ls_op_.set_result(result.data);- } else {- ls_op_.set_error(result.error);- }- }).detach();- }- } else {- if (theme::AccentButton("Start Streaming")) {- ls_streaming_ = true;- ls_last_refresh_ = 0;- log_status("Signal streaming started", panel_colors::GREEN);- }- }-- // Signal cards- if (!ls_signals_.empty()) {- ImGui::Dummy(ImVec2(0, 8));- for (auto& sig : ls_signals_) {- // Filter- if (ls_filter_idx_ == 1 && sig.signal != "BUY") continue;- if (ls_filter_idx_ == 2 && sig.signal != "SELL") continue;-- ImVec4 sig_color = sig.signal == "BUY" ? MARKET_GREEN :- sig.signal == "SELL" ? MARKET_RED : WARNING;-- ImGui::PushStyleColor(ImGuiCol_ChildBg, ImVec4(sig_color.x, sig_color.y, sig_color.z, 0.05f));- ImGui::BeginChild(ImGui::GetID(sig.symbol.c_str()), ImVec2(-1, 0),- ImGuiChildFlags_AutoResizeY | ImGuiChildFlags_Borders);-- ImGui::TextColored(TEXT_PRIMARY, "%s", sig.symbol.c_str());- ImGui::SameLine(120);- status_badge(sig.signal.c_str(),- ImVec4(sig_color.x, sig_color.y, sig_color.z, 0.2f), sig_color);- ImGui::SameLine(220);- ImGui::TextColored(TEXT_SECONDARY, "Score: %.4f", sig.score);- ImGui::SameLine(350);- ImGui::TextColored(TEXT_SECONDARY, "$%.2f", sig.price);- ImGui::SameLine(440);- ImGui::TextColored(TEXT_DIM, "Conf: %.1f%%", sig.confidence * 100);-- ImGui::EndChild();- ImGui::PopStyleColor();- ImGui::Dummy(ImVec2(0, 2));- }- } else if (!ls_op_.loading.load() && !ls_streaming_) {- ImGui::Dummy(ImVec2(0, 20));- ImGui::TextColored(TEXT_DIM, "Click 'Start Streaming' to receive live predictions");- }-- if (!ls_op_.error.empty()) theme::ErrorMessage(ls_op_.error.c_str());-}--// ============================================================================-// PANEL 5: Deep Agent — LLM-powered autonomous research-// ============================================================================-void AIQuantLabScreen::render_deep_agent() {- using namespace theme::colors;- section_header("DEEP AGENT", ACCENT);- ImGui::TextColored(TEXT_DIM, "LLM-powered autonomous financial research agent");- ImGui::Dummy(ImVec2(0, 8));-- static const char* agents[] = {"Research", "Strategy Builder", "Portfolio Manager", "Risk Analyzer", "General"};- config_combo("Agent Type", &da_agent_idx_, agents, 5, 120);- config_input_text("Query", da_query_, sizeof(da_query_), 120);-- ImGui::Dummy(ImVec2(0, 8));-- // Phase indicator- static const char* phases[] = {"Ready", "Planning", "Executing", "Synthesizing", "Complete"};- ImGui::TextColored(TEXT_DIM, "Phase:");- ImGui::SameLine();- ImVec4 phase_color = da_phase_ == 4 ? SUCCESS :- da_phase_ > 0 ? WARNING : TEXT_SECONDARY;- ImGui::TextColored(phase_color, "%s", phases[da_phase_]);-- if (da_phase_ > 0 && da_phase_ < 4) {- float prog = (float)da_phase_ / 4.0f;- progress_bar(prog, phases[da_phase_]);- }-- ImGui::Dummy(ImVec2(0, 8));-- if (da_phase_ == 0) {- if (theme::AccentButton("Create Plan")) {- if (std::strlen(da_query_) == 0) return;- da_phase_ = 1;- da_steps_.clear();- da_plan_text_.clear();- da_synthesis_.clear();- da_op_.loading.store(true);- log_status("Deep Agent: Creating plan...", ACCENT);-- json config = {- {"agent_type", agents[da_agent_idx_]},- {"query", da_query_},- };- std::thread([this, config]() {- auto result = QuantLabApi::instance().deep_agent_create_plan(config).get();- if (result.success) {- da_plan_text_ = result.data.value("plan", "");- if (result.data.contains("steps") && result.data["steps"].is_array()) {- int idx = 0;- for (auto& s : result.data["steps"]) {- AgentStep step;- step.index = idx++;- step.description = s.value("description", "");- step.status = "pending";- da_steps_.push_back(step);- }- }- da_phase_ = 2;- da_current_step_ = 0;- log_status("Plan created with " + std::to_string(da_steps_.size()) + " steps", SUCCESS);- } else {- da_phase_ = 0;- log_status("Planning failed: " + result.error, ERROR_RED);- }- da_op_.loading.store(false);- }).detach();- }- } else if (da_phase_ == 2) {- // Show plan and steps- if (!da_plan_text_.empty()) {- ImGui::TextColored(TEXT_SECONDARY, "Plan:");- ImGui::TextWrapped("%s", da_plan_text_.c_str());- ImGui::Dummy(ImVec2(0, 8));- }-- section_header("EXECUTION STEPS", ACCENT);- for (auto& step : da_steps_) {- ImVec4 sc = step.status == "completed" ? SUCCESS :- step.status == "running" ? WARNING :- step.status == "failed" ? ERROR_RED : TEXT_DIM;- ImGui::TextColored(sc, "[%d] %s — %s",- step.index + 1, step.description.c_str(), step.status.c_str());- if (!step.result.empty() && step.status == "completed") {- ImGui::Indent(20);- ImGui::TextColored(TEXT_DIM, "%s", step.result.c_str());- ImGui::Unindent(20);- }- }-- ImGui::Dummy(ImVec2(0, 8));-- if (!da_op_.loading.load() && da_current_step_ < (int)da_steps_.size()) {- if (theme::AccentButton("Execute Next Step")) {- da_op_.loading.store(true);- int step_idx = da_current_step_;- da_steps_[step_idx].status = "running";- json config = {- {"step_index", step_idx},- {"description", da_steps_[step_idx].description},- {"agent_type", agents[da_agent_idx_]},- {"query", da_query_},- };- std::thread([this, config, step_idx]() {- auto result = QuantLabApi::instance().deep_agent_execute_step(config).get();- if (result.success) {- da_steps_[step_idx].status = "completed";- da_steps_[step_idx].result = result.data.value("result", "");- da_current_step_++;- if (da_current_step_ >= (int)da_steps_.size()) {- da_phase_ = 3; // Ready to synthesize- }- } else {- da_steps_[step_idx].status = "failed";- da_steps_[step_idx].result = result.error;- }- da_op_.loading.store(false);- }).detach();- }- } else if (da_op_.loading.load()) {- theme::LoadingSpinner("Executing step...");- }-- if (da_current_step_ >= (int)da_steps_.size() && !da_op_.loading.load()) {- if (theme::AccentButton("Synthesize Results")) {- da_phase_ = 3;- da_op_.loading.store(true);- json config = {- {"agent_type", agents[da_agent_idx_]},- {"query", da_query_},- {"steps", json::array()},- };- for (auto& s : da_steps_) {- config["steps"].push_back({- {"description", s.description},- {"result", s.result},- });- }- std::thread([this, config]() {- auto result = QuantLabApi::instance().deep_agent_synthesize(config).get();- if (result.success) {- da_synthesis_ = result.data.value("synthesis", "");- da_phase_ = 4;- log_status("Deep Agent: Synthesis complete", SUCCESS);- } else {- da_phase_ = 2;- log_status("Synthesis failed: " + result.error, ERROR_RED);- }- da_op_.loading.store(false);- }).detach();- }- }- } else if (da_phase_ == 3) {- theme::LoadingSpinner("Synthesizing results...");- } else if (da_phase_ == 4) {- section_header("SYNTHESIS", SUCCESS);- ImGui::TextWrapped("%s", da_synthesis_.c_str());-- ImGui::Dummy(ImVec2(0, 8));- if (theme::SecondaryButton("New Query")) {- da_phase_ = 0;- da_steps_.clear();- da_plan_text_.clear();- da_synthesis_.clear();- }- }-}--// ============================================================================-// PANEL 6: RL Trading — PURPLE THEME-// ============================================================================-void AIQuantLabScreen::render_rl_trading() {- using namespace theme::colors;- section_header("RL TRADING", panel_colors::PURPLE);- ImGui::TextColored(TEXT_DIM, "Reinforcement learning trading strategies");- ImGui::Dummy(ImVec2(0, 8));-- static const char* algos[] = {"PPO", "A2C", "DQN", "SAC", "TD3"};- static const char* action_spaces[] = {"Continuous", "Discrete"};-- config_combo("Algorithm", &rl_algo_idx_, algos, 5, 130);- config_input_text("Tickers", rl_tickers_, sizeof(rl_tickers_), 130);- config_input_text("Start Date", rl_start_, sizeof(rl_start_), 130);- config_input_text("End Date", rl_end_, sizeof(rl_end_), 130);- config_input_float("Initial Cash", &rl_initial_cash_, 130);- config_input_float("Commission", &rl_commission_, 130);- config_combo("Action Space", &rl_action_space_, action_spaces, 2, 130);- config_input_int("Timesteps", &rl_timesteps_, 130);- config_input_float("Learning Rate", &rl_learning_rate_, 130);-- ImGui::Dummy(ImVec2(0, 8));-- // Phase display- static const char* rl_phases[] = {"Configure", "Env Created", "Training", "Evaluating", "Done"};- ImGui::TextColored(TEXT_DIM, "Phase:");- ImGui::SameLine();- ImGui::TextColored(rl_phase_ == 4 ? SUCCESS : WARNING, "%s", rl_phases[rl_phase_]);-- if (rl_phase_ > 0 && rl_phase_ < 4)- progress_bar((float)rl_phase_ / 4.0f);-- ImGui::Dummy(ImVec2(0, 8));-- if (!rl_op_.loading.load()) {- const char* btn_label = rl_phase_ == 0 ? "Create Environment" :- rl_phase_ == 1 ? "Train Agent" :- rl_phase_ == 3 ? "Evaluate" : "Reset";-- if (theme::AccentButton(btn_label)) {- if (rl_phase_ >= 4) {- rl_phase_ = 0;- rl_op_.clear();- return;- }-- rl_op_.loading.store(true);- json config = {- {"algorithm", algos[rl_algo_idx_]},- {"tickers", rl_tickers_},- {"start_date", rl_start_},- {"end_date", rl_end_},- {"initial_cash", rl_initial_cash_},- {"commission", rl_commission_},- {"action_space", action_spaces[rl_action_space_]},- {"timesteps", rl_timesteps_},- {"learning_rate", rl_learning_rate_},- };-- int phase = rl_phase_;- std::thread([this, config, phase]() {- ApiResult result;- if (phase == 0) {- result = QuantLabApi::instance().rl_create_env(config).get();- if (result.success) rl_phase_ = 1;- } else if (phase == 1) {- result = QuantLabApi::instance().rl_train_agent(config).get();- if (result.success) rl_phase_ = 3;- } else if (phase == 3) {- result = QuantLabApi::instance().rl_evaluate(config).get();- if (result.success) rl_phase_ = 4;- }-- if (result.success) {- rl_op_.set_result(result.data);- log_status("RL Phase complete", SUCCESS);- } else {- rl_op_.set_error(result.error);- log_status("RL failed: " + result.error, ERROR_RED);- }- }).detach();- }- } else {- theme::LoadingSpinner("Processing...");- }-- // Show results- if (rl_op_.has_result && rl_phase_ == 4) {- ImGui::Dummy(ImVec2(0, 12));- section_header("EVALUATION RESULTS", panel_colors::PURPLE);-- std::lock_guard<std::mutex> lock(rl_op_.mutex);- auto& d = rl_op_.result;- double total_ret = d.value("total_return", 0.0);- double sharpe = d.value("sharpe_ratio", 0.0);- double max_dd = d.value("max_drawdown", 0.0);-- metric_card("Total Return", total_ret * 100, "%.2f%%", total_ret > 0 ? MARKET_GREEN : MARKET_RED);- ImGui::SameLine();- metric_card("Sharpe", sharpe, "%.2f", sharpe > 1 ? MARKET_GREEN : WARNING);- ImGui::SameLine();- metric_card("Max Drawdown", max_dd * 100, "%.2f%%", MARKET_RED);- }-- if (!rl_op_.error.empty()) theme::ErrorMessage(rl_op_.error.c_str());-}--// ============================================================================-// PANEL 7: Online Learning — YELLOW THEME-// ============================================================================-void AIQuantLabScreen::render_online_learning() {- using namespace theme::colors;- section_header("ONLINE LEARNING", panel_colors::YELLOW);- ImGui::TextColored(TEXT_DIM, "Continuous model adaptation with drift detection");- ImGui::Dummy(ImVec2(0, 8));-- static const char* model_types[] = {- "LinearRegression", "RidgeRegression", "LogisticRegression",- "DecisionTree", "RandomForest", "GradientBoosting",- "AdaBoost", "BaggingClassifier", "VotingEnsemble"- };- static const char* drift_strategies[] = {"Retrain", "Adaptive"};-- config_combo("Model Type", &ol_model_idx_, model_types, 9, 130);- config_combo("Drift Strategy", &ol_drift_strategy_, drift_strategies, 2, 130);-- ImGui::Dummy(ImVec2(0, 8));-- // Create Model- if (!ol_create_op_.loading.load()) {- if (theme::AccentButton("Create Model")) {- ol_create_op_.loading.store(true);- json config = {{"model_type", model_types[ol_model_idx_]}};- log_status("Creating online model...", panel_colors::YELLOW);- std::thread([this, config]() {- auto result = QuantLabApi::instance().qlib_online_create(config).get();- if (result.success) {- ol_create_op_.set_result(result.data);- log_status("Online model created", SUCCESS);- } else {- ol_create_op_.set_error(result.error);- }- }).detach();- }- } else {- theme::LoadingSpinner("Creating model...");- }-- ImGui::SameLine();-- // Train- if (!ol_train_op_.loading.load()) {- if (theme::SecondaryButton("Train")) {- ol_train_op_.loading.store(true);- json config = {{"model_type", model_types[ol_model_idx_]}};- std::thread([this, config]() {- auto result = QuantLabApi::instance().qlib_online_train(config).get();- if (result.success) ol_train_op_.set_result(result.data);- else ol_train_op_.set_error(result.error);- }).detach();- }- } else {- theme::LoadingSpinner("Training...");- }-- ImGui::Dummy(ImVec2(0, 8));-- // Live mode toggle- if (ImGui::Checkbox("Live Mode (2s updates)", &ol_live_mode_)) {- log_status(ol_live_mode_ ? "Live mode enabled" : "Live mode disabled",- ol_live_mode_ ? panel_colors::YELLOW : TEXT_DIM);- }-- if (ol_live_mode_) {- double now = ImGui::GetTime();- if (now - ol_last_update_ > 2.0 && !ol_perf_op_.loading.load()) {- ol_last_update_ = now;- ol_perf_op_.loading.store(true);- std::thread([this]() {- auto result = QuantLabApi::instance().qlib_online_performance("current").get();- if (result.success) ol_perf_op_.set_result(result.data);- else ol_perf_op_.set_error(result.error);- }).detach();- }- }-- // Performance display- if (ol_perf_op_.has_result) {- ImGui::Dummy(ImVec2(0, 8));- section_header("PERFORMANCE", panel_colors::YELLOW);- std::lock_guard<std::mutex> lock(ol_perf_op_.mutex);- auto& d = ol_perf_op_.result;- double acc = d.value("accuracy", 0.0);- double loss = d.value("loss", 0.0);- metric_card("Accuracy", acc * 100, "%.1f%%", acc > 0.6 ? MARKET_GREEN : WARNING);- ImGui::SameLine();- metric_card("Loss", loss, "%.4f", TEXT_SECONDARY);- }-- if (!ol_create_op_.error.empty()) theme::ErrorMessage(ol_create_op_.error.c_str());- if (!ol_train_op_.error.empty()) theme::ErrorMessage(ol_train_op_.error.c_str());-}--// ============================================================================-// PANEL 8: HFT Analytics — RED THEME-// ============================================================================-void AIQuantLabScreen::render_hft() {- using namespace theme::colors;- section_header("HFT ANALYTICS", panel_colors::RED);- ImGui::TextColored(TEXT_DIM, "Order book visualization & microstructure analysis");- ImGui::Dummy(ImVec2(0, 8));-- config_input_text("Symbol", hft_symbol_, sizeof(hft_symbol_), 120);- config_input_float("Spread Target", &hft_spread_target_, 120);- config_input_float("Position Limit", &hft_position_limit_, 120);-- ImGui::Dummy(ImVec2(0, 4));-- // Live toggle- if (ImGui::Checkbox("Live Mode (1s updates)", &hft_live_)) {- if (hft_live_) {- log_status("HFT live mode started", panel_colors::RED);- // Generate initial mock data- hft_bids_.clear();- hft_asks_.clear();- double base = 185.50;- for (int i = 0; i < 10; i++) {- hft_bids_.push_back({base - i * 0.01, 100.0 + rand() % 500, 1 + rand() % 10});- hft_asks_.push_back({base + 0.01 + i * 0.01, 100.0 + rand() % 500, 1 + rand() % 10});- }- hft_metrics_ = {0.15, base - 0.05, base + 0.05, 0.23, 0.02, base};- }- }-- if (hft_live_) {- double now = ImGui::GetTime();- if (now - hft_last_update_ > 1.0) {- hft_last_update_ = now;- // Update mock data with slight randomization- for (auto& b : hft_bids_) b.size += (rand() % 100) - 50;- for (auto& a : hft_asks_) a.size += (rand() % 100) - 50;- hft_metrics_.depth_imbalance = 0.1 + (rand() % 30) / 100.0;- hft_metrics_.toxicity_score = 0.15 + (rand() % 20) / 100.0;- }- }-- // Order Book- if (!hft_bids_.empty()) {- ImGui::Dummy(ImVec2(0, 8));- section_header("ORDER BOOK", panel_colors::RED);-- // Bids and asks side by side- ImGui::Columns(2, "##orderbook", true);-- // Bids- ImGui::TextColored(MARKET_GREEN, "BIDS");- ImGui::Separator();- ImGui::TextColored(TEXT_DIM, "%-10s %-10s %-6s", "Price", "Size", "Orders");- for (auto& b : hft_bids_) {- float pct = (float)(b.size / 600.0);- ImVec2 p = ImGui::GetCursorScreenPos();- ImGui::GetWindowDrawList()->AddRectFilled(p,- ImVec2(p.x + ImGui::GetColumnWidth() * pct, p.y + ImGui::GetTextLineHeight()),- IM_COL32(5, 217, 107, 30));- ImGui::TextColored(MARKET_GREEN, "%.2f %.0f %d", b.price, b.size, b.orders);- }-- ImGui::NextColumn();-- // Asks- ImGui::TextColored(MARKET_RED, "ASKS");- ImGui::Separator();- ImGui::TextColored(TEXT_DIM, "%-10s %-10s %-6s", "Price", "Size", "Orders");- for (auto& a : hft_asks_) {- float pct = (float)(a.size / 600.0);- ImVec2 p2 = ImGui::GetCursorScreenPos();- ImGui::GetWindowDrawList()->AddRectFilled(p2,- ImVec2(p2.x + ImGui::GetColumnWidth() * pct, p2.y + ImGui::GetTextLineHeight()),- IM_COL32(245, 64, 64, 30));- ImGui::TextColored(MARKET_RED, "%.2f %.0f %d", a.price, a.size, a.orders);- }-- ImGui::Columns(1);-- // Microstructure metrics- ImGui::Dummy(ImVec2(0, 8));- section_header("MICROSTRUCTURE", panel_colors::RED);-- metric_card("Depth Imbalance", hft_metrics_.depth_imbalance, "%.4f",- std::abs(hft_metrics_.depth_imbalance) > 0.3 ? WARNING : TEXT_SECONDARY);- ImGui::SameLine();- metric_card("VWAP Bid", hft_metrics_.vwap_bid, "%.2f", MARKET_GREEN);- ImGui::SameLine();- metric_card("VWAP Ask", hft_metrics_.vwap_ask, "%.2f", MARKET_RED);-- metric_card("Toxicity", hft_metrics_.toxicity_score, "%.4f",- hft_metrics_.toxicity_score > 0.5 ? MARKET_RED : TEXT_SECONDARY);- ImGui::SameLine();- metric_card("Spread", hft_metrics_.spread, "%.4f", TEXT_SECONDARY);- ImGui::SameLine();- metric_card("Mid Price", hft_metrics_.mid_price, "%.2f", TEXT_PRIMARY);-- // Market Making Quote Calculator- ImGui::Dummy(ImVec2(0, 8));- section_header("MARKET MAKING QUOTES", panel_colors::RED);-- double bid_quote = hft_metrics_.mid_price - hft_spread_target_ / 2;- double ask_quote = hft_metrics_.mid_price + hft_spread_target_ / 2;- ImGui::TextColored(MARKET_GREEN, "Bid Quote: $%.4f", bid_quote);- ImGui::TextColored(MARKET_RED, "Ask Quote: $%.4f", ask_quote);- ImGui::TextColored(TEXT_DIM, "Spread: $%.4f (%.2f bps)",- ask_quote - bid_quote,- (ask_quote - bid_quote) / hft_metrics_.mid_price * 10000);- }-}--// ============================================================================-// PANEL 9: Meta Learning — MAGENTA THEME-// ============================================================================-void AIQuantLabScreen::render_meta_learning() {- using namespace theme::colors;- section_header("META LEARNING", panel_colors::MAGENTA);- ImGui::TextColored(TEXT_DIM, "Automated model selection and comparison");- ImGui::Dummy(ImVec2(0, 8));-- static const char* task_types[] = {"Classification", "Regression"};- config_combo("Task Type", &meta_task_type_, task_types, 2, 130);-- ImGui::Dummy(ImVec2(0, 8));-- if (!meta_run_op_.loading.load()) {- if (theme::AccentButton("Run Model Selection")) {- meta_run_op_.loading.store(true);- json config = {- {"task_type", task_types[meta_task_type_]},- {"models", json::array({"LightGBM", "XGBoost", "CatBoost", "RandomForest"})},- };- log_status("Running meta-learning selection...", panel_colors::MAGENTA);- std::thread([this, config]() {- auto result = QuantLabApi::instance().qlib_meta_run_selection(config).get();- if (result.success) {- meta_run_op_.set_result(result.data);- log_status("Meta-learning complete", SUCCESS);- } else {- meta_run_op_.set_error(result.error);- }- }).detach();- }- } else {- theme::LoadingSpinner("Running model selection...");- }-- // Results — show default comparison if no results yet- ImGui::Dummy(ImVec2(0, 12));- section_header("MODEL COMPARISON", panel_colors::MAGENTA);-- if (ImGui::BeginTable("##meta_models", 7,- ImGuiTableFlags_Borders | ImGuiTableFlags_RowBg | ImGuiTableFlags_Resizable)) {- ImGui::TableSetupColumn("Rank", ImGuiTableColumnFlags_WidthFixed, 40);- ImGui::TableSetupColumn("Model");- ImGui::TableSetupColumn("Accuracy");- ImGui::TableSetupColumn("F1 Score");- ImGui::TableSetupColumn("AUC-ROC");- ImGui::TableSetupColumn("MSE");- ImGui::TableSetupColumn("R2");- ImGui::TableHeadersRow();-- // Default data (or API results)- struct ModelResult { const char* name; double acc; double f1; double auc; double mse; double r2; };- ModelResult defaults[] = {- {"LightGBM", 0.847, 0.832, 0.891, 0.0234, 0.765},- {"XGBoost", 0.841, 0.825, 0.885, 0.0241, 0.758},- {"CatBoost", 0.838, 0.821, 0.882, 0.0247, 0.752},- {"RandomForest", 0.823, 0.808, 0.869, 0.0268, 0.731},- };-- for (int i = 0; i < 4; i++) {- auto& m = defaults[i];- ImGui::TableNextRow();- ImGui::TableNextColumn();- ImGui::TextColored(i == 0 ? panel_colors::MAGENTA : TEXT_SECONDARY, "#%d", i + 1);- ImGui::TableNextColumn();- ImGui::TextColored(TEXT_PRIMARY, "%s", m.name);- ImGui::TableNextColumn();- ImGui::TextColored(m.acc > 0.84 ? MARKET_GREEN : TEXT_SECONDARY, "%.3f", m.acc);- ImGui::TableNextColumn();- ImGui::TextColored(TEXT_SECONDARY, "%.3f", m.f1);- ImGui::TableNextColumn();- ImGui::TextColored(TEXT_SECONDARY, "%.3f", m.auc);- ImGui::TableNextColumn();- ImGui::TextColored(TEXT_SECONDARY, "%.4f", m.mse);- ImGui::TableNextColumn();- ImGui::TextColored(m.r2 > 0.75 ? MARKET_GREEN : TEXT_SECONDARY, "%.3f", m.r2);- }-- ImGui::EndTable();- }-- if (!meta_run_op_.error.empty()) theme::ErrorMessage(meta_run_op_.error.c_str());-}--// ============================================================================-// PANEL 10: Rolling Retraining — CYAN THEME-// ============================================================================-void AIQuantLabScreen::render_rolling_retraining() {- using namespace theme::colors;- section_header("ROLLING RETRAINING", panel_colors::CYAN);- ImGui::TextColored(TEXT_DIM, "Scheduled model updates and retraining pipelines");- ImGui::Dummy(ImVec2(0, 8));-- static const char* frequencies[] = {"Hourly", "Daily", "Weekly"};-- config_input_text("Model Name", rr_model_name_, sizeof(rr_model_name_), 130);- config_input_int("Window (days)", &rr_window_days_, 130);- config_combo("Frequency", &rr_frequency_, frequencies, 3, 130);-- ImGui::Dummy(ImVec2(0, 8));-- if (!rr_create_op_.loading.load()) {- if (theme::AccentButton("Create Schedule")) {- rr_create_op_.loading.store(true);- json config = {- {"model_name", rr_model_name_},- {"training_window_days", rr_window_days_},- {"frequency", frequencies[rr_frequency_]},- };- log_status("Creating retraining schedule...", panel_colors::CYAN);- std::thread([this, config]() {- auto result = QuantLabApi::instance().qlib_rolling_create_schedule(config).get();- if (result.success) {- rr_create_op_.set_result(result.data);- log_status("Schedule created", SUCCESS);- } else {- rr_create_op_.set_error(result.error);- }- }).detach();- }- } else {- theme::LoadingSpinner("Creating schedule...");- }-- ImGui::SameLine();- if (theme::SecondaryButton("List Schedules")) {- rr_list_op_.loading.store(true);- std::thread([this]() {- auto result = QuantLabApi::instance().qlib_rolling_list_schedules().get();- if (result.success) rr_list_op_.set_result(result.data);- else rr_list_op_.set_error(result.error);- }).detach();- }-- if (!rr_create_op_.error.empty()) theme::ErrorMessage(rr_create_op_.error.c_str());- if (!rr_list_op_.error.empty()) theme::ErrorMessage(rr_list_op_.error.c_str());-}--// ============================================================================-// PANEL 11: Advanced Models-// ============================================================================-void AIQuantLabScreen::render_advanced_models() {- using namespace theme::colors;- section_header("ADVANCED MODELS", panel_colors::BLUE);- ImGui::TextColored(TEXT_DIM, "LSTM, GRU, and Transformer neural network architectures");- ImGui::Dummy(ImVec2(0, 8));-- static const char* models[] = {"LSTM", "GRU", "Transformer"};- config_combo("Architecture", &am_model_idx_, models, 3, 130);-- // Model details- ImGui::Dummy(ImVec2(0, 8));- const char* descs[] = {- "Long Short-Term Memory — excels at capturing long-range temporal dependencies in sequential financial data",- "Gated Recurrent Unit — lightweight alternative to LSTM with comparable performance and faster training",- "Transformer — attention-based architecture that captures complex multi-variate relationships",- };- ImGui::TextColored(TEXT_SECONDARY, "%s", descs[am_model_idx_]);-- ImGui::Dummy(ImVec2(0, 8));-- if (!am_train_op_.loading.load()) {- if (theme::AccentButton("Train Model")) {- am_train_op_.loading.store(true);- json config = {{"model_type", models[am_model_idx_]}};- log_status(std::string("Training ") + models[am_model_idx_] + "...", panel_colors::BLUE);- std::thread([this, config]() {- auto result = QuantLabApi::instance().qlib_advanced_train(config).get();- if (result.success) {- am_train_op_.set_result(result.data);- log_status("Training complete", SUCCESS);- } else {- am_train_op_.set_error(result.error);- }- }).detach();- }- } else {- theme::LoadingSpinner("Training neural network...");- }-- if (am_train_op_.has_result) {- ImGui::Dummy(ImVec2(0, 8));- section_header("TRAINING RESULTS", SUCCESS);- std::lock_guard<std::mutex> lock(am_train_op_.mutex);- auto& d = am_train_op_.result;- double loss = d.value("final_loss", 0.0);- int epochs = d.value("epochs", 0);- double val_acc = d.value("val_accuracy", 0.0);- char epochs_buf[16];- std::snprintf(epochs_buf, sizeof(epochs_buf), "%d", epochs);- metric_card("Final Loss", loss, "%.6f", TEXT_SECONDARY);- ImGui::SameLine();- metric_card("Epochs", epochs_buf, TEXT_PRIMARY);- ImGui::SameLine();- metric_card("Val Accuracy", val_acc * 100, "%.1f%%", val_acc > 0.6 ? MARKET_GREEN : WARNING);- }-- if (!am_train_op_.error.empty()) theme::ErrorMessage(am_train_op_.error.c_str());-}--// ============================================================================-// PANEL 12: GluonTS — GLUON BLUE THEME-// ============================================================================-void AIQuantLabScreen::render_gluonts() {- using namespace theme::colors;- section_header("GLUONTS", panel_colors::GLUON_BLUE);- ImGui::TextColored(TEXT_DIM, "Deep learning time series forecasting");- ImGui::Dummy(ImVec2(0, 8));-- auto models = get_gluonts_models();- // Build combo items- std::vector<const char*> model_names;- for (auto& m : models) model_names.push_back(m.label);-- config_combo("Model", >s_model_idx_, model_names.data(), (int)model_names.size(), 130);- config_input_text("Data Path (CSV)", gts_data_path_, sizeof(gts_data_path_), 130);- config_input_int("Prediction Length", >s_pred_length_, 130);-- static const char* freqs[] = {"H (Hourly)", "D (Daily)", "W (Weekly)", "M (Monthly)"};- config_combo("Frequency", >s_freq_idx_, freqs, 4, 130);- config_input_int("Epochs", >s_epochs_, 130);-- ImGui::Dummy(ImVec2(0, 8));-- if (!gts_op_.loading.load()) {- if (theme::AccentButton("Run Forecast")) {- gts_op_.loading.store(true);- static const char* freq_codes[] = {"H", "D", "W", "M"};- json config = {- {"model", models[gts_model_idx_].name},- {"data_path", gts_data_path_},- {"prediction_length", gts_pred_length_},- {"freq", freq_codes[gts_freq_idx_]},- {"epochs", gts_epochs_},- };- log_status("Running GluonTS forecast...", panel_colors::GLUON_BLUE);- std::thread([this, config]() {- auto result = QuantLabApi::instance().gluonts_forecast(config).get();- if (result.success) {- gts_op_.set_result(result.data);- log_status("Forecast complete", SUCCESS);- } else {- gts_op_.set_error(result.error);- log_status("Forecast failed", ERROR_RED);- }- }).detach();- }- } else {- theme::LoadingSpinner("Forecasting...");- }-- // Forecast results- if (gts_op_.has_result) {- ImGui::Dummy(ImVec2(0, 12));- section_header("FORECAST RESULTS", panel_colors::GLUON_BLUE);-- std::lock_guard<std::mutex> lock(gts_op_.mutex);- auto& d = gts_op_.result;-- // Metrics- double mse = d.value("mse", 0.0);- double mae = d.value("mae", 0.0);- double mape = d.value("mape", 0.0);- metric_card("MSE", mse, "%.4f", TEXT_SECONDARY);- ImGui::SameLine();- metric_card("MAE", mae, "%.4f", TEXT_SECONDARY);- ImGui::SameLine();- metric_card("MAPE", mape * 100, "%.2f%%", mape < 0.1 ? MARKET_GREEN : WARNING);-- // Forecast plot with ImPlot- if (d.contains("forecast") && d["forecast"].is_array()) {- ImGui::Dummy(ImVec2(0, 8));- auto& fc = d["forecast"];- std::vector<double> values;- for (auto& v : fc) values.push_back(v.get<double>());-- if (ImPlot::BeginPlot("##forecast_plot", ImVec2(-1, 250))) {- ImPlot::SetupAxes("Time", "Value");- ImPlot::PushStyleColor(ImPlotCol_Line, panel_colors::GLUON_BLUE);- std::vector<double> xs(values.size());- for (size_t i = 0; i < xs.size(); i++) xs[i] = (double)i;- ImPlot::PlotLine("Forecast", xs.data(), values.data(), (int)values.size());- ImPlot::PopStyleColor();- ImPlot::EndPlot();- }- }- }-- if (!gts_op_.error.empty()) theme::ErrorMessage(gts_op_.error.c_str());-}--// ============================================================================-// PANEL 13: GS Quant — GS PURPLE THEME-// ============================================================================-void AIQuantLabScreen::render_gs_quant() {- using namespace theme::colors;- section_header("GS QUANT", panel_colors::GS_PURPLE);- ImGui::TextColored(TEXT_DIM, "Goldman Sachs-style quantitative analytics");- ImGui::Dummy(ImVec2(0, 8));-- static const char* modes[] = {- "Risk Metrics", "Portfolio Analytics", "Greeks",- "VaR", "Stress Testing", "Backtesting", "Statistics"- };- config_combo("Analysis Mode", &gsq_mode_idx_, modes, 7, 130);- config_input_text("Symbols", gsq_symbols_, sizeof(gsq_symbols_), 130);-- ImGui::Dummy(ImVec2(0, 8));-- if (!gsq_op_.loading.load()) {- if (theme::AccentButton("Run Analysis")) {- gsq_op_.loading.store(true);- json config = {- {"mode", modes[gsq_mode_idx_]},- {"symbols", gsq_symbols_},- };- log_status("Running GS Quant analysis...", panel_colors::GS_PURPLE);- std::thread([this, config]() {- auto result = QuantLabApi::instance().gs_quant_analyze(config).get();- if (result.success) {- gsq_op_.set_result(result.data);- log_status("GS Quant analysis complete", SUCCESS);- } else {- gsq_op_.set_error(result.error);- }- }).detach();- }- } else {- theme::LoadingSpinner("Analyzing...");- }-- // Results- if (gsq_op_.has_result) {- ImGui::Dummy(ImVec2(0, 12));- section_header("ANALYSIS RESULTS", panel_colors::GS_PURPLE);-- std::lock_guard<std::mutex> lock(gsq_op_.mutex);- // Render JSON results in a structured way- if (gsq_op_.result.is_object()) {- for (auto& [key, val] : gsq_op_.result.items()) {- if (val.is_number()) {- ImGui::TextColored(TEXT_DIM, "%s:", key.c_str());- ImGui::SameLine(200);- ImGui::TextColored(TEXT_PRIMARY, "%.4f", val.get<double>());- } else if (val.is_string()) {- ImGui::TextColored(TEXT_DIM, "%s:", key.c_str());- ImGui::SameLine(200);- ImGui::TextColored(TEXT_SECONDARY, "%s", val.get<std::string>().c_str());- }- }- }- }-- if (!gsq_op_.error.empty()) theme::ErrorMessage(gsq_op_.error.c_str());-}--// ============================================================================-// PANEL 14: Statsmodels — TEAL THEME-// ============================================================================-void AIQuantLabScreen::render_statsmodels() {- using namespace theme::colors;- section_header("STATSMODELS", panel_colors::TEAL);- ImGui::TextColored(TEXT_DIM, "Statistical time series analysis (ARIMA, SARIMAX, decomposition)");- ImGui::Dummy(ImVec2(0, 8));-- static const char* analyses[] = {- "ARIMA", "SARIMAX", "Exp Smoothing", "STL Decompose",- "ADF Test", "KPSS Test", "ACF", "PACF"- };- static const char* data_sources[] = {"Manual Data", "Symbol (Yahoo Finance)"};-- config_combo("Analysis", &sm_analysis_idx_, analyses, 8, 130);- config_combo("Data Source", &sm_data_source_, data_sources, 2, 130);-- if (sm_data_source_ == 1) {- config_input_text("Symbol", sm_symbol_, sizeof(sm_symbol_), 130);- } else {- ImGui::TextColored(TEXT_DIM, "Data (CSV):");- ImGui::InputTextMultiline("##sm_data", sm_data_, sizeof(sm_data_), ImVec2(-1, 80));- }-- // ARIMA params- if (sm_analysis_idx_ <= 1) {- ImGui::Dummy(ImVec2(0, 4));- ImGui::TextColored(TEXT_DIM, "ARIMA Order:");- ImGui::SameLine(130);- ImGui::SetNextItemWidth(50);- ImGui::InputInt("##p", &sm_arima_p_);- ImGui::SameLine();- ImGui::SetNextItemWidth(50);- ImGui::InputInt("##d", &sm_arima_d_);- ImGui::SameLine();- ImGui::SetNextItemWidth(50);- ImGui::InputInt("##q", &sm_arima_q_);- }-- ImGui::Dummy(ImVec2(0, 8));-- if (!sm_op_.loading.load()) {- if (theme::AccentButton("Run Analysis")) {- sm_op_.loading.store(true);- json config = {- {"analysis_type", analyses[sm_analysis_idx_]},- {"data_source", sm_data_source_ == 1 ? "symbol" : "manual"},- {"symbol", sm_symbol_},- {"data", sm_data_},- {"p", sm_arima_p_},- {"d", sm_arima_d_},- {"q", sm_arima_q_},- };- log_status("Running statsmodels analysis...", panel_colors::TEAL);- std::thread([this, config]() {- auto result = QuantLabApi::instance().statsmodels_analyze(config).get();- if (result.success) {- sm_op_.set_result(result.data);- log_status("Analysis complete", SUCCESS);- } else {- sm_op_.set_error(result.error);- }- }).detach();- }- } else {- theme::LoadingSpinner("Analyzing...");- }-- // Results- if (sm_op_.has_result) {- ImGui::Dummy(ImVec2(0, 12));- section_header("RESULTS", panel_colors::TEAL);- std::lock_guard<std::mutex> lock(sm_op_.mutex);- if (sm_op_.result.is_object()) {- for (auto& [key, val] : sm_op_.result.items()) {- if (val.is_number()) {- ImGui::TextColored(TEXT_DIM, "%s:", key.c_str());- ImGui::SameLine(200);- ImGui::TextColored(TEXT_PRIMARY, "%.6f", val.get<double>());- } else if (val.is_string()) {- ImGui::TextColored(TEXT_DIM, "%s:", key.c_str());- ImGui::SameLine(200);- ImGui::TextColored(TEXT_SECONDARY, "%s", val.get<std::string>().c_str());- }- }- }- }-- if (!sm_op_.error.empty()) theme::ErrorMessage(sm_op_.error.c_str());-}--// ============================================================================-// PANEL 15: Functime-// ============================================================================-void AIQuantLabScreen::render_functime() {- using namespace theme::colors;- section_header("FUNCTIME", ACCENT);- ImGui::TextColored(TEXT_DIM, "Fast time series forecasting with Functime library");- ImGui::Dummy(ImVec2(0, 8));-- static const char* models[] = {- "Naive", "SeasonalNaive", "LinearForecaster",- "LightGBMForecaster", "AutoARIMA", "AutoETS",- };- config_input_text("Symbol", ft_symbol_, sizeof(ft_symbol_), 130);- config_combo("Model", &ft_model_idx_, models, 6, 130);- config_input_int("Horizon", &ft_horizon_, 130);-- ImGui::Dummy(ImVec2(0, 8));-- if (!ft_op_.loading.load()) {- if (theme::AccentButton("Forecast")) {- ft_op_.loading.store(true);- json config = {- {"symbol", ft_symbol_},- {"model", models[ft_model_idx_]},- {"horizon", ft_horizon_},- };- log_status("Running functime forecast...", ACCENT);- std::thread([this, config]() {- auto result = QuantLabApi::instance().functime_forecast(config).get();- if (result.success) ft_op_.set_result(result.data);- else ft_op_.set_error(result.error);- }).detach();- }- } else {- theme::LoadingSpinner("Forecasting...");- }-- if (ft_op_.has_result) {- ImGui::Dummy(ImVec2(0, 8));- section_header("FORECAST", SUCCESS);- std::lock_guard<std::mutex> lock(ft_op_.mutex);- auto& d = ft_op_.result;-- // Plot forecast if available- if (d.contains("forecast") && d["forecast"].is_array()) {- std::vector<double> values;- for (auto& v : d["forecast"]) values.push_back(v.get<double>());-- if (ImPlot::BeginPlot("##ft_forecast", ImVec2(-1, 200))) {- ImPlot::SetupAxes("Step", "Value");- std::vector<double> xs(values.size());- for (size_t i = 0; i < xs.size(); i++) xs[i] = (double)i;- ImPlot::PlotLine("Forecast", xs.data(), values.data(), (int)values.size());- ImPlot::EndPlot();- }- }- }-- if (!ft_op_.error.empty()) theme::ErrorMessage(ft_op_.error.c_str());-}--// ============================================================================-// PANEL 16: Fortitudo-// ============================================================================-void AIQuantLabScreen::render_fortitudo() {- using namespace theme::colors;- section_header("FORTITUDO", ACCENT);- ImGui::TextColored(TEXT_DIM, "Entropy pooling, portfolio optimization, and risk analysis");- ImGui::Dummy(ImVec2(0, 8));-- static const char* modes[] = {"Entropy Pooling", "Optimization", "Option Pricing", "Portfolio Risk"};- config_combo("Mode", &fort_mode_idx_, modes, 4, 130);- config_input_text("Symbols", fort_symbols_, sizeof(fort_symbols_), 130);-- ImGui::Dummy(ImVec2(0, 8));-- if (!fort_op_.loading.load()) {- if (theme::AccentButton("Run Analysis")) {- fort_op_.loading.store(true);- json config = {- {"mode", modes[fort_mode_idx_]},- {"symbols", fort_symbols_},- };- log_status("Running Fortitudo analysis...", ACCENT);- std::thread([this, config]() {- auto result = QuantLabApi::instance().fortitudo_analyze(config).get();- if (result.success) fort_op_.set_result(result.data);- else fort_op_.set_error(result.error);- }).detach();- }- } else {- theme::LoadingSpinner("Analyzing...");- }-- if (fort_op_.has_result) {- ImGui::Dummy(ImVec2(0, 8));- section_header("RESULTS", SUCCESS);- std::lock_guard<std::mutex> lock(fort_op_.mutex);- if (fort_op_.result.is_object()) {- for (auto& [key, val] : fort_op_.result.items()) {- if (val.is_number()) {- ImGui::TextColored(TEXT_DIM, "%s:", key.c_str());- ImGui::SameLine(200);- ImGui::TextColored(TEXT_PRIMARY, "%.6f", val.get<double>());- }- }- }- }-- if (!fort_op_.error.empty()) theme::ErrorMessage(fort_op_.error.c_str());-}--// ============================================================================-// PANEL 17: CFA Quant-// ============================================================================-void AIQuantLabScreen::render_cfa_quant() {- using namespace theme::colors;- section_header("CFA QUANT", ACCENT);- ImGui::TextColored(TEXT_DIM, "CFA-level quantitative financial analysis");- ImGui::Dummy(ImVec2(0, 8));-- static const char* analyses[] = {- "Equity Valuation", "Fixed Income", "Derivatives",- "Portfolio Management", "Corporate Finance", "Economics",- };- config_input_text("Symbol", cfa_symbol_, sizeof(cfa_symbol_), 130);- config_combo("Analysis", &cfa_analysis_idx_, analyses, 6, 130);-- ImGui::Dummy(ImVec2(0, 8));-- if (!cfa_op_.loading.load()) {- if (theme::AccentButton("Run Analysis")) {- cfa_op_.loading.store(true);- json config = {- {"symbol", cfa_symbol_},- {"analysis_type", analyses[cfa_analysis_idx_]},- };- log_status("Running CFA analysis...", ACCENT);- std::thread([this, config]() {- auto result = QuantLabApi::instance().cfa_quant_analyze(config).get();- if (result.success) cfa_op_.set_result(result.data);- else cfa_op_.set_error(result.error);- }).detach();- }- } else {- theme::LoadingSpinner("Analyzing...");- }-- if (cfa_op_.has_result) {- ImGui::Dummy(ImVec2(0, 8));- section_header("RESULTS", SUCCESS);- std::lock_guard<std::mutex> lock(cfa_op_.mutex);- if (cfa_op_.result.is_object()) {- for (auto& [key, val] : cfa_op_.result.items()) {- if (val.is_number()) {- ImGui::TextColored(TEXT_DIM, "%s:", key.c_str());- ImGui::SameLine(200);- ImGui::TextColored(TEXT_PRIMARY, "%.4f", val.get<double>());- }- }- }- }-- if (!cfa_op_.error.empty()) theme::ErrorMessage(cfa_op_.error.c_str());-}--// ============================================================================-// PANEL 18: Pattern Intelligence — VisionQuant-// ============================================================================-void AIQuantLabScreen::render_pattern_intelligence() {- using namespace theme::colors;- section_header("PATTERN INTELLIGENCE", panel_colors::PURPLE);- ImGui::TextColored(TEXT_DIM, "VisionQuant K-line pattern recognition and analysis");- ImGui::Dummy(ImVec2(0, 8));-- static const char* patterns[] = {- "Doji", "Hammer", "Engulfing", "Morning Star", "Evening Star",- "Three White Soldiers", "Three Black Crows", "Harami",- "Piercing Line", "Dark Cloud Cover",- };- config_input_text("Symbol", pi_symbol_, sizeof(pi_symbol_), 130);- config_combo("Pattern", &pi_pattern_idx_, patterns, 10, 130);-- ImGui::Dummy(ImVec2(0, 8));-- // Three action buttons- if (!pi_search_op_.loading.load()) {- if (theme::AccentButton("Search Patterns")) {- pi_search_op_.loading.store(true);- json config = {- {"symbol", pi_symbol_},- {"pattern", patterns[pi_pattern_idx_]},- };- log_status("Searching patterns...", panel_colors::PURPLE);- std::thread([this, config]() {- auto result = QuantLabApi::instance().visionquant_search(config).get();- if (result.success) pi_search_op_.set_result(result.data);- else pi_search_op_.set_error(result.error);- }).detach();- }- } else {- theme::LoadingSpinner("Searching...");- }-- ImGui::SameLine();-- if (!pi_score_op_.loading.load()) {- if (theme::SecondaryButton("Score Pattern")) {- pi_score_op_.loading.store(true);- json config = {- {"symbol", pi_symbol_},- {"pattern", patterns[pi_pattern_idx_]},- };- std::thread([this, config]() {- auto result = QuantLabApi::instance().visionquant_score(config).get();- if (result.success) pi_score_op_.set_result(result.data);- else pi_score_op_.set_error(result.error);- }).detach();- }- } else {- theme::LoadingSpinner("Scoring...");- }-- ImGui::SameLine();-- if (!pi_backtest_op_.loading.load()) {- if (theme::SecondaryButton("Backtest Pattern")) {- pi_backtest_op_.loading.store(true);- json config = {- {"symbol", pi_symbol_},- {"pattern", patterns[pi_pattern_idx_]},- };- std::thread([this, config]() {- auto result = QuantLabApi::instance().visionquant_backtest(config).get();- if (result.success) pi_backtest_op_.set_result(result.data);- else pi_backtest_op_.set_error(result.error);- }).detach();- }- } else {- theme::LoadingSpinner("Backtesting...");- }-- // Search results- if (pi_search_op_.has_result) {- ImGui::Dummy(ImVec2(0, 8));- section_header("PATTERN MATCHES", panel_colors::PURPLE);- std::lock_guard<std::mutex> lock(pi_search_op_.mutex);- if (pi_search_op_.result.contains("matches") && pi_search_op_.result["matches"].is_array()) {- for (auto& m : pi_search_op_.result["matches"]) {- ImGui::TextColored(TEXT_PRIMARY, "%s at %s",- m.value("pattern", "").c_str(),- m.value("date", "").c_str());- ImGui::SameLine(300);- double conf = m.value("confidence", 0.0);- ImGui::TextColored(conf > 0.8 ? MARKET_GREEN : WARNING, "%.1f%%", conf * 100);- }- }- }-- // Score results- if (pi_score_op_.has_result) {- ImGui::Dummy(ImVec2(0, 8));- section_header("PATTERN SCORE", panel_colors::PURPLE);- std::lock_guard<std::mutex> lock(pi_score_op_.mutex);- auto& d = pi_score_op_.result;- double score = d.value("score", 0.0);- double reliability = d.value("reliability", 0.0);- metric_card("Score", score, "%.2f", score > 0.7 ? MARKET_GREEN : WARNING);- ImGui::SameLine();- metric_card("Reliability", reliability * 100, "%.1f%%", reliability > 0.6 ? MARKET_GREEN : WARNING);- }-- // Backtest results- if (pi_backtest_op_.has_result) {- ImGui::Dummy(ImVec2(0, 8));- section_header("PATTERN BACKTEST", panel_colors::PURPLE);- std::lock_guard<std::mutex> lock(pi_backtest_op_.mutex);- auto& d = pi_backtest_op_.result;- double win_rate = d.value("win_rate", 0.0);- double avg_return = d.value("avg_return", 0.0);- int occurrences = d.value("occurrences", 0);- metric_card("Win Rate", win_rate * 100, "%.1f%%", win_rate > 0.5 ? MARKET_GREEN : WARNING);- ImGui::SameLine();- metric_card("Avg Return", avg_return * 100, "%.2f%%", avg_return > 0 ? MARKET_GREEN : MARKET_RED);- ImGui::SameLine();- char occ_buf[16];- std::snprintf(occ_buf, sizeof(occ_buf), "%d", occurrences);- metric_card("Occurrences", occ_buf, TEXT_PRIMARY);- }-- if (!pi_search_op_.error.empty()) theme::ErrorMessage(pi_search_op_.error.c_str());- if (!pi_score_op_.error.empty()) theme::ErrorMessage(pi_score_op_.error.c_str());- if (!pi_backtest_op_.error.empty()) theme::ErrorMessage(pi_backtest_op_.error.c_str());-}--} // namespace fincept::ai_quant_lab+// ai_quant_lab_screen.cpp — split into focused files.+// All implementations live in:+// aql_screen.cpp — init, render, sidebar, content dispatch, status panel, UI helpers+// aql_panels_1.cpp — panels 1–9 (Factor Discovery, Model Library, Backtesting, Live Signals,+// Deep Agent, RL Trading, Online Learning, HFT Analytics, Meta Learning)+// aql_panels_2.cpp — panels 10–18 (Rolling Retraining, Advanced Models, GluonTS, GS Quant,+// Statsmodels, Functime, Fortitudo, CFA Quant, Pattern Intelligence)diff --git a/fincept-cpp/src/screens/ai_quant_lab/aql_panels_1.cpp b/fincept-cpp/src/screens/ai_quant_lab/aql_panels_1.cppnew file mode 100644index 000000000..07b03f4e8--- /dev/null+++ b/fincept-cpp/src/screens/ai_quant_lab/aql_panels_1.cpp@@ -0,0 +1,1005 @@+#include "ai_quant_lab_screen.h"+#include "ui/theme.h"+#include "core/logger.h"+#include <imgui.h>+#include <implot.h>+#include <cstring>+#include <cstdio>+#include <cmath>+#include <algorithm>+#include <ctime>++namespace fincept::ai_quant_lab {++// ============================================================================+// PANEL 1: Factor Discovery (RD-Agent) — PURPLE THEME+// ============================================================================+void AIQuantLabScreen::render_factor_discovery() {+ using namespace theme::colors;+ section_header("FACTOR DISCOVERY", panel_colors::PURPLE);+ ImGui::TextColored(TEXT_DIM, "RD-Agent automated alpha factor mining with AI-driven research");+ ImGui::Dummy(ImVec2(0, 8));++ // Config+ static const char* markets[] = {"US", "CN", "CRYPTO"};+ config_input_text("Task Description", fd_task_desc_, sizeof(fd_task_desc_), 130);+ config_input_text("API Key", fd_api_key_, sizeof(fd_api_key_), 130);+ config_combo("Target Market", &fd_market_idx_, markets, 3, 130);+ config_input_int("Budget", &fd_budget_, 130);++ ImGui::Dummy(ImVec2(0, 8));++ // Start button+ bool is_running = fd_op_.loading.load() || fd_polling_;+ if (is_running) {+ theme::LoadingSpinner("Mining factors...");+ progress_bar(0.5f, "Searching for alpha...");++ // Poll status every 5 seconds+ if (fd_polling_ && !fd_task_id_.empty()) {+ double now = ImGui::GetTime();+ if (now - fd_last_poll_ > 5.0) {+ fd_last_poll_ = now;+ // Check status+ auto status_future = QuantLabApi::instance().rdagent_get_status(fd_task_id_);+ if (status_future.wait_for(std::chrono::milliseconds(0)) == std::future_status::ready) {+ auto r = status_future.get();+ if (r.success && r.data.value("status", "") == "completed") {+ fd_polling_ = false;+ // Fetch factors+ auto fac_future = QuantLabApi::instance().rdagent_get_factors(fd_task_id_);+ // Will be picked up next frame+ }+ }+ }+ }+ } else {+ if (theme::AccentButton("Start Factor Mining")) {+ json config = {+ {"task_description", fd_task_desc_},+ {"api_key", fd_api_key_},+ {"target_market", markets[fd_market_idx_]},+ {"budget", fd_budget_},+ };+ fd_op_.loading.store(true);+ log_status("Starting factor mining...", panel_colors::PURPLE);++ std::thread([this, config]() {+ auto result = QuantLabApi::instance().rdagent_start_mining(config).get();+ if (result.success) {+ fd_task_id_ = result.data.value("task_id", "");+ fd_polling_ = true;+ fd_last_poll_ = 0;+ log_status("Factor mining started: " + fd_task_id_, SUCCESS);+ } else {+ fd_op_.set_error(result.error);+ log_status("Factor mining failed: " + result.error, ERROR_RED);+ }+ fd_op_.loading.store(false);+ }).detach();+ }+ }++ // Display discovered factors+ if (!fd_factors_.empty()) {+ ImGui::Dummy(ImVec2(0, 12));+ section_header("DISCOVERED FACTORS", panel_colors::PURPLE);++ for (size_t i = 0; i < fd_factors_.size(); i++) {+ auto& f = fd_factors_[i];+ ImGui::PushID((int)i);++ ImGui::PushStyleColor(ImGuiCol_ChildBg, BG_WIDGET);+ ImGui::BeginChild("##factor", ImVec2(-1, 0), ImGuiChildFlags_AutoResizeY | ImGuiChildFlags_Borders);++ ImGui::TextColored(panel_colors::PURPLE, "%s", f.name.c_str());+ ImGui::TextColored(TEXT_DIM, "%s", f.description.c_str());++ // Metrics row+ metric_card("IC", f.ic, "%.4f", f.ic > 0.03 ? MARKET_GREEN : TEXT_SECONDARY);+ ImGui::SameLine();+ metric_card("Sharpe", f.sharpe, "%.2f", f.sharpe > 1.0 ? MARKET_GREEN : TEXT_SECONDARY);+ ImGui::SameLine();+ metric_card("Annual Return", f.annual_return, "%.2f%%", f.annual_return > 0 ? MARKET_GREEN : MARKET_RED);++ // Code display+ if (ImGui::CollapsingHeader("Factor Code")) {+ ImGui::PushStyleColor(ImGuiCol_ChildBg, BG_DARKEST);+ ImGui::BeginChild("##code", ImVec2(-1, 100));+ ImGui::TextWrapped("%s", f.code.c_str());+ ImGui::EndChild();+ ImGui::PopStyleColor();++ if (ImGui::SmallButton("Copy Code")) {+ ImGui::SetClipboardText(f.code.c_str());+ log_status("Factor code copied", SUCCESS);+ }+ }++ ImGui::EndChild();+ ImGui::PopStyleColor();+ ImGui::PopID();+ ImGui::Dummy(ImVec2(0, 4));+ }+ }++ // Error display+ if (!fd_op_.error.empty()) {+ theme::ErrorMessage(fd_op_.error.c_str());+ }+}++// ============================================================================+// PANEL 2: Model Library (Qlib) — BLUE THEME+// ============================================================================+void AIQuantLabScreen::render_model_library() {+ using namespace theme::colors;+ section_header("MODEL LIBRARY", panel_colors::BLUE);+ ImGui::TextColored(TEXT_DIM, "Microsoft Qlib ML models for financial prediction");+ ImGui::Dummy(ImVec2(0, 8));++ // Filter+ static const char* filters[] = {"All", "Tree-Based", "Neural Network", "Linear", "Ensemble"};+ config_combo("Filter", &ml_filter_idx_, filters, 5, 100);++ // Load models button+ if (!ml_list_op_.loading.load()) {+ if (theme::SecondaryButton("Refresh Models")) {+ ml_list_op_.loading.store(true);+ std::thread([this]() {+ auto result = QuantLabApi::instance().qlib_list_models().get();+ if (result.success) {+ std::lock_guard<std::mutex> lock(ml_list_op_.mutex);+ ml_models_.clear();+ if (result.data.is_array()) {+ for (auto& m : result.data) {+ QlibModel model;+ model.name = m.value("name", "");+ model.type = m.value("type", "");+ model.description = m.value("description", "");+ ml_models_.push_back(model);+ }+ }+ ml_list_op_.set_result(result.data);+ } else {+ ml_list_op_.set_error(result.error);+ }+ }).detach();+ }+ } else {+ theme::LoadingSpinner("Loading models...");+ }++ ImGui::Dummy(ImVec2(0, 8));++ // Model list+ if (ml_models_.empty() && !ml_list_op_.has_result) {+ // Show default models+ static const struct { const char* name; const char* type; const char* desc; } defaults[] = {+ {"LightGBM", "tree_based", "Gradient boosting framework with high efficiency"},+ {"XGBoost", "tree_based", "Extreme gradient boosting for structured data"},+ {"CatBoost", "tree_based", "Gradient boosting with native categorical support"},+ {"LSTM", "neural_network", "Long Short-Term Memory recurrent network"},+ {"GRU", "neural_network", "Gated Recurrent Unit network"},+ {"Transformer", "neural_network", "Attention-based architecture for sequences"},+ {"Linear", "linear", "Linear regression with regularization"},+ {"Ridge", "linear", "L2-regularized linear regression"},+ {"RandomForest","ensemble", "Bagged decision tree ensemble"},+ {"AdaBoost", "ensemble", "Adaptive boosting ensemble method"},+ };++ for (auto& d : defaults) {+ if (ml_filter_idx_ > 0) {+ const char* filter_types[] = {"", "tree_based", "neural_network", "linear", "ensemble"};+ if (std::strcmp(d.type, filter_types[ml_filter_idx_]) != 0) continue;+ }++ bool selected = false;+ ImGui::PushStyleColor(ImGuiCol_Header, ImVec4(panel_colors::BLUE.x, panel_colors::BLUE.y, panel_colors::BLUE.z, 0.1f));+ if (ImGui::Selectable(d.name, &selected, ImGuiSelectableFlags_None, ImVec2(0, 28))) {+ // Select model+ }+ ImGui::PopStyleColor();+ ImGui::SameLine(200);+ ImGui::TextColored(TEXT_DIM, "[%s]", d.type);+ ImGui::SameLine(350);+ ImGui::TextColored(TEXT_SECONDARY, "%s", d.desc);+ }+ }++ ImGui::Dummy(ImVec2(0, 12));++ // Train config+ section_header("TRAIN MODEL", panel_colors::BLUE);+ config_input_text("Instruments", ml_instruments_, sizeof(ml_instruments_), 120);+ config_input_text("Start Date", ml_start_date_, sizeof(ml_start_date_), 120);+ config_input_text("End Date", ml_end_date_, sizeof(ml_end_date_), 120);++ if (!ml_train_op_.loading.load()) {+ if (theme::AccentButton("Train Model")) {+ ml_train_op_.loading.store(true);+ json config = {+ {"instruments", ml_instruments_},+ {"start_date", ml_start_date_},+ {"end_date", ml_end_date_},+ };+ log_status("Training model...", panel_colors::BLUE);+ std::thread([this, config]() {+ auto result = QuantLabApi::instance().qlib_train_model(config).get();+ if (result.success) {+ ml_train_op_.set_result(result.data);+ log_status("Model training completed", SUCCESS);+ } else {+ ml_train_op_.set_error(result.error);+ log_status("Training failed: " + result.error, ERROR_RED);+ }+ }).detach();+ }+ } else {+ theme::LoadingSpinner("Training...");+ }++ if (!ml_train_op_.error.empty()) theme::ErrorMessage(ml_train_op_.error.c_str());+}++// ============================================================================+// PANEL 3: Backtesting (Qlib)+// ============================================================================+void AIQuantLabScreen::render_backtesting() {+ using namespace theme::colors;+ section_header("STRATEGY BACKTESTING", ACCENT);+ ImGui::TextColored(TEXT_DIM, "Qlib-powered strategy backtesting engine");+ ImGui::Dummy(ImVec2(0, 8));++ static const char* strategies[] = {"TopK Dropout", "Weight Base", "Enhanced Indexing"};+ config_combo("Strategy", &bt_strategy_idx_, strategies, 3, 120);+ config_input_text("Instruments", bt_instruments_, sizeof(bt_instruments_), 120);+ config_input_text("Start Date", bt_start_, sizeof(bt_start_), 120);+ config_input_text("End Date", bt_end_, sizeof(bt_end_), 120);+ config_input_float("Initial Capital", &bt_capital_, 120);+ config_input_text("Benchmark", bt_benchmark_, sizeof(bt_benchmark_), 120);+ config_input_float("Commission", &bt_commission_, 120);+ config_input_float("Slippage", &bt_slippage_, 120);++ ImGui::Dummy(ImVec2(0, 8));++ if (!bt_op_.loading.load()) {+ if (theme::AccentButton("Run Backtest")) {+ static const char* strat_keys[] = {"topk_dropout", "weight_base", "enhanced_indexing"};+ json config = {+ {"strategy", strat_keys[bt_strategy_idx_]},+ {"instruments", bt_instruments_},+ {"start_date", bt_start_},+ {"end_date", bt_end_},+ {"initial_capital", bt_capital_},+ {"benchmark", bt_benchmark_},+ {"commission", bt_commission_},+ {"slippage", bt_slippage_},+ };+ bt_op_.loading.store(true);+ log_status("Running backtest...", ACCENT);+ std::thread([this, config]() {+ auto result = QuantLabApi::instance().qlib_run_backtest(config).get();+ if (result.success) {+ bt_op_.set_result(result.data);+ log_status("Backtest completed", SUCCESS);+ } else {+ bt_op_.set_error(result.error);+ log_status("Backtest failed: " + result.error, ERROR_RED);+ }+ }).detach();+ }+ } else {+ theme::LoadingSpinner("Running backtest...");+ }++ // Results+ if (bt_op_.has_result) {+ ImGui::Dummy(ImVec2(0, 12));+ section_header("BACKTEST RESULTS", SUCCESS);++ std::lock_guard<std::mutex> lock(bt_op_.mutex);+ auto& d = bt_op_.result;++ double ann_ret = d.value("annual_return", 0.0);+ double sharpe = d.value("sharpe_ratio", 0.0);+ double max_dd = d.value("max_drawdown", 0.0);+ double win_rate = d.value("win_rate", 0.0);+ int trades = d.value("total_trades", 0);+ double pf = d.value("profit_factor", 0.0);++ metric_card("Annual Return", ann_ret * 100, "%.2f%%", ann_ret > 0 ? MARKET_GREEN : MARKET_RED);+ ImGui::SameLine();+ metric_card("Sharpe Ratio", sharpe, "%.2f", sharpe > 1 ? MARKET_GREEN : WARNING);+ ImGui::SameLine();+ metric_card("Max Drawdown", max_dd * 100, "%.2f%%", MARKET_RED);++ metric_card("Win Rate", win_rate * 100, "%.1f%%", win_rate > 0.5 ? MARKET_GREEN : WARNING);+ ImGui::SameLine();+ char trades_buf[32];+ std::snprintf(trades_buf, sizeof(trades_buf), "%d", trades);+ metric_card("Total Trades", trades_buf, TEXT_PRIMARY);+ ImGui::SameLine();+ metric_card("Profit Factor", pf, "%.2f", pf > 1 ? MARKET_GREEN : MARKET_RED);+ }++ if (!bt_op_.error.empty()) theme::ErrorMessage(bt_op_.error.c_str());+}++// ============================================================================+// PANEL 4: Live Signals — GREEN THEME+// ============================================================================+void AIQuantLabScreen::render_live_signals() {+ using namespace theme::colors;+ section_header("LIVE SIGNALS", panel_colors::GREEN);+ ImGui::TextColored(TEXT_DIM, "Real-time model predictions & trading signals");+ ImGui::Dummy(ImVec2(0, 8));++ static const char* models[] = {"LightGBM", "XGBoost", "LSTM", "Transformer"};+ config_combo("Model", &ls_model_idx_, models, 4, 120);+ config_input_int("Refresh (sec)", &ls_refresh_sec_, 120);++ static const char* signal_filters[] = {"ALL", "BUY", "SELL"};+ config_combo("Filter", &ls_filter_idx_, signal_filters, 3, 120);++ ImGui::Dummy(ImVec2(0, 8));++ // Stream toggle+ if (ls_streaming_) {+ ImGui::PushStyleColor(ImGuiCol_Button, ImVec4(panel_colors::GREEN.x, panel_colors::GREEN.y, panel_colors::GREEN.z, 0.3f));+ if (ImGui::Button("Stop Streaming")) {+ ls_streaming_ = false;+ log_status("Signal streaming stopped", WARNING);+ }+ ImGui::PopStyleColor();+ ImGui::SameLine();+ theme::LoadingSpinner("Streaming...");++ // Auto-refresh+ double now = ImGui::GetTime();+ if (now - ls_last_refresh_ > ls_refresh_sec_ && !ls_op_.loading.load()) {+ ls_last_refresh_ = now;+ ls_op_.loading.store(true);+ json config = {{"model", models[ls_model_idx_]}};+ std::thread([this, config]() {+ auto result = QuantLabApi::instance().qlib_get_live_predictions(config).get();+ if (result.success) {+ std::lock_guard<std::mutex> lock(ls_op_.mutex);+ ls_signals_.clear();+ if (result.data.is_array()) {+ for (auto& s : result.data) {+ SignalEntry sig;+ sig.symbol = s.value("symbol", "");+ sig.signal = s.value("signal", "HOLD");+ sig.score = s.value("score", 0.0);+ sig.price = s.value("price", 0.0);+ sig.confidence = s.value("confidence", 0.0);+ sig.model = s.value("model", "");+ sig.timestamp = s.value("timestamp", "");+ ls_signals_.push_back(sig);+ }+ }+ ls_op_.set_result(result.data);+ } else {+ ls_op_.set_error(result.error);+ }+ }).detach();+ }+ } else {+ if (theme::AccentButton("Start Streaming")) {+ ls_streaming_ = true;+ ls_last_refresh_ = 0;+ log_status("Signal streaming started", panel_colors::GREEN);+ }+ }++ // Signal cards+ if (!ls_signals_.empty()) {+ ImGui::Dummy(ImVec2(0, 8));+ for (auto& sig : ls_signals_) {+ // Filter+ if (ls_filter_idx_ == 1 && sig.signal != "BUY") continue;+ if (ls_filter_idx_ == 2 && sig.signal != "SELL") continue;++ ImVec4 sig_color = sig.signal == "BUY" ? MARKET_GREEN :+ sig.signal == "SELL" ? MARKET_RED : WARNING;++ ImGui::PushStyleColor(ImGuiCol_ChildBg, ImVec4(sig_color.x, sig_color.y, sig_color.z, 0.05f));+ ImGui::BeginChild(ImGui::GetID(sig.symbol.c_str()), ImVec2(-1, 0),+ ImGuiChildFlags_AutoResizeY | ImGuiChildFlags_Borders);++ ImGui::TextColored(TEXT_PRIMARY, "%s", sig.symbol.c_str());+ ImGui::SameLine(120);+ status_badge(sig.signal.c_str(),+ ImVec4(sig_color.x, sig_color.y, sig_color.z, 0.2f), sig_color);+ ImGui::SameLine(220);+ ImGui::TextColored(TEXT_SECONDARY, "Score: %.4f", sig.score);+ ImGui::SameLine(350);+ ImGui::TextColored(TEXT_SECONDARY, "$%.2f", sig.price);+ ImGui::SameLine(440);+ ImGui::TextColored(TEXT_DIM, "Conf: %.1f%%", sig.confidence * 100);++ ImGui::EndChild();+ ImGui::PopStyleColor();+ ImGui::Dummy(ImVec2(0, 2));+ }+ } else if (!ls_op_.loading.load() && !ls_streaming_) {+ ImGui::Dummy(ImVec2(0, 20));+ ImGui::TextColored(TEXT_DIM, "Click 'Start Streaming' to receive live predictions");+ }++ if (!ls_op_.error.empty()) theme::ErrorMessage(ls_op_.error.c_str());+}++// ============================================================================+// PANEL 5: Deep Agent — LLM-powered autonomous research+// ============================================================================+void AIQuantLabScreen::render_deep_agent() {+ using namespace theme::colors;+ section_header("DEEP AGENT", ACCENT);+ ImGui::TextColored(TEXT_DIM, "LLM-powered autonomous financial research agent");+ ImGui::Dummy(ImVec2(0, 8));++ static const char* agents[] = {"Research", "Strategy Builder", "Portfolio Manager", "Risk Analyzer", "General"};+ config_combo("Agent Type", &da_agent_idx_, agents, 5, 120);+ config_input_text("Query", da_query_, sizeof(da_query_), 120);++ ImGui::Dummy(ImVec2(0, 8));++ // Phase indicator+ static const char* phases[] = {"Ready", "Planning", "Executing", "Synthesizing", "Complete"};+ ImGui::TextColored(TEXT_DIM, "Phase:");+ ImGui::SameLine();+ ImVec4 phase_color = da_phase_ == 4 ? SUCCESS :+ da_phase_ > 0 ? WARNING : TEXT_SECONDARY;+ ImGui::TextColored(phase_color, "%s", phases[da_phase_]);++ if (da_phase_ > 0 && da_phase_ < 4) {+ float prog = (float)da_phase_ / 4.0f;+ progress_bar(prog, phases[da_phase_]);+ }++ ImGui::Dummy(ImVec2(0, 8));++ if (da_phase_ == 0) {+ if (theme::AccentButton("Create Plan")) {+ if (std::strlen(da_query_) == 0) return;+ da_phase_ = 1;+ da_steps_.clear();+ da_plan_text_.clear();+ da_synthesis_.clear();+ da_op_.loading.store(true);+ log_status("Deep Agent: Creating plan...", ACCENT);++ json config = {+ {"agent_type", agents[da_agent_idx_]},+ {"query", da_query_},+ };+ std::thread([this, config]() {+ auto result = QuantLabApi::instance().deep_agent_create_plan(config).get();+ if (result.success) {+ da_plan_text_ = result.data.value("plan", "");+ if (result.data.contains("steps") && result.data["steps"].is_array()) {+ int idx = 0;+ for (auto& s : result.data["steps"]) {+ AgentStep step;+ step.index = idx++;+ step.description = s.value("description", "");+ step.status = "pending";+ da_steps_.push_back(step);+ }+ }+ da_phase_ = 2;+ da_current_step_ = 0;+ log_status("Plan created with " + std::to_string(da_steps_.size()) + " steps", SUCCESS);+ } else {+ da_phase_ = 0;+ log_status("Planning failed: " + result.error, ERROR_RED);+ }+ da_op_.loading.store(false);+ }).detach();+ }+ } else if (da_phase_ == 2) {+ // Show plan and steps+ if (!da_plan_text_.empty()) {+ ImGui::TextColored(TEXT_SECONDARY, "Plan:");+ ImGui::TextWrapped("%s", da_plan_text_.c_str());+ ImGui::Dummy(ImVec2(0, 8));+ }++ section_header("EXECUTION STEPS", ACCENT);+ for (auto& step : da_steps_) {+ ImVec4 sc = step.status == "completed" ? SUCCESS :+ step.status == "running" ? WARNING :+ step.status == "failed" ? ERROR_RED : TEXT_DIM;+ ImGui::TextColored(sc, "[%d] %s — %s",+ step.index + 1, step.description.c_str(), step.status.c_str());+ if (!step.result.empty() && step.status == "completed") {+ ImGui::Indent(20);+ ImGui::TextColored(TEXT_DIM, "%s", step.result.c_str());+ ImGui::Unindent(20);+ }+ }++ ImGui::Dummy(ImVec2(0, 8));++ if (!da_op_.loading.load() && da_current_step_ < (int)da_steps_.size()) {+ if (theme::AccentButton("Execute Next Step")) {+ da_op_.loading.store(true);+ int step_idx = da_current_step_;+ da_steps_[step_idx].status = "running";+ json config = {+ {"step_index", step_idx},+ {"description", da_steps_[step_idx].description},+ {"agent_type", agents[da_agent_idx_]},+ {"query", da_query_},+ };+ std::thread([this, config, step_idx]() {+ auto result = QuantLabApi::instance().deep_agent_execute_step(config).get();+ if (result.success) {+ da_steps_[step_idx].status = "completed";+ da_steps_[step_idx].result = result.data.value("result", "");+ da_current_step_++;+ if (da_current_step_ >= (int)da_steps_.size()) {+ da_phase_ = 3; // Ready to synthesize+ }+ } else {+ da_steps_[step_idx].status = "failed";+ da_steps_[step_idx].result = result.error;+ }+ da_op_.loading.store(false);+ }).detach();+ }+ } else if (da_op_.loading.load()) {+ theme::LoadingSpinner("Executing step...");+ }++ if (da_current_step_ >= (int)da_steps_.size() && !da_op_.loading.load()) {+ if (theme::AccentButton("Synthesize Results")) {+ da_phase_ = 3;+ da_op_.loading.store(true);+ json config = {+ {"agent_type", agents[da_agent_idx_]},+ {"query", da_query_},+ {"steps", json::array()},+ };+ for (auto& s : da_steps_) {+ config["steps"].push_back({+ {"description", s.description},+ {"result", s.result},+ });+ }+ std::thread([this, config]() {+ auto result = QuantLabApi::instance().deep_agent_synthesize(config).get();+ if (result.success) {+ da_synthesis_ = result.data.value("synthesis", "");+ da_phase_ = 4;+ log_status("Deep Agent: Synthesis complete", SUCCESS);+ } else {+ da_phase_ = 2;+ log_status("Synthesis failed: " + result.error, ERROR_RED);+ }+ da_op_.loading.store(false);+ }).detach();+ }+ }+ } else if (da_phase_ == 3) {+ theme::LoadingSpinner("Synthesizing results...");+ } else if (da_phase_ == 4) {+ section_header("SYNTHESIS", SUCCESS);+ ImGui::TextWrapped("%s", da_synthesis_.c_str());++ ImGui::Dummy(ImVec2(0, 8));+ if (theme::SecondaryButton("New Query")) {+ da_phase_ = 0;+ da_steps_.clear();+ da_plan_text_.clear();+ da_synthesis_.clear();+ }+ }+}++// ============================================================================+// PANEL 6: RL Trading — PURPLE THEME+// ============================================================================+void AIQuantLabScreen::render_rl_trading() {+ using namespace theme::colors;+ section_header("RL TRADING", panel_colors::PURPLE);+ ImGui::TextColored(TEXT_DIM, "Reinforcement learning trading strategies");+ ImGui::Dummy(ImVec2(0, 8));++ static const char* algos[] = {"PPO", "A2C", "DQN", "SAC", "TD3"};+ static const char* action_spaces[] = {"Continuous", "Discrete"};++ config_combo("Algorithm", &rl_algo_idx_, algos, 5, 130);+ config_input_text("Tickers", rl_tickers_, sizeof(rl_tickers_), 130);+ config_input_text("Start Date", rl_start_, sizeof(rl_start_), 130);+ config_input_text("End Date", rl_end_, sizeof(rl_end_), 130);+ config_input_float("Initial Cash", &rl_initial_cash_, 130);+ config_input_float("Commission", &rl_commission_, 130);+ config_combo("Action Space", &rl_action_space_, action_spaces, 2, 130);+ config_input_int("Timesteps", &rl_timesteps_, 130);+ config_input_float("Learning Rate", &rl_learning_rate_, 130);++ ImGui::Dummy(ImVec2(0, 8));++ // Phase display+ static const char* rl_phases[] = {"Configure", "Env Created", "Training", "Evaluating", "Done"};+ ImGui::TextColored(TEXT_DIM, "Phase:");+ ImGui::SameLine();+ ImGui::TextColored(rl_phase_ == 4 ? SUCCESS : WARNING, "%s", rl_phases[rl_phase_]);++ if (rl_phase_ > 0 && rl_phase_ < 4)+ progress_bar((float)rl_phase_ / 4.0f);++ ImGui::Dummy(ImVec2(0, 8));++ if (!rl_op_.loading.load()) {+ const char* btn_label = rl_phase_ == 0 ? "Create Environment" :+ rl_phase_ == 1 ? "Train Agent" :+ rl_phase_ == 3 ? "Evaluate" : "Reset";++ if (theme::AccentButton(btn_label)) {+ if (rl_phase_ >= 4) {+ rl_phase_ = 0;+ rl_op_.clear();+ return;+ }++ rl_op_.loading.store(true);+ json config = {+ {"algorithm", algos[rl_algo_idx_]},+ {"tickers", rl_tickers_},+ {"start_date", rl_start_},+ {"end_date", rl_end_},+ {"initial_cash", rl_initial_cash_},+ {"commission", rl_commission_},+ {"action_space", action_spaces[rl_action_space_]},+ {"timesteps", rl_timesteps_},+ {"learning_rate", rl_learning_rate_},+ };++ int phase = rl_phase_;+ std::thread([this, config, phase]() {+ ApiResult result;+ if (phase == 0) {+ result = QuantLabApi::instance().rl_create_env(config).get();+ if (result.success) rl_phase_ = 1;+ } else if (phase == 1) {+ result = QuantLabApi::instance().rl_train_agent(config).get();+ if (result.success) rl_phase_ = 3;+ } else if (phase == 3) {+ result = QuantLabApi::instance().rl_evaluate(config).get();+ if (result.success) rl_phase_ = 4;+ }++ if (result.success) {+ rl_op_.set_result(result.data);+ log_status("RL Phase complete", SUCCESS);+ } else {+ rl_op_.set_error(result.error);+ log_status("RL failed: " + result.error, ERROR_RED);+ }+ }).detach();+ }+ } else {+ theme::LoadingSpinner("Processing...");+ }++ // Show results+ if (rl_op_.has_result && rl_phase_ == 4) {+ ImGui::Dummy(ImVec2(0, 12));+ section_header("EVALUATION RESULTS", panel_colors::PURPLE);++ std::lock_guard<std::mutex> lock(rl_op_.mutex);+ auto& d = rl_op_.result;+ double total_ret = d.value("total_return", 0.0);+ double sharpe = d.value("sharpe_ratio", 0.0);+ double max_dd = d.value("max_drawdown", 0.0);++ metric_card("Total Return", total_ret * 100, "%.2f%%", total_ret > 0 ? MARKET_GREEN : MARKET_RED);+ ImGui::SameLine();+ metric_card("Sharpe", sharpe, "%.2f", sharpe > 1 ? MARKET_GREEN : WARNING);+ ImGui::SameLine();+ metric_card("Max Drawdown", max_dd * 100, "%.2f%%", MARKET_RED);+ }++ if (!rl_op_.error.empty()) theme::ErrorMessage(rl_op_.error.c_str());+}++// ============================================================================+// PANEL 7: Online Learning — YELLOW THEME+// ============================================================================+void AIQuantLabScreen::render_online_learning() {+ using namespace theme::colors;+ section_header("ONLINE LEARNING", panel_colors::YELLOW);+ ImGui::TextColored(TEXT_DIM, "Continuous model adaptation with drift detection");+ ImGui::Dummy(ImVec2(0, 8));++ static const char* model_types[] = {+ "LinearRegression", "RidgeRegression", "LogisticRegression",+ "DecisionTree", "RandomForest", "GradientBoosting",+ "AdaBoost", "BaggingClassifier", "VotingEnsemble"+ };+ static const char* drift_strategies[] = {"Retrain", "Adaptive"};++ config_combo("Model Type", &ol_model_idx_, model_types, 9, 130);+ config_combo("Drift Strategy", &ol_drift_strategy_, drift_strategies, 2, 130);++ ImGui::Dummy(ImVec2(0, 8));++ // Create Model+ if (!ol_create_op_.loading.load()) {+ if (theme::AccentButton("Create Model")) {+ ol_create_op_.loading.store(true);+ json config = {{"model_type", model_types[ol_model_idx_]}};+ log_status("Creating online model...", panel_colors::YELLOW);+ std::thread([this, config]() {+ auto result = QuantLabApi::instance().qlib_online_create(config).get();+ if (result.success) {+ ol_create_op_.set_result(result.data);+ log_status("Online model created", SUCCESS);+ } else {+ ol_create_op_.set_error(result.error);+ }+ }).detach();+ }+ } else {+ theme::LoadingSpinner("Creating model...");+ }++ ImGui::SameLine();++ // Train+ if (!ol_train_op_.loading.load()) {+ if (theme::SecondaryButton("Train")) {+ ol_train_op_.loading.store(true);+ json config = {{"model_type", model_types[ol_model_idx_]}};+ std::thread([this, config]() {+ auto result = QuantLabApi::instance().qlib_online_train(config).get();+ if (result.success) ol_train_op_.set_result(result.data);+ else ol_train_op_.set_error(result.error);+ }).detach();+ }+ } else {+ theme::LoadingSpinner("Training...");+ }++ ImGui::Dummy(ImVec2(0, 8));++ // Live mode toggle+ if (ImGui::Checkbox("Live Mode (2s updates)", &ol_live_mode_)) {+ log_status(ol_live_mode_ ? "Live mode enabled" : "Live mode disabled",+ ol_live_mode_ ? panel_colors::YELLOW : TEXT_DIM);+ }++ if (ol_live_mode_) {+ double now = ImGui::GetTime();+ if (now - ol_last_update_ > 2.0 && !ol_perf_op_.loading.load()) {+ ol_last_update_ = now;+ ol_perf_op_.loading.store(true);+ std::thread([this]() {+ auto result = QuantLabApi::instance().qlib_online_performance("current").get();+ if (result.success) ol_perf_op_.set_result(result.data);+ else ol_perf_op_.set_error(result.error);+ }).detach();+ }+ }++ // Performance display+ if (ol_perf_op_.has_result) {+ ImGui::Dummy(ImVec2(0, 8));+ section_header("PERFORMANCE", panel_colors::YELLOW);+ std::lock_guard<std::mutex> lock(ol_perf_op_.mutex);+ auto& d = ol_perf_op_.result;+ double acc = d.value("accuracy", 0.0);+ double loss = d.value("loss", 0.0);+ metric_card("Accuracy", acc * 100, "%.1f%%", acc > 0.6 ? MARKET_GREEN : WARNING);+ ImGui::SameLine();+ metric_card("Loss", loss, "%.4f", TEXT_SECONDARY);+ }++ if (!ol_create_op_.error.empty()) theme::ErrorMessage(ol_create_op_.error.c_str());+ if (!ol_train_op_.error.empty()) theme::ErrorMessage(ol_train_op_.error.c_str());+}++// ============================================================================+// PANEL 8: HFT Analytics — RED THEME+// ============================================================================+void AIQuantLabScreen::render_hft() {+ using namespace theme::colors;+ section_header("HFT ANALYTICS", panel_colors::RED);+ ImGui::TextColored(TEXT_DIM, "Order book visualization & microstructure analysis");+ ImGui::Dummy(ImVec2(0, 8));++ config_input_text("Symbol", hft_symbol_, sizeof(hft_symbol_), 120);+ config_input_float("Spread Target", &hft_spread_target_, 120);+ config_input_float("Position Limit", &hft_position_limit_, 120);++ ImGui::Dummy(ImVec2(0, 4));++ // Live toggle+ if (ImGui::Checkbox("Live Mode (1s updates)", &hft_live_)) {+ if (hft_live_) {+ log_status("HFT live mode started", panel_colors::RED);+ // Generate initial mock data+ hft_bids_.clear();+ hft_asks_.clear();+ double base = 185.50;+ for (int i = 0; i < 10; i++) {+ hft_bids_.push_back({base - i * 0.01, 100.0 + rand() % 500, 1 + rand() % 10});+ hft_asks_.push_back({base + 0.01 + i * 0.01, 100.0 + rand() % 500, 1 + rand() % 10});+ }+ hft_metrics_ = {0.15, base - 0.05, base + 0.05, 0.23, 0.02, base};+ }+ }++ if (hft_live_) {+ double now = ImGui::GetTime();+ if (now - hft_last_update_ > 1.0) {+ hft_last_update_ = now;+ // Update mock data with slight randomization+ for (auto& b : hft_bids_) b.size += (rand() % 100) - 50;+ for (auto& a : hft_asks_) a.size += (rand() % 100) - 50;+ hft_metrics_.depth_imbalance = 0.1 + (rand() % 30) / 100.0;+ hft_metrics_.toxicity_score = 0.15 + (rand() % 20) / 100.0;+ }+ }++ // Order Book+ if (!hft_bids_.empty()) {+ ImGui::Dummy(ImVec2(0, 8));+ section_header("ORDER BOOK", panel_colors::RED);++ // Bids and asks side by side+ ImGui::Columns(2, "##orderbook", true);++ // Bids+ ImGui::TextColored(MARKET_GREEN, "BIDS");+ ImGui::Separator();+ ImGui::TextColored(TEXT_DIM, "%-10s %-10s %-6s", "Price", "Size", "Orders");+ for (auto& b : hft_bids_) {+ float pct = (float)(b.size / 600.0);+ ImVec2 p = ImGui::GetCursorScreenPos();+ ImGui::GetWindowDrawList()->AddRectFilled(p,+ ImVec2(p.x + ImGui::GetColumnWidth() * pct, p.y + ImGui::GetTextLineHeight()),+ IM_COL32(5, 217, 107, 30));+ ImGui::TextColored(MARKET_GREEN, "%.2f %.0f %d", b.price, b.size, b.orders);+ }++ ImGui::NextColumn();++ // Asks+ ImGui::TextColored(MARKET_RED, "ASKS");+ ImGui::Separator();+ ImGui::TextColored(TEXT_DIM, "%-10s %-10s %-6s", "Price", "Size", "Orders");+ for (auto& a : hft_asks_) {+ float pct = (float)(a.size / 600.0);+ ImVec2 p2 = ImGui::GetCursorScreenPos();+ ImGui::GetWindowDrawList()->AddRectFilled(p2,+ ImVec2(p2.x + ImGui::GetColumnWidth() * pct, p2.y + ImGui::GetTextLineHeight()),+ IM_COL32(245, 64, 64, 30));+ ImGui::TextColored(MARKET_RED, "%.2f %.0f %d", a.price, a.size, a.orders);+ }++ ImGui::Columns(1);++ // Microstructure metrics+ ImGui::Dummy(ImVec2(0, 8));+ section_header("MICROSTRUCTURE", panel_colors::RED);++ metric_card("Depth Imbalance", hft_metrics_.depth_imbalance, "%.4f",+ std::abs(hft_metrics_.depth_imbalance) > 0.3 ? WARNING : TEXT_SECONDARY);+ ImGui::SameLine();+ metric_card("VWAP Bid", hft_metrics_.vwap_bid, "%.2f", MARKET_GREEN);+ ImGui::SameLine();+ metric_card("VWAP Ask", hft_metrics_.vwap_ask, "%.2f", MARKET_RED);++ metric_card("Toxicity", hft_metrics_.toxicity_score, "%.4f",+ hft_metrics_.toxicity_score > 0.5 ? MARKET_RED : TEXT_SECONDARY);+ ImGui::SameLine();+ metric_card("Spread", hft_metrics_.spread, "%.4f", TEXT_SECONDARY);+ ImGui::SameLine();+ metric_card("Mid Price", hft_metrics_.mid_price, "%.2f", TEXT_PRIMARY);++ // Market Making Quote Calculator+ ImGui::Dummy(ImVec2(0, 8));+ section_header("MARKET MAKING QUOTES", panel_colors::RED);++ double bid_quote = hft_metrics_.mid_price - hft_spread_target_ / 2;+ double ask_quote = hft_metrics_.mid_price + hft_spread_target_ / 2;+ ImGui::TextColored(MARKET_GREEN, "Bid Quote: $%.4f", bid_quote);+ ImGui::TextColored(MARKET_RED, "Ask Quote: $%.4f", ask_quote);+ ImGui::TextColored(TEXT_DIM, "Spread: $%.4f (%.2f bps)",+ ask_quote - bid_quote,+ (ask_quote - bid_quote) / hft_metrics_.mid_price * 10000);+ }+}++// ============================================================================+// PANEL 9: Meta Learning — MAGENTA THEME+// ============================================================================+void AIQuantLabScreen::render_meta_learning() {+ using namespace theme::colors;+ section_header("META LEARNING", panel_colors::MAGENTA);+ ImGui::TextColored(TEXT_DIM, "Automated model selection and comparison");+ ImGui::Dummy(ImVec2(0, 8));++ static const char* task_types[] = {"Classification", "Regression"};+ config_combo("Task Type", &meta_task_type_, task_types, 2, 130);++ ImGui::Dummy(ImVec2(0, 8));++ if (!meta_run_op_.loading.load()) {+ if (theme::AccentButton("Run Model Selection")) {+ meta_run_op_.loading.store(true);+ json config = {+ {"task_type", task_types[meta_task_type_]},+ {"models", json::array({"LightGBM", "XGBoost", "CatBoost", "RandomForest"})},+ };+ log_status("Running meta-learning selection...", panel_colors::MAGENTA);+ std::thread([this, config]() {+ auto result = QuantLabApi::instance().qlib_meta_run_selection(config).get();+ if (result.success) {+ meta_run_op_.set_result(result.data);+ log_status("Meta-learning complete", SUCCESS);+ } else {+ meta_run_op_.set_error(result.error);+ }+ }).detach();+ }+ } else {+ theme::LoadingSpinner("Running model selection...");+ }++ // Results — show default comparison if no results yet+ ImGui::Dummy(ImVec2(0, 12));+ section_header("MODEL COMPARISON", panel_colors::MAGENTA);++ if (ImGui::BeginTable("##meta_models", 7,+ ImGuiTableFlags_Borders | ImGuiTableFlags_RowBg | ImGuiTableFlags_Resizable)) {+ ImGui::TableSetupColumn("Rank", ImGuiTableColumnFlags_WidthFixed, 40);+ ImGui::TableSetupColumn("Model");+ ImGui::TableSetupColumn("Accuracy");+ ImGui::TableSetupColumn("F1 Score");+ ImGui::TableSetupColumn("AUC-ROC");+ ImGui::TableSetupColumn("MSE");+ ImGui::TableSetupColumn("R2");+ ImGui::TableHeadersRow();++ // Default data (or API results)+ struct ModelResult { const char* name; double acc; double f1; double auc; double mse; double r2; };+ ModelResult defaults[] = {+ {"LightGBM", 0.847, 0.832, 0.891, 0.0234, 0.765},+ {"XGBoost", 0.841, 0.825, 0.885, 0.0241, 0.758},+ {"CatBoost", 0.838, 0.821, 0.882, 0.0247, 0.752},+ {"RandomForest", 0.823, 0.808, 0.869, 0.0268, 0.731},+ };++ for (int i = 0; i < 4; i++) {+ auto& m = defaults[i];+ ImGui::TableNextRow();+ ImGui::TableNextColumn();+ ImGui::TextColored(i == 0 ? panel_colors::MAGENTA : TEXT_SECONDARY, "#%d", i + 1);+ ImGui::TableNextColumn();+ ImGui::TextColored(TEXT_PRIMARY, "%s", m.name);+ ImGui::TableNextColumn();+ ImGui::TextColored(m.acc > 0.84 ? MARKET_GREEN : TEXT_SECONDARY, "%.3f", m.acc);+ ImGui::TableNextColumn();+ ImGui::TextColored(TEXT_SECONDARY, "%.3f", m.f1);+ ImGui::TableNextColumn();+ ImGui::TextColored(TEXT_SECONDARY, "%.3f", m.auc);+ ImGui::TableNextColumn();+ ImGui::TextColored(TEXT_SECONDARY, "%.4f", m.mse);+ ImGui::TableNextColumn();+ ImGui::TextColored(m.r2 > 0.75 ? MARKET_GREEN : TEXT_SECONDARY, "%.3f", m.r2);+ }++ ImGui::EndTable();+ }++ if (!meta_run_op_.error.empty()) theme::ErrorMessage(meta_run_op_.error.c_str());+}+++} // namespace fincept::ai_quant_labdiff --git a/fincept-cpp/src/screens/ai_quant_lab/aql_panels_2.cpp b/fincept-cpp/src/screens/ai_quant_lab/aql_panels_2.cppnew file mode 100644index 000000000..60e387d02--- /dev/null+++ b/fincept-cpp/src/screens/ai_quant_lab/aql_panels_2.cpp@@ -0,0 +1,674 @@+#include "ai_quant_lab_screen.h"+#include "ui/theme.h"+#include "core/logger.h"+#include <imgui.h>+#include <implot.h>+#include <cstring>+#include <cstdio>+#include <cmath>+#include <algorithm>+#include <ctime>++namespace fincept::ai_quant_lab {++// ============================================================================+// PANEL 10: Rolling Retraining — CYAN THEME+// ============================================================================+void AIQuantLabScreen::render_rolling_retraining() {+ using namespace theme::colors;+ section_header("ROLLING RETRAINING", panel_colors::CYAN);+ ImGui::TextColored(TEXT_DIM, "Scheduled model updates and retraining pipelines");+ ImGui::Dummy(ImVec2(0, 8));++ static const char* frequencies[] = {"Hourly", "Daily", "Weekly"};++ config_input_text("Model Name", rr_model_name_, sizeof(rr_model_name_), 130);+ config_input_int("Window (days)", &rr_window_days_, 130);+ config_combo("Frequency", &rr_frequency_, frequencies, 3, 130);++ ImGui::Dummy(ImVec2(0, 8));++ if (!rr_create_op_.loading.load()) {+ if (theme::AccentButton("Create Schedule")) {+ rr_create_op_.loading.store(true);+ json config = {+ {"model_name", rr_model_name_},+ {"training_window_days", rr_window_days_},+ {"frequency", frequencies[rr_frequency_]},+ };+ log_status("Creating retraining schedule...", panel_colors::CYAN);+ std::thread([this, config]() {+ auto result = QuantLabApi::instance().qlib_rolling_create_schedule(config).get();+ if (result.success) {+ rr_create_op_.set_result(result.data);+ log_status("Schedule created", SUCCESS);+ } else {+ rr_create_op_.set_error(result.error);+ }+ }).detach();+ }+ } else {+ theme::LoadingSpinner("Creating schedule...");+ }++ ImGui::SameLine();+ if (theme::SecondaryButton("List Schedules")) {+ rr_list_op_.loading.store(true);+ std::thread([this]() {+ auto result = QuantLabApi::instance().qlib_rolling_list_schedules().get();+ if (result.success) rr_list_op_.set_result(result.data);+ else rr_list_op_.set_error(result.error);+ }).detach();+ }++ if (!rr_create_op_.error.empty()) theme::ErrorMessage(rr_create_op_.error.c_str());+ if (!rr_list_op_.error.empty()) theme::ErrorMessage(rr_list_op_.error.c_str());+}++// ============================================================================+// PANEL 11: Advanced Models+// ============================================================================+void AIQuantLabScreen::render_advanced_models() {+ using namespace theme::colors;+ section_header("ADVANCED MODELS", panel_colors::BLUE);+ ImGui::TextColored(TEXT_DIM, "LSTM, GRU, and Transformer neural network architectures");+ ImGui::Dummy(ImVec2(0, 8));++ static const char* models[] = {"LSTM", "GRU", "Transformer"};+ config_combo("Architecture", &am_model_idx_, models, 3, 130);++ // Model details+ ImGui::Dummy(ImVec2(0, 8));+ const char* descs[] = {+ "Long Short-Term Memory — excels at capturing long-range temporal dependencies in sequential financial data",+ "Gated Recurrent Unit — lightweight alternative to LSTM with comparable performance and faster training",+ "Transformer — attention-based architecture that captures complex multi-variate relationships",+ };+ ImGui::TextColored(TEXT_SECONDARY, "%s", descs[am_model_idx_]);++ ImGui::Dummy(ImVec2(0, 8));++ if (!am_train_op_.loading.load()) {+ if (theme::AccentButton("Train Model")) {+ am_train_op_.loading.store(true);+ json config = {{"model_type", models[am_model_idx_]}};+ log_status(std::string("Training ") + models[am_model_idx_] + "...", panel_colors::BLUE);+ std::thread([this, config]() {+ auto result = QuantLabApi::instance().qlib_advanced_train(config).get();+ if (result.success) {+ am_train_op_.set_result(result.data);+ log_status("Training complete", SUCCESS);+ } else {+ am_train_op_.set_error(result.error);+ }+ }).detach();+ }+ } else {+ theme::LoadingSpinner("Training neural network...");+ }++ if (am_train_op_.has_result) {+ ImGui::Dummy(ImVec2(0, 8));+ section_header("TRAINING RESULTS", SUCCESS);+ std::lock_guard<std::mutex> lock(am_train_op_.mutex);+ auto& d = am_train_op_.result;+ double loss = d.value("final_loss", 0.0);+ int epochs = d.value("epochs", 0);+ double val_acc = d.value("val_accuracy", 0.0);+ char epochs_buf[16];+ std::snprintf(epochs_buf, sizeof(epochs_buf), "%d", epochs);+ metric_card("Final Loss", loss, "%.6f", TEXT_SECONDARY);+ ImGui::SameLine();+ metric_card("Epochs", epochs_buf, TEXT_PRIMARY);+ ImGui::SameLine();+ metric_card("Val Accuracy", val_acc * 100, "%.1f%%", val_acc > 0.6 ? MARKET_GREEN : WARNING);+ }++ if (!am_train_op_.error.empty()) theme::ErrorMessage(am_train_op_.error.c_str());+}++// ============================================================================+// PANEL 12: GluonTS — GLUON BLUE THEME+// ============================================================================+void AIQuantLabScreen::render_gluonts() {+ using namespace theme::colors;+ section_header("GLUONTS", panel_colors::GLUON_BLUE);+ ImGui::TextColored(TEXT_DIM, "Deep learning time series forecasting");+ ImGui::Dummy(ImVec2(0, 8));++ auto models = get_gluonts_models();+ // Build combo items+ std::vector<const char*> model_names;+ for (auto& m : models) model_names.push_back(m.label);++ config_combo("Model", >s_model_idx_, model_names.data(), (int)model_names.size(), 130);+ config_input_text("Data Path (CSV)", gts_data_path_, sizeof(gts_data_path_), 130);+ config_input_int("Prediction Length", >s_pred_length_, 130);++ static const char* freqs[] = {"H (Hourly)", "D (Daily)", "W (Weekly)", "M (Monthly)"};+ config_combo("Frequency", >s_freq_idx_, freqs, 4, 130);+ config_input_int("Epochs", >s_epochs_, 130);++ ImGui::Dummy(ImVec2(0, 8));++ if (!gts_op_.loading.load()) {+ if (theme::AccentButton("Run Forecast")) {+ gts_op_.loading.store(true);+ static const char* freq_codes[] = {"H", "D", "W", "M"};+ json config = {+ {"model", models[gts_model_idx_].name},+ {"data_path", gts_data_path_},+ {"prediction_length", gts_pred_length_},+ {"freq", freq_codes[gts_freq_idx_]},+ {"epochs", gts_epochs_},+ };+ log_status("Running GluonTS forecast...", panel_colors::GLUON_BLUE);+ std::thread([this, config]() {+ auto result = QuantLabApi::instance().gluonts_forecast(config).get();+ if (result.success) {+ gts_op_.set_result(result.data);+ log_status("Forecast complete", SUCCESS);+ } else {+ gts_op_.set_error(result.error);+ log_status("Forecast failed", ERROR_RED);+ }+ }).detach();+ }+ } else {+ theme::LoadingSpinner("Forecasting...");+ }++ // Forecast results+ if (gts_op_.has_result) {+ ImGui::Dummy(ImVec2(0, 12));+ section_header("FORECAST RESULTS", panel_colors::GLUON_BLUE);++ std::lock_guard<std::mutex> lock(gts_op_.mutex);+ auto& d = gts_op_.result;++ // Metrics+ double mse = d.value("mse", 0.0);+ double mae = d.value("mae", 0.0);+ double mape = d.value("mape", 0.0);+ metric_card("MSE", mse, "%.4f", TEXT_SECONDARY);+ ImGui::SameLine();+ metric_card("MAE", mae, "%.4f", TEXT_SECONDARY);+ ImGui::SameLine();+ metric_card("MAPE", mape * 100, "%.2f%%", mape < 0.1 ? MARKET_GREEN : WARNING);++ // Forecast plot with ImPlot+ if (d.contains("forecast") && d["forecast"].is_array()) {+ ImGui::Dummy(ImVec2(0, 8));+ auto& fc = d["forecast"];+ std::vector<double> values;+ for (auto& v : fc) values.push_back(v.get<double>());++ if (ImPlot::BeginPlot("##forecast_plot", ImVec2(-1, 250))) {+ ImPlot::SetupAxes("Time", "Value");+ ImPlot::PushStyleColor(ImPlotCol_Line, panel_colors::GLUON_BLUE);+ std::vector<double> xs(values.size());+ for (size_t i = 0; i < xs.size(); i++) xs[i] = (double)i;+ ImPlot::PlotLine("Forecast", xs.data(), values.data(), (int)values.size());+ ImPlot::PopStyleColor();+ ImPlot::EndPlot();+ }+ }+ }++ if (!gts_op_.error.empty()) theme::ErrorMessage(gts_op_.error.c_str());+}++// ============================================================================+// PANEL 13: GS Quant — GS PURPLE THEME+// ============================================================================+void AIQuantLabScreen::render_gs_quant() {+ using namespace theme::colors;+ section_header("GS QUANT", panel_colors::GS_PURPLE);+ ImGui::TextColored(TEXT_DIM, "Goldman Sachs-style quantitative analytics");+ ImGui::Dummy(ImVec2(0, 8));++ static const char* modes[] = {+ "Risk Metrics", "Portfolio Analytics", "Greeks",+ "VaR", "Stress Testing", "Backtesting", "Statistics"+ };+ config_combo("Analysis Mode", &gsq_mode_idx_, modes, 7, 130);+ config_input_text("Symbols", gsq_symbols_, sizeof(gsq_symbols_), 130);++ ImGui::Dummy(ImVec2(0, 8));++ if (!gsq_op_.loading.load()) {+ if (theme::AccentButton("Run Analysis")) {+ gsq_op_.loading.store(true);+ json config = {+ {"mode", modes[gsq_mode_idx_]},+ {"symbols", gsq_symbols_},+ };+ log_status("Running GS Quant analysis...", panel_colors::GS_PURPLE);+ std::thread([this, config]() {+ auto result = QuantLabApi::instance().gs_quant_analyze(config).get();+ if (result.success) {+ gsq_op_.set_result(result.data);+ log_status("GS Quant analysis complete", SUCCESS);+ } else {+ gsq_op_.set_error(result.error);+ }+ }).detach();+ }+ } else {+ theme::LoadingSpinner("Analyzing...");+ }++ // Results+ if (gsq_op_.has_result) {+ ImGui::Dummy(ImVec2(0, 12));+ section_header("ANALYSIS RESULTS", panel_colors::GS_PURPLE);++ std::lock_guard<std::mutex> lock(gsq_op_.mutex);+ // Render JSON results in a structured way+ if (gsq_op_.result.is_object()) {+ for (auto& [key, val] : gsq_op_.result.items()) {+ if (val.is_number()) {+ ImGui::TextColored(TEXT_DIM, "%s:", key.c_str());+ ImGui::SameLine(200);+ ImGui::TextColored(TEXT_PRIMARY, "%.4f", val.get<double>());+ } else if (val.is_string()) {+ ImGui::TextColored(TEXT_DIM, "%s:", key.c_str());+ ImGui::SameLine(200);+ ImGui::TextColored(TEXT_SECONDARY, "%s", val.get<std::string>().c_str());+ }+ }+ }+ }++ if (!gsq_op_.error.empty()) theme::ErrorMessage(gsq_op_.error.c_str());+}++// ============================================================================+// PANEL 14: Statsmodels — TEAL THEME+// ============================================================================+void AIQuantLabScreen::render_statsmodels() {+ using namespace theme::colors;+ section_header("STATSMODELS", panel_colors::TEAL);+ ImGui::TextColored(TEXT_DIM, "Statistical time series analysis (ARIMA, SARIMAX, decomposition)");+ ImGui::Dummy(ImVec2(0, 8));++ static const char* analyses[] = {+ "ARIMA", "SARIMAX", "Exp Smoothing", "STL Decompose",+ "ADF Test", "KPSS Test", "ACF", "PACF"+ };+ static const char* data_sources[] = {"Manual Data", "Symbol (Yahoo Finance)"};++ config_combo("Analysis", &sm_analysis_idx_, analyses, 8, 130);+ config_combo("Data Source", &sm_data_source_, data_sources, 2, 130);++ if (sm_data_source_ == 1) {+ config_input_text("Symbol", sm_symbol_, sizeof(sm_symbol_), 130);+ } else {+ ImGui::TextColored(TEXT_DIM, "Data (CSV):");+ ImGui::InputTextMultiline("##sm_data", sm_data_, sizeof(sm_data_), ImVec2(-1, 80));+ }++ // ARIMA params+ if (sm_analysis_idx_ <= 1) {+ ImGui::Dummy(ImVec2(0, 4));+ ImGui::TextColored(TEXT_DIM, "ARIMA Order:");+ ImGui::SameLine(130);+ ImGui::SetNextItemWidth(50);+ ImGui::InputInt("##p", &sm_arima_p_);+ ImGui::SameLine();+ ImGui::SetNextItemWidth(50);+ ImGui::InputInt("##d", &sm_arima_d_);+ ImGui::SameLine();+ ImGui::SetNextItemWidth(50);+ ImGui::InputInt("##q", &sm_arima_q_);+ }++ ImGui::Dummy(ImVec2(0, 8));++ if (!sm_op_.loading.load()) {+ if (theme::AccentButton("Run Analysis")) {+ sm_op_.loading.store(true);+ json config = {+ {"analysis_type", analyses[sm_analysis_idx_]},+ {"data_source", sm_data_source_ == 1 ? "symbol" : "manual"},+ {"symbol", sm_symbol_},+ {"data", sm_data_},+ {"p", sm_arima_p_},+ {"d", sm_arima_d_},+ {"q", sm_arima_q_},+ };+ log_status("Running statsmodels analysis...", panel_colors::TEAL);+ std::thread([this, config]() {+ auto result = QuantLabApi::instance().statsmodels_analyze(config).get();+ if (result.success) {+ sm_op_.set_result(result.data);+ log_status("Analysis complete", SUCCESS);+ } else {+ sm_op_.set_error(result.error);+ }+ }).detach();+ }+ } else {+ theme::LoadingSpinner("Analyzing...");+ }++ // Results+ if (sm_op_.has_result) {+ ImGui::Dummy(ImVec2(0, 12));+ section_header("RESULTS", panel_colors::TEAL);+ std::lock_guard<std::mutex> lock(sm_op_.mutex);+ if (sm_op_.result.is_object()) {+ for (auto& [key, val] : sm_op_.result.items()) {+ if (val.is_number()) {+ ImGui::TextColored(TEXT_DIM, "%s:", key.c_str());+ ImGui::SameLine(200);+ ImGui::TextColored(TEXT_PRIMARY, "%.6f", val.get<double>());+ } else if (val.is_string()) {+ ImGui::TextColored(TEXT_DIM, "%s:", key.c_str());+ ImGui::SameLine(200);+ ImGui::TextColored(TEXT_SECONDARY, "%s", val.get<std::string>().c_str());+ }+ }+ }+ }++ if (!sm_op_.error.empty()) theme::ErrorMessage(sm_op_.error.c_str());+}++// ============================================================================+// PANEL 15: Functime+// ============================================================================+void AIQuantLabScreen::render_functime() {+ using namespace theme::colors;+ section_header("FUNCTIME", ACCENT);+ ImGui::TextColored(TEXT_DIM, "Fast time series forecasting with Functime library");+ ImGui::Dummy(ImVec2(0, 8));++ static const char* models[] = {+ "Naive", "SeasonalNaive", "LinearForecaster",+ "LightGBMForecaster", "AutoARIMA", "AutoETS",+ };+ config_input_text("Symbol", ft_symbol_, sizeof(ft_symbol_), 130);+ config_combo("Model", &ft_model_idx_, models, 6, 130);+ config_input_int("Horizon", &ft_horizon_, 130);++ ImGui::Dummy(ImVec2(0, 8));++ if (!ft_op_.loading.load()) {+ if (theme::AccentButton("Forecast")) {+ ft_op_.loading.store(true);+ json config = {+ {"symbol", ft_symbol_},+ {"model", models[ft_model_idx_]},+ {"horizon", ft_horizon_},+ };+ log_status("Running functime forecast...", ACCENT);+ std::thread([this, config]() {+ auto result = QuantLabApi::instance().functime_forecast(config).get();+ if (result.success) ft_op_.set_result(result.data);+ else ft_op_.set_error(result.error);+ }).detach();+ }+ } else {+ theme::LoadingSpinner("Forecasting...");+ }++ if (ft_op_.has_result) {+ ImGui::Dummy(ImVec2(0, 8));+ section_header("FORECAST", SUCCESS);+ std::lock_guard<std::mutex> lock(ft_op_.mutex);+ auto& d = ft_op_.result;++ // Plot forecast if available+ if (d.contains("forecast") && d["forecast"].is_array()) {+ std::vector<double> values;+ for (auto& v : d["forecast"]) values.push_back(v.get<double>());++ if (ImPlot::BeginPlot("##ft_forecast", ImVec2(-1, 200))) {+ ImPlot::SetupAxes("Step", "Value");+ std::vector<double> xs(values.size());+ for (size_t i = 0; i < xs.size(); i++) xs[i] = (double)i;+ ImPlot::PlotLine("Forecast", xs.data(), values.data(), (int)values.size());+ ImPlot::EndPlot();+ }+ }+ }++ if (!ft_op_.error.empty()) theme::ErrorMessage(ft_op_.error.c_str());+}++// ============================================================================+// PANEL 16: Fortitudo+// ============================================================================+void AIQuantLabScreen::render_fortitudo() {+ using namespace theme::colors;+ section_header("FORTITUDO", ACCENT);+ ImGui::TextColored(TEXT_DIM, "Entropy pooling, portfolio optimization, and risk analysis");+ ImGui::Dummy(ImVec2(0, 8));++ static const char* modes[] = {"Entropy Pooling", "Optimization", "Option Pricing", "Portfolio Risk"};+ config_combo("Mode", &fort_mode_idx_, modes, 4, 130);+ config_input_text("Symbols", fort_symbols_, sizeof(fort_symbols_), 130);++ ImGui::Dummy(ImVec2(0, 8));++ if (!fort_op_.loading.load()) {+ if (theme::AccentButton("Run Analysis")) {+ fort_op_.loading.store(true);+ json config = {+ {"mode", modes[fort_mode_idx_]},+ {"symbols", fort_symbols_},+ };+ log_status("Running Fortitudo analysis...", ACCENT);+ std::thread([this, config]() {+ auto result = QuantLabApi::instance().fortitudo_analyze(config).get();+ if (result.success) fort_op_.set_result(result.data);+ else fort_op_.set_error(result.error);+ }).detach();+ }+ } else {+ theme::LoadingSpinner("Analyzing...");+ }++ if (fort_op_.has_result) {+ ImGui::Dummy(ImVec2(0, 8));+ section_header("RESULTS", SUCCESS);+ std::lock_guard<std::mutex> lock(fort_op_.mutex);+ if (fort_op_.result.is_object()) {+ for (auto& [key, val] : fort_op_.result.items()) {+ if (val.is_number()) {+ ImGui::TextColored(TEXT_DIM, "%s:", key.c_str());+ ImGui::SameLine(200);+ ImGui::TextColored(TEXT_PRIMARY, "%.6f", val.get<double>());+ }+ }+ }+ }++ if (!fort_op_.error.empty()) theme::ErrorMessage(fort_op_.error.c_str());+}++// ============================================================================+// PANEL 17: CFA Quant+// ============================================================================+void AIQuantLabScreen::render_cfa_quant() {+ using namespace theme::colors;+ section_header("CFA QUANT", ACCENT);+ ImGui::TextColored(TEXT_DIM, "CFA-level quantitative financial analysis");+ ImGui::Dummy(ImVec2(0, 8));++ static const char* analyses[] = {+ "Equity Valuation", "Fixed Income", "Derivatives",+ "Portfolio Management", "Corporate Finance", "Economics",+ };+ config_input_text("Symbol", cfa_symbol_, sizeof(cfa_symbol_), 130);+ config_combo("Analysis", &cfa_analysis_idx_, analyses, 6, 130);++ ImGui::Dummy(ImVec2(0, 8));++ if (!cfa_op_.loading.load()) {+ if (theme::AccentButton("Run Analysis")) {+ cfa_op_.loading.store(true);+ json config = {+ {"symbol", cfa_symbol_},+ {"analysis_type", analyses[cfa_analysis_idx_]},+ };+ log_status("Running CFA analysis...", ACCENT);+ std::thread([this, config]() {+ auto result = QuantLabApi::instance().cfa_quant_analyze(config).get();+ if (result.success) cfa_op_.set_result(result.data);+ else cfa_op_.set_error(result.error);+ }).detach();+ }+ } else {+ theme::LoadingSpinner("Analyzing...");+ }++ if (cfa_op_.has_result) {+ ImGui::Dummy(ImVec2(0, 8));+ section_header("RESULTS", SUCCESS);+ std::lock_guard<std::mutex> lock(cfa_op_.mutex);+ if (cfa_op_.result.is_object()) {+ for (auto& [key, val] : cfa_op_.result.items()) {+ if (val.is_number()) {+ ImGui::TextColored(TEXT_DIM, "%s:", key.c_str());+ ImGui::SameLine(200);+ ImGui::TextColored(TEXT_PRIMARY, "%.4f", val.get<double>());+ }+ }+ }+ }++ if (!cfa_op_.error.empty()) theme::ErrorMessage(cfa_op_.error.c_str());+}++// ============================================================================+// PANEL 18: Pattern Intelligence — VisionQuant+// ============================================================================+void AIQuantLabScreen::render_pattern_intelligence() {+ using namespace theme::colors;+ section_header("PATTERN INTELLIGENCE", panel_colors::PURPLE);+ ImGui::TextColored(TEXT_DIM, "VisionQuant K-line pattern recognition and analysis");+ ImGui::Dummy(ImVec2(0, 8));++ static const char* patterns[] = {+ "Doji", "Hammer", "Engulfing", "Morning Star", "Evening Star",+ "Three White Soldiers", "Three Black Crows", "Harami",+ "Piercing Line", "Dark Cloud Cover",+ };+ config_input_text("Symbol", pi_symbol_, sizeof(pi_symbol_), 130);+ config_combo("Pattern", &pi_pattern_idx_, patterns, 10, 130);++ ImGui::Dummy(ImVec2(0, 8));++ // Three action buttons+ if (!pi_search_op_.loading.load()) {+ if (theme::AccentButton("Search Patterns")) {+ pi_search_op_.loading.store(true);+ json config = {+ {"symbol", pi_symbol_},+ {"pattern", patterns[pi_pattern_idx_]},+ };+ log_status("Searching patterns...", panel_colors::PURPLE);+ std::thread([this, config]() {+ auto result = QuantLabApi::instance().visionquant_search(config).get();+ if (result.success) pi_search_op_.set_result(result.data);+ else pi_search_op_.set_error(result.error);+ }).detach();+ }+ } else {+ theme::LoadingSpinner("Searching...");+ }++ ImGui::SameLine();++ if (!pi_score_op_.loading.load()) {+ if (theme::SecondaryButton("Score Pattern")) {+ pi_score_op_.loading.store(true);+ json config = {+ {"symbol", pi_symbol_},+ {"pattern", patterns[pi_pattern_idx_]},+ };+ std::thread([this, config]() {+ auto result = QuantLabApi::instance().visionquant_score(config).get();+ if (result.success) pi_score_op_.set_result(result.data);+ else pi_score_op_.set_error(result.error);+ }).detach();+ }+ } else {+ theme::LoadingSpinner("Scoring...");+ }++ ImGui::SameLine();++ if (!pi_backtest_op_.loading.load()) {+ if (theme::SecondaryButton("Backtest Pattern")) {+ pi_backtest_op_.loading.store(true);+ json config = {+ {"symbol", pi_symbol_},+ {"pattern", patterns[pi_pattern_idx_]},+ };+ std::thread([this, config]() {+ auto result = QuantLabApi::instance().visionquant_backtest(config).get();+ if (result.success) pi_backtest_op_.set_result(result.data);+ else pi_backtest_op_.set_error(result.error);+ }).detach();+ }+ } else {+ theme::LoadingSpinner("Backtesting...");+ }++ // Search results+ if (pi_search_op_.has_result) {+ ImGui::Dummy(ImVec2(0, 8));+ section_header("PATTERN MATCHES", panel_colors::PURPLE);+ std::lock_guard<std::mutex> lock(pi_search_op_.mutex);+ if (pi_search_op_.result.contains("matches") && pi_search_op_.result["matches"].is_array()) {+ for (auto& m : pi_search_op_.result["matches"]) {+ ImGui::TextColored(TEXT_PRIMARY, "%s at %s",+ m.value("pattern", "").c_str(),+ m.value("date", "").c_str());+ ImGui::SameLine(300);+ double conf = m.value("confidence", 0.0);+ ImGui::TextColored(conf > 0.8 ? MARKET_GREEN : WARNING, "%.1f%%", conf * 100);+ }+ }+ }++ // Score results+ if (pi_score_op_.has_result) {+ ImGui::Dummy(ImVec2(0, 8));+ section_header("PATTERN SCORE", panel_colors::PURPLE);+ std::lock_guard<std::mutex> lock(pi_score_op_.mutex);+ auto& d = pi_score_op_.result;+ double score = d.value("score", 0.0);+ double reliability = d.value("reliability", 0.0);+ metric_card("Score", score, "%.2f", score > 0.7 ? MARKET_GREEN : WARNING);+ ImGui::SameLine();+ metric_card("Reliability", reliability * 100, "%.1f%%", reliability > 0.6 ? MARKET_GREEN : WARNING);+ }++ // Backtest results+ if (pi_backtest_op_.has_result) {+ ImGui::Dummy(ImVec2(0, 8));+ section_header("PATTERN BACKTEST", panel_colors::PURPLE);+ std::lock_guard<std::mutex> lock(pi_backtest_op_.mutex);+ auto& d = pi_backtest_op_.result;+ double win_rate = d.value("win_rate", 0.0);+ double avg_return = d.value("avg_return", 0.0);+ int occurrences = d.value("occurrences", 0);+ metric_card("Win Rate", win_rate * 100, "%.1f%%", win_rate > 0.5 ? MARKET_GREEN : WARNING);+ ImGui::SameLine();+ metric_card("Avg Return", avg_return * 100, "%.2f%%", avg_return > 0 ? MARKET_GREEN : MARKET_RED);+ ImGui::SameLine();+ char occ_buf[16];+ std::snprintf(occ_buf, sizeof(occ_buf), "%d", occurrences);+ metric_card("Occurrences", occ_buf, TEXT_PRIMARY);+ }++ if (!pi_search_op_.error.empty()) theme::ErrorMessage(pi_search_op_.error.c_str());+ if (!pi_score_op_.error.empty()) theme::ErrorMessage(pi_score_op_.error.c_str());+ if (!pi_backtest_op_.error.empty()) theme::ErrorMessage(pi_backtest_op_.error.c_str());+}++} // namespace fincept::ai_quant_labdiff --git a/fincept-cpp/src/screens/ai_quant_lab/aql_screen.cpp b/fincept-cpp/src/screens/ai_quant_lab/aql_screen.cppnew file mode 100644index 000000000..11a2bb333--- /dev/null+++ b/fincept-cpp/src/screens/ai_quant_lab/aql_screen.cpp@@ -0,0 +1,392 @@+#include "ai_quant_lab_screen.h"+#include "ui/theme.h"+#include "core/logger.h"+#include <imgui.h>+#include <implot.h>+#include <cstring>+#include <cstdio>+#include <cmath>+#include <algorithm>+#include <ctime>++namespace fincept::ai_quant_lab {+++// ============================================================================+// Module theme colors (per-panel accent)+// ============================================================================+namespace panel_colors {+ constexpr ImVec4 PURPLE = {0.55f, 0.26f, 0.87f, 1.0f}; // Factor Discovery, RL Trading+ constexpr ImVec4 BLUE = {0.18f, 0.53f, 0.96f, 1.0f}; // Model Library+ constexpr ImVec4 GREEN = {0.05f, 0.85f, 0.42f, 1.0f}; // Live Signals+ constexpr ImVec4 CYAN = {0.00f, 0.79f, 0.89f, 1.0f}; // Rolling Retraining+ constexpr ImVec4 RED = {0.96f, 0.25f, 0.25f, 1.0f}; // HFT+ constexpr ImVec4 MAGENTA = {0.87f, 0.26f, 0.55f, 1.0f}; // Meta Learning+ constexpr ImVec4 YELLOW = {1.0f, 0.78f, 0.08f, 1.0f}; // Online Learning+ constexpr ImVec4 TEAL = {0.00f, 0.79f, 0.65f, 1.0f}; // Statsmodels+ constexpr ImVec4 GLUON_BLUE = {0.00f, 0.63f, 0.89f, 1.0f}; // GluonTS+ constexpr ImVec4 GS_PURPLE = {0.44f, 0.26f, 0.76f, 1.0f}; // GS Quant+ constexpr ImVec4 ORANGE = {1.0f, 0.45f, 0.05f, 1.0f}; // Default / Accent+}++// ============================================================================+// Init+// ============================================================================+void AIQuantLabScreen::init() {+ if (initialized_) return;+ modules_ = get_modules();+ expanded_categories_ = {ModuleCategory::Core, ModuleCategory::AIML};+ initialized_ = true;+ log_status("AI Quant Lab initialized", theme::colors::SUCCESS);+ LOG_INFO("AIQuantLab", "Initialized with %zu modules", modules_.size());+}++void AIQuantLabScreen::log_status(const std::string& msg, ImVec4 color) {+ status_log_.push_back({ImGui::GetTime(), msg, color});+ if (status_log_.size() > 100) status_log_.erase(status_log_.begin());+}++// ============================================================================+// Main render+// ============================================================================+void AIQuantLabScreen::render() {+ init();+ using namespace theme::colors;++ ImGuiViewport* vp = ImGui::GetMainViewport();+ float tab_bar_h = ImGui::GetFrameHeight() + 4;+ float footer_h = ImGui::GetFrameHeight();++ float x = vp->WorkPos.x;+ float y = vp->WorkPos.y + tab_bar_h;+ float w = vp->WorkSize.x;+ float h = vp->WorkSize.y - tab_bar_h - footer_h;++ ImGui::SetNextWindowPos(ImVec2(x, y));+ ImGui::SetNextWindowSize(ImVec2(w, h));++ ImGui::PushStyleColor(ImGuiCol_WindowBg, BG_DARK);+ ImGui::PushStyleVar(ImGuiStyleVar_WindowPadding, ImVec2(0, 0));++ ImGui::Begin("##ai_quant_lab", nullptr,+ ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_NoResize |+ ImGuiWindowFlags_NoMove | ImGuiWindowFlags_NoScrollbar |+ ImGuiWindowFlags_NoDocking);++ float sidebar_w = left_panel_visible_ ? 220.0f : 0.0f;+ float status_w = right_panel_visible_ ? 260.0f : 0.0f;+ float content_w = w - sidebar_w - status_w - 4;++ // Left sidebar+ if (left_panel_visible_) {+ ImGui::BeginChild("##aql_sidebar", ImVec2(sidebar_w, h), true);+ render_sidebar(h);+ ImGui::EndChild();+ ImGui::SameLine();+ }++ // Center content+ ImGui::BeginChild("##aql_content", ImVec2(content_w, h), false);+ render_content(content_w, h);+ ImGui::EndChild();++ // Right status panel+ if (right_panel_visible_) {+ ImGui::SameLine();+ ImGui::BeginChild("##aql_status", ImVec2(status_w, h), true);+ render_status_panel(h);+ ImGui::EndChild();+ }++ ImGui::End();+ ImGui::PopStyleVar();+ ImGui::PopStyleColor();+}++// ============================================================================+// Sidebar — Module navigation grouped by category+// ============================================================================+void AIQuantLabScreen::render_sidebar(float /*height*/) {+ using namespace theme::colors;++ // Header+ ImGui::PushStyleColor(ImGuiCol_ChildBg, BG_DARKEST);+ ImGui::BeginChild("##aql_header", ImVec2(-1, 50), false);+ ImGui::SetCursorPos(ImVec2(12, 8));+ ImGui::TextColored(panel_colors::ORANGE, "AI QUANT LAB");+ ImGui::SetCursorPos(ImVec2(12, 28));+ ImGui::TextColored(TEXT_DIM, "18 MODULES | QUANT RESEARCH");+ ImGui::EndChild();+ ImGui::PopStyleColor();++ // Accent line+ ImVec2 p = ImGui::GetCursorScreenPos();+ ImGui::GetWindowDrawList()->AddRectFilled(p,+ ImVec2(p.x + ImGui::GetContentRegionAvail().x, p.y + 2),+ IM_COL32(255, 115, 13, 255));+ ImGui::Dummy(ImVec2(0, 4));++ // Toggle buttons+ ImGui::PushStyleVar(ImGuiStyleVar_FramePadding, ImVec2(6, 2));+ if (ImGui::SmallButton(right_panel_visible_ ? "Hide Status >>" : "<< Show Status")) {+ right_panel_visible_ = !right_panel_visible_;+ }+ ImGui::PopStyleVar();+ ImGui::Dummy(ImVec2(0, 4));++ // Category groups+ ModuleCategory categories[] = {+ ModuleCategory::Core, ModuleCategory::AIML,+ ModuleCategory::Advanced, ModuleCategory::Analytics+ };++ for (auto cat : categories) {+ bool expanded = expanded_categories_.count(cat) > 0;+ ImVec4 cat_color;+ switch (cat) {+ case ModuleCategory::Core: cat_color = panel_colors::BLUE; break;+ case ModuleCategory::AIML: cat_color = panel_colors::PURPLE; break;+ case ModuleCategory::Advanced: cat_color = panel_colors::RED; break;+ case ModuleCategory::Analytics: cat_color = panel_colors::TEAL; break;+ }++ char cat_label[64];+ std::snprintf(cat_label, sizeof(cat_label), "%s %s",+ expanded ? "v" : ">", category_label(cat));++ ImGui::PushStyleColor(ImGuiCol_Header, ImVec4(cat_color.x, cat_color.y, cat_color.z, 0.08f));+ ImGui::PushStyleColor(ImGuiCol_HeaderHovered, BG_HOVER);++ if (ImGui::Selectable(cat_label, false, ImGuiSelectableFlags_None, ImVec2(0, 22))) {+ if (expanded) expanded_categories_.erase(cat);+ else expanded_categories_.insert(cat);+ }+ ImGui::PopStyleColor(2);++ if (!expanded) continue;++ ImGui::Indent(12);+ for (auto& mod : modules_) {+ if (mod.category != cat) continue;+ bool is_active = (mod.view == active_view_);++ if (is_active) {+ ImGui::PushStyleColor(ImGuiCol_Header, ImVec4(cat_color.x, cat_color.y, cat_color.z, 0.15f));+ ImGui::PushStyleColor(ImGuiCol_Text, cat_color);+ } else {+ ImGui::PushStyleColor(ImGuiCol_Header, ImVec4(0, 0, 0, 0));+ ImGui::PushStyleColor(ImGuiCol_Text, TEXT_SECONDARY);+ }++ if (ImGui::Selectable(mod.label, is_active, ImGuiSelectableFlags_None, ImVec2(0, 20))) {+ active_view_ = mod.view;+ log_status(std::string("Switched to ") + mod.label, cat_color);+ }+ ImGui::PopStyleColor(2);++ if (ImGui::IsItemHovered()) {+ ImGui::SetTooltip("%s", mod.description);+ }+ }+ ImGui::Unindent(12);+ ImGui::Dummy(ImVec2(0, 2));+ }+}++// ============================================================================+// Content — dispatches to the active panel+// ============================================================================+void AIQuantLabScreen::render_content(float width, float height) {+ using namespace theme::colors;+ (void)width; (void)height;++ ImGui::PushStyleVar(ImGuiStyleVar_WindowPadding, ImVec2(12, 8));++ // Panel toggle for left sidebar+ ImGui::PushStyleVar(ImGuiStyleVar_FramePadding, ImVec2(4, 2));+ if (ImGui::SmallButton(left_panel_visible_ ? "<< Hide" : ">> Show")) {+ left_panel_visible_ = !left_panel_visible_;+ }+ ImGui::SameLine();++ // Current module title+ for (auto& mod : modules_) {+ if (mod.view == active_view_) {+ ImGui::TextColored(ACCENT, "%s", mod.label);+ ImGui::SameLine();+ ImGui::TextColored(TEXT_DIM, "- %s", mod.description);+ break;+ }+ }+ ImGui::PopStyleVar();+ ImGui::Separator();+ ImGui::Dummy(ImVec2(0, 4));++ // Dispatch to panel+ switch (active_view_) {+ case ViewMode::FactorDiscovery: render_factor_discovery(); break;+ case ViewMode::ModelLibrary: render_model_library(); break;+ case ViewMode::Backtesting: render_backtesting(); break;+ case ViewMode::LiveSignals: render_live_signals(); break;+ case ViewMode::Functime: render_functime(); break;+ case ViewMode::Fortitudo: render_fortitudo(); break;+ case ViewMode::Statsmodels: render_statsmodels(); break;+ case ViewMode::CFAQuant: render_cfa_quant(); break;+ case ViewMode::DeepAgent: render_deep_agent(); break;+ case ViewMode::RLTrading: render_rl_trading(); break;+ case ViewMode::OnlineLearning: render_online_learning(); break;+ case ViewMode::HFT: render_hft(); break;+ case ViewMode::MetaLearning: render_meta_learning(); break;+ case ViewMode::RollingRetraining: render_rolling_retraining(); break;+ case ViewMode::AdvancedModels: render_advanced_models(); break;+ case ViewMode::GluonTS: render_gluonts(); break;+ case ViewMode::GSQuant: render_gs_quant(); break;+ case ViewMode::PatternIntelligence: render_pattern_intelligence(); break;+ }++ ImGui::PopStyleVar();+}++// ============================================================================+// Status Panel (Right) — System status + activity log+// ============================================================================+void AIQuantLabScreen::render_status_panel(float /*height*/) {+ using namespace theme::colors;++ ImGui::PushStyleColor(ImGuiCol_ChildBg, BG_DARKEST);+ ImGui::BeginChild("##status_header", ImVec2(-1, 40), false);+ ImGui::SetCursorPos(ImVec2(8, 8));+ ImGui::TextColored(TEXT_DIM, "SYSTEM STATUS");+ ImGui::EndChild();+ ImGui::PopStyleColor();++ ImVec2 p = ImGui::GetCursorScreenPos();+ ImGui::GetWindowDrawList()->AddRectFilled(p,+ ImVec2(p.x + ImGui::GetContentRegionAvail().x, p.y + 1),+ IM_COL32(88, 88, 97, 255));+ ImGui::Dummy(ImVec2(0, 4));++ // Service status indicators+ theme::StatusIndicator("Qlib Engine", true);+ theme::StatusIndicator("RD-Agent", true);+ theme::StatusIndicator("Deep Agent", true);+ theme::StatusIndicator("Python Runtime", true);+ ImGui::Dummy(ImVec2(0, 8));++ // Active module+ ImGui::TextColored(TEXT_DIM, "Active Module:");+ for (auto& mod : modules_) {+ if (mod.view == active_view_) {+ ImGui::TextColored(ACCENT, " %s", mod.label);+ break;+ }+ }+ ImGui::Dummy(ImVec2(0, 8));++ // Activity log+ ImGui::TextColored(TEXT_DIM, "ACTIVITY LOG");+ ImGui::Separator();++ ImGui::BeginChild("##log_scroll", ImVec2(-1, -1), false);+ for (int i = (int)status_log_.size() - 1; i >= 0; i--) {+ auto& entry = status_log_[i];+ double age = ImGui::GetTime() - entry.time;+ char time_buf[16];+ if (age < 60) std::snprintf(time_buf, sizeof(time_buf), "%.0fs ago", age);+ else if (age < 3600) std::snprintf(time_buf, sizeof(time_buf), "%.0fm ago", age / 60);+ else std::snprintf(time_buf, sizeof(time_buf), "%.0fh ago", age / 3600);++ ImGui::TextColored(TEXT_DISABLED, "%s", time_buf);+ ImGui::SameLine();+ ImGui::TextColored(entry.color, "%s", entry.msg.c_str());+ }+ ImGui::EndChild();+}++// ============================================================================+// UI Helpers+// ============================================================================+void AIQuantLabScreen::metric_card(const char* label, const char* value, ImVec4 color) {+ using namespace theme::colors;+ ImGui::BeginGroup();+ ImGui::PushStyleColor(ImGuiCol_ChildBg, BG_WIDGET);+ ImGui::BeginChild(ImGui::GetID(label), ImVec2(140, 56), true);+ ImGui::TextColored(TEXT_DIM, "%s", label);+ ImGui::TextColored(color, "%s", value);+ ImGui::EndChild();+ ImGui::PopStyleColor();+ ImGui::EndGroup();+}++void AIQuantLabScreen::metric_card(const char* label, double value, const char* fmt, ImVec4 color) {+ char buf[64];+ std::snprintf(buf, sizeof(buf), fmt, value);+ metric_card(label, buf, color);+}++void AIQuantLabScreen::progress_bar(float fraction, const char* label) {+ using namespace theme::colors;+ ImGui::PushStyleColor(ImGuiCol_PlotHistogram, ACCENT);+ ImGui::PushStyleColor(ImGuiCol_FrameBg, BG_INPUT);+ if (label)+ ImGui::ProgressBar(fraction, ImVec2(-1, 18), label);+ else+ ImGui::ProgressBar(fraction, ImVec2(-1, 18));+ ImGui::PopStyleColor(2);+}++bool AIQuantLabScreen::config_input_text(const char* label, char* buf, int buf_size, float width) {+ ImGui::TextColored(theme::colors::TEXT_DIM, "%s", label);+ ImGui::SameLine(width);+ char id[128];+ std::snprintf(id, sizeof(id), "##%s", label);+ ImGui::SetNextItemWidth(ImGui::GetContentRegionAvail().x);+ return ImGui::InputText(id, buf, buf_size);+}++bool AIQuantLabScreen::config_input_float(const char* label, float* val, float width) {+ ImGui::TextColored(theme::colors::TEXT_DIM, "%s", label);+ ImGui::SameLine(width);+ char id[128];+ std::snprintf(id, sizeof(id), "##%s", label);+ ImGui::SetNextItemWidth(ImGui::GetContentRegionAvail().x);+ return ImGui::InputFloat(id, val, 0, 0, "%.4f");+}++bool AIQuantLabScreen::config_input_int(const char* label, int* val, float width) {+ ImGui::TextColored(theme::colors::TEXT_DIM, "%s", label);+ ImGui::SameLine(width);+ char id[128];+ std::snprintf(id, sizeof(id), "##%s", label);+ ImGui::SetNextItemWidth(ImGui::GetContentRegionAvail().x);+ return ImGui::InputInt(id, val);+}++bool AIQuantLabScreen::config_combo(const char* label, int* current, const char* const* items, int count, float width) {+ ImGui::TextColored(theme::colors::TEXT_DIM, "%s", label);+ ImGui::SameLine(width);+ char id[128];+ std::snprintf(id, sizeof(id), "##%s", label);+ ImGui::SetNextItemWidth(ImGui::GetContentRegionAvail().x);+ return ImGui::Combo(id, current, items, count);+}++void AIQuantLabScreen::section_header(const char* title, ImVec4 color) {+ ImGui::PushStyleColor(ImGuiCol_Text, color);+ ImGui::SeparatorText(title);+ ImGui::PopStyleColor();+}++void AIQuantLabScreen::status_badge(const char* text, ImVec4 bg_color, ImVec4 text_color) {+ ImVec2 p = ImGui::GetCursorScreenPos();+ ImVec2 sz = ImGui::CalcTextSize(text);+ ImGui::GetWindowDrawList()->AddRectFilled(p,+ ImVec2(p.x + sz.x + 12, p.y + sz.y + 6),+ ImGui::ColorConvertFloat4ToU32(bg_color), 3.0f);+ ImGui::SetCursorPosX(ImGui::GetCursorPosX() + 6);+ ImGui::TextColored(text_color, "%s", text);+ ImGui::Dummy(ImVec2(sz.x + 16, sz.y + 8));+}+++} // namespace fincept::ai_quant_labdiff --git a/fincept-cpp/src/screens/data_mapping/data_mapping_screen.cpp b/fincept-cpp/src/screens/data_mapping/data_mapping_screen.cppindex 714948ea4..6b7d42b80 100644--- a/fincept-cpp/src/screens/data_mapping/data_mapping_screen.cpp+++ b/fincept-cpp/src/screens/data_mapping/data_mapping_screen.cpp@@ -1,2035 +1,4 @@-// Data Mapping Screen — Fincept-themed API mapping configuration UI-// 2-panel layout with horizontal stepper, card-based sections, rich visual hierarchy-// Uses theme::colors exclusively — no custom BB_* palette--#include "data_mapping_screen.h"-#include "data_mapping_schemas.h"-#include "ui/theme.h"-#include "storage/database.h"-#include "core/logger.h"-#include <imgui.h>-#include <nlohmann/json.hpp>-#include <algorithm>-#include <cstring>-#include <chrono>-#include <cmath>--namespace fincept::data_mapping {--using json = nlohmann::json;-using namespace theme::colors;--// Step definitions-static constexpr CreateStep ALL_STEPS[] = {- CreateStep::api_config, CreateStep::schema_select,- CreateStep::field_mapping, CreateStep::cache_settings,- CreateStep::test_save-};-static constexpr int NUM_STEPS = 5;--// Method colors for badges-static ImVec4 method_color(HttpMethod m) {- switch (m) {- case HttpMethod::get: return SUCCESS;- case HttpMethod::post: return INFO;- case HttpMethod::put: return WARNING;- case HttpMethod::del: return ERROR_RED;- case HttpMethod::patch: return {0.70f, 0.50f, 0.90f, 1.0f};- }- return TEXT_DIM;-}--// Schema colors for badges-static ImVec4 schema_color(SchemaType t) {- switch (t) {- case SchemaType::ohlcv: return {0.30f, 0.70f, 1.00f, 1.0f};- case SchemaType::quote: return {0.40f, 0.85f, 0.55f, 1.0f};- case SchemaType::tick: return {0.90f, 0.60f, 0.20f, 1.0f};- case SchemaType::order: return {0.80f, 0.40f, 0.80f, 1.0f};- case SchemaType::position: return {0.50f, 0.80f, 0.90f, 1.0f};- case SchemaType::portfolio: return {0.90f, 0.75f, 0.30f, 1.0f};- case SchemaType::instrument: return {0.65f, 0.65f, 0.80f, 1.0f};- }- return TEXT_DIM;-}--// ============================================================================-// UI Helpers — reusable card/badge/label components-// ============================================================================--bool DataMappingScreen::card_begin(const char* id, const char* title, float w) {- ImGui::PushStyleColor(ImGuiCol_ChildBg, BG_WIDGET);- ImGui::PushStyleColor(ImGuiCol_Border, BORDER_DIM);- ImGui::PushStyleVar(ImGuiStyleVar_ChildRounding, 3.0f);- ImGui::PushStyleVar(ImGuiStyleVar_WindowPadding, {10, 8});-- const float card_w = (w > 0) ? w : ImGui::GetContentRegionAvail().x;- ImGui::BeginChild(id, {card_w, 0}, ImGuiChildFlags_AutoResizeY | ImGuiChildFlags_Borders);-- // Card title with accent underline- if (title && title[0] != '\0') {- ImGui::PushStyleColor(ImGuiCol_Text, ACCENT);- ImGui::Text("%s", title);- ImGui::PopStyleColor();-- // Orange accent line under title- const ImVec2 p = ImGui::GetCursorScreenPos();- ImGui::GetWindowDrawList()->AddLine(- {p.x, p.y}, {p.x + card_w - 20, p.y},- ImGui::ColorConvertFloat4ToU32({ACCENT.x, ACCENT.y, ACCENT.z, 0.4f}), 1.0f);- ImGui::Spacing();- }- return true;-}--void DataMappingScreen::card_end() {- ImGui::EndChild();- ImGui::PopStyleVar(2);- ImGui::PopStyleColor(2);- ImGui::Spacing();-}--void DataMappingScreen::method_badge(HttpMethod method) {- const ImVec4 col = method_color(method);- const char* label = http_method_label(method);-- ImGui::PushStyleColor(ImGuiCol_Button, {col.x, col.y, col.z, 0.20f});- ImGui::PushStyleColor(ImGuiCol_ButtonHovered, {col.x, col.y, col.z, 0.30f});- ImGui::PushStyleColor(ImGuiCol_Text, col);- ImGui::PushStyleVar(ImGuiStyleVar_FramePadding, {6, 2});- ImGui::PushStyleVar(ImGuiStyleVar_FrameRounding, 3.0f);- ImGui::SmallButton(label);- ImGui::PopStyleVar(2);- ImGui::PopStyleColor(3);-}--void DataMappingScreen::schema_badge(SchemaType type) {- const ImVec4 col = schema_color(type);- const char* label = schema_type_id(type);-- ImGui::PushStyleColor(ImGuiCol_Button, {col.x, col.y, col.z, 0.18f});- ImGui::PushStyleColor(ImGuiCol_ButtonHovered, {col.x, col.y, col.z, 0.28f});- ImGui::PushStyleColor(ImGuiCol_Text, col);- ImGui::PushStyleVar(ImGuiStyleVar_FramePadding, {8, 2});- ImGui::PushStyleVar(ImGuiStyleVar_FrameRounding, 10.0f);- ImGui::SmallButton(label);- ImGui::PopStyleVar(2);- ImGui::PopStyleColor(3);-}--void DataMappingScreen::tag_pill(const char* text, const ImVec4& color) {- ImGui::PushStyleColor(ImGuiCol_Button, {color.x, color.y, color.z, 0.12f});- ImGui::PushStyleColor(ImGuiCol_ButtonHovered, {color.x, color.y, color.z, 0.20f});- ImGui::PushStyleColor(ImGuiCol_Text, {color.x, color.y, color.z, 0.85f});- ImGui::PushStyleVar(ImGuiStyleVar_FramePadding, {5, 1});- ImGui::PushStyleVar(ImGuiStyleVar_FrameRounding, 8.0f);- ImGui::SmallButton(text);- ImGui::PopStyleVar(2);- ImGui::PopStyleColor(3);-}--void DataMappingScreen::inline_label(const char* label, float label_w) {- ImGui::PushStyleColor(ImGuiCol_Text, TEXT_SECONDARY);- ImGui::Text("%s", label);- ImGui::PopStyleColor();- ImGui::SameLine(label_w);-}--// ============================================================================-// Initialization-// ============================================================================--void DataMappingScreen::init() {- if (initialized_) return;- mapping_ops::initialize_tables();- load_mappings();- load_templates();- reset_create_form();- initialized_ = true;-}--// ============================================================================-// Main render — 2-panel layout-// ============================================================================--void DataMappingScreen::render() {- init();-- // Check async operations- if (testing_ && test_future_.valid() &&- test_future_.wait_for(std::chrono::milliseconds(0)) == std::future_status::ready) {- test_result_ = test_future_.get();- testing_ = false;- }- if (fetching_ && fetch_future_.valid() &&- fetch_future_.wait_for(std::chrono::milliseconds(0)) == std::future_status::ready) {- const auto response = fetch_future_.get();- fetching_ = false;- if (response.success) {- sample_data_json_ = response.data_json;- }- }-- const ImGuiViewport* vp = ImGui::GetMainViewport();- // Account for app chrome (menu bar + tab bar at top, app footer at bottom)- const float chrome_top = ImGui::GetFrameHeight() + 4.0f;- const float chrome_bot = ImGui::GetFrameHeight();- const float ox = vp->WorkPos.x;- const float oy = vp->WorkPos.y + chrome_top;- const float w = vp->WorkSize.x;- const float h = vp->WorkSize.y - chrome_top - chrome_bot;-- // Background- ImGui::GetWindowDrawList()->AddRectFilled(- {ox, oy}, {ox + w, oy + h},- ImGui::ColorConvertFloat4ToU32(BG_DARKEST));-- // Layout: command bar (top) | sidebar + content | footer- const float cmd_h = 32.0f;- const float footer_h = 24.0f;- const float sidebar_w = sidebar_minimized_ ? 36.0f : 220.0f;- const float content_x = ox + sidebar_w;- const float content_y = oy + cmd_h;- const float content_w = w - sidebar_w;- const float content_h = h - cmd_h - footer_h;-- render_command_bar(w);- render_sidebar(ox, content_y, sidebar_w, content_h);- render_content(content_x, content_y, content_w, content_h);- render_footer(w, footer_h);-}--// ============================================================================-// Command bar — top navigation with view tabs and search-// ============================================================================--void DataMappingScreen::render_command_bar(float w) {- const ImGuiViewport* vp = ImGui::GetMainViewport();- const float chrome_top = ImGui::GetFrameHeight() + 4.0f;- ImGui::SetNextWindowPos({vp->WorkPos.x, vp->WorkPos.y + chrome_top});- ImGui::SetNextWindowSize({w, 32.0f});- ImGui::PushStyleColor(ImGuiCol_WindowBg, BG_DARK);- ImGui::PushStyleVar(ImGuiStyleVar_WindowPadding, {12, 6});-- ImGui::Begin("##dm_cmdbar", nullptr,- ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_NoResize | ImGuiWindowFlags_NoMove |- ImGuiWindowFlags_NoScrollbar | ImGuiWindowFlags_NoDocking);-- // Title- ImGui::PushStyleColor(ImGuiCol_Text, ACCENT);- ImGui::Text("DATA MAPPING");- ImGui::PopStyleColor();-- // View tabs — styled like proper tab buttons- ImGui::SameLine(170);-- auto tab_button = [&](const char* label, MappingView target_view) {- const bool active = (view_ == target_view);- if (active) {- ImGui::PushStyleColor(ImGuiCol_Button, ACCENT_BG);- ImGui::PushStyleColor(ImGuiCol_Text, ACCENT);- } else {- ImGui::PushStyleColor(ImGuiCol_Button, {0, 0, 0, 0});- ImGui::PushStyleColor(ImGuiCol_Text, TEXT_SECONDARY);- }- ImGui::PushStyleVar(ImGuiStyleVar_FramePadding, {10, 3});- ImGui::PushStyleVar(ImGuiStyleVar_FrameRounding, 3.0f);- if (ImGui::Button(label)) {- view_ = target_view;- if (target_view == MappingView::list) load_mappings();- if (target_view == MappingView::create) reset_create_form();- }- ImGui::PopStyleVar(2);- ImGui::PopStyleColor(2);- ImGui::SameLine();- };-- tab_button("Mappings", MappingView::list);- tab_button("+ New", MappingView::create);- tab_button("Templates", MappingView::templates);-- // Search bar (right-aligned)- const float search_w = 220.0f;- ImGui::SameLine(w - search_w - 16);- ImGui::PushItemWidth(search_w);- ImGui::PushStyleColor(ImGuiCol_FrameBg, BG_INPUT);- ImGui::PushStyleVar(ImGuiStyleVar_FrameRounding, 3.0f);- ImGui::InputTextWithHint("##dm_search", "Search mappings...", search_buf_, sizeof(search_buf_));- ImGui::PopStyleVar();- ImGui::PopStyleColor();- ImGui::PopItemWidth();-- ImGui::End();- ImGui::PopStyleVar();- ImGui::PopStyleColor();-}--// ============================================================================-// Sidebar — context-sensitive: stats/filter in list, config summary in create-// ============================================================================--void DataMappingScreen::render_sidebar(float x, float y, float w, float h) {- ImGui::SetNextWindowPos({x, y});- ImGui::SetNextWindowSize({w, h});- ImGui::PushStyleColor(ImGuiCol_WindowBg, BG_PANEL);- ImGui::PushStyleVar(ImGuiStyleVar_WindowPadding, {8, 8});-- ImGui::Begin("##dm_sidebar", nullptr,- ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_NoResize | ImGuiWindowFlags_NoMove |- ImGuiWindowFlags_NoDocking);-- // Collapse toggle- if (sidebar_minimized_) {- if (ImGui::Button(">", {20, 20})) sidebar_minimized_ = false;- ImGui::End();- ImGui::PopStyleVar();- ImGui::PopStyleColor();- return;- }-- ImGui::PushStyleColor(ImGuiCol_Text, TEXT_DIM);- if (ImGui::Button("<", {20, 20})) sidebar_minimized_ = true;- ImGui::PopStyleColor();-- ImGui::Spacing();-- if (view_ == MappingView::create) {- // ---- Create mode: config summary ----- theme::SectionHeader("CONFIG SUMMARY");- ImGui::Spacing();-- // Live URL preview- if (api_base_url_buf_[0] != '\0') {- ImGui::PushStyleColor(ImGuiCol_Text, TEXT_DIM);- ImGui::Text("URL");- ImGui::PopStyleColor();- ImGui::PushStyleColor(ImGuiCol_Text, INFO);- ImGui::TextWrapped("%s%s", api_base_url_buf_, api_endpoint_buf_);- ImGui::PopStyleColor();- ImGui::Spacing();- }-- // Method badge- if (api_base_url_buf_[0] != '\0') {- ImGui::PushStyleColor(ImGuiCol_Text, TEXT_DIM);- ImGui::Text("Method");- ImGui::PopStyleColor();- ImGui::SameLine(70);- method_badge(static_cast<HttpMethod>(api_method_idx_));- ImGui::Spacing();- }-- // Schema badge- ImGui::PushStyleColor(ImGuiCol_Text, TEXT_DIM);- ImGui::Text("Schema");- ImGui::PopStyleColor();- ImGui::SameLine(70);- if (current_mapping_.is_predefined_schema) {- schema_badge(current_mapping_.schema_type);- } else {- ImGui::PushStyleColor(ImGuiCol_Text, TEXT_SECONDARY);- ImGui::Text("Custom");- ImGui::PopStyleColor();- }-- ImGui::Spacing();-- // Field count- ImGui::PushStyleColor(ImGuiCol_Text, TEXT_DIM);- ImGui::Text("Fields");- ImGui::PopStyleColor();- ImGui::SameLine(70);- ImGui::PushStyleColor(ImGuiCol_Text, TEXT_PRIMARY);- ImGui::Text("%d", static_cast<int>(current_mapping_.field_mappings.size()));- ImGui::PopStyleColor();-- // Sample data status- ImGui::Spacing();- if (!sample_data_json_.empty()) {- theme::StatusIndicator("Sample data loaded", true);- } else {- theme::StatusIndicator("No sample data", false);- }-- // Test status- if (test_result_) {- theme::StatusIndicator(- test_result_->success ? "Last test: PASSED" : "Last test: FAILED",- test_result_->success);- }-- ImGui::Spacing();- ImGui::Separator();- ImGui::Spacing();-- // Navigation buttons- const int step_idx = static_cast<int>(current_step_);- if (step_idx > 0) {- if (theme::SecondaryButton("< Back", {w - 20, 0})) {- current_step_ = ALL_STEPS[step_idx - 1];- }- ImGui::Spacing();- }- if (step_idx < NUM_STEPS - 1) {- if (theme::AccentButton("Next >", {w - 20, 0})) {- current_step_ = ALL_STEPS[step_idx + 1];- }- }-- } else {- // ---- List/Templates mode: overview + schema filter ----- theme::SectionHeader("OVERVIEW");- ImGui::Spacing();-- // Stats- ImGui::PushStyleColor(ImGuiCol_Text, TEXT_PRIMARY);- ImGui::Text("%d", static_cast<int>(saved_mappings_.size()));- ImGui::PopStyleColor();- ImGui::SameLine();- ImGui::PushStyleColor(ImGuiCol_Text, TEXT_DIM);- ImGui::Text("mappings saved");- ImGui::PopStyleColor();-- ImGui::PushStyleColor(ImGuiCol_Text, TEXT_PRIMARY);- ImGui::Text("%d", static_cast<int>(templates_.size()));- ImGui::PopStyleColor();- ImGui::SameLine();- ImGui::PushStyleColor(ImGuiCol_Text, TEXT_DIM);- ImGui::Text("templates available");- ImGui::PopStyleColor();-- ImGui::Spacing();- ImGui::Separator();- ImGui::Spacing();-- // Schema filter (clickable)- theme::SectionHeader("FILTER BY SCHEMA");- ImGui::Spacing();-- // "All" option- {- const bool selected = (filter_schema_idx_ == -1);- if (selected) ImGui::PushStyleColor(ImGuiCol_Text, ACCENT);- else ImGui::PushStyleColor(ImGuiCol_Text, TEXT_SECONDARY);-- if (ImGui::Selectable(" All", selected)) filter_schema_idx_ = -1;- ImGui::PopStyleColor();- }-- const auto schema_names = get_schema_type_names();- for (int i = 0; i < static_cast<int>(schema_names.size()); ++i) {- int count = 0;- for (const auto& m : saved_mappings_) {- if (m.is_predefined_schema &&- schema_type_id(m.schema_type) == schema_names[static_cast<size_t>(i)]) {- ++count;- }- }-- const bool selected = (filter_schema_idx_ == i);- if (selected) ImGui::PushStyleColor(ImGuiCol_Text, ACCENT);- else if (count > 0) ImGui::PushStyleColor(ImGuiCol_Text, TEXT_PRIMARY);- else ImGui::PushStyleColor(ImGuiCol_Text, TEXT_DISABLED);-- char label[64];- std::snprintf(label, sizeof(label), " %s (%d)", schema_names[static_cast<size_t>(i)].c_str(), count);- if (ImGui::Selectable(label, selected)) {- filter_schema_idx_ = selected ? -1 : i;- }- ImGui::PopStyleColor();- }-- ImGui::Spacing();- ImGui::Separator();- ImGui::Spacing();-- // Quick actions- if (theme::AccentButton("+ New Mapping", {w - 20, 0})) {- view_ = MappingView::create;- reset_create_form();- }- }-- ImGui::End();- ImGui::PopStyleVar();- ImGui::PopStyleColor();-}--// ============================================================================-// Main content area-// ============================================================================--void DataMappingScreen::render_content(float x, float y, float w, float h) {- ImGui::SetNextWindowPos({x, y});- ImGui::SetNextWindowSize({w, h});- ImGui::PushStyleColor(ImGuiCol_WindowBg, BG_DARKEST);- ImGui::PushStyleVar(ImGuiStyleVar_WindowPadding, {12, 10});-- ImGui::Begin("##dm_content", nullptr,- ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_NoResize | ImGuiWindowFlags_NoMove |- ImGuiWindowFlags_NoDocking);-- switch (view_) {- case MappingView::list: render_list_view(w, h); break;- case MappingView::create: render_create_view(w, h); break;- case MappingView::templates: render_templates_view(w, h); break;- }-- ImGui::End();- ImGui::PopStyleVar();- ImGui::PopStyleColor();-}--// ============================================================================-// List View — card-style rows with badges, method tags, inline actions-// ============================================================================--void DataMappingScreen::render_list_view(float w, float /*h*/) {- if (saved_mappings_.empty()) {- // Empty state- ImGui::Spacing();- ImGui::Spacing();- ImGui::PushStyleColor(ImGuiCol_Text, TEXT_DIM);- ImGui::SetCursorPosX((w - 300) * 0.5f);- ImGui::Text("No mappings configured yet.");- ImGui::PopStyleColor();- ImGui::Spacing();- ImGui::SetCursorPosX((w - 160) * 0.5f);- if (theme::AccentButton("Create First Mapping")) {- view_ = MappingView::create;- reset_create_form();- }- return;- }-- const std::string filter(search_buf_);- const auto schema_names = get_schema_type_names();-- // Count visible items for header- int visible_count = 0;-- for (size_t i = 0; i < saved_mappings_.size(); ++i) {- const auto& m = saved_mappings_[i];-- // Search filter- if (!filter.empty()) {- std::string name_lower = m.name;- std::transform(name_lower.begin(), name_lower.end(), name_lower.begin(),- [](unsigned char c) { return std::tolower(c); });- std::string filter_lower = filter;- std::transform(filter_lower.begin(), filter_lower.end(),- filter_lower.begin(), [](unsigned char c) { return std::tolower(c); });- if (name_lower.find(filter_lower) == std::string::npos) continue;- }-- // Schema filter- if (filter_schema_idx_ >= 0 && m.is_predefined_schema) {- if (schema_type_id(m.schema_type) !=- schema_names[static_cast<size_t>(filter_schema_idx_)]) continue;- }-- visible_count++;-- // Card for each mapping- ImGui::PushID(static_cast<int>(i));-- ImGui::PushStyleColor(ImGuiCol_ChildBg, BG_PANEL);- ImGui::PushStyleColor(ImGuiCol_Border, BORDER_DIM);- ImGui::PushStyleVar(ImGuiStyleVar_ChildRounding, 3.0f);- ImGui::PushStyleVar(ImGuiStyleVar_WindowPadding, {10, 8});- ImGui::BeginChild("##map_card", {0, 0}, ImGuiChildFlags_AutoResizeY | ImGuiChildFlags_Borders);-- // Row 1: Name + Schema badge + Method badge- ImGui::PushStyleColor(ImGuiCol_Text, TEXT_PRIMARY);- ImGui::Text("%s", m.name.c_str());- ImGui::PopStyleColor();-- ImGui::SameLine(w * 0.35f);- if (m.is_predefined_schema) {- schema_badge(m.schema_type);- } else {- tag_pill("Custom", TEXT_DIM);- }-- ImGui::SameLine(w * 0.48f);- method_badge(m.api_config.method);-- // Field count- ImGui::SameLine(w * 0.58f);- ImGui::PushStyleColor(ImGuiCol_Text, TEXT_DIM);- ImGui::Text("%d fields", static_cast<int>(m.field_mappings.size()));- ImGui::PopStyleColor();-- // Actions (right-aligned)- ImGui::SameLine(w * 0.72f);- if (theme::SecondaryButton("Edit")) {- edit_mapping(m);- }- ImGui::SameLine();- if (theme::SecondaryButton("Dup")) {- mapping_ops::duplicate_mapping(m.id);- load_mappings();- }- ImGui::SameLine();- ImGui::PushStyleColor(ImGuiCol_Button, {ERROR_RED.x, ERROR_RED.y, ERROR_RED.z, 0.15f});- ImGui::PushStyleColor(ImGuiCol_ButtonHovered, {ERROR_RED.x, ERROR_RED.y, ERROR_RED.z, 0.30f});- ImGui::PushStyleColor(ImGuiCol_Text, ERROR_RED);- if (ImGui::Button("Del")) {- pending_delete_id_ = m.id;- }- ImGui::PopStyleColor(3);-- // Row 2: Endpoint + Updated date- ImGui::PushStyleColor(ImGuiCol_Text, TEXT_DIM);- const std::string endpoint_display =- m.api_config.base_url.substr(0, std::min<size_t>(40, m.api_config.base_url.size())) +- m.api_config.endpoint;- ImGui::Text("%s", endpoint_display.c_str());- ImGui::PopStyleColor();-- if (!m.updated_at.empty()) {- ImGui::SameLine(w * 0.72f);- ImGui::PushStyleColor(ImGuiCol_Text, TEXT_DISABLED);- ImGui::Text("Updated %s", m.updated_at.substr(0, 10).c_str());- ImGui::PopStyleColor();- }-- ImGui::EndChild();- ImGui::PopStyleVar(2);- ImGui::PopStyleColor(2);-- ImGui::PopID();- }-- if (visible_count == 0) {- ImGui::Spacing();- ImGui::PushStyleColor(ImGuiCol_Text, TEXT_DIM);- ImGui::Text("No mappings match the current filter.");- ImGui::PopStyleColor();- }-- // Delete confirmation popup- if (!pending_delete_id_.empty()) {- ImGui::OpenPopup("Confirm Delete");- }- if (ImGui::BeginPopupModal("Confirm Delete", nullptr, ImGuiWindowFlags_AlwaysAutoResize)) {- ImGui::PushStyleColor(ImGuiCol_Text, TEXT_PRIMARY);- ImGui::Text("Delete this mapping permanently?");- ImGui::PopStyleColor();- ImGui::Spacing();-- if (theme::AccentButton("Delete")) {- delete_mapping_by_id(pending_delete_id_);- pending_delete_id_.clear();- ImGui::CloseCurrentPopup();- }- ImGui::SameLine();- if (theme::SecondaryButton("Cancel")) {- pending_delete_id_.clear();- ImGui::CloseCurrentPopup();- }- ImGui::EndPopup();- }-}--// ============================================================================-// Create View — horizontal stepper + step content-// ============================================================================--void DataMappingScreen::render_create_view(float w, float h) {- // Horizontal step progress bar- render_step_progress_bar(w);-- ImGui::Spacing();- ImGui::Separator();- ImGui::Spacing();-- // Step content- switch (current_step_) {- case CreateStep::api_config: render_step_api_config(w, h); break;- case CreateStep::schema_select: render_step_schema_select(w, h); break;- case CreateStep::field_mapping: render_step_field_mapping(w, h); break;- case CreateStep::cache_settings: render_step_cache_settings(w, h); break;- case CreateStep::test_save: render_step_test_save(w, h); break;- }-}--// ============================================================================-// Horizontal step progress bar — circles connected by lines-// ============================================================================--void DataMappingScreen::render_step_progress_bar(float w) {- const float step_area_w = w - 40;- const float step_spacing = step_area_w / (NUM_STEPS);- const float circle_r = 12.0f;- const float start_x = ImGui::GetCursorScreenPos().x + 20;- const float center_y = ImGui::GetCursorScreenPos().y + circle_r + 2;-- ImDrawList* dl = ImGui::GetWindowDrawList();-- for (int i = 0; i < NUM_STEPS; ++i) {- const float cx = start_x + step_spacing * i + step_spacing * 0.5f;- const bool is_current = (ALL_STEPS[i] == current_step_);- const bool is_past = (i < static_cast<int>(current_step_));- const bool is_future = (i > static_cast<int>(current_step_));-- // Connecting line to next step- if (i < NUM_STEPS - 1) {- const float nx = start_x + step_spacing * (i + 1) + step_spacing * 0.5f;- const ImU32 line_col = is_past- ? ImGui::ColorConvertFloat4ToU32(SUCCESS)- : ImGui::ColorConvertFloat4ToU32(BORDER_DIM);- dl->AddLine({cx + circle_r + 4, center_y}, {nx - circle_r - 4, center_y}, line_col, 2.0f);- }-- // Circle- if (is_current) {- // Active: filled orange with glow- dl->AddCircleFilled({cx, center_y}, circle_r + 2,- ImGui::ColorConvertFloat4ToU32({ACCENT.x, ACCENT.y, ACCENT.z, 0.2f}));- dl->AddCircleFilled({cx, center_y}, circle_r,- ImGui::ColorConvertFloat4ToU32(ACCENT));- dl->AddCircle({cx, center_y}, circle_r,- ImGui::ColorConvertFloat4ToU32({1, 1, 1, 0.3f}), 0, 2.0f);- } else if (is_past) {- // Completed: green filled with checkmark- dl->AddCircleFilled({cx, center_y}, circle_r,- ImGui::ColorConvertFloat4ToU32(SUCCESS));- // Checkmark- dl->AddLine({cx - 4, center_y}, {cx - 1, center_y + 3},- ImGui::ColorConvertFloat4ToU32({1, 1, 1, 1}), 2.0f);- dl->AddLine({cx - 1, center_y + 3}, {cx + 5, center_y - 4},- ImGui::ColorConvertFloat4ToU32({1, 1, 1, 1}), 2.0f);- } else {- // Future: dim border only- dl->AddCircle({cx, center_y}, circle_r,- ImGui::ColorConvertFloat4ToU32(BORDER), 0, 2.0f);- }-- // Step number in circle- if (is_current || is_future) {- char num[4];- std::snprintf(num, sizeof(num), "%d", i + 1);- const ImVec2 text_size = ImGui::CalcTextSize(num);- const ImU32 text_col = is_current- ? ImGui::ColorConvertFloat4ToU32({1, 1, 1, 1})- : ImGui::ColorConvertFloat4ToU32(TEXT_DISABLED);- dl->AddText({cx - text_size.x * 0.5f, center_y - text_size.y * 0.5f}, text_col, num);- }-- // Label below circle (clickable)- const char* step_label = create_step_label(ALL_STEPS[i]);- const ImVec2 label_size = ImGui::CalcTextSize(step_label);- const float label_x = cx - label_size.x * 0.5f;- const float label_y = center_y + circle_r + 6;-- ImU32 label_col;- if (is_current) label_col = ImGui::ColorConvertFloat4ToU32(ACCENT);- else if (is_past) label_col = ImGui::ColorConvertFloat4ToU32(TEXT_SECONDARY);- else label_col = ImGui::ColorConvertFloat4ToU32(TEXT_DISABLED);-- dl->AddText({label_x, label_y}, label_col, step_label);-- // Invisible button for clicking- ImGui::SetCursorScreenPos({cx - circle_r - 4, center_y - circle_r - 4});- ImGui::PushID(i);- if (ImGui::InvisibleButton("##step", {circle_r * 2 + 8, circle_r * 2 + label_size.y + 14})) {- current_step_ = ALL_STEPS[i];- }- ImGui::PopID();- }-- // Reserve vertical space for the stepper- ImGui::SetCursorScreenPos({ImGui::GetCursorScreenPos().x,- center_y + circle_r + 26});- ImGui::Dummy({0, 0});-}--// ============================================================================-// Step 1: API Configuration — grouped into cards-// ============================================================================--void DataMappingScreen::render_step_api_config(float w, float /*h*/) {- const float input_w = std::min(w * 0.55f, 500.0f);- const float label_w = 90.0f;-- // === Connection Card ===- card_begin("##card_conn", "API CONNECTION");-- inline_label("Name", label_w);- ImGui::PushItemWidth(input_w);- ImGui::InputText("##api_name", api_name_buf_, sizeof(api_name_buf_));- ImGui::PopItemWidth();-- inline_label("Description", label_w);- ImGui::PushItemWidth(input_w);- ImGui::InputText("##api_desc", api_desc_buf_, sizeof(api_desc_buf_));- ImGui::PopItemWidth();-- ImGui::Spacing();-- // Method + URL on same visual row- static const char* methods[] = {"GET", "POST", "PUT", "DELETE", "PATCH"};- inline_label("Method", label_w);- ImGui::PushItemWidth(90);- ImGui::Combo("##method", &api_method_idx_, methods, 5);- ImGui::PopItemWidth();-- inline_label("Base URL", label_w);- ImGui::PushItemWidth(input_w);- ImGui::InputTextWithHint("##base_url", "https://api.example.com/v1", api_base_url_buf_, sizeof(api_base_url_buf_));- ImGui::PopItemWidth();-- inline_label("Endpoint", label_w);- ImGui::PushItemWidth(input_w);- ImGui::InputTextWithHint("##endpoint", "/ticker/{symbol}/candles", api_endpoint_buf_, sizeof(api_endpoint_buf_));- ImGui::PopItemWidth();-- ImGui::PushStyleColor(ImGuiCol_Text, TEXT_DISABLED);- ImGui::Text(" Use {placeholders} for runtime parameters");- ImGui::PopStyleColor();-- // Body for POST/PUT/PATCH- if (api_method_idx_ >= 1 && api_method_idx_ <= 4) {- ImGui::Spacing();- inline_label("Body", label_w);- ImGui::InputTextMultiline("##body", api_body_buf_, sizeof(api_body_buf_),- {input_w, 80});- }-- // Fetch button- ImGui::Spacing();- if (fetching_) {- theme::LoadingSpinner("Fetching sample data...");- } else {- if (theme::AccentButton("Fetch Sample Data")) {- fetch_sample_data();- }- if (!sample_data_json_.empty()) {- ImGui::SameLine();- ImGui::PushStyleColor(ImGuiCol_Text, SUCCESS);- ImGui::Text("Sample data loaded (%d bytes)",- static_cast<int>(sample_data_json_.size()));- ImGui::PopStyleColor();- }- }-- card_end();-- // === Authentication Card ===- render_auth_config(w);-- // === Headers Card ===- render_headers_editor(w);-- // === Query Params Card ===- render_query_params_editor(w);-}--// ============================================================================-// Auth config card-// ============================================================================--void DataMappingScreen::render_auth_config(float w) {- card_begin("##card_auth", "AUTHENTICATION");-- const float input_w = std::min(w * 0.45f, 400.0f);- const float label_w = 90.0f;- static const char* auth_types[] = {"None", "API Key", "Bearer Token", "Basic Auth", "OAuth2"};-- inline_label("Type", label_w);- ImGui::PushItemWidth(160);- ImGui::Combo("##auth_type", &api_auth_type_idx_, auth_types, 5);- ImGui::PopItemWidth();-- switch (api_auth_type_idx_) {- case 1: { // API Key- static const char* locations[] = {"Header", "Query Param"};- ImGui::Spacing();- inline_label("Location", label_w);- ImGui::PushItemWidth(130);- ImGui::Combo("##key_loc", &auth_key_location_idx_, locations, 2);- ImGui::PopItemWidth();-- inline_label("Key Name", label_w);- ImGui::PushItemWidth(input_w * 0.6f);- ImGui::InputTextWithHint("##key_name", "X-API-Key", auth_key_name_buf_, sizeof(auth_key_name_buf_));- ImGui::PopItemWidth();-- inline_label("Value", label_w);- ImGui::PushItemWidth(input_w);- ImGui::InputText("##key_val", auth_key_value_buf_, sizeof(auth_key_value_buf_),- ImGuiInputTextFlags_Password);- ImGui::PopItemWidth();- break;- }- case 2: { // Bearer- ImGui::Spacing();- inline_label("Token", label_w);- ImGui::PushItemWidth(input_w);- ImGui::InputText("##bearer", auth_bearer_buf_, sizeof(auth_bearer_buf_),- ImGuiInputTextFlags_Password);- ImGui::PopItemWidth();- break;- }- case 3: { // Basic- ImGui::Spacing();- inline_label("Username", label_w);- ImGui::PushItemWidth(input_w * 0.6f);- ImGui::InputText("##basic_user", auth_basic_user_buf_, sizeof(auth_basic_user_buf_));- ImGui::PopItemWidth();-- inline_label("Password", label_w);- ImGui::PushItemWidth(input_w * 0.6f);- ImGui::InputText("##basic_pass", auth_basic_pass_buf_, sizeof(auth_basic_pass_buf_),- ImGuiInputTextFlags_Password);- ImGui::PopItemWidth();- break;- }- default: break;- }-- card_end();-}--// ============================================================================-// Headers editor card-// ============================================================================--void DataMappingScreen::render_headers_editor(float /*w*/) {- card_begin("##card_headers", "CUSTOM HEADERS");-- auto& hdrs = current_mapping_.api_config.headers;- std::string to_remove;-- // Existing headers as mini-rows- for (const auto& [k, v] : hdrs) {- ImGui::PushStyleColor(ImGuiCol_Text, TEXT_PRIMARY);- ImGui::Text("%s", k.c_str());- ImGui::PopStyleColor();- ImGui::SameLine(150);- ImGui::PushStyleColor(ImGuiCol_Text, TEXT_DIM);- ImGui::Text("%s", v.c_str());- ImGui::PopStyleColor();- ImGui::SameLine(ImGui::GetContentRegionAvail().x + ImGui::GetCursorPosX() - 20);- ImGui::PushID(k.c_str());- ImGui::PushStyleColor(ImGuiCol_Text, ERROR_RED);- if (ImGui::SmallButton("x")) to_remove = k;- ImGui::PopStyleColor();- ImGui::PopID();- }- if (!to_remove.empty()) hdrs.erase(to_remove);-- // Add new- ImGui::Spacing();- ImGui::PushItemWidth(130);- ImGui::InputTextWithHint("##hdr_key", "Key", header_key_buf_, sizeof(header_key_buf_));- ImGui::PopItemWidth();- ImGui::SameLine();- ImGui::PushItemWidth(200);- ImGui::InputTextWithHint("##hdr_val", "Value", header_val_buf_, sizeof(header_val_buf_));- ImGui::PopItemWidth();- ImGui::SameLine();- if (theme::SecondaryButton("+ Add")) {- if (std::strlen(header_key_buf_) > 0) {- hdrs[header_key_buf_] = header_val_buf_;- header_key_buf_[0] = '\0';- header_val_buf_[0] = '\0';- }- }-- card_end();-}--// ============================================================================-// Query params editor card-// ============================================================================--void DataMappingScreen::render_query_params_editor(float /*w*/) {- card_begin("##card_qparams", "QUERY PARAMETERS");-- auto& qparams = current_mapping_.api_config.query_params;- std::string to_remove;-- for (const auto& [k, v] : qparams) {- ImGui::PushStyleColor(ImGuiCol_Text, TEXT_PRIMARY);- ImGui::Text("%s", k.c_str());- ImGui::PopStyleColor();- ImGui::SameLine(150);- ImGui::PushStyleColor(ImGuiCol_Text, TEXT_DIM);- ImGui::Text("%s", v.c_str());- ImGui::PopStyleColor();- ImGui::SameLine(ImGui::GetContentRegionAvail().x + ImGui::GetCursorPosX() - 20);- ImGui::PushID(("qp_" + k).c_str());- ImGui::PushStyleColor(ImGuiCol_Text, ERROR_RED);- if (ImGui::SmallButton("x")) to_remove = k;- ImGui::PopStyleColor();- ImGui::PopID();- }- if (!to_remove.empty()) qparams.erase(to_remove);-- ImGui::Spacing();- ImGui::PushItemWidth(130);- ImGui::InputTextWithHint("##qp_key", "Key", qparam_key_buf_, sizeof(qparam_key_buf_));- ImGui::PopItemWidth();- ImGui::SameLine();- ImGui::PushItemWidth(200);- ImGui::InputTextWithHint("##qp_val", "Value", qparam_val_buf_, sizeof(qparam_val_buf_));- ImGui::PopItemWidth();- ImGui::SameLine();- if (theme::SecondaryButton("+ Add")) {- if (std::strlen(qparam_key_buf_) > 0) {- qparams[qparam_key_buf_] = qparam_val_buf_;- qparam_key_buf_[0] = '\0';- qparam_val_buf_[0] = '\0';- }- }-- card_end();-}--// ============================================================================-// Step 2: Schema Selection-// ============================================================================--void DataMappingScreen::render_step_schema_select(float w, float /*h*/) {- const float input_w = std::min(w * 0.55f, 500.0f);- const float label_w = 100.0f;-- // === Schema Card ===- card_begin("##card_schema", "TARGET SCHEMA");-- ImGui::Checkbox("Use predefined schema", ¤t_mapping_.is_predefined_schema);- is_custom_schema_ = !current_mapping_.is_predefined_schema;-- ImGui::Spacing();-- if (current_mapping_.is_predefined_schema) {- static const char* schema_items[] = {"OHLCV", "QUOTE", "TICK", "ORDER", "POSITION", "PORTFOLIO", "INSTRUMENT"};- inline_label("Schema", label_w);- ImGui::PushItemWidth(200);- if (ImGui::Combo("##schema_type", &schema_type_idx_, schema_items, 7)) {- current_mapping_.schema_type = static_cast<SchemaType>(schema_type_idx_);- }- ImGui::PopItemWidth();- ImGui::SameLine();- schema_badge(current_mapping_.schema_type);-- // Schema fields table- const auto* schema = get_schema_for_type(current_mapping_.schema_type);- if (schema) {- ImGui::Spacing();- ImGui::PushStyleColor(ImGuiCol_Text, TEXT_SECONDARY);- ImGui::Text("%s — %s", schema->name.c_str(), schema->description.c_str());- ImGui::PopStyleColor();- ImGui::Spacing();-- if (ImGui::BeginTable("##schema_fields", 4,- ImGuiTableFlags_RowBg | ImGuiTableFlags_Borders |- ImGuiTableFlags_Resizable | ImGuiTableFlags_ScrollY,- {0, std::min(250.0f, schema->fields.size() * 26.0f + 30.0f)})) {-- ImGui::TableSetupColumn("Field", ImGuiTableColumnFlags_None, input_w * 0.28f);- ImGui::TableSetupColumn("Type", ImGuiTableColumnFlags_None, input_w * 0.14f);- ImGui::TableSetupColumn("Required", ImGuiTableColumnFlags_None, input_w * 0.12f);- ImGui::TableSetupColumn("Description", ImGuiTableColumnFlags_None, input_w * 0.46f);- ImGui::PushStyleColor(ImGuiCol_TableHeaderBg, BG_WIDGET);- ImGui::TableHeadersRow();- ImGui::PopStyleColor();-- for (const auto& f : schema->fields) {- ImGui::TableNextRow();-- ImGui::TableNextColumn();- ImGui::PushStyleColor(ImGuiCol_Text, TEXT_PRIMARY);- ImGui::Text("%s", f.name.c_str());- ImGui::PopStyleColor();-- ImGui::TableNextColumn();- ImGui::PushStyleColor(ImGuiCol_Text, INFO);- ImGui::Text("%s", field_type_label(f.type));- ImGui::PopStyleColor();-- ImGui::TableNextColumn();- if (f.required) {- ImGui::PushStyleColor(ImGuiCol_Text, ACCENT);- ImGui::Text("YES");- } else {- ImGui::PushStyleColor(ImGuiCol_Text, TEXT_DISABLED);- ImGui::Text("no");- }- ImGui::PopStyleColor();-- ImGui::TableNextColumn();- ImGui::PushStyleColor(ImGuiCol_Text, TEXT_DIM);- ImGui::Text("%s", f.description.c_str());- ImGui::PopStyleColor();- }- ImGui::EndTable();- }- }- } else {- ImGui::PushStyleColor(ImGuiCol_Text, TEXT_DIM);- ImGui::Text("Custom schema fields are configured in the Field Mapping step.");- ImGui::PopStyleColor();- }-- card_end();-- // === Extraction Card ===- card_begin("##card_extract", "DATA EXTRACTION");-- inline_label("Root Path", label_w);- ImGui::PushItemWidth(300);- ImGui::InputTextWithHint("##root_path", "e.g. data.candles or results",- root_path_buf_, sizeof(root_path_buf_));- ImGui::PopItemWidth();-- ImGui::PushStyleColor(ImGuiCol_Text, TEXT_DISABLED);- ImGui::Text(" JSON path to the data array in the API response");- ImGui::PopStyleColor();-- ImGui::Spacing();- ImGui::Checkbox("Source data is an array", ¤t_mapping_.extraction.is_array);- ImGui::SameLine(0, 20);- ImGui::Checkbox("Array of arrays", ¤t_mapping_.extraction.is_array_of_arrays);-- card_end();-}--// ============================================================================-// Step 3: Field Mapping-// ============================================================================--void DataMappingScreen::render_step_field_mapping(float w, float /*h*/) {- // Auto-populate from schema if empty- if (current_mapping_.field_mappings.empty() && current_mapping_.is_predefined_schema) {- const auto* schema = get_schema_for_type(current_mapping_.schema_type);- if (schema) {- for (const auto& f : schema->fields) {- FieldMapping fm;- fm.target_field = f.name;- fm.source_path = f.name;- fm.required = f.required;- current_mapping_.field_mappings.push_back(fm);- }- }- }-- card_begin("##card_fieldmap", "FIELD MAPPINGS");-- // Header row with add button- ImGui::PushStyleColor(ImGuiCol_Text, TEXT_SECONDARY);- ImGui::Text("Map source data fields to target schema fields.");- ImGui::PopStyleColor();- ImGui::SameLine(ImGui::GetContentRegionAvail().x + ImGui::GetCursorPosX() - 140);- if (theme::AccentButton("+ Add Field")) {- current_mapping_.field_mappings.push_back({});- }-- ImGui::Spacing();-- // Field mapping table- if (!current_mapping_.field_mappings.empty() &&- ImGui::BeginTable("##field_map_table", 6,- ImGuiTableFlags_RowBg | ImGuiTableFlags_Borders |- ImGuiTableFlags_Resizable | ImGuiTableFlags_ScrollY,- {0, std::min(400.0f, current_mapping_.field_mappings.size() * 30.0f + 35.0f)})) {-- ImGui::TableSetupColumn("Target Field", ImGuiTableColumnFlags_None, w * 0.18f);- ImGui::TableSetupColumn("Source Path", ImGuiTableColumnFlags_None, w * 0.22f);- ImGui::TableSetupColumn("Parser", ImGuiTableColumnFlags_None, w * 0.10f);- ImGui::TableSetupColumn("Transform", ImGuiTableColumnFlags_None, w * 0.18f);- ImGui::TableSetupColumn("Req", ImGuiTableColumnFlags_None, w * 0.06f);- ImGui::TableSetupColumn("", ImGuiTableColumnFlags_NoResize, 30.0f);- ImGui::PushStyleColor(ImGuiCol_TableHeaderBg, BG_WIDGET);- ImGui::TableHeadersRow();- ImGui::PopStyleColor();-- int to_delete = -1;- for (size_t i = 0; i < current_mapping_.field_mappings.size(); ++i) {- auto& fm = current_mapping_.field_mappings[i];- ImGui::PushID(static_cast<int>(i));- ImGui::TableNextRow();-- // Target field- ImGui::TableNextColumn();- char target_buf[64] = {};- std::strncpy(target_buf, fm.target_field.c_str(), sizeof(target_buf) - 1);- ImGui::PushItemWidth(-1);- if (ImGui::InputText("##target", target_buf, sizeof(target_buf))) {- fm.target_field = target_buf;- }- ImGui::PopItemWidth();-- // Source path- ImGui::TableNextColumn();- char source_buf[128] = {};- std::strncpy(source_buf, fm.source_path.c_str(), sizeof(source_buf) - 1);- ImGui::PushItemWidth(-1);- if (ImGui::InputText("##source", source_buf, sizeof(source_buf))) {- fm.source_path = source_buf;- }- ImGui::PopItemWidth();-- // Parser- ImGui::TableNextColumn();- static const char* parsers[] = {"Direct", "JSONPath", "Regex"};- int parser_idx = static_cast<int>(fm.parser);- ImGui::PushItemWidth(-1);- if (ImGui::Combo("##parser", &parser_idx, parsers, 3)) {- fm.parser = static_cast<ParserEngine>(parser_idx);- }- ImGui::PopItemWidth();-- // Transform- ImGui::TableNextColumn();- ImGui::PushItemWidth(-1);- char xform_buf[64] = {};- if (!fm.transforms.empty()) {- std::strncpy(xform_buf, fm.transforms[0].c_str(), sizeof(xform_buf) - 1);- }- if (ImGui::InputTextWithHint("##xform", "e.g. toNumber", xform_buf, sizeof(xform_buf))) {- if (std::strlen(xform_buf) > 0) {- if (fm.transforms.empty()) fm.transforms.push_back(xform_buf);- else fm.transforms[0] = xform_buf;- } else {- fm.transforms.clear();- }- }- ImGui::PopItemWidth();-- // Required checkbox- ImGui::TableNextColumn();- ImGui::Checkbox("##req", &fm.required);-- // Delete button- ImGui::TableNextColumn();- ImGui::PushStyleColor(ImGuiCol_Text, ERROR_RED);- if (ImGui::SmallButton("X")) to_delete = static_cast<int>(i);- ImGui::PopStyleColor();-- ImGui::PopID();- }-- if (to_delete >= 0) {- current_mapping_.field_mappings.erase(- current_mapping_.field_mappings.begin() + to_delete);- }-- ImGui::EndTable();- }-- // Available transforms reference- ImGui::Spacing();- if (ImGui::TreeNodeEx("Available Transforms", ImGuiTreeNodeFlags_None)) {- const auto transforms = TransformRegistry::all_transforms();- if (ImGui::BeginTable("##transforms_ref", 3, ImGuiTableFlags_RowBg | ImGuiTableFlags_Borders)) {- ImGui::TableSetupColumn("Name", ImGuiTableColumnFlags_None, 140);- ImGui::TableSetupColumn("Description", ImGuiTableColumnFlags_None, 280);- ImGui::TableSetupColumn("Category", ImGuiTableColumnFlags_None, 80);- ImGui::PushStyleColor(ImGuiCol_TableHeaderBg, BG_WIDGET);- ImGui::TableHeadersRow();- ImGui::PopStyleColor();-- for (const auto& t : transforms) {- ImGui::TableNextRow();- ImGui::TableNextColumn();- ImGui::PushStyleColor(ImGuiCol_Text, ACCENT);- ImGui::Text("%s", t.name);- ImGui::PopStyleColor();- ImGui::TableNextColumn();- ImGui::PushStyleColor(ImGuiCol_Text, TEXT_DIM);- ImGui::Text("%s", t.description);- ImGui::PopStyleColor();- ImGui::TableNextColumn();- tag_pill(transform_category_label(t.category), TEXT_SECONDARY);- }- ImGui::EndTable();- }- ImGui::TreePop();- }-- card_end();-}--// ============================================================================-// Step 4: Cache & Validation Settings-// ============================================================================--void DataMappingScreen::render_step_cache_settings(float /*w*/, float /*h*/) {- // === Cache Card ===- card_begin("##card_cache", "RESPONSE CACHING");-- ImGui::Checkbox("Enable caching", ¤t_mapping_.api_config.cache_enabled);-- if (current_mapping_.api_config.cache_enabled) {- ImGui::Spacing();- inline_label("TTL (seconds)", 110);- ImGui::PushItemWidth(100);- ImGui::InputInt("##cache_ttl", ¤t_mapping_.api_config.cache_ttl_seconds);- ImGui::PopItemWidth();-- if (current_mapping_.api_config.cache_ttl_seconds < 0)- current_mapping_.api_config.cache_ttl_seconds = 0;-- ImGui::PushStyleColor(ImGuiCol_Text, TEXT_DISABLED);- if (current_mapping_.api_config.cache_ttl_seconds > 0) {- const int mins = current_mapping_.api_config.cache_ttl_seconds / 60;- if (mins > 0) ImGui::Text(" = %d min %d sec", mins,- current_mapping_.api_config.cache_ttl_seconds % 60);- } else {- ImGui::Text(" 0 = no caching");- }- ImGui::PopStyleColor();- }-- card_end();-- // === Validation Card ===- card_begin("##card_validation", "DATA VALIDATION");-- ImGui::Checkbox("Enable validation", ¤t_mapping_.validation.enabled);- if (current_mapping_.validation.enabled) {- ImGui::Spacing();- ImGui::Checkbox("Strict mode (reject records with errors)", ¤t_mapping_.validation.strict_mode);- ImGui::Spacing();- ImGui::PushStyleColor(ImGuiCol_Text, TEXT_DIM);- ImGui::Text("Validates transformed data against the target schema.");- ImGui::Text("Checks required fields, data types, and value ranges.");- ImGui::PopStyleColor();- }-- card_end();-- // === Post-Processing Card ===- card_begin("##card_postproc", "POST-PROCESSING");-- // Limit- int limit_val = current_mapping_.post_processing.limit.value_or(0);- inline_label("Record limit", 110);- ImGui::PushItemWidth(100);- if (ImGui::InputInt("##pp_limit", &limit_val)) {- current_mapping_.post_processing.limit =- (limit_val > 0) ? std::optional<int>(limit_val) : std::nullopt;- }- ImGui::PopItemWidth();-- ImGui::PushStyleColor(ImGuiCol_Text, TEXT_DISABLED);- ImGui::Text(" 0 = no limit");- ImGui::PopStyleColor();-- // Sort- ImGui::Spacing();- bool has_sort = current_mapping_.post_processing.sort.has_value();- if (ImGui::Checkbox("Enable sorting", &has_sort)) {- if (has_sort) current_mapping_.post_processing.sort = SortConfig{"timestamp", false};- else current_mapping_.post_processing.sort = std::nullopt;- }- if (current_mapping_.post_processing.sort) {- char sort_buf[64] = {};- std::strncpy(sort_buf, current_mapping_.post_processing.sort->field.c_str(),- sizeof(sort_buf) - 1);- inline_label("Sort field", 110);- ImGui::PushItemWidth(160);- if (ImGui::InputText("##sort_field", sort_buf, sizeof(sort_buf))) {- current_mapping_.post_processing.sort->field = sort_buf;- }- ImGui::PopItemWidth();- ImGui::SameLine(0, 10);- ImGui::Checkbox("Descending", ¤t_mapping_.post_processing.sort->descending);- }-- // Deduplicate- ImGui::Spacing();- bool has_dedup = current_mapping_.post_processing.deduplicate_field.has_value();- if (ImGui::Checkbox("Deduplicate", &has_dedup)) {- if (has_dedup) current_mapping_.post_processing.deduplicate_field = "symbol";- else current_mapping_.post_processing.deduplicate_field = std::nullopt;- }- if (current_mapping_.post_processing.deduplicate_field) {- char dedup_buf[64] = {};- std::strncpy(dedup_buf, current_mapping_.post_processing.deduplicate_field->c_str(),- sizeof(dedup_buf) - 1);- inline_label("Dedup field", 110);- ImGui::PushItemWidth(160);- if (ImGui::InputText("##dedup_field", dedup_buf, sizeof(dedup_buf))) {- current_mapping_.post_processing.deduplicate_field = dedup_buf;- }- ImGui::PopItemWidth();- }-- card_end();-}--// ============================================================================-// Step 5: Test & Save-// ============================================================================--void DataMappingScreen::render_step_test_save(float w, float h) {- const float input_w = std::min(w * 0.55f, 500.0f);- const float label_w = 90.0f;-- // === Details Card ===- card_begin("##card_details", "MAPPING DETAILS");-- inline_label("Name", label_w);- ImGui::PushItemWidth(input_w);- ImGui::InputTextWithHint("##map_name", "My API Mapping", mapping_name_buf_, sizeof(mapping_name_buf_));- ImGui::PopItemWidth();-- inline_label("Description", label_w);- ImGui::PushItemWidth(input_w);- ImGui::InputText("##map_desc", mapping_desc_buf_, sizeof(mapping_desc_buf_));- ImGui::PopItemWidth();-- card_end();-- // === Test Card ===- card_begin("##card_test", "TEST MAPPING");-- ImGui::PushStyleColor(ImGuiCol_Text, TEXT_DIM);- ImGui::Text("Paste sample JSON data to test the transformation pipeline:");- ImGui::PopStyleColor();- ImGui::Spacing();-- // Sample data input- static char sample_buf[8192] = {};- if (!sample_data_json_.empty() && sample_buf[0] == '\0') {- std::strncpy(sample_buf, sample_data_json_.c_str(),- std::min<size_t>(sizeof(sample_buf) - 1, sample_data_json_.size()));- }-- ImGui::PushStyleColor(ImGuiCol_FrameBg, BG_INPUT);- ImGui::InputTextMultiline("##sample_json", sample_buf, sizeof(sample_buf),- {std::min(w * 0.75f, 700.0f), 120});- ImGui::PopStyleColor();-- ImGui::Spacing();-- if (testing_) {- theme::LoadingSpinner("Running test...");- } else {- if (theme::AccentButton("Run Test")) {- sample_data_json_ = sample_buf;- start_test();- }- }-- // Test results- if (test_result_) {- ImGui::Spacing();- ImGui::Separator();- ImGui::Spacing();-- if (test_result_->success) {- ImGui::PushStyleColor(ImGuiCol_Text, SUCCESS);- ImGui::Text("SUCCESS");- ImGui::PopStyleColor();- ImGui::SameLine();- ImGui::PushStyleColor(ImGuiCol_Text, TEXT_SECONDARY);- ImGui::Text("— %d records processed, %d returned in %lldms",- test_result_->records_processed, test_result_->records_returned,- static_cast<long long>(test_result_->duration_ms));- ImGui::PopStyleColor();-- ImGui::Spacing();- render_json_preview("Transformed Output", test_result_->data_json, 180);- } else {- ImGui::PushStyleColor(ImGuiCol_Text, ERROR_RED);- ImGui::Text("FAILED");- ImGui::PopStyleColor();- for (const auto& err : test_result_->errors) {- ImGui::PushStyleColor(ImGuiCol_Text, ERROR_RED);- ImGui::Bullet();- ImGui::Text("%s", err.c_str());- ImGui::PopStyleColor();- }- }-- render_validation_results();- }-- card_end();-- // Save button (prominent, bottom)- ImGui::Spacing();- ImGui::Spacing();- if (theme::AccentButton(editing_existing_ ? "Update Mapping" : "Save Mapping",- {180, 36})) {- save_current_mapping();- }- ImGui::SameLine(0, 12);- if (theme::SecondaryButton("Cancel", {100, 36})) {- view_ = MappingView::list;- load_mappings();- }-}--// ============================================================================-// Templates view — card grid with category badges and tag pills-// ============================================================================--void DataMappingScreen::render_templates_view(float w, float /*h*/) {- ImGui::PushStyleColor(ImGuiCol_Text, TEXT_SECONDARY);- ImGui::Text("Pre-built mapping configurations for popular brokers and data providers.");- ImGui::PopStyleColor();- ImGui::Spacing();-- if (templates_.empty()) {- ImGui::Spacing();- ImGui::PushStyleColor(ImGuiCol_Text, TEXT_DIM);- ImGui::Text("No templates available.");- ImGui::PopStyleColor();- return;- }-- for (size_t i = 0; i < templates_.size(); ++i) {- const auto& t = templates_[i];-- ImGui::PushID(static_cast<int>(i));-- ImGui::PushStyleColor(ImGuiCol_ChildBg, BG_PANEL);- ImGui::PushStyleColor(ImGuiCol_Border, BORDER_DIM);- ImGui::PushStyleVar(ImGuiStyleVar_ChildRounding, 3.0f);- ImGui::PushStyleVar(ImGuiStyleVar_WindowPadding, {12, 8});- ImGui::BeginChild("##tmpl_card", {0, 0}, ImGuiChildFlags_AutoResizeY | ImGuiChildFlags_Borders);-- // Row 1: Name + category badge + verified indicator- ImGui::PushStyleColor(ImGuiCol_Text, TEXT_PRIMARY);- ImGui::Text("%s", t.name.c_str());- ImGui::PopStyleColor();-- ImGui::SameLine(w * 0.45f);- tag_pill(t.category.c_str(), INFO);-- if (t.verified) {- ImGui::SameLine();- tag_pill("verified", SUCCESS);- }- if (t.official) {- ImGui::SameLine();- tag_pill("official", ACCENT);- }-- // Use button (right-aligned)- ImGui::SameLine(w * 0.80f);- if (theme::AccentButton("Use Template")) {- load_template(t);- }-- // Row 2: Description- ImGui::PushStyleColor(ImGuiCol_Text, TEXT_DIM);- ImGui::Text("%s", t.description.c_str());- ImGui::PopStyleColor();-- // Row 3: Tags- if (!t.tags.empty()) {- for (const auto& tag : t.tags) {- tag_pill(tag.c_str(), TEXT_SECONDARY);- ImGui::SameLine(0, 4);- }- ImGui::NewLine();- }-- // Instructions if available- if (!t.instructions.empty()) {- ImGui::PushStyleColor(ImGuiCol_Text, TEXT_DISABLED);- ImGui::Text("Tip: %s", t.instructions.c_str());- ImGui::PopStyleColor();- }-- ImGui::EndChild();- ImGui::PopStyleVar(2);- ImGui::PopStyleColor(2);-- ImGui::PopID();- }-}--// ============================================================================-// Footer — stats + keyboard hints-// ============================================================================--void DataMappingScreen::render_footer(float w, float footer_h) {- const ImGuiViewport* vp = ImGui::GetMainViewport();- const float chrome_top = ImGui::GetFrameHeight() + 4.0f;- const float chrome_bot = ImGui::GetFrameHeight();- const float screen_bottom = vp->WorkPos.y + chrome_top + (vp->WorkSize.y - chrome_top - chrome_bot);- ImGui::SetNextWindowPos({vp->WorkPos.x, screen_bottom - footer_h});- ImGui::SetNextWindowSize({w, footer_h});- ImGui::PushStyleColor(ImGuiCol_WindowBg, BG_DARK);- ImGui::PushStyleVar(ImGuiStyleVar_WindowPadding, {12, 3});-- ImGui::Begin("##dm_footer", nullptr,- ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_NoResize | ImGuiWindowFlags_NoMove |- ImGuiWindowFlags_NoScrollbar | ImGuiWindowFlags_NoDocking);-- ImGui::PushStyleColor(ImGuiCol_Text, TEXT_DISABLED);- ImGui::Text("DATA MAPPING");- ImGui::PopStyleColor();-- ImGui::SameLine(160);- ImGui::PushStyleColor(ImGuiCol_Text, TEXT_DIM);- ImGui::Text("%d mappings | %d templates | 7 schemas | 19 transforms",- static_cast<int>(saved_mappings_.size()),- static_cast<int>(templates_.size()));- ImGui::PopStyleColor();-- ImGui::End();- ImGui::PopStyleVar();- ImGui::PopStyleColor();-}--// ============================================================================-// JSON Preview — syntax-colored read-only display-// ============================================================================--void DataMappingScreen::render_json_preview(const std::string& label,- const std::string& json_str,- float height) {- ImGui::PushStyleColor(ImGuiCol_Text, ACCENT);- ImGui::Text("%s:", label.c_str());- ImGui::PopStyleColor();-- ImGui::PushStyleColor(ImGuiCol_FrameBg, BG_INPUT);- ImGui::PushStyleColor(ImGuiCol_Text, TEXT_PRIMARY);- const std::string display = (json_str.size() > 4000)- ? json_str.substr(0, 4000) + "\n... (truncated)"- : json_str;- char preview_buf[4096] = {};- std::strncpy(preview_buf, display.c_str(),- std::min<size_t>(sizeof(preview_buf) - 1, display.size()));- ImGui::InputTextMultiline("##json_preview", preview_buf, sizeof(preview_buf),- {-1, height}, ImGuiInputTextFlags_ReadOnly);- ImGui::PopStyleColor(2);-}--// ============================================================================-// Validation results — inline colored indicators-// ============================================================================--void DataMappingScreen::render_validation_results() {- if (!test_result_) return;-- ImGui::Spacing();- if (test_result_->validation.errors.empty()) {- ImGui::PushStyleColor(ImGuiCol_Text, SUCCESS);- ImGui::Text("Validation: PASSED");- ImGui::PopStyleColor();- } else {- ImGui::PushStyleColor(ImGuiCol_Text, ERROR_RED);- ImGui::Text("Validation: %d error(s)", static_cast<int>(test_result_->validation.errors.size()));- ImGui::PopStyleColor();- for (const auto& e : test_result_->validation.errors) {- ImGui::PushStyleColor(ImGuiCol_Text, ERROR_RED);- ImGui::Bullet();- ImGui::Text("[%s] %s: %s", e.rule.c_str(), e.field.c_str(), e.message.c_str());- ImGui::PopStyleColor();- }- }-}--// ============================================================================-// Actions — load, save, delete, test, fetch, edit, template, reset-// ============================================================================--void DataMappingScreen::load_mappings() {- saved_mappings_ = mapping_ops::get_all_mappings();-}--void DataMappingScreen::save_current_mapping() {- // Sync form buffers to current_mapping_- current_mapping_.name = mapping_name_buf_;- current_mapping_.description = mapping_desc_buf_;- current_mapping_.api_config.name = api_name_buf_;- current_mapping_.api_config.description = api_desc_buf_;- current_mapping_.api_config.base_url = api_base_url_buf_;- current_mapping_.api_config.endpoint = api_endpoint_buf_;- current_mapping_.api_config.method = static_cast<HttpMethod>(api_method_idx_);- current_mapping_.extraction.root_path = root_path_buf_;-- if (std::strlen(api_body_buf_) > 0) {- current_mapping_.api_config.body = api_body_buf_;- }-- // Auth- switch (api_auth_type_idx_) {- case 0: current_mapping_.api_config.authentication.type = AuthType::none; break;- case 1: {- current_mapping_.api_config.authentication.type = AuthType::apikey;- current_mapping_.api_config.authentication.apikey = ApiKeyConfig{- auth_key_location_idx_ == 1 ? ApiKeyLocation::query : ApiKeyLocation::header,- auth_key_name_buf_, auth_key_value_buf_- };- break;- }- case 2: {- current_mapping_.api_config.authentication.type = AuthType::bearer;- current_mapping_.api_config.authentication.bearer = BearerConfig{auth_bearer_buf_};- break;- }- case 3: {- current_mapping_.api_config.authentication.type = AuthType::basic;- current_mapping_.api_config.authentication.basic = BasicAuthConfig{- auth_basic_user_buf_, auth_basic_pass_buf_};- break;- }- default: break;- }-- // Generate timestamps- if (current_mapping_.id.empty()) {- current_mapping_.id = db::generate_uuid();- }- if (current_mapping_.api_config.id.empty()) {- current_mapping_.api_config.id = db::generate_uuid();- }-- const auto now = std::chrono::system_clock::now();- const auto tt = std::chrono::system_clock::to_time_t(now);- std::tm tm_buf{};-#ifdef _WIN32- gmtime_s(&tm_buf, &tt);-#else- gmtime_r(&tt, &tm_buf);-#endif- char time_str[64];- std::strftime(time_str, sizeof(time_str), "%Y-%m-%dT%H:%M:%SZ", &tm_buf);-- if (current_mapping_.created_at.empty()) {- current_mapping_.created_at = time_str;- }- current_mapping_.updated_at = time_str;-- mapping_ops::save_mapping(current_mapping_);- load_mappings();- editing_existing_ = false;- view_ = MappingView::list;-}--void DataMappingScreen::delete_mapping_by_id(const std::string& id) {- mapping_ops::delete_mapping(id);- load_mappings();-}--void DataMappingScreen::start_test() {- current_mapping_.extraction.root_path = root_path_buf_;-- json sample_json;- if (!sample_data_json_.empty()) {- try {- sample_json = json::parse(sample_data_json_);- } catch (...) {- test_result_ = ExecutionResult{};- test_result_->errors.push_back("Invalid JSON in sample data");- return;- }- }-- testing_ = true;- test_future_ = std::async(std::launch::async, [this, sample_json]() {- return engine_.test(current_mapping_, sample_json);- });-}--void DataMappingScreen::fetch_sample_data() {- current_mapping_.api_config.base_url = api_base_url_buf_;- current_mapping_.api_config.endpoint = api_endpoint_buf_;- current_mapping_.api_config.method = static_cast<HttpMethod>(api_method_idx_);-- fetching_ = true;- fetch_future_ = std::async(std::launch::async, [this]() {- return engine_.fetch_api(current_mapping_.api_config);- });-}--void DataMappingScreen::reset_create_form() {- current_mapping_ = MappingConfig{};- current_mapping_.id = db::generate_uuid();- current_mapping_.api_config.id = db::generate_uuid();- current_step_ = CreateStep::api_config;- test_result_ = std::nullopt;- sample_data_json_.clear();- editing_existing_ = false;-- std::memset(api_name_buf_, 0, sizeof(api_name_buf_));- std::memset(api_desc_buf_, 0, sizeof(api_desc_buf_));- std::memset(api_base_url_buf_, 0, sizeof(api_base_url_buf_));- std::memset(api_endpoint_buf_, 0, sizeof(api_endpoint_buf_));- std::memset(api_body_buf_, 0, sizeof(api_body_buf_));- std::memset(mapping_name_buf_, 0, sizeof(mapping_name_buf_));- std::memset(mapping_desc_buf_, 0, sizeof(mapping_desc_buf_));- std::memset(root_path_buf_, 0, sizeof(root_path_buf_));- std::memset(auth_key_name_buf_, 0, sizeof(auth_key_name_buf_));- std::memset(auth_key_value_buf_, 0, sizeof(auth_key_value_buf_));- std::memset(auth_bearer_buf_, 0, sizeof(auth_bearer_buf_));- std::memset(auth_basic_user_buf_, 0, sizeof(auth_basic_user_buf_));- std::memset(auth_basic_pass_buf_, 0, sizeof(auth_basic_pass_buf_));-- api_method_idx_ = 0;- api_auth_type_idx_ = 0;- schema_type_idx_ = 0;- parser_engine_idx_ = 0;-}--void DataMappingScreen::edit_mapping(const MappingConfig& config) {- current_mapping_ = config;- view_ = MappingView::create;- current_step_ = CreateStep::api_config;- editing_existing_ = true;-- std::strncpy(api_name_buf_, config.api_config.name.c_str(), sizeof(api_name_buf_) - 1);- std::strncpy(api_desc_buf_, config.api_config.description.c_str(), sizeof(api_desc_buf_) - 1);- std::strncpy(api_base_url_buf_, config.api_config.base_url.c_str(), sizeof(api_base_url_buf_) - 1);- std::strncpy(api_endpoint_buf_, config.api_config.endpoint.c_str(), sizeof(api_endpoint_buf_) - 1);- std::strncpy(mapping_name_buf_, config.name.c_str(), sizeof(mapping_name_buf_) - 1);- std::strncpy(mapping_desc_buf_, config.description.c_str(), sizeof(mapping_desc_buf_) - 1);- std::strncpy(root_path_buf_, config.extraction.root_path.c_str(), sizeof(root_path_buf_) - 1);-- api_method_idx_ = static_cast<int>(config.api_config.method);- api_auth_type_idx_ = static_cast<int>(config.api_config.authentication.type);- schema_type_idx_ = static_cast<int>(config.schema_type);-- if (config.api_config.body) {- std::strncpy(api_body_buf_, config.api_config.body->c_str(), sizeof(api_body_buf_) - 1);- }-- // Auth details- if (config.api_config.authentication.apikey) {- const auto& ak = *config.api_config.authentication.apikey;- std::strncpy(auth_key_name_buf_, ak.key_name.c_str(), sizeof(auth_key_name_buf_) - 1);- std::strncpy(auth_key_value_buf_, ak.value.c_str(), sizeof(auth_key_value_buf_) - 1);- auth_key_location_idx_ = (ak.location == ApiKeyLocation::query) ? 1 : 0;- }- if (config.api_config.authentication.bearer) {- std::strncpy(auth_bearer_buf_, config.api_config.authentication.bearer->token.c_str(),- sizeof(auth_bearer_buf_) - 1);- }- if (config.api_config.authentication.basic) {- std::strncpy(auth_basic_user_buf_, config.api_config.authentication.basic->username.c_str(),- sizeof(auth_basic_user_buf_) - 1);- std::strncpy(auth_basic_pass_buf_, config.api_config.authentication.basic->password.c_str(),- sizeof(auth_basic_pass_buf_) - 1);- }-}--void DataMappingScreen::load_template(const MappingTemplate& tmpl) {- reset_create_form();- current_mapping_ = tmpl.config;- current_mapping_.id = db::generate_uuid();- current_mapping_.api_config.id = db::generate_uuid();-- std::strncpy(mapping_name_buf_, tmpl.config.name.c_str(), sizeof(mapping_name_buf_) - 1);- std::strncpy(mapping_desc_buf_, tmpl.config.description.c_str(), sizeof(mapping_desc_buf_) - 1);- std::strncpy(api_name_buf_, tmpl.config.api_config.name.c_str(), sizeof(api_name_buf_) - 1);- std::strncpy(api_base_url_buf_, tmpl.config.api_config.base_url.c_str(), sizeof(api_base_url_buf_) - 1);- std::strncpy(api_endpoint_buf_, tmpl.config.api_config.endpoint.c_str(), sizeof(api_endpoint_buf_) - 1);- std::strncpy(root_path_buf_, tmpl.config.extraction.root_path.c_str(), sizeof(root_path_buf_) - 1);-- api_method_idx_ = static_cast<int>(tmpl.config.api_config.method);- schema_type_idx_ = static_cast<int>(tmpl.config.schema_type);-- view_ = MappingView::create;- current_step_ = CreateStep::api_config;-}--// ============================================================================-// Template loader — built-in broker templates-// ============================================================================--void DataMappingScreen::load_templates() {- templates_.clear();-- // Upstox Historical OHLCV- {- MappingTemplate t;- t.id = "upstox_historical_ohlcv";- t.name = "Upstox Historical Candles -> OHLCV";- t.description = "Map Upstox historical candle data to standard OHLCV format";- t.category = "broker";- t.tags = {"upstox", "historical", "ohlcv", "india"};- t.verified = true;- t.official = true;-- t.config.name = "Upstox Historical -> OHLCV";- t.config.description = "Transform Upstox historical candle data";- t.config.is_predefined_schema = true;- t.config.schema_type = SchemaType::ohlcv;- t.config.extraction.engine = ParserEngine::direct;- t.config.extraction.root_path = "data.candles";- t.config.extraction.is_array = true;- t.config.extraction.is_array_of_arrays = true;-- t.config.field_mappings = {- {"timestamp", FieldSourceType::path, "$[0]", "", ParserEngine::direct, {"toISODate"}, {}, true, 0.0f},- {"open", FieldSourceType::path, "$[1]", "", ParserEngine::direct, {}, {}, true, 0.0f},- {"high", FieldSourceType::path, "$[2]", "", ParserEngine::direct, {}, {}, true, 0.0f},- {"low", FieldSourceType::path, "$[3]", "", ParserEngine::direct, {}, {}, true, 0.0f},- {"close", FieldSourceType::path, "$[4]", "", ParserEngine::direct, {}, {}, true, 0.0f},- {"volume", FieldSourceType::path, "$[5]", "", ParserEngine::direct, {}, {}, true, 0.0f},- };- t.config.validation.enabled = true;- t.instructions = "Use endpoint: /historical-candle/{instrument_key}/{interval}/{to_date}/{from_date}";- templates_.push_back(t);- }-- // Fyers Quotes- {- MappingTemplate t;- t.id = "fyers_quotes";- t.name = "Fyers Quotes -> QUOTE";- t.description = "Map Fyers quote data to standard QUOTE format";- t.category = "broker";- t.tags = {"fyers", "quote", "india"};- t.verified = true;- t.official = true;-- t.config.name = "Fyers Quote -> QUOTE";- t.config.is_predefined_schema = true;- t.config.schema_type = SchemaType::quote;- t.config.extraction.root_path = "d";- t.config.extraction.is_array = true;-- t.config.field_mappings = {- {"symbol", FieldSourceType::path, "n", "", ParserEngine::direct, {}, {}, true, 0.0f},- {"timestamp", FieldSourceType::path, "v.tt", "", ParserEngine::direct, {"toISODate"}, {}, true, 0.0f},- {"price", FieldSourceType::path, "v.lp", "", ParserEngine::direct, {}, {}, true, 0.0f},- {"bid", FieldSourceType::path, "v.bid", "", ParserEngine::direct, {}, {}, false, 0.0f},- {"ask", FieldSourceType::path, "v.ask", "", ParserEngine::direct, {}, {}, false, 0.0f},- {"volume", FieldSourceType::path, "v.volume", "", ParserEngine::direct, {}, {}, false, 0.0f},- {"open", FieldSourceType::path, "v.open_price", "", ParserEngine::direct, {}, {}, false, 0.0f},- {"high", FieldSourceType::path, "v.high_price", "", ParserEngine::direct, {}, {}, false, 0.0f},- {"low", FieldSourceType::path, "v.low_price", "", ParserEngine::direct, {}, {}, false, 0.0f},- {"previousClose", FieldSourceType::path, "v.prev_close_price", "", ParserEngine::direct, {}, {}, false, 0.0f},- {"change", FieldSourceType::path, "v.ch", "", ParserEngine::direct, {}, {}, false, 0.0f},- {"changePercent", FieldSourceType::path, "v.chp", "", ParserEngine::direct, {}, {}, false, 0.0f},- };- t.config.validation.enabled = true;- t.instructions = "Use endpoint: /data/quotes with POST method and symbols in body";- templates_.push_back(t);- }-- // Fyers Positions- {- MappingTemplate t;- t.id = "fyers_positions";- t.name = "Fyers Positions -> POSITION";- t.description = "Map Fyers position data to standard POSITION format";- t.category = "broker";- t.tags = {"fyers", "position", "india"};- t.verified = true;- t.official = true;-- t.config.name = "Fyers Position -> POSITION";- t.config.is_predefined_schema = true;- t.config.schema_type = SchemaType::position;- t.config.extraction.root_path = "netPositions";- t.config.extraction.is_array = true;-- t.config.field_mappings = {- {"symbol", FieldSourceType::path, "symbol", "", ParserEngine::direct, {}, {}, true, 0.0f},- {"quantity", FieldSourceType::path, "netQty", "", ParserEngine::direct, {}, {}, true, 0.0f},- {"averagePrice", FieldSourceType::path, "avgPrice", "", ParserEngine::direct, {}, {}, true, 0.0f},- {"currentPrice", FieldSourceType::path, "ltp", "", ParserEngine::direct, {}, {}, true, 0.0f},- {"pnl", FieldSourceType::path, "pl", "", ParserEngine::direct, {}, {}, true, 0.0f},- {"pnlPercent", FieldSourceType::path, "plPercent", "", ParserEngine::direct, {}, {}, true, 0.0f},- {"productType", FieldSourceType::path, "productType", "", ParserEngine::direct, {"uppercase"}, {}, false, 0.0f},- };- t.config.validation.enabled = true;- templates_.push_back(t);- }-- // Dhan Positions- {- MappingTemplate t;- t.id = "dhan_positions";- t.name = "Dhan Positions -> POSITION";- t.description = "Map Dhan position data to standard POSITION format";- t.category = "broker";- t.tags = {"dhan", "position", "india"};- t.verified = true;- t.official = true;-- t.config.name = "Dhan Position -> POSITION";- t.config.is_predefined_schema = true;- t.config.schema_type = SchemaType::position;- t.config.extraction.root_path = "data";- t.config.extraction.is_array = true;-- t.config.field_mappings = {- {"symbol", FieldSourceType::path, "tradingSymbol", "", ParserEngine::direct, {}, {}, true, 0.0f},- {"quantity", FieldSourceType::path, "netQty", "", ParserEngine::direct, {}, {}, true, 0.0f},- {"averagePrice", FieldSourceType::path, "costPrice", "", ParserEngine::direct, {}, {}, true, 0.0f},- {"currentPrice", FieldSourceType::path, "ltp", "", ParserEngine::direct, {}, {}, true, 0.0f},- {"pnl", FieldSourceType::path, "realizedProfit", "", ParserEngine::direct, {}, {}, true, 0.0f},- {"exchange", FieldSourceType::path, "exchangeSegment", "", ParserEngine::direct, {}, {}, false, 0.0f},- };- t.config.validation.enabled = true;- templates_.push_back(t);- }-- // Dhan Orders- {- MappingTemplate t;- t.id = "dhan_orders";- t.name = "Dhan Orders -> ORDER";- t.description = "Map Dhan order data to standard ORDER format";- t.category = "broker";- t.tags = {"dhan", "order", "india"};- t.verified = true;- t.official = true;-- t.config.name = "Dhan Order -> ORDER";- t.config.is_predefined_schema = true;- t.config.schema_type = SchemaType::order;- t.config.extraction.root_path = "data";- t.config.extraction.is_array = true;-- t.config.field_mappings = {- {"orderId", FieldSourceType::path, "orderId", "", ParserEngine::direct, {}, {}, true, 0.0f},- {"symbol", FieldSourceType::path, "tradingSymbol", "", ParserEngine::direct, {}, {}, true, 0.0f},- {"side", FieldSourceType::path, "transactionType", "", ParserEngine::direct, {"uppercase"}, {}, true, 0.0f},- {"type", FieldSourceType::path, "orderType", "", ParserEngine::direct, {"uppercase"}, {}, true, 0.0f},- {"quantity", FieldSourceType::path, "quantity", "", ParserEngine::direct, {}, {}, true, 0.0f},- {"filledQuantity", FieldSourceType::path, "tradedQuantity", "", ParserEngine::direct, {}, {}, false, 0.0f},- {"price", FieldSourceType::path, "price", "", ParserEngine::direct, {}, {}, false, 0.0f},- {"averagePrice", FieldSourceType::path, "tradedPrice", "", ParserEngine::direct, {}, {}, false, 0.0f},- {"status", FieldSourceType::path, "orderStatus", "", ParserEngine::direct, {"uppercase"}, {}, true, 0.0f},- {"timestamp", FieldSourceType::path, "createTime", "", ParserEngine::direct, {"toISODate"}, {}, true, 0.0f},- {"exchange", FieldSourceType::path, "exchangeSegment", "", ParserEngine::direct, {}, {}, false, 0.0f},- };- t.config.validation.enabled = true;- templates_.push_back(t);- }-- // Zerodha OHLC- {- MappingTemplate t;- t.id = "zerodha_ohlc";- t.name = "Zerodha OHLC -> OHLCV";- t.description = "Map Zerodha/Kite OHLC data to standard OHLCV format";- t.category = "broker";- t.tags = {"zerodha", "kite", "ohlc", "india"};- t.verified = true;-- t.config.name = "Zerodha OHLC -> OHLCV";- t.config.is_predefined_schema = true;- t.config.schema_type = SchemaType::ohlcv;- t.config.extraction.root_path = "data";- t.config.extraction.is_array = false;-- t.config.field_mappings = {- {"open", FieldSourceType::path, "ohlc.open", "", ParserEngine::direct, {}, {}, true, 0.0f},- {"high", FieldSourceType::path, "ohlc.high", "", ParserEngine::direct, {}, {}, true, 0.0f},- {"low", FieldSourceType::path, "ohlc.low", "", ParserEngine::direct, {}, {}, true, 0.0f},- {"close", FieldSourceType::path, "last_price", "", ParserEngine::direct, {}, {}, true, 0.0f},- {"volume", FieldSourceType::path, "volume", "", ParserEngine::direct, {}, {}, true, 0.0f},- };- t.config.validation.enabled = true;- t.instructions = "Use endpoint: /quote/ohlc with query params i=NSE:SBIN&i=NSE:RELIANCE";- templates_.push_back(t);- }-}--} // namespace fincept::data_mapping+// data_mapping_screen.cpp — split into focused files.+// All implementations live in:+// dm_screen.cpp — static helpers, init, render, command_bar, sidebar, content dispatch, list_view+// dm_create.cpp — create_view, stepper, all step panels, actions, templates loaderdiff --git a/fincept-cpp/src/screens/data_mapping/dm_create.cpp b/fincept-cpp/src/screens/data_mapping/dm_create.cppnew file mode 100644index 000000000..5b0a843b5--- /dev/null+++ b/fincept-cpp/src/screens/data_mapping/dm_create.cpp@@ -0,0 +1,1419 @@+#include "data_mapping_screen.h"+#include "data_mapping_schemas.h"+#include "ui/theme.h"+#include "storage/database.h"+#include "core/logger.h"+#include <imgui.h>+#include <nlohmann/json.hpp>+#include <algorithm>+#include <cstring>+#include <chrono>+#include <cmath>++namespace fincept::data_mapping {++using json = nlohmann::json;+using namespace theme::colors;+++// ============================================================================+// Create View — horizontal stepper + step content+// ============================================================================++void DataMappingScreen::render_create_view(float w, float h) {+ // Horizontal step progress bar+ render_step_progress_bar(w);++ ImGui::Spacing();+ ImGui::Separator();+ ImGui::Spacing();++ // Step content+ switch (current_step_) {+ case CreateStep::api_config: render_step_api_config(w, h); break;+ case CreateStep::schema_select: render_step_schema_select(w, h); break;+ case CreateStep::field_mapping: render_step_field_mapping(w, h); break;+ case CreateStep::cache_settings: render_step_cache_settings(w, h); break;+ case CreateStep::test_save: render_step_test_save(w, h); break;+ }+}++// ============================================================================+// Horizontal step progress bar — circles connected by lines+// ============================================================================++void DataMappingScreen::render_step_progress_bar(float w) {+ const float step_area_w = w - 40;+ const float step_spacing = step_area_w / (NUM_STEPS);+ const float circle_r = 12.0f;+ const float start_x = ImGui::GetCursorScreenPos().x + 20;+ const float center_y = ImGui::GetCursorScreenPos().y + circle_r + 2;++ ImDrawList* dl = ImGui::GetWindowDrawList();++ for (int i = 0; i < NUM_STEPS; ++i) {+ const float cx = start_x + step_spacing * i + step_spacing * 0.5f;+ const bool is_current = (ALL_STEPS[i] == current_step_);+ const bool is_past = (i < static_cast<int>(current_step_));+ const bool is_future = (i > static_cast<int>(current_step_));++ // Connecting line to next step+ if (i < NUM_STEPS - 1) {+ const float nx = start_x + step_spacing * (i + 1) + step_spacing * 0.5f;+ const ImU32 line_col = is_past+ ? ImGui::ColorConvertFloat4ToU32(SUCCESS)+ : ImGui::ColorConvertFloat4ToU32(BORDER_DIM);+ dl->AddLine({cx + circle_r + 4, center_y}, {nx - circle_r - 4, center_y}, line_col, 2.0f);+ }++ // Circle+ if (is_current) {+ // Active: filled orange with glow+ dl->AddCircleFilled({cx, center_y}, circle_r + 2,+ ImGui::ColorConvertFloat4ToU32({ACCENT.x, ACCENT.y, ACCENT.z, 0.2f}));+ dl->AddCircleFilled({cx, center_y}, circle_r,+ ImGui::ColorConvertFloat4ToU32(ACCENT));+ dl->AddCircle({cx, center_y}, circle_r,+ ImGui::ColorConvertFloat4ToU32({1, 1, 1, 0.3f}), 0, 2.0f);+ } else if (is_past) {+ // Completed: green filled with checkmark+ dl->AddCircleFilled({cx, center_y}, circle_r,+ ImGui::ColorConvertFloat4ToU32(SUCCESS));+ // Checkmark+ dl->AddLine({cx - 4, center_y}, {cx - 1, center_y + 3},+ ImGui::ColorConvertFloat4ToU32({1, 1, 1, 1}), 2.0f);+ dl->AddLine({cx - 1, center_y + 3}, {cx + 5, center_y - 4},+ ImGui::ColorConvertFloat4ToU32({1, 1, 1, 1}), 2.0f);+ } else {+ // Future: dim border only+ dl->AddCircle({cx, center_y}, circle_r,+ ImGui::ColorConvertFloat4ToU32(BORDER), 0, 2.0f);+ }++ // Step number in circle+ if (is_current || is_future) {+ char num[4];+ std::snprintf(num, sizeof(num), "%d", i + 1);+ const ImVec2 text_size = ImGui::CalcTextSize(num);+ const ImU32 text_col = is_current+ ? ImGui::ColorConvertFloat4ToU32({1, 1, 1, 1})+ : ImGui::ColorConvertFloat4ToU32(TEXT_DISABLED);+ dl->AddText({cx - text_size.x * 0.5f, center_y - text_size.y * 0.5f}, text_col, num);+ }++ // Label below circle (clickable)+ const char* step_label = create_step_label(ALL_STEPS[i]);+ const ImVec2 label_size = ImGui::CalcTextSize(step_label);+ const float label_x = cx - label_size.x * 0.5f;+ const float label_y = center_y + circle_r + 6;++ ImU32 label_col;+ if (is_current) label_col = ImGui::ColorConvertFloat4ToU32(ACCENT);+ else if (is_past) label_col = ImGui::ColorConvertFloat4ToU32(TEXT_SECONDARY);+ else label_col = ImGui::ColorConvertFloat4ToU32(TEXT_DISABLED);++ dl->AddText({label_x, label_y}, label_col, step_label);++ // Invisible button for clicking+ ImGui::SetCursorScreenPos({cx - circle_r - 4, center_y - circle_r - 4});+ ImGui::PushID(i);+ if (ImGui::InvisibleButton("##step", {circle_r * 2 + 8, circle_r * 2 + label_size.y + 14})) {+ current_step_ = ALL_STEPS[i];+ }+ ImGui::PopID();+ }++ // Reserve vertical space for the stepper+ ImGui::SetCursorScreenPos({ImGui::GetCursorScreenPos().x,+ center_y + circle_r + 26});+ ImGui::Dummy({0, 0});+}++// ============================================================================+// Step 1: API Configuration — grouped into cards+// ============================================================================++void DataMappingScreen::render_step_api_config(float w, float /*h*/) {+ const float input_w = std::min(w * 0.55f, 500.0f);+ const float label_w = 90.0f;++ // === Connection Card ===+ card_begin("##card_conn", "API CONNECTION");++ inline_label("Name", label_w);+ ImGui::PushItemWidth(input_w);+ ImGui::InputText("##api_name", api_name_buf_, sizeof(api_name_buf_));+ ImGui::PopItemWidth();++ inline_label("Description", label_w);+ ImGui::PushItemWidth(input_w);+ ImGui::InputText("##api_desc", api_desc_buf_, sizeof(api_desc_buf_));+ ImGui::PopItemWidth();++ ImGui::Spacing();++ // Method + URL on same visual row+ static const char* methods[] = {"GET", "POST", "PUT", "DELETE", "PATCH"};+ inline_label("Method", label_w);+ ImGui::PushItemWidth(90);+ ImGui::Combo("##method", &api_method_idx_, methods, 5);+ ImGui::PopItemWidth();++ inline_label("Base URL", label_w);+ ImGui::PushItemWidth(input_w);+ ImGui::InputTextWithHint("##base_url", "https://api.example.com/v1", api_base_url_buf_, sizeof(api_base_url_buf_));+ ImGui::PopItemWidth();++ inline_label("Endpoint", label_w);+ ImGui::PushItemWidth(input_w);+ ImGui::InputTextWithHint("##endpoint", "/ticker/{symbol}/candles", api_endpoint_buf_, sizeof(api_endpoint_buf_));+ ImGui::PopItemWidth();++ ImGui::PushStyleColor(ImGuiCol_Text, TEXT_DISABLED);+ ImGui::Text(" Use {placeholders} for runtime parameters");+ ImGui::PopStyleColor();++ // Body for POST/PUT/PATCH+ if (api_method_idx_ >= 1 && api_method_idx_ <= 4) {+ ImGui::Spacing();+ inline_label("Body", label_w);+ ImGui::InputTextMultiline("##body", api_body_buf_, sizeof(api_body_buf_),+ {input_w, 80});+ }++ // Fetch button+ ImGui::Spacing();+ if (fetching_) {+ theme::LoadingSpinner("Fetching sample data...");+ } else {+ if (theme::AccentButton("Fetch Sample Data")) {+ fetch_sample_data();+ }+ if (!sample_data_json_.empty()) {+ ImGui::SameLine();+ ImGui::PushStyleColor(ImGuiCol_Text, SUCCESS);+ ImGui::Text("Sample data loaded (%d bytes)",+ static_cast<int>(sample_data_json_.size()));+ ImGui::PopStyleColor();+ }+ }++ card_end();++ // === Authentication Card ===+ render_auth_config(w);++ // === Headers Card ===+ render_headers_editor(w);++ // === Query Params Card ===+ render_query_params_editor(w);+}++// ============================================================================+// Auth config card+// ============================================================================++void DataMappingScreen::render_auth_config(float w) {+ card_begin("##card_auth", "AUTHENTICATION");++ const float input_w = std::min(w * 0.45f, 400.0f);+ const float label_w = 90.0f;+ static const char* auth_types[] = {"None", "API Key", "Bearer Token", "Basic Auth", "OAuth2"};++ inline_label("Type", label_w);+ ImGui::PushItemWidth(160);+ ImGui::Combo("##auth_type", &api_auth_type_idx_, auth_types, 5);+ ImGui::PopItemWidth();++ switch (api_auth_type_idx_) {+ case 1: { // API Key+ static const char* locations[] = {"Header", "Query Param"};+ ImGui::Spacing();+ inline_label("Location", label_w);+ ImGui::PushItemWidth(130);+ ImGui::Combo("##key_loc", &auth_key_location_idx_, locations, 2);+ ImGui::PopItemWidth();++ inline_label("Key Name", label_w);+ ImGui::PushItemWidth(input_w * 0.6f);+ ImGui::InputTextWithHint("##key_name", "X-API-Key", auth_key_name_buf_, sizeof(auth_key_name_buf_));+ ImGui::PopItemWidth();++ inline_label("Value", label_w);+ ImGui::PushItemWidth(input_w);+ ImGui::InputText("##key_val", auth_key_value_buf_, sizeof(auth_key_value_buf_),+ ImGuiInputTextFlags_Password);+ ImGui::PopItemWidth();+ break;+ }+ case 2: { // Bearer+ ImGui::Spacing();+ inline_label("Token", label_w);+ ImGui::PushItemWidth(input_w);+ ImGui::InputText("##bearer", auth_bearer_buf_, sizeof(auth_bearer_buf_),+ ImGuiInputTextFlags_Password);+ ImGui::PopItemWidth();+ break;+ }+ case 3: { // Basic+ ImGui::Spacing();+ inline_label("Username", label_w);+ ImGui::PushItemWidth(input_w * 0.6f);+ ImGui::InputText("##basic_user", auth_basic_user_buf_, sizeof(auth_basic_user_buf_));+ ImGui::PopItemWidth();++ inline_label("Password", label_w);+ ImGui::PushItemWidth(input_w * 0.6f);+ ImGui::InputText("##basic_pass", auth_basic_pass_buf_, sizeof(auth_basic_pass_buf_),+ ImGuiInputTextFlags_Password);+ ImGui::PopItemWidth();+ break;+ }+ default: break;+ }++ card_end();+}++// ============================================================================+// Headers editor card+// ============================================================================++void DataMappingScreen::render_headers_editor(float /*w*/) {+ card_begin("##card_headers", "CUSTOM HEADERS");++ auto& hdrs = current_mapping_.api_config.headers;+ std::string to_remove;++ // Existing headers as mini-rows+ for (const auto& [k, v] : hdrs) {+ ImGui::PushStyleColor(ImGuiCol_Text, TEXT_PRIMARY);+ ImGui::Text("%s", k.c_str());+ ImGui::PopStyleColor();+ ImGui::SameLine(150);+ ImGui::PushStyleColor(ImGuiCol_Text, TEXT_DIM);+ ImGui::Text("%s", v.c_str());+ ImGui::PopStyleColor();+ ImGui::SameLine(ImGui::GetContentRegionAvail().x + ImGui::GetCursorPosX() - 20);+ ImGui::PushID(k.c_str());+ ImGui::PushStyleColor(ImGuiCol_Text, ERROR_RED);+ if (ImGui::SmallButton("x")) to_remove = k;+ ImGui::PopStyleColor();+ ImGui::PopID();+ }+ if (!to_remove.empty()) hdrs.erase(to_remove);++ // Add new+ ImGui::Spacing();+ ImGui::PushItemWidth(130);+ ImGui::InputTextWithHint("##hdr_key", "Key", header_key_buf_, sizeof(header_key_buf_));+ ImGui::PopItemWidth();+ ImGui::SameLine();+ ImGui::PushItemWidth(200);+ ImGui::InputTextWithHint("##hdr_val", "Value", header_val_buf_, sizeof(header_val_buf_));+ ImGui::PopItemWidth();+ ImGui::SameLine();+ if (theme::SecondaryButton("+ Add")) {+ if (std::strlen(header_key_buf_) > 0) {+ hdrs[header_key_buf_] = header_val_buf_;+ header_key_buf_[0] = '\0';+ header_val_buf_[0] = '\0';+ }+ }++ card_end();+}++// ============================================================================+// Query params editor card+// ============================================================================++void DataMappingScreen::render_query_params_editor(float /*w*/) {+ card_begin("##card_qparams", "QUERY PARAMETERS");++ auto& qparams = current_mapping_.api_config.query_params;+ std::string to_remove;++ for (const auto& [k, v] : qparams) {+ ImGui::PushStyleColor(ImGuiCol_Text, TEXT_PRIMARY);+ ImGui::Text("%s", k.c_str());+ ImGui::PopStyleColor();+ ImGui::SameLine(150);+ ImGui::PushStyleColor(ImGuiCol_Text, TEXT_DIM);+ ImGui::Text("%s", v.c_str());+ ImGui::PopStyleColor();+ ImGui::SameLine(ImGui::GetContentRegionAvail().x + ImGui::GetCursorPosX() - 20);+ ImGui::PushID(("qp_" + k).c_str());+ ImGui::PushStyleColor(ImGuiCol_Text, ERROR_RED);+ if (ImGui::SmallButton("x")) to_remove = k;+ ImGui::PopStyleColor();+ ImGui::PopID();+ }+ if (!to_remove.empty()) qparams.erase(to_remove);++ ImGui::Spacing();+ ImGui::PushItemWidth(130);+ ImGui::InputTextWithHint("##qp_key", "Key", qparam_key_buf_, sizeof(qparam_key_buf_));+ ImGui::PopItemWidth();+ ImGui::SameLine();+ ImGui::PushItemWidth(200);+ ImGui::InputTextWithHint("##qp_val", "Value", qparam_val_buf_, sizeof(qparam_val_buf_));+ ImGui::PopItemWidth();+ ImGui::SameLine();+ if (theme::SecondaryButton("+ Add")) {+ if (std::strlen(qparam_key_buf_) > 0) {+ qparams[qparam_key_buf_] = qparam_val_buf_;+ qparam_key_buf_[0] = '\0';+ qparam_val_buf_[0] = '\0';+ }+ }++ card_end();+}++// ============================================================================+// Step 2: Schema Selection+// ============================================================================++void DataMappingScreen::render_step_schema_select(float w, float /*h*/) {+ const float input_w = std::min(w * 0.55f, 500.0f);+ const float label_w = 100.0f;++ // === Schema Card ===+ card_begin("##card_schema", "TARGET SCHEMA");++ ImGui::Checkbox("Use predefined schema", ¤t_mapping_.is_predefined_schema);+ is_custom_schema_ = !current_mapping_.is_predefined_schema;++ ImGui::Spacing();++ if (current_mapping_.is_predefined_schema) {+ static const char* schema_items[] = {"OHLCV", "QUOTE", "TICK", "ORDER", "POSITION", "PORTFOLIO", "INSTRUMENT"};+ inline_label("Schema", label_w);+ ImGui::PushItemWidth(200);+ if (ImGui::Combo("##schema_type", &schema_type_idx_, schema_items, 7)) {+ current_mapping_.schema_type = static_cast<SchemaType>(schema_type_idx_);+ }+ ImGui::PopItemWidth();+ ImGui::SameLine();+ schema_badge(current_mapping_.schema_type);++ // Schema fields table+ const auto* schema = get_schema_for_type(current_mapping_.schema_type);+ if (schema) {+ ImGui::Spacing();+ ImGui::PushStyleColor(ImGuiCol_Text, TEXT_SECONDARY);+ ImGui::Text("%s — %s", schema->name.c_str(), schema->description.c_str());+ ImGui::PopStyleColor();+ ImGui::Spacing();++ if (ImGui::BeginTable("##schema_fields", 4,+ ImGuiTableFlags_RowBg | ImGuiTableFlags_Borders |+ ImGuiTableFlags_Resizable | ImGuiTableFlags_ScrollY,+ {0, std::min(250.0f, schema->fields.size() * 26.0f + 30.0f)})) {++ ImGui::TableSetupColumn("Field", ImGuiTableColumnFlags_None, input_w * 0.28f);+ ImGui::TableSetupColumn("Type", ImGuiTableColumnFlags_None, input_w * 0.14f);+ ImGui::TableSetupColumn("Required", ImGuiTableColumnFlags_None, input_w * 0.12f);+ ImGui::TableSetupColumn("Description", ImGuiTableColumnFlags_None, input_w * 0.46f);+ ImGui::PushStyleColor(ImGuiCol_TableHeaderBg, BG_WIDGET);+ ImGui::TableHeadersRow();+ ImGui::PopStyleColor();++ for (const auto& f : schema->fields) {+ ImGui::TableNextRow();++ ImGui::TableNextColumn();+ ImGui::PushStyleColor(ImGuiCol_Text, TEXT_PRIMARY);+ ImGui::Text("%s", f.name.c_str());+ ImGui::PopStyleColor();++ ImGui::TableNextColumn();+ ImGui::PushStyleColor(ImGuiCol_Text, INFO);+ ImGui::Text("%s", field_type_label(f.type));+ ImGui::PopStyleColor();++ ImGui::TableNextColumn();+ if (f.required) {+ ImGui::PushStyleColor(ImGuiCol_Text, ACCENT);+ ImGui::Text("YES");+ } else {+ ImGui::PushStyleColor(ImGuiCol_Text, TEXT_DISABLED);+ ImGui::Text("no");+ }+ ImGui::PopStyleColor();++ ImGui::TableNextColumn();+ ImGui::PushStyleColor(ImGuiCol_Text, TEXT_DIM);+ ImGui::Text("%s", f.description.c_str());+ ImGui::PopStyleColor();+ }+ ImGui::EndTable();+ }+ }+ } else {+ ImGui::PushStyleColor(ImGuiCol_Text, TEXT_DIM);+ ImGui::Text("Custom schema fields are configured in the Field Mapping step.");+ ImGui::PopStyleColor();+ }++ card_end();++ // === Extraction Card ===+ card_begin("##card_extract", "DATA EXTRACTION");++ inline_label("Root Path", label_w);+ ImGui::PushItemWidth(300);+ ImGui::InputTextWithHint("##root_path", "e.g. data.candles or results",+ root_path_buf_, sizeof(root_path_buf_));+ ImGui::PopItemWidth();++ ImGui::PushStyleColor(ImGuiCol_Text, TEXT_DISABLED);+ ImGui::Text(" JSON path to the data array in the API response");+ ImGui::PopStyleColor();++ ImGui::Spacing();+ ImGui::Checkbox("Source data is an array", ¤t_mapping_.extraction.is_array);+ ImGui::SameLine(0, 20);+ ImGui::Checkbox("Array of arrays", ¤t_mapping_.extraction.is_array_of_arrays);++ card_end();+}++// ============================================================================+// Step 3: Field Mapping+// ============================================================================++void DataMappingScreen::render_step_field_mapping(float w, float /*h*/) {+ // Auto-populate from schema if empty+ if (current_mapping_.field_mappings.empty() && current_mapping_.is_predefined_schema) {+ const auto* schema = get_schema_for_type(current_mapping_.schema_type);+ if (schema) {+ for (const auto& f : schema->fields) {+ FieldMapping fm;+ fm.target_field = f.name;+ fm.source_path = f.name;+ fm.required = f.required;+ current_mapping_.field_mappings.push_back(fm);+ }+ }+ }++ card_begin("##card_fieldmap", "FIELD MAPPINGS");++ // Header row with add button+ ImGui::PushStyleColor(ImGuiCol_Text, TEXT_SECONDARY);+ ImGui::Text("Map source data fields to target schema fields.");+ ImGui::PopStyleColor();+ ImGui::SameLine(ImGui::GetContentRegionAvail().x + ImGui::GetCursorPosX() - 140);+ if (theme::AccentButton("+ Add Field")) {+ current_mapping_.field_mappings.push_back({});+ }++ ImGui::Spacing();++ // Field mapping table+ if (!current_mapping_.field_mappings.empty() &&+ ImGui::BeginTable("##field_map_table", 6,+ ImGuiTableFlags_RowBg | ImGuiTableFlags_Borders |+ ImGuiTableFlags_Resizable | ImGuiTableFlags_ScrollY,+ {0, std::min(400.0f, current_mapping_.field_mappings.size() * 30.0f + 35.0f)})) {++ ImGui::TableSetupColumn("Target Field", ImGuiTableColumnFlags_None, w * 0.18f);+ ImGui::TableSetupColumn("Source Path", ImGuiTableColumnFlags_None, w * 0.22f);+ ImGui::TableSetupColumn("Parser", ImGuiTableColumnFlags_None, w * 0.10f);+ ImGui::TableSetupColumn("Transform", ImGuiTableColumnFlags_None, w * 0.18f);+ ImGui::TableSetupColumn("Req", ImGuiTableColumnFlags_None, w * 0.06f);+ ImGui::TableSetupColumn("", ImGuiTableColumnFlags_NoResize, 30.0f);+ ImGui::PushStyleColor(ImGuiCol_TableHeaderBg, BG_WIDGET);+ ImGui::TableHeadersRow();+ ImGui::PopStyleColor();++ int to_delete = -1;+ for (size_t i = 0; i < current_mapping_.field_mappings.size(); ++i) {+ auto& fm = current_mapping_.field_mappings[i];+ ImGui::PushID(static_cast<int>(i));+ ImGui::TableNextRow();++ // Target field+ ImGui::TableNextColumn();+ char target_buf[64] = {};+ std::strncpy(target_buf, fm.target_field.c_str(), sizeof(target_buf) - 1);+ ImGui::PushItemWidth(-1);+ if (ImGui::InputText("##target", target_buf, sizeof(target_buf))) {+ fm.target_field = target_buf;+ }+ ImGui::PopItemWidth();++ // Source path+ ImGui::TableNextColumn();+ char source_buf[128] = {};+ std::strncpy(source_buf, fm.source_path.c_str(), sizeof(source_buf) - 1);+ ImGui::PushItemWidth(-1);+ if (ImGui::InputText("##source", source_buf, sizeof(source_buf))) {+ fm.source_path = source_buf;+ }+ ImGui::PopItemWidth();++ // Parser+ ImGui::TableNextColumn();+ static const char* parsers[] = {"Direct", "JSONPath", "Regex"};+ int parser_idx = static_cast<int>(fm.parser);+ ImGui::PushItemWidth(-1);+ if (ImGui::Combo("##parser", &parser_idx, parsers, 3)) {+ fm.parser = static_cast<ParserEngine>(parser_idx);+ }+ ImGui::PopItemWidth();++ // Transform+ ImGui::TableNextColumn();+ ImGui::PushItemWidth(-1);+ char xform_buf[64] = {};+ if (!fm.transforms.empty()) {+ std::strncpy(xform_buf, fm.transforms[0].c_str(), sizeof(xform_buf) - 1);+ }+ if (ImGui::InputTextWithHint("##xform", "e.g. toNumber", xform_buf, sizeof(xform_buf))) {+ if (std::strlen(xform_buf) > 0) {+ if (fm.transforms.empty()) fm.transforms.push_back(xform_buf);+ else fm.transforms[0] = xform_buf;+ } else {+ fm.transforms.clear();+ }+ }+ ImGui::PopItemWidth();++ // Required checkbox+ ImGui::TableNextColumn();+ ImGui::Checkbox("##req", &fm.required);++ // Delete button+ ImGui::TableNextColumn();+ ImGui::PushStyleColor(ImGuiCol_Text, ERROR_RED);+ if (ImGui::SmallButton("X")) to_delete = static_cast<int>(i);+ ImGui::PopStyleColor();++ ImGui::PopID();+ }++ if (to_delete >= 0) {+ current_mapping_.field_mappings.erase(+ current_mapping_.field_mappings.begin() + to_delete);+ }++ ImGui::EndTable();+ }++ // Available transforms reference+ ImGui::Spacing();+ if (ImGui::TreeNodeEx("Available Transforms", ImGuiTreeNodeFlags_None)) {+ const auto transforms = TransformRegistry::all_transforms();+ if (ImGui::BeginTable("##transforms_ref", 3, ImGuiTableFlags_RowBg | ImGuiTableFlags_Borders)) {+ ImGui::TableSetupColumn("Name", ImGuiTableColumnFlags_None, 140);+ ImGui::TableSetupColumn("Description", ImGuiTableColumnFlags_None, 280);+ ImGui::TableSetupColumn("Category", ImGuiTableColumnFlags_None, 80);+ ImGui::PushStyleColor(ImGuiCol_TableHeaderBg, BG_WIDGET);+ ImGui::TableHeadersRow();+ ImGui::PopStyleColor();++ for (const auto& t : transforms) {+ ImGui::TableNextRow();+ ImGui::TableNextColumn();+ ImGui::PushStyleColor(ImGuiCol_Text, ACCENT);+ ImGui::Text("%s", t.name);+ ImGui::PopStyleColor();+ ImGui::TableNextColumn();+ ImGui::PushStyleColor(ImGuiCol_Text, TEXT_DIM);+ ImGui::Text("%s", t.description);+ ImGui::PopStyleColor();+ ImGui::TableNextColumn();+ tag_pill(transform_category_label(t.category), TEXT_SECONDARY);+ }+ ImGui::EndTable();+ }+ ImGui::TreePop();+ }++ card_end();+}++// ============================================================================+// Step 4: Cache & Validation Settings+// ============================================================================++void DataMappingScreen::render_step_cache_settings(float /*w*/, float /*h*/) {+ // === Cache Card ===+ card_begin("##card_cache", "RESPONSE CACHING");++ ImGui::Checkbox("Enable caching", ¤t_mapping_.api_config.cache_enabled);++ if (current_mapping_.api_config.cache_enabled) {+ ImGui::Spacing();+ inline_label("TTL (seconds)", 110);+ ImGui::PushItemWidth(100);+ ImGui::InputInt("##cache_ttl", ¤t_mapping_.api_config.cache_ttl_seconds);+ ImGui::PopItemWidth();++ if (current_mapping_.api_config.cache_ttl_seconds < 0)+ current_mapping_.api_config.cache_ttl_seconds = 0;++ ImGui::PushStyleColor(ImGuiCol_Text, TEXT_DISABLED);+ if (current_mapping_.api_config.cache_ttl_seconds > 0) {+ const int mins = current_mapping_.api_config.cache_ttl_seconds / 60;+ if (mins > 0) ImGui::Text(" = %d min %d sec", mins,+ current_mapping_.api_config.cache_ttl_seconds % 60);+ } else {+ ImGui::Text(" 0 = no caching");+ }+ ImGui::PopStyleColor();+ }++ card_end();++ // === Validation Card ===+ card_begin("##card_validation", "DATA VALIDATION");++ ImGui::Checkbox("Enable validation", ¤t_mapping_.validation.enabled);+ if (current_mapping_.validation.enabled) {+ ImGui::Spacing();+ ImGui::Checkbox("Strict mode (reject records with errors)", ¤t_mapping_.validation.strict_mode);+ ImGui::Spacing();+ ImGui::PushStyleColor(ImGuiCol_Text, TEXT_DIM);+ ImGui::Text("Validates transformed data against the target schema.");+ ImGui::Text("Checks required fields, data types, and value ranges.");+ ImGui::PopStyleColor();+ }++ card_end();++ // === Post-Processing Card ===+ card_begin("##card_postproc", "POST-PROCESSING");++ // Limit+ int limit_val = current_mapping_.post_processing.limit.value_or(0);+ inline_label("Record limit", 110);+ ImGui::PushItemWidth(100);+ if (ImGui::InputInt("##pp_limit", &limit_val)) {+ current_mapping_.post_processing.limit =+ (limit_val > 0) ? std::optional<int>(limit_val) : std::nullopt;+ }+ ImGui::PopItemWidth();++ ImGui::PushStyleColor(ImGuiCol_Text, TEXT_DISABLED);+ ImGui::Text(" 0 = no limit");+ ImGui::PopStyleColor();++ // Sort+ ImGui::Spacing();+ bool has_sort = current_mapping_.post_processing.sort.has_value();+ if (ImGui::Checkbox("Enable sorting", &has_sort)) {+ if (has_sort) current_mapping_.post_processing.sort = SortConfig{"timestamp", false};+ else current_mapping_.post_processing.sort = std::nullopt;+ }+ if (current_mapping_.post_processing.sort) {+ char sort_buf[64] = {};+ std::strncpy(sort_buf, current_mapping_.post_processing.sort->field.c_str(),+ sizeof(sort_buf) - 1);+ inline_label("Sort field", 110);+ ImGui::PushItemWidth(160);+ if (ImGui::InputText("##sort_field", sort_buf, sizeof(sort_buf))) {+ current_mapping_.post_processing.sort->field = sort_buf;+ }+ ImGui::PopItemWidth();+ ImGui::SameLine(0, 10);+ ImGui::Checkbox("Descending", ¤t_mapping_.post_processing.sort->descending);+ }++ // Deduplicate+ ImGui::Spacing();+ bool has_dedup = current_mapping_.post_processing.deduplicate_field.has_value();+ if (ImGui::Checkbox("Deduplicate", &has_dedup)) {+ if (has_dedup) current_mapping_.post_processing.deduplicate_field = "symbol";+ else current_mapping_.post_processing.deduplicate_field = std::nullopt;+ }+ if (current_mapping_.post_processing.deduplicate_field) {+ char dedup_buf[64] = {};+ std::strncpy(dedup_buf, current_mapping_.post_processing.deduplicate_field->c_str(),+ sizeof(dedup_buf) - 1);+ inline_label("Dedup field", 110);+ ImGui::PushItemWidth(160);+ if (ImGui::InputText("##dedup_field", dedup_buf, sizeof(dedup_buf))) {+ current_mapping_.post_processing.deduplicate_field = dedup_buf;+ }+ ImGui::PopItemWidth();+ }++ card_end();+}++// ============================================================================+// Step 5: Test & Save+// ============================================================================++void DataMappingScreen::render_step_test_save(float w, float h) {+ const float input_w = std::min(w * 0.55f, 500.0f);+ const float label_w = 90.0f;++ // === Details Card ===+ card_begin("##card_details", "MAPPING DETAILS");++ inline_label("Name", label_w);+ ImGui::PushItemWidth(input_w);+ ImGui::InputTextWithHint("##map_name", "My API Mapping", mapping_name_buf_, sizeof(mapping_name_buf_));+ ImGui::PopItemWidth();++ inline_label("Description", label_w);+ ImGui::PushItemWidth(input_w);+ ImGui::InputText("##map_desc", mapping_desc_buf_, sizeof(mapping_desc_buf_));+ ImGui::PopItemWidth();++ card_end();++ // === Test Card ===+ card_begin("##card_test", "TEST MAPPING");++ ImGui::PushStyleColor(ImGuiCol_Text, TEXT_DIM);+ ImGui::Text("Paste sample JSON data to test the transformation pipeline:");+ ImGui::PopStyleColor();+ ImGui::Spacing();++ // Sample data input+ static char sample_buf[8192] = {};+ if (!sample_data_json_.empty() && sample_buf[0] == '\0') {+ std::strncpy(sample_buf, sample_data_json_.c_str(),+ std::min<size_t>(sizeof(sample_buf) - 1, sample_data_json_.size()));+ }++ ImGui::PushStyleColor(ImGuiCol_FrameBg, BG_INPUT);+ ImGui::InputTextMultiline("##sample_json", sample_buf, sizeof(sample_buf),+ {std::min(w * 0.75f, 700.0f), 120});+ ImGui::PopStyleColor();++ ImGui::Spacing();++ if (testing_) {+ theme::LoadingSpinner("Running test...");+ } else {+ if (theme::AccentButton("Run Test")) {+ sample_data_json_ = sample_buf;+ start_test();+ }+ }++ // Test results+ if (test_result_) {+ ImGui::Spacing();+ ImGui::Separator();+ ImGui::Spacing();++ if (test_result_->success) {+ ImGui::PushStyleColor(ImGuiCol_Text, SUCCESS);+ ImGui::Text("SUCCESS");+ ImGui::PopStyleColor();+ ImGui::SameLine();+ ImGui::PushStyleColor(ImGuiCol_Text, TEXT_SECONDARY);+ ImGui::Text("— %d records processed, %d returned in %lldms",+ test_result_->records_processed, test_result_->records_returned,+ static_cast<long long>(test_result_->duration_ms));+ ImGui::PopStyleColor();++ ImGui::Spacing();+ render_json_preview("Transformed Output", test_result_->data_json, 180);+ } else {+ ImGui::PushStyleColor(ImGuiCol_Text, ERROR_RED);+ ImGui::Text("FAILED");+ ImGui::PopStyleColor();+ for (const auto& err : test_result_->errors) {+ ImGui::PushStyleColor(ImGuiCol_Text, ERROR_RED);+ ImGui::Bullet();+ ImGui::Text("%s", err.c_str());+ ImGui::PopStyleColor();+ }+ }++ render_validation_results();+ }++ card_end();++ // Save button (prominent, bottom)+ ImGui::Spacing();+ ImGui::Spacing();+ if (theme::AccentButton(editing_existing_ ? "Update Mapping" : "Save Mapping",+ {180, 36})) {+ save_current_mapping();+ }+ ImGui::SameLine(0, 12);+ if (theme::SecondaryButton("Cancel", {100, 36})) {+ view_ = MappingView::list;+ load_mappings();+ }+}++// ============================================================================+// Templates view — card grid with category badges and tag pills+// ============================================================================++void DataMappingScreen::render_templates_view(float w, float /*h*/) {+ ImGui::PushStyleColor(ImGuiCol_Text, TEXT_SECONDARY);+ ImGui::Text("Pre-built mapping configurations for popular brokers and data providers.");+ ImGui::PopStyleColor();+ ImGui::Spacing();++ if (templates_.empty()) {+ ImGui::Spacing();+ ImGui::PushStyleColor(ImGuiCol_Text, TEXT_DIM);+ ImGui::Text("No templates available.");+ ImGui::PopStyleColor();+ return;+ }++ for (size_t i = 0; i < templates_.size(); ++i) {+ const auto& t = templates_[i];++ ImGui::PushID(static_cast<int>(i));++ ImGui::PushStyleColor(ImGuiCol_ChildBg, BG_PANEL);+ ImGui::PushStyleColor(ImGuiCol_Border, BORDER_DIM);+ ImGui::PushStyleVar(ImGuiStyleVar_ChildRounding, 3.0f);+ ImGui::PushStyleVar(ImGuiStyleVar_WindowPadding, {12, 8});+ ImGui::BeginChild("##tmpl_card", {0, 0}, ImGuiChildFlags_AutoResizeY | ImGuiChildFlags_Borders);++ // Row 1: Name + category badge + verified indicator+ ImGui::PushStyleColor(ImGuiCol_Text, TEXT_PRIMARY);+ ImGui::Text("%s", t.name.c_str());+ ImGui::PopStyleColor();++ ImGui::SameLine(w * 0.45f);+ tag_pill(t.category.c_str(), INFO);++ if (t.verified) {+ ImGui::SameLine();+ tag_pill("verified", SUCCESS);+ }+ if (t.official) {+ ImGui::SameLine();+ tag_pill("official", ACCENT);+ }++ // Use button (right-aligned)+ ImGui::SameLine(w * 0.80f);+ if (theme::AccentButton("Use Template")) {+ load_template(t);+ }++ // Row 2: Description+ ImGui::PushStyleColor(ImGuiCol_Text, TEXT_DIM);+ ImGui::Text("%s", t.description.c_str());+ ImGui::PopStyleColor();++ // Row 3: Tags+ if (!t.tags.empty()) {+ for (const auto& tag : t.tags) {+ tag_pill(tag.c_str(), TEXT_SECONDARY);+ ImGui::SameLine(0, 4);+ }+ ImGui::NewLine();+ }++ // Instructions if available+ if (!t.instructions.empty()) {+ ImGui::PushStyleColor(ImGuiCol_Text, TEXT_DISABLED);+ ImGui::Text("Tip: %s", t.instructions.c_str());+ ImGui::PopStyleColor();+ }++ ImGui::EndChild();+ ImGui::PopStyleVar(2);+ ImGui::PopStyleColor(2);++ ImGui::PopID();+ }+}++// ============================================================================+// Footer — stats + keyboard hints+// ============================================================================++void DataMappingScreen::render_footer(float w, float footer_h) {+ const ImGuiViewport* vp = ImGui::GetMainViewport();+ const float chrome_top = ImGui::GetFrameHeight() + 4.0f;+ const float chrome_bot = ImGui::GetFrameHeight();+ const float screen_bottom = vp->WorkPos.y + chrome_top + (vp->WorkSize.y - chrome_top - chrome_bot);+ ImGui::SetNextWindowPos({vp->WorkPos.x, screen_bottom - footer_h});+ ImGui::SetNextWindowSize({w, footer_h});+ ImGui::PushStyleColor(ImGuiCol_WindowBg, BG_DARK);+ ImGui::PushStyleVar(ImGuiStyleVar_WindowPadding, {12, 3});++ ImGui::Begin("##dm_footer", nullptr,+ ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_NoResize | ImGuiWindowFlags_NoMove |+ ImGuiWindowFlags_NoScrollbar | ImGuiWindowFlags_NoDocking);++ ImGui::PushStyleColor(ImGuiCol_Text, TEXT_DISABLED);+ ImGui::Text("DATA MAPPING");+ ImGui::PopStyleColor();++ ImGui::SameLine(160);+ ImGui::PushStyleColor(ImGuiCol_Text, TEXT_DIM);+ ImGui::Text("%d mappings | %d templates | 7 schemas | 19 transforms",+ static_cast<int>(saved_mappings_.size()),+ static_cast<int>(templates_.size()));+ ImGui::PopStyleColor();++ ImGui::End();+ ImGui::PopStyleVar();+ ImGui::PopStyleColor();+}++// ============================================================================+// JSON Preview — syntax-colored read-only display+// ============================================================================++void DataMappingScreen::render_json_preview(const std::string& label,+ const std::string& json_str,+ float height) {+ ImGui::PushStyleColor(ImGuiCol_Text, ACCENT);+ ImGui::Text("%s:", label.c_str());+ ImGui::PopStyleColor();++ ImGui::PushStyleColor(ImGuiCol_FrameBg, BG_INPUT);+ ImGui::PushStyleColor(ImGuiCol_Text, TEXT_PRIMARY);+ const std::string display = (json_str.size() > 4000)+ ? json_str.substr(0, 4000) + "\n... (truncated)"+ : json_str;+ char preview_buf[4096] = {};+ std::strncpy(preview_buf, display.c_str(),+ std::min<size_t>(sizeof(preview_buf) - 1, display.size()));+ ImGui::InputTextMultiline("##json_preview", preview_buf, sizeof(preview_buf),+ {-1, height}, ImGuiInputTextFlags_ReadOnly);+ ImGui::PopStyleColor(2);+}++// ============================================================================+// Validation results — inline colored indicators+// ============================================================================++void DataMappingScreen::render_validation_results() {+ if (!test_result_) return;++ ImGui::Spacing();+ if (test_result_->validation.errors.empty()) {+ ImGui::PushStyleColor(ImGuiCol_Text, SUCCESS);+ ImGui::Text("Validation: PASSED");+ ImGui::PopStyleColor();+ } else {+ ImGui::PushStyleColor(ImGuiCol_Text, ERROR_RED);+ ImGui::Text("Validation: %d error(s)", static_cast<int>(test_result_->validation.errors.size()));+ ImGui::PopStyleColor();+ for (const auto& e : test_result_->validation.errors) {+ ImGui::PushStyleColor(ImGuiCol_Text, ERROR_RED);+ ImGui::Bullet();+ ImGui::Text("[%s] %s: %s", e.rule.c_str(), e.field.c_str(), e.message.c_str());+ ImGui::PopStyleColor();+ }+ }+}++// ============================================================================+// Actions — load, save, delete, test, fetch, edit, template, reset+// ============================================================================++void DataMappingScreen::load_mappings() {+ saved_mappings_ = mapping_ops::get_all_mappings();+}++void DataMappingScreen::save_current_mapping() {+ // Sync form buffers to current_mapping_+ current_mapping_.name = mapping_name_buf_;+ current_mapping_.description = mapping_desc_buf_;+ current_mapping_.api_config.name = api_name_buf_;+ current_mapping_.api_config.description = api_desc_buf_;+ current_mapping_.api_config.base_url = api_base_url_buf_;+ current_mapping_.api_config.endpoint = api_endpoint_buf_;+ current_mapping_.api_config.method = static_cast<HttpMethod>(api_method_idx_);+ current_mapping_.extraction.root_path = root_path_buf_;++ if (std::strlen(api_body_buf_) > 0) {+ current_mapping_.api_config.body = api_body_buf_;+ }++ // Auth+ switch (api_auth_type_idx_) {+ case 0: current_mapping_.api_config.authentication.type = AuthType::none; break;+ case 1: {+ current_mapping_.api_config.authentication.type = AuthType::apikey;+ current_mapping_.api_config.authentication.apikey = ApiKeyConfig{+ auth_key_location_idx_ == 1 ? ApiKeyLocation::query : ApiKeyLocation::header,+ auth_key_name_buf_, auth_key_value_buf_+ };+ break;+ }+ case 2: {+ current_mapping_.api_config.authentication.type = AuthType::bearer;+ current_mapping_.api_config.authentication.bearer = BearerConfig{auth_bearer_buf_};+ break;+ }+ case 3: {+ current_mapping_.api_config.authentication.type = AuthType::basic;+ current_mapping_.api_config.authentication.basic = BasicAuthConfig{+ auth_basic_user_buf_, auth_basic_pass_buf_};+ break;+ }+ default: break;+ }++ // Generate timestamps+ if (current_mapping_.id.empty()) {+ current_mapping_.id = db::generate_uuid();+ }+ if (current_mapping_.api_config.id.empty()) {+ current_mapping_.api_config.id = db::generate_uuid();+ }++ const auto now = std::chrono::system_clock::now();+ const auto tt = std::chrono::system_clock::to_time_t(now);+ std::tm tm_buf{};+#ifdef _WIN32+ gmtime_s(&tm_buf, &tt);+#else+ gmtime_r(&tt, &tm_buf);+#endif+ char time_str[64];+ std::strftime(time_str, sizeof(time_str), "%Y-%m-%dT%H:%M:%SZ", &tm_buf);++ if (current_mapping_.created_at.empty()) {+ current_mapping_.created_at = time_str;+ }+ current_mapping_.updated_at = time_str;++ mapping_ops::save_mapping(current_mapping_);+ load_mappings();+ editing_existing_ = false;+ view_ = MappingView::list;+}++void DataMappingScreen::delete_mapping_by_id(const std::string& id) {+ mapping_ops::delete_mapping(id);+ load_mappings();+}++void DataMappingScreen::start_test() {+ current_mapping_.extraction.root_path = root_path_buf_;++ json sample_json;+ if (!sample_data_json_.empty()) {+ try {+ sample_json = json::parse(sample_data_json_);+ } catch (...) {+ test_result_ = ExecutionResult{};+ test_result_->errors.push_back("Invalid JSON in sample data");+ return;+ }+ }++ testing_ = true;+ test_future_ = std::async(std::launch::async, [this, sample_json]() {+ return engine_.test(current_mapping_, sample_json);+ });+}++void DataMappingScreen::fetch_sample_data() {+ current_mapping_.api_config.base_url = api_base_url_buf_;+ current_mapping_.api_config.endpoint = api_endpoint_buf_;+ current_mapping_.api_config.method = static_cast<HttpMethod>(api_method_idx_);++ fetching_ = true;+ fetch_future_ = std::async(std::launch::async, [this]() {+ return engine_.fetch_api(current_mapping_.api_config);+ });+}++void DataMappingScreen::reset_create_form() {+ current_mapping_ = MappingConfig{};+ current_mapping_.id = db::generate_uuid();+ current_mapping_.api_config.id = db::generate_uuid();+ current_step_ = CreateStep::api_config;+ test_result_ = std::nullopt;+ sample_data_json_.clear();+ editing_existing_ = false;++ std::memset(api_name_buf_, 0, sizeof(api_name_buf_));+ std::memset(api_desc_buf_, 0, sizeof(api_desc_buf_));+ std::memset(api_base_url_buf_, 0, sizeof(api_base_url_buf_));+ std::memset(api_endpoint_buf_, 0, sizeof(api_endpoint_buf_));+ std::memset(api_body_buf_, 0, sizeof(api_body_buf_));+ std::memset(mapping_name_buf_, 0, sizeof(mapping_name_buf_));+ std::memset(mapping_desc_buf_, 0, sizeof(mapping_desc_buf_));+ std::memset(root_path_buf_, 0, sizeof(root_path_buf_));+ std::memset(auth_key_name_buf_, 0, sizeof(auth_key_name_buf_));+ std::memset(auth_key_value_buf_, 0, sizeof(auth_key_value_buf_));+ std::memset(auth_bearer_buf_, 0, sizeof(auth_bearer_buf_));+ std::memset(auth_basic_user_buf_, 0, sizeof(auth_basic_user_buf_));+ std::memset(auth_basic_pass_buf_, 0, sizeof(auth_basic_pass_buf_));++ api_method_idx_ = 0;+ api_auth_type_idx_ = 0;+ schema_type_idx_ = 0;+ parser_engine_idx_ = 0;+}++void DataMappingScreen::edit_mapping(const MappingConfig& config) {+ current_mapping_ = config;+ view_ = MappingView::create;+ current_step_ = CreateStep::api_config;+ editing_existing_ = true;++ std::strncpy(api_name_buf_, config.api_config.name.c_str(), sizeof(api_name_buf_) - 1);+ std::strncpy(api_desc_buf_, config.api_config.description.c_str(), sizeof(api_desc_buf_) - 1);+ std::strncpy(api_base_url_buf_, config.api_config.base_url.c_str(), sizeof(api_base_url_buf_) - 1);+ std::strncpy(api_endpoint_buf_, config.api_config.endpoint.c_str(), sizeof(api_endpoint_buf_) - 1);+ std::strncpy(mapping_name_buf_, config.name.c_str(), sizeof(mapping_name_buf_) - 1);+ std::strncpy(mapping_desc_buf_, config.description.c_str(), sizeof(mapping_desc_buf_) - 1);+ std::strncpy(root_path_buf_, config.extraction.root_path.c_str(), sizeof(root_path_buf_) - 1);++ api_method_idx_ = static_cast<int>(config.api_config.method);+ api_auth_type_idx_ = static_cast<int>(config.api_config.authentication.type);+ schema_type_idx_ = static_cast<int>(config.schema_type);++ if (config.api_config.body) {+ std::strncpy(api_body_buf_, config.api_config.body->c_str(), sizeof(api_body_buf_) - 1);+ }++ // Auth details+ if (config.api_config.authentication.apikey) {+ const auto& ak = *config.api_config.authentication.apikey;+ std::strncpy(auth_key_name_buf_, ak.key_name.c_str(), sizeof(auth_key_name_buf_) - 1);+ std::strncpy(auth_key_value_buf_, ak.value.c_str(), sizeof(auth_key_value_buf_) - 1);+ auth_key_location_idx_ = (ak.location == ApiKeyLocation::query) ? 1 : 0;+ }+ if (config.api_config.authentication.bearer) {+ std::strncpy(auth_bearer_buf_, config.api_config.authentication.bearer->token.c_str(),+ sizeof(auth_bearer_buf_) - 1);+ }+ if (config.api_config.authentication.basic) {+ std::strncpy(auth_basic_user_buf_, config.api_config.authentication.basic->username.c_str(),+ sizeof(auth_basic_user_buf_) - 1);+ std::strncpy(auth_basic_pass_buf_, config.api_config.authentication.basic->password.c_str(),+ sizeof(auth_basic_pass_buf_) - 1);+ }+}++void DataMappingScreen::load_template(const MappingTemplate& tmpl) {+ reset_create_form();+ current_mapping_ = tmpl.config;+ current_mapping_.id = db::generate_uuid();+ current_mapping_.api_config.id = db::generate_uuid();++ std::strncpy(mapping_name_buf_, tmpl.config.name.c_str(), sizeof(mapping_name_buf_) - 1);+ std::strncpy(mapping_desc_buf_, tmpl.config.description.c_str(), sizeof(mapping_desc_buf_) - 1);+ std::strncpy(api_name_buf_, tmpl.config.api_config.name.c_str(), sizeof(api_name_buf_) - 1);+ std::strncpy(api_base_url_buf_, tmpl.config.api_config.base_url.c_str(), sizeof(api_base_url_buf_) - 1);+ std::strncpy(api_endpoint_buf_, tmpl.config.api_config.endpoint.c_str(), sizeof(api_endpoint_buf_) - 1);+ std::strncpy(root_path_buf_, tmpl.config.extraction.root_path.c_str(), sizeof(root_path_buf_) - 1);++ api_method_idx_ = static_cast<int>(tmpl.config.api_config.method);+ schema_type_idx_ = static_cast<int>(tmpl.config.schema_type);++ view_ = MappingView::create;+ current_step_ = CreateStep::api_config;+}++// ============================================================================+// Template loader — built-in broker templates+// ============================================================================++void DataMappingScreen::load_templates() {+ templates_.clear();++ // Upstox Historical OHLCV+ {+ MappingTemplate t;+ t.id = "upstox_historical_ohlcv";+ t.name = "Upstox Historical Candles -> OHLCV";+ t.description = "Map Upstox historical candle data to standard OHLCV format";+ t.category = "broker";+ t.tags = {"upstox", "historical", "ohlcv", "india"};+ t.verified = true;+ t.official = true;++ t.config.name = "Upstox Historical -> OHLCV";+ t.config.description = "Transform Upstox historical candle data";+ t.config.is_predefined_schema = true;+ t.config.schema_type = SchemaType::ohlcv;+ t.config.extraction.engine = ParserEngine::direct;+ t.config.extraction.root_path = "data.candles";+ t.config.extraction.is_array = true;+ t.config.extraction.is_array_of_arrays = true;++ t.config.field_mappings = {+ {"timestamp", FieldSourceType::path, "$[0]", "", ParserEngine::direct, {"toISODate"}, {}, true, 0.0f},+ {"open", FieldSourceType::path, "$[1]", "", ParserEngine::direct, {}, {}, true, 0.0f},+ {"high", FieldSourceType::path, "$[2]", "", ParserEngine::direct, {}, {}, true, 0.0f},+ {"low", FieldSourceType::path, "$[3]", "", ParserEngine::direct, {}, {}, true, 0.0f},+ {"close", FieldSourceType::path, "$[4]", "", ParserEngine::direct, {}, {}, true, 0.0f},+ {"volume", FieldSourceType::path, "$[5]", "", ParserEngine::direct, {}, {}, true, 0.0f},+ };+ t.config.validation.enabled = true;+ t.instructions = "Use endpoint: /historical-candle/{instrument_key}/{interval}/{to_date}/{from_date}";+ templates_.push_back(t);+ }++ // Fyers Quotes+ {+ MappingTemplate t;+ t.id = "fyers_quotes";+ t.name = "Fyers Quotes -> QUOTE";+ t.description = "Map Fyers quote data to standard QUOTE format";+ t.category = "broker";+ t.tags = {"fyers", "quote", "india"};+ t.verified = true;+ t.official = true;++ t.config.name = "Fyers Quote -> QUOTE";+ t.config.is_predefined_schema = true;+ t.config.schema_type = SchemaType::quote;+ t.config.extraction.root_path = "d";+ t.config.extraction.is_array = true;++ t.config.field_mappings = {+ {"symbol", FieldSourceType::path, "n", "", ParserEngine::direct, {}, {}, true, 0.0f},+ {"timestamp", FieldSourceType::path, "v.tt", "", ParserEngine::direct, {"toISODate"}, {}, true, 0.0f},+ {"price", FieldSourceType::path, "v.lp", "", ParserEngine::direct, {}, {}, true, 0.0f},+ {"bid", FieldSourceType::path, "v.bid", "", ParserEngine::direct, {}, {}, false, 0.0f},+ {"ask", FieldSourceType::path, "v.ask", "", ParserEngine::direct, {}, {}, false, 0.0f},+ {"volume", FieldSourceType::path, "v.volume", "", ParserEngine::direct, {}, {}, false, 0.0f},+ {"open", FieldSourceType::path, "v.open_price", "", ParserEngine::direct, {}, {}, false, 0.0f},+ {"high", FieldSourceType::path, "v.high_price", "", ParserEngine::direct, {}, {}, false, 0.0f},+ {"low", FieldSourceType::path, "v.low_price", "", ParserEngine::direct, {}, {}, false, 0.0f},+ {"previousClose", FieldSourceType::path, "v.prev_close_price", "", ParserEngine::direct, {}, {}, false, 0.0f},+ {"change", FieldSourceType::path, "v.ch", "", ParserEngine::direct, {}, {}, false, 0.0f},+ {"changePercent", FieldSourceType::path, "v.chp", "", ParserEngine::direct, {}, {}, false, 0.0f},+ };+ t.config.validation.enabled = true;+ t.instructions = "Use endpoint: /data/quotes with POST method and symbols in body";+ templates_.push_back(t);+ }++ // Fyers Positions+ {+ MappingTemplate t;+ t.id = "fyers_positions";+ t.name = "Fyers Positions -> POSITION";+ t.description = "Map Fyers position data to standard POSITION format";+ t.category = "broker";+ t.tags = {"fyers", "position", "india"};+ t.verified = true;+ t.official = true;++ t.config.name = "Fyers Position -> POSITION";+ t.config.is_predefined_schema = true;+ t.config.schema_type = SchemaType::position;+ t.config.extraction.root_path = "netPositions";+ t.config.extraction.is_array = true;++ t.config.field_mappings = {+ {"symbol", FieldSourceType::path, "symbol", "", ParserEngine::direct, {}, {}, true, 0.0f},+ {"quantity", FieldSourceType::path, "netQty", "", ParserEngine::direct, {}, {}, true, 0.0f},+ {"averagePrice", FieldSourceType::path, "avgPrice", "", ParserEngine::direct, {}, {}, true, 0.0f},+ {"currentPrice", FieldSourceType::path, "ltp", "", ParserEngine::direct, {}, {}, true, 0.0f},+ {"pnl", FieldSourceType::path, "pl", "", ParserEngine::direct, {}, {}, true, 0.0f},+ {"pnlPercent", FieldSourceType::path, "plPercent", "", ParserEngine::direct, {}, {}, true, 0.0f},+ {"productType", FieldSourceType::path, "productType", "", ParserEngine::direct, {"uppercase"}, {}, false, 0.0f},+ };+ t.config.validation.enabled = true;+ templates_.push_back(t);+ }++ // Dhan Positions+ {+ MappingTemplate t;+ t.id = "dhan_positions";+ t.name = "Dhan Positions -> POSITION";+ t.description = "Map Dhan position data to standard POSITION format";+ t.category = "broker";+ t.tags = {"dhan", "position", "india"};+ t.verified = true;+ t.official = true;++ t.config.name = "Dhan Position -> POSITION";+ t.config.is_predefined_schema = true;+ t.config.schema_type = SchemaType::position;+ t.config.extraction.root_path = "data";+ t.config.extraction.is_array = true;++ t.config.field_mappings = {+ {"symbol", FieldSourceType::path, "tradingSymbol", "", ParserEngine::direct, {}, {}, true, 0.0f},+ {"quantity", FieldSourceType::path, "netQty", "", ParserEngine::direct, {}, {}, true, 0.0f},+ {"averagePrice", FieldSourceType::path, "costPrice", "", ParserEngine::direct, {}, {}, true, 0.0f},+ {"currentPrice", FieldSourceType::path, "ltp", "", ParserEngine::direct, {}, {}, true, 0.0f},+ {"pnl", FieldSourceType::path, "realizedProfit", "", ParserEngine::direct, {}, {}, true, 0.0f},+ {"exchange", FieldSourceType::path, "exchangeSegment", "", ParserEngine::direct, {}, {}, false, 0.0f},+ };+ t.config.validation.enabled = true;+ templates_.push_back(t);+ }++ // Dhan Orders+ {+ MappingTemplate t;+ t.id = "dhan_orders";+ t.name = "Dhan Orders -> ORDER";+ t.description = "Map Dhan order data to standard ORDER format";+ t.category = "broker";+ t.tags = {"dhan", "order", "india"};+ t.verified = true;+ t.official = true;++ t.config.name = "Dhan Order -> ORDER";+ t.config.is_predefined_schema = true;+ t.config.schema_type = SchemaType::order;+ t.config.extraction.root_path = "data";+ t.config.extraction.is_array = true;++ t.config.field_mappings = {+ {"orderId", FieldSourceType::path, "orderId", "", ParserEngine::direct, {}, {}, true, 0.0f},+ {"symbol", FieldSourceType::path, "tradingSymbol", "", ParserEngine::direct, {}, {}, true, 0.0f},+ {"side", FieldSourceType::path, "transactionType", "", ParserEngine::direct, {"uppercase"}, {}, true, 0.0f},+ {"type", FieldSourceType::path, "orderType", "", ParserEngine::direct, {"uppercase"}, {}, true, 0.0f},+ {"quantity", FieldSourceType::path, "quantity", "", ParserEngine::direct, {}, {}, true, 0.0f},+ {"filledQuantity", FieldSourceType::path, "tradedQuantity", "", ParserEngine::direct, {}, {}, false, 0.0f},+ {"price", FieldSourceType::path, "price", "", ParserEngine::direct, {}, {}, false, 0.0f},+ {"averagePrice", FieldSourceType::path, "tradedPrice", "", ParserEngine::direct, {}, {}, false, 0.0f},+ {"status", FieldSourceType::path, "orderStatus", "", ParserEngine::direct, {"uppercase"}, {}, true, 0.0f},+ {"timestamp", FieldSourceType::path, "createTime", "", ParserEngine::direct, {"toISODate"}, {}, true, 0.0f},+ {"exchange", FieldSourceType::path, "exchangeSegment", "", ParserEngine::direct, {}, {}, false, 0.0f},+ };+ t.config.validation.enabled = true;+ templates_.push_back(t);+ }++ // Zerodha OHLC+ {+ MappingTemplate t;+ t.id = "zerodha_ohlc";+ t.name = "Zerodha OHLC -> OHLCV";+ t.description = "Map Zerodha/Kite OHLC data to standard OHLCV format";+ t.category = "broker";+ t.tags = {"zerodha", "kite", "ohlc", "india"};+ t.verified = true;++ t.config.name = "Zerodha OHLC -> OHLCV";+ t.config.is_predefined_schema = true;+ t.config.schema_type = SchemaType::ohlcv;+ t.config.extraction.root_path = "data";+ t.config.extraction.is_array = false;++ t.config.field_mappings = {+ {"open", FieldSourceType::path, "ohlc.open", "", ParserEngine::direct, {}, {}, true, 0.0f},+ {"high", FieldSourceType::path, "ohlc.high", "", ParserEngine::direct, {}, {}, true, 0.0f},+ {"low", FieldSourceType::path, "ohlc.low", "", ParserEngine::direct, {}, {}, true, 0.0f},+ {"close", FieldSourceType::path, "last_price", "", ParserEngine::direct, {}, {}, true, 0.0f},+ {"volume", FieldSourceType::path, "volume", "", ParserEngine::direct, {}, {}, true, 0.0f},+ };+ t.config.validation.enabled = true;+ t.instructions = "Use endpoint: /quote/ohlc with query params i=NSE:SBIN&i=NSE:RELIANCE";+ templates_.push_back(t);+ }+}++} // namespace fincept::data_mappingdiff --git a/fincept-cpp/src/screens/data_mapping/dm_screen.cpp b/fincept-cpp/src/screens/data_mapping/dm_screen.cppnew file mode 100644index 000000000..42576f9c8--- /dev/null+++ b/fincept-cpp/src/screens/data_mapping/dm_screen.cpp@@ -0,0 +1,634 @@+#include "data_mapping_screen.h"+#include "data_mapping_schemas.h"+#include "ui/theme.h"+#include "storage/database.h"+#include "core/logger.h"+#include <imgui.h>+#include <nlohmann/json.hpp>+#include <algorithm>+#include <cstring>+#include <chrono>+#include <cmath>++namespace fincept::data_mapping {++using json = nlohmann::json;+using namespace theme::colors;++using json = nlohmann::json;+using namespace theme::colors;++// Step definitions+static constexpr CreateStep ALL_STEPS[] = {+ CreateStep::api_config, CreateStep::schema_select,+ CreateStep::field_mapping, CreateStep::cache_settings,+ CreateStep::test_save+};+static constexpr int NUM_STEPS = 5;++// Method colors for badges+static ImVec4 method_color(HttpMethod m) {+ switch (m) {+ case HttpMethod::get: return SUCCESS;+ case HttpMethod::post: return INFO;+ case HttpMethod::put: return WARNING;+ case HttpMethod::del: return ERROR_RED;+ case HttpMethod::patch: return {0.70f, 0.50f, 0.90f, 1.0f};+ }+ return TEXT_DIM;+}++// Schema colors for badges+static ImVec4 schema_color(SchemaType t) {+ switch (t) {+ case SchemaType::ohlcv: return {0.30f, 0.70f, 1.00f, 1.0f};+ case SchemaType::quote: return {0.40f, 0.85f, 0.55f, 1.0f};+ case SchemaType::tick: return {0.90f, 0.60f, 0.20f, 1.0f};+ case SchemaType::order: return {0.80f, 0.40f, 0.80f, 1.0f};+ case SchemaType::position: return {0.50f, 0.80f, 0.90f, 1.0f};+ case SchemaType::portfolio: return {0.90f, 0.75f, 0.30f, 1.0f};+ case SchemaType::instrument: return {0.65f, 0.65f, 0.80f, 1.0f};+ }+ return TEXT_DIM;+}++// ============================================================================+// UI Helpers — reusable card/badge/label components+// ============================================================================++bool DataMappingScreen::card_begin(const char* id, const char* title, float w) {+ ImGui::PushStyleColor(ImGuiCol_ChildBg, BG_WIDGET);+ ImGui::PushStyleColor(ImGuiCol_Border, BORDER_DIM);+ ImGui::PushStyleVar(ImGuiStyleVar_ChildRounding, 3.0f);+ ImGui::PushStyleVar(ImGuiStyleVar_WindowPadding, {10, 8});++ const float card_w = (w > 0) ? w : ImGui::GetContentRegionAvail().x;+ ImGui::BeginChild(id, {card_w, 0}, ImGuiChildFlags_AutoResizeY | ImGuiChildFlags_Borders);++ // Card title with accent underline+ if (title && title[0] != '\0') {+ ImGui::PushStyleColor(ImGuiCol_Text, ACCENT);+ ImGui::Text("%s", title);+ ImGui::PopStyleColor();++ // Orange accent line under title+ const ImVec2 p = ImGui::GetCursorScreenPos();+ ImGui::GetWindowDrawList()->AddLine(+ {p.x, p.y}, {p.x + card_w - 20, p.y},+ ImGui::ColorConvertFloat4ToU32({ACCENT.x, ACCENT.y, ACCENT.z, 0.4f}), 1.0f);+ ImGui::Spacing();+ }+ return true;+}++void DataMappingScreen::card_end() {+ ImGui::EndChild();+ ImGui::PopStyleVar(2);+ ImGui::PopStyleColor(2);+ ImGui::Spacing();+}++void DataMappingScreen::method_badge(HttpMethod method) {+ const ImVec4 col = method_color(method);+ const char* label = http_method_label(method);++ ImGui::PushStyleColor(ImGuiCol_Button, {col.x, col.y, col.z, 0.20f});+ ImGui::PushStyleColor(ImGuiCol_ButtonHovered, {col.x, col.y, col.z, 0.30f});+ ImGui::PushStyleColor(ImGuiCol_Text, col);+ ImGui::PushStyleVar(ImGuiStyleVar_FramePadding, {6, 2});+ ImGui::PushStyleVar(ImGuiStyleVar_FrameRounding, 3.0f);+ ImGui::SmallButton(label);+ ImGui::PopStyleVar(2);+ ImGui::PopStyleColor(3);+}++void DataMappingScreen::schema_badge(SchemaType type) {+ const ImVec4 col = schema_color(type);+ const char* label = schema_type_id(type);++ ImGui::PushStyleColor(ImGuiCol_Button, {col.x, col.y, col.z, 0.18f});+ ImGui::PushStyleColor(ImGuiCol_ButtonHovered, {col.x, col.y, col.z, 0.28f});+ ImGui::PushStyleColor(ImGuiCol_Text, col);+ ImGui::PushStyleVar(ImGuiStyleVar_FramePadding, {8, 2});+ ImGui::PushStyleVar(ImGuiStyleVar_FrameRounding, 10.0f);+ ImGui::SmallButton(label);+ ImGui::PopStyleVar(2);+ ImGui::PopStyleColor(3);+}++void DataMappingScreen::tag_pill(const char* text, const ImVec4& color) {+ ImGui::PushStyleColor(ImGuiCol_Button, {color.x, color.y, color.z, 0.12f});+ ImGui::PushStyleColor(ImGuiCol_ButtonHovered, {color.x, color.y, color.z, 0.20f});+ ImGui::PushStyleColor(ImGuiCol_Text, {color.x, color.y, color.z, 0.85f});+ ImGui::PushStyleVar(ImGuiStyleVar_FramePadding, {5, 1});+ ImGui::PushStyleVar(ImGuiStyleVar_FrameRounding, 8.0f);+ ImGui::SmallButton(text);+ ImGui::PopStyleVar(2);+ ImGui::PopStyleColor(3);+}++void DataMappingScreen::inline_label(const char* label, float label_w) {+ ImGui::PushStyleColor(ImGuiCol_Text, TEXT_SECONDARY);+ ImGui::Text("%s", label);+ ImGui::PopStyleColor();+ ImGui::SameLine(label_w);+}++// ============================================================================+// Initialization+// ============================================================================++void DataMappingScreen::init() {+ if (initialized_) return;+ mapping_ops::initialize_tables();+ load_mappings();+ load_templates();+ reset_create_form();+ initialized_ = true;+}++// ============================================================================+// Main render — 2-panel layout+// ============================================================================++void DataMappingScreen::render() {+ init();++ // Check async operations+ if (testing_ && test_future_.valid() &&+ test_future_.wait_for(std::chrono::milliseconds(0)) == std::future_status::ready) {+ test_result_ = test_future_.get();+ testing_ = false;+ }+ if (fetching_ && fetch_future_.valid() &&+ fetch_future_.wait_for(std::chrono::milliseconds(0)) == std::future_status::ready) {+ const auto response = fetch_future_.get();+ fetching_ = false;+ if (response.success) {+ sample_data_json_ = response.data_json;+ }+ }++ const ImGuiViewport* vp = ImGui::GetMainViewport();+ // Account for app chrome (menu bar + tab bar at top, app footer at bottom)+ const float chrome_top = ImGui::GetFrameHeight() + 4.0f;+ const float chrome_bot = ImGui::GetFrameHeight();+ const float ox = vp->WorkPos.x;+ const float oy = vp->WorkPos.y + chrome_top;+ const float w = vp->WorkSize.x;+ const float h = vp->WorkSize.y - chrome_top - chrome_bot;++ // Background+ ImGui::GetWindowDrawList()->AddRectFilled(+ {ox, oy}, {ox + w, oy + h},+ ImGui::ColorConvertFloat4ToU32(BG_DARKEST));++ // Layout: command bar (top) | sidebar + content | footer+ const float cmd_h = 32.0f;+ const float footer_h = 24.0f;+ const float sidebar_w = sidebar_minimized_ ? 36.0f : 220.0f;+ const float content_x = ox + sidebar_w;+ const float content_y = oy + cmd_h;+ const float content_w = w - sidebar_w;+ const float content_h = h - cmd_h - footer_h;++ render_command_bar(w);+ render_sidebar(ox, content_y, sidebar_w, content_h);+ render_content(content_x, content_y, content_w, content_h);+ render_footer(w, footer_h);+}++// ============================================================================+// Command bar — top navigation with view tabs and search+// ============================================================================++void DataMappingScreen::render_command_bar(float w) {+ const ImGuiViewport* vp = ImGui::GetMainViewport();+ const float chrome_top = ImGui::GetFrameHeight() + 4.0f;+ ImGui::SetNextWindowPos({vp->WorkPos.x, vp->WorkPos.y + chrome_top});+ ImGui::SetNextWindowSize({w, 32.0f});+ ImGui::PushStyleColor(ImGuiCol_WindowBg, BG_DARK);+ ImGui::PushStyleVar(ImGuiStyleVar_WindowPadding, {12, 6});++ ImGui::Begin("##dm_cmdbar", nullptr,+ ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_NoResize | ImGuiWindowFlags_NoMove |+ ImGuiWindowFlags_NoScrollbar | ImGuiWindowFlags_NoDocking);++ // Title+ ImGui::PushStyleColor(ImGuiCol_Text, ACCENT);+ ImGui::Text("DATA MAPPING");+ ImGui::PopStyleColor();++ // View tabs — styled like proper tab buttons+ ImGui::SameLine(170);++ auto tab_button = [&](const char* label, MappingView target_view) {+ const bool active = (view_ == target_view);+ if (active) {+ ImGui::PushStyleColor(ImGuiCol_Button, ACCENT_BG);+ ImGui::PushStyleColor(ImGuiCol_Text, ACCENT);+ } else {+ ImGui::PushStyleColor(ImGuiCol_Button, {0, 0, 0, 0});+ ImGui::PushStyleColor(ImGuiCol_Text, TEXT_SECONDARY);+ }+ ImGui::PushStyleVar(ImGuiStyleVar_FramePadding, {10, 3});+ ImGui::PushStyleVar(ImGuiStyleVar_FrameRounding, 3.0f);+ if (ImGui::Button(label)) {+ view_ = target_view;+ if (target_view == MappingView::list) load_mappings();+ if (target_view == MappingView::create) reset_create_form();+ }+ ImGui::PopStyleVar(2);+ ImGui::PopStyleColor(2);+ ImGui::SameLine();+ };++ tab_button("Mappings", MappingView::list);+ tab_button("+ New", MappingView::create);+ tab_button("Templates", MappingView::templates);++ // Search bar (right-aligned)+ const float search_w = 220.0f;+ ImGui::SameLine(w - search_w - 16);+ ImGui::PushItemWidth(search_w);+ ImGui::PushStyleColor(ImGuiCol_FrameBg, BG_INPUT);+ ImGui::PushStyleVar(ImGuiStyleVar_FrameRounding, 3.0f);+ ImGui::InputTextWithHint("##dm_search", "Search mappings...", search_buf_, sizeof(search_buf_));+ ImGui::PopStyleVar();+ ImGui::PopStyleColor();+ ImGui::PopItemWidth();++ ImGui::End();+ ImGui::PopStyleVar();+ ImGui::PopStyleColor();+}++// ============================================================================+// Sidebar — context-sensitive: stats/filter in list, config summary in create+// ============================================================================++void DataMappingScreen::render_sidebar(float x, float y, float w, float h) {+ ImGui::SetNextWindowPos({x, y});+ ImGui::SetNextWindowSize({w, h});+ ImGui::PushStyleColor(ImGuiCol_WindowBg, BG_PANEL);+ ImGui::PushStyleVar(ImGuiStyleVar_WindowPadding, {8, 8});++ ImGui::Begin("##dm_sidebar", nullptr,+ ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_NoResize | ImGuiWindowFlags_NoMove |+ ImGuiWindowFlags_NoDocking);++ // Collapse toggle+ if (sidebar_minimized_) {+ if (ImGui::Button(">", {20, 20})) sidebar_minimized_ = false;+ ImGui::End();+ ImGui::PopStyleVar();+ ImGui::PopStyleColor();+ return;+ }++ ImGui::PushStyleColor(ImGuiCol_Text, TEXT_DIM);+ if (ImGui::Button("<", {20, 20})) sidebar_minimized_ = true;+ ImGui::PopStyleColor();++ ImGui::Spacing();++ if (view_ == MappingView::create) {+ // ---- Create mode: config summary ----+ theme::SectionHeader("CONFIG SUMMARY");+ ImGui::Spacing();++ // Live URL preview+ if (api_base_url_buf_[0] != '\0') {+ ImGui::PushStyleColor(ImGuiCol_Text, TEXT_DIM);+ ImGui::Text("URL");+ ImGui::PopStyleColor();+ ImGui::PushStyleColor(ImGuiCol_Text, INFO);+ ImGui::TextWrapped("%s%s", api_base_url_buf_, api_endpoint_buf_);+ ImGui::PopStyleColor();+ ImGui::Spacing();+ }++ // Method badge+ if (api_base_url_buf_[0] != '\0') {+ ImGui::PushStyleColor(ImGuiCol_Text, TEXT_DIM);+ ImGui::Text("Method");+ ImGui::PopStyleColor();+ ImGui::SameLine(70);+ method_badge(static_cast<HttpMethod>(api_method_idx_));+ ImGui::Spacing();+ }++ // Schema badge+ ImGui::PushStyleColor(ImGuiCol_Text, TEXT_DIM);+ ImGui::Text("Schema");+ ImGui::PopStyleColor();+ ImGui::SameLine(70);+ if (current_mapping_.is_predefined_schema) {+ schema_badge(current_mapping_.schema_type);+ } else {+ ImGui::PushStyleColor(ImGuiCol_Text, TEXT_SECONDARY);+ ImGui::Text("Custom");+ ImGui::PopStyleColor();+ }++ ImGui::Spacing();++ // Field count+ ImGui::PushStyleColor(ImGuiCol_Text, TEXT_DIM);+ ImGui::Text("Fields");+ ImGui::PopStyleColor();+ ImGui::SameLine(70);+ ImGui::PushStyleColor(ImGuiCol_Text, TEXT_PRIMARY);+ ImGui::Text("%d", static_cast<int>(current_mapping_.field_mappings.size()));+ ImGui::PopStyleColor();++ // Sample data status+ ImGui::Spacing();+ if (!sample_data_json_.empty()) {+ theme::StatusIndicator("Sample data loaded", true);+ } else {+ theme::StatusIndicator("No sample data", false);+ }++ // Test status+ if (test_result_) {+ theme::StatusIndicator(+ test_result_->success ? "Last test: PASSED" : "Last test: FAILED",+ test_result_->success);+ }++ ImGui::Spacing();+ ImGui::Separator();+ ImGui::Spacing();++ // Navigation buttons+ const int step_idx = static_cast<int>(current_step_);+ if (step_idx > 0) {+ if (theme::SecondaryButton("< Back", {w - 20, 0})) {+ current_step_ = ALL_STEPS[step_idx - 1];+ }+ ImGui::Spacing();+ }+ if (step_idx < NUM_STEPS - 1) {+ if (theme::AccentButton("Next >", {w - 20, 0})) {+ current_step_ = ALL_STEPS[step_idx + 1];+ }+ }++ } else {+ // ---- List/Templates mode: overview + schema filter ----+ theme::SectionHeader("OVERVIEW");+ ImGui::Spacing();++ // Stats+ ImGui::PushStyleColor(ImGuiCol_Text, TEXT_PRIMARY);+ ImGui::Text("%d", static_cast<int>(saved_mappings_.size()));+ ImGui::PopStyleColor();+ ImGui::SameLine();+ ImGui::PushStyleColor(ImGuiCol_Text, TEXT_DIM);+ ImGui::Text("mappings saved");+ ImGui::PopStyleColor();++ ImGui::PushStyleColor(ImGuiCol_Text, TEXT_PRIMARY);+ ImGui::Text("%d", static_cast<int>(templates_.size()));+ ImGui::PopStyleColor();+ ImGui::SameLine();+ ImGui::PushStyleColor(ImGuiCol_Text, TEXT_DIM);+ ImGui::Text("templates available");+ ImGui::PopStyleColor();++ ImGui::Spacing();+ ImGui::Separator();+ ImGui::Spacing();++ // Schema filter (clickable)+ theme::SectionHeader("FILTER BY SCHEMA");+ ImGui::Spacing();++ // "All" option+ {+ const bool selected = (filter_schema_idx_ == -1);+ if (selected) ImGui::PushStyleColor(ImGuiCol_Text, ACCENT);+ else ImGui::PushStyleColor(ImGuiCol_Text, TEXT_SECONDARY);++ if (ImGui::Selectable(" All", selected)) filter_schema_idx_ = -1;+ ImGui::PopStyleColor();+ }++ const auto schema_names = get_schema_type_names();+ for (int i = 0; i < static_cast<int>(schema_names.size()); ++i) {+ int count = 0;+ for (const auto& m : saved_mappings_) {+ if (m.is_predefined_schema &&+ schema_type_id(m.schema_type) == schema_names[static_cast<size_t>(i)]) {+ ++count;+ }+ }++ const bool selected = (filter_schema_idx_ == i);+ if (selected) ImGui::PushStyleColor(ImGuiCol_Text, ACCENT);+ else if (count > 0) ImGui::PushStyleColor(ImGuiCol_Text, TEXT_PRIMARY);+ else ImGui::PushStyleColor(ImGuiCol_Text, TEXT_DISABLED);++ char label[64];+ std::snprintf(label, sizeof(label), " %s (%d)", schema_names[static_cast<size_t>(i)].c_str(), count);+ if (ImGui::Selectable(label, selected)) {+ filter_schema_idx_ = selected ? -1 : i;+ }+ ImGui::PopStyleColor();+ }++ ImGui::Spacing();+ ImGui::Separator();+ ImGui::Spacing();++ // Quick actions+ if (theme::AccentButton("+ New Mapping", {w - 20, 0})) {+ view_ = MappingView::create;+ reset_create_form();+ }+ }++ ImGui::End();+ ImGui::PopStyleVar();+ ImGui::PopStyleColor();+}++// ============================================================================+// Main content area+// ============================================================================++void DataMappingScreen::render_content(float x, float y, float w, float h) {+ ImGui::SetNextWindowPos({x, y});+ ImGui::SetNextWindowSize({w, h});+ ImGui::PushStyleColor(ImGuiCol_WindowBg, BG_DARKEST);+ ImGui::PushStyleVar(ImGuiStyleVar_WindowPadding, {12, 10});++ ImGui::Begin("##dm_content", nullptr,+ ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_NoResize | ImGuiWindowFlags_NoMove |+ ImGuiWindowFlags_NoDocking);++ switch (view_) {+ case MappingView::list: render_list_view(w, h); break;+ case MappingView::create: render_create_view(w, h); break;+ case MappingView::templates: render_templates_view(w, h); break;+ }++ ImGui::End();+ ImGui::PopStyleVar();+ ImGui::PopStyleColor();+}++// ============================================================================+// List View — card-style rows with badges, method tags, inline actions+// ============================================================================++void DataMappingScreen::render_list_view(float w, float /*h*/) {+ if (saved_mappings_.empty()) {+ // Empty state+ ImGui::Spacing();+ ImGui::Spacing();+ ImGui::PushStyleColor(ImGuiCol_Text, TEXT_DIM);+ ImGui::SetCursorPosX((w - 300) * 0.5f);+ ImGui::Text("No mappings configured yet.");+ ImGui::PopStyleColor();+ ImGui::Spacing();+ ImGui::SetCursorPosX((w - 160) * 0.5f);+ if (theme::AccentButton("Create First Mapping")) {+ view_ = MappingView::create;+ reset_create_form();+ }+ return;+ }++ const std::string filter(search_buf_);+ const auto schema_names = get_schema_type_names();++ // Count visible items for header+ int visible_count = 0;++ for (size_t i = 0; i < saved_mappings_.size(); ++i) {+ const auto& m = saved_mappings_[i];++ // Search filter+ if (!filter.empty()) {+ std::string name_lower = m.name;+ std::transform(name_lower.begin(), name_lower.end(), name_lower.begin(),+ [](unsigned char c) { return std::tolower(c); });+ std::string filter_lower = filter;+ std::transform(filter_lower.begin(), filter_lower.end(),+ filter_lower.begin(), [](unsigned char c) { return std::tolower(c); });+ if (name_lower.find(filter_lower) == std::string::npos) continue;+ }++ // Schema filter+ if (filter_schema_idx_ >= 0 && m.is_predefined_schema) {+ if (schema_type_id(m.schema_type) !=+ schema_names[static_cast<size_t>(filter_schema_idx_)]) continue;+ }++ visible_count++;++ // Card for each mapping+ ImGui::PushID(static_cast<int>(i));++ ImGui::PushStyleColor(ImGuiCol_ChildBg, BG_PANEL);+ ImGui::PushStyleColor(ImGuiCol_Border, BORDER_DIM);+ ImGui::PushStyleVar(ImGuiStyleVar_ChildRounding, 3.0f);+ ImGui::PushStyleVar(ImGuiStyleVar_WindowPadding, {10, 8});+ ImGui::BeginChild("##map_card", {0, 0}, ImGuiChildFlags_AutoResizeY | ImGuiChildFlags_Borders);++ // Row 1: Name + Schema badge + Method badge+ ImGui::PushStyleColor(ImGuiCol_Text, TEXT_PRIMARY);+ ImGui::Text("%s", m.name.c_str());+ ImGui::PopStyleColor();++ ImGui::SameLine(w * 0.35f);+ if (m.is_predefined_schema) {+ schema_badge(m.schema_type);+ } else {+ tag_pill("Custom", TEXT_DIM);+ }++ ImGui::SameLine(w * 0.48f);+ method_badge(m.api_config.method);++ // Field count+ ImGui::SameLine(w * 0.58f);+ ImGui::PushStyleColor(ImGuiCol_Text, TEXT_DIM);+ ImGui::Text("%d fields", static_cast<int>(m.field_mappings.size()));+ ImGui::PopStyleColor();++ // Actions (right-aligned)+ ImGui::SameLine(w * 0.72f);+ if (theme::SecondaryButton("Edit")) {+ edit_mapping(m);+ }+ ImGui::SameLine();+ if (theme::SecondaryButton("Dup")) {+ mapping_ops::duplicate_mapping(m.id);+ load_mappings();+ }+ ImGui::SameLine();+ ImGui::PushStyleColor(ImGuiCol_Button, {ERROR_RED.x, ERROR_RED.y, ERROR_RED.z, 0.15f});+ ImGui::PushStyleColor(ImGuiCol_ButtonHovered, {ERROR_RED.x, ERROR_RED.y, ERROR_RED.z, 0.30f});+ ImGui::PushStyleColor(ImGuiCol_Text, ERROR_RED);+ if (ImGui::Button("Del")) {+ pending_delete_id_ = m.id;+ }+ ImGui::PopStyleColor(3);++ // Row 2: Endpoint + Updated date+ ImGui::PushStyleColor(ImGuiCol_Text, TEXT_DIM);+ const std::string endpoint_display =+ m.api_config.base_url.substr(0, std::min<size_t>(40, m.api_config.base_url.size())) ++ m.api_config.endpoint;+ ImGui::Text("%s", endpoint_display.c_str());+ ImGui::PopStyleColor();++ if (!m.updated_at.empty()) {+ ImGui::SameLine(w * 0.72f);+ ImGui::PushStyleColor(ImGuiCol_Text, TEXT_DISABLED);+ ImGui::Text("Updated %s", m.updated_at.substr(0, 10).c_str());+ ImGui::PopStyleColor();+ }++ ImGui::EndChild();+ ImGui::PopStyleVar(2);+ ImGui::PopStyleColor(2);++ ImGui::PopID();+ }++ if (visible_count == 0) {+ ImGui::Spacing();+ ImGui::PushStyleColor(ImGuiCol_Text, TEXT_DIM);+ ImGui::Text("No mappings match the current filter.");+ ImGui::PopStyleColor();+ }++ // Delete confirmation popup+ if (!pending_delete_id_.empty()) {+ ImGui::OpenPopup("Confirm Delete");+ }+ if (ImGui::BeginPopupModal("Confirm Delete", nullptr, ImGuiWindowFlags_AlwaysAutoResize)) {+ ImGui::PushStyleColor(ImGuiCol_Text, TEXT_PRIMARY);+ ImGui::Text("Delete this mapping permanently?");+ ImGui::PopStyleColor();+ ImGui::Spacing();++ if (theme::AccentButton("Delete")) {+ delete_mapping_by_id(pending_delete_id_);+ pending_delete_id_.clear();+ ImGui::CloseCurrentPopup();+ }+ ImGui::SameLine();+ if (theme::SecondaryButton("Cancel")) {+ pending_delete_id_.clear();+ ImGui::CloseCurrentPopup();+ }+ ImGui::EndPopup();+ }+}++} // namespace fincept::data_mapping