Skip to content

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.

refactor(crypto-trading): split 3789-line screen into 8 focused files

tilakpatel2235fdcb77d92c
diff --git a/fincept-cpp/CMakeLists.txt b/fincept-cpp/CMakeLists.txt
index 0ff02635f..0076730a9 100644
--- a/fincept-cpp/CMakeLists.txt
+++ b/fincept-cpp/CMakeLists.txt
@@ -160,6 +160,14 @@ set(SOURCES
# Screens — Crypto Trading
src/screens/crypto_trading/crypto_trading_screen.cpp
+ src/screens/crypto_trading/crypto_lifecycle.cpp
+ src/screens/crypto_trading/crypto_screen.cpp
+ src/screens/crypto_trading/crypto_watchlist.cpp
+ src/screens/crypto_trading/crypto_chart.cpp
+ src/screens/crypto_trading/crypto_bottom_tabs.cpp
+ src/screens/crypto_trading/crypto_order_entry.cpp
+ src/screens/crypto_trading/crypto_order_actions.cpp
+ src/screens/crypto_trading/crypto_credentials.cpp
# Screens — Node Editor
src/screens/node_editor/node_registry.cpp
diff --git a/fincept-cpp/src/screens/crypto_trading/crypto_bottom_tabs.cpp b/fincept-cpp/src/screens/crypto_trading/crypto_bottom_tabs.cpp
new file mode 100644
index 000000000..19c9f4eb2
--- /dev/null
+++ b/fincept-cpp/src/screens/crypto_trading/crypto_bottom_tabs.cpp
@@ -0,0 +1,806 @@
+#include "crypto_trading_screen.h"
+#include "crypto_internal.h"
+#include "ui/theme.h"
+#include "trading/exchange_service.h"
+#include "trading/paper_trading.h"
+#include "core/logger.h"
+#include <imgui.h>
+#include <cstdio>
+#include <cstring>
+#include <thread>
+
+namespace fincept::crypto {
+
+using namespace theme::colors;
+
+void CryptoTradingScreen::render_positions_tab() {
+ bool is_live = (trading_mode_ == TradingMode::Live);
+
+ // Mode label
+ ImGui::TextColored(is_live ? ImVec4(0.9f, 0.2f, 0.2f, 1.0f) : ImVec4(0.0f, 0.7f, 0.3f, 1.0f),
+ is_live ? "[LIVE POSITIONS]" : "[PAPER POSITIONS]");
+
+ if (is_live) {
+ if (!has_credentials_) {
+ ImGui::TextColored(TEXT_DIM, "API credentials required for live trading.");
+ ImGui::SameLine(0, 8);
+ ImGui::PushStyleColor(ImGuiCol_Button, ACCENT_BG);
+ if (ImGui::SmallButton("Configure API Key")) {
+ show_credentials_popup_ = true;
+ load_exchange_credentials();
+ }
+ ImGui::PopStyleColor();
+ return;
+ }
+
+ std::lock_guard<std::mutex> lock(data_mutex_);
+
+ if (live_positions_fetching_) {
+ theme::LoadingSpinner("Fetching positions...");
+ return;
+ }
+
+ if (live_positions_.empty()) {
+ ImGui::TextColored(TEXT_DIM, "No open positions on %s", exchange_id_.c_str());
+ return;
+ }
+
+ ImGuiTableFlags flags = ImGuiTableFlags_RowBg | ImGuiTableFlags_BordersInnerH |
+ ImGuiTableFlags_SizingStretchProp | ImGuiTableFlags_ScrollY;
+
+ if (ImGui::BeginTable("##live_positions", 7, flags)) {
+ ImGui::TableSetupColumn("Symbol", ImGuiTableColumnFlags_WidthStretch, 1.2f);
+ ImGui::TableSetupColumn("Side", ImGuiTableColumnFlags_WidthStretch, 0.6f);
+ ImGui::TableSetupColumn("Qty", ImGuiTableColumnFlags_WidthStretch, 0.8f);
+ ImGui::TableSetupColumn("Entry", ImGuiTableColumnFlags_WidthStretch, 1.0f);
+ ImGui::TableSetupColumn("Current", ImGuiTableColumnFlags_WidthStretch, 1.0f);
+ ImGui::TableSetupColumn("PnL", ImGuiTableColumnFlags_WidthStretch, 1.0f);
+ ImGui::TableSetupColumn("Lev", ImGuiTableColumnFlags_WidthStretch, 0.5f);
+ ImGui::TableSetupScrollFreeze(0, 1);
+ ImGui::PushStyleColor(ImGuiCol_TableHeaderBg, BG_DARKEST);
+ ImGui::TableHeadersRow();
+ ImGui::PopStyleColor();
+
+ char buf[32];
+ for (const auto& pos : live_positions_) {
+ ImGui::TableNextRow();
+
+ ImGui::TableSetColumnIndex(0);
+ ImGui::TextColored(TEXT_PRIMARY, "%s", pos.symbol.c_str());
+
+ ImGui::TableSetColumnIndex(1);
+ ImVec4 side_col = (pos.side == "long") ? MARKET_GREEN : MARKET_RED;
+ ImGui::TextColored(side_col, "%s", pos.side == "long" ? "LONG" : "SHORT");
+
+ ImGui::TableSetColumnIndex(2);
+ std::snprintf(buf, sizeof(buf), "%.4f", pos.quantity);
+ ImGui::TextColored(TEXT_SECONDARY, "%s", buf);
+
+ ImGui::TableSetColumnIndex(3);
+ std::snprintf(buf, sizeof(buf), "%.2f", pos.entry_price);
+ ImGui::TextColored(TEXT_SECONDARY, "%s", buf);
+
+ ImGui::TableSetColumnIndex(4);
+ std::snprintf(buf, sizeof(buf), "%.2f", pos.current_price);
+ ImGui::TextColored(TEXT_PRIMARY, "%s", buf);
+
+ ImGui::TableSetColumnIndex(5);
+ ImVec4 pnl_col = pos.unrealized_pnl >= 0 ? MARKET_GREEN : MARKET_RED;
+ std::snprintf(buf, sizeof(buf), "%s%.2f",
+ pos.unrealized_pnl >= 0 ? "+" : "", pos.unrealized_pnl);
+ ImGui::TextColored(pnl_col, "%s", buf);
+
+ ImGui::TableSetColumnIndex(6);
+ std::snprintf(buf, sizeof(buf), "%.0fx", pos.leverage);
+ ImGui::TextColored(TEXT_DIM, "%s", buf);
+ }
+
+ ImGui::EndTable();
+ }
+ return;
+ }
+
+ // Paper mode — show simulated positions
+ std::lock_guard<std::mutex> lock(data_mutex_);
+
+ if (!portfolio_loaded_) {
+ theme::LoadingSpinner("Loading portfolio...");
+ return;
+ }
+
+ if (positions_.empty()) {
+ ImGui::TextColored(TEXT_DIM, "No open positions");
+ return;
+ }
+
+ ImGuiTableFlags flags = ImGuiTableFlags_RowBg | ImGuiTableFlags_BordersInnerH |
+ ImGuiTableFlags_SizingStretchProp | ImGuiTableFlags_ScrollY;
+
+ if (ImGui::BeginTable("##positions", 7, flags)) {
+ ImGui::TableSetupColumn("Symbol", ImGuiTableColumnFlags_WidthStretch, 1.2f);
+ ImGui::TableSetupColumn("Side", ImGuiTableColumnFlags_WidthStretch, 0.6f);
+ ImGui::TableSetupColumn("Qty", ImGuiTableColumnFlags_WidthStretch, 0.8f);
+ ImGui::TableSetupColumn("Entry", ImGuiTableColumnFlags_WidthStretch, 1.0f);
+ ImGui::TableSetupColumn("Current", ImGuiTableColumnFlags_WidthStretch, 1.0f);
+ ImGui::TableSetupColumn("PnL", ImGuiTableColumnFlags_WidthStretch, 1.0f);
+ ImGui::TableSetupColumn("Lev", ImGuiTableColumnFlags_WidthStretch, 0.5f);
+ ImGui::TableSetupScrollFreeze(0, 1);
+ ImGui::PushStyleColor(ImGuiCol_TableHeaderBg, BG_DARKEST);
+ ImGui::TableHeadersRow();
+ ImGui::PopStyleColor();
+
+ char buf[32];
+ for (auto& pos : positions_) {
+ ImGui::TableNextRow();
+
+ ImGui::TableSetColumnIndex(0);
+ ImGui::TextColored(TEXT_PRIMARY, "%s", pos.symbol.c_str());
+
+ ImGui::TableSetColumnIndex(1);
+ ImVec4 side_col = (pos.side == "long") ? MARKET_GREEN : MARKET_RED;
+ ImGui::TextColored(side_col, "%s", pos.side == "long" ? "LONG" : "SHORT");
+
+ ImGui::TableSetColumnIndex(2);
+ std::snprintf(buf, sizeof(buf), "%.4f", pos.quantity);
+ ImGui::TextColored(TEXT_SECONDARY, "%s", buf);
+
+ ImGui::TableSetColumnIndex(3);
+ std::snprintf(buf, sizeof(buf), "%.2f", pos.entry_price);
+ ImGui::TextColored(TEXT_SECONDARY, "%s", buf);
+
+ ImGui::TableSetColumnIndex(4);
+ std::snprintf(buf, sizeof(buf), "%.2f", pos.current_price);
+ ImGui::TextColored(TEXT_PRIMARY, "%s", buf);
+
+ ImGui::TableSetColumnIndex(5);
+ ImVec4 pnl_col = pos.unrealized_pnl >= 0 ? MARKET_GREEN : MARKET_RED;
+ std::snprintf(buf, sizeof(buf), "%s%.2f",
+ pos.unrealized_pnl >= 0 ? "+" : "", pos.unrealized_pnl);
+ ImGui::TextColored(pnl_col, "%s", buf);
+
+ ImGui::TableSetColumnIndex(6);
+ std::snprintf(buf, sizeof(buf), "%.0fx", pos.leverage);
+ ImGui::TextColored(TEXT_DIM, "%s", buf);
+ }
+
+ ImGui::EndTable();
+ }
+}
+
+void CryptoTradingScreen::render_orders_tab() {
+ bool is_live = (trading_mode_ == TradingMode::Live);
+
+ ImGui::TextColored(is_live ? ImVec4(0.9f, 0.2f, 0.2f, 1.0f) : ImVec4(0.0f, 0.7f, 0.3f, 1.0f),
+ is_live ? "[LIVE ORDERS]" : "[PAPER ORDERS]");
+
+ if (is_live) {
+ if (!has_credentials_) {
+ ImGui::TextColored(TEXT_DIM, "API credentials required.");
+ ImGui::SameLine(0, 8);
+ ImGui::PushStyleColor(ImGuiCol_Button, ACCENT_BG);
+ if (ImGui::SmallButton("Configure##orders")) {
+ show_credentials_popup_ = true;
+ load_exchange_credentials();
+ }
+ ImGui::PopStyleColor();
+ return;
+ }
+
+ std::lock_guard<std::mutex> lock(data_mutex_);
+
+ if (live_orders_fetching_) {
+ theme::LoadingSpinner("Fetching orders...");
+ return;
+ }
+
+ if (live_orders_.empty()) {
+ ImGui::TextColored(TEXT_DIM, "No open orders on %s", exchange_id_.c_str());
+ return;
+ }
+
+ ImGuiTableFlags flags = ImGuiTableFlags_RowBg | ImGuiTableFlags_BordersInnerH |
+ ImGuiTableFlags_SizingStretchProp | ImGuiTableFlags_ScrollY;
+
+ if (ImGui::BeginTable("##live_orders", 7, flags)) {
+ ImGui::TableSetupColumn("Symbol", ImGuiTableColumnFlags_WidthStretch, 1.0f);
+ ImGui::TableSetupColumn("Side", ImGuiTableColumnFlags_WidthStretch, 0.5f);
+ ImGui::TableSetupColumn("Type", ImGuiTableColumnFlags_WidthStretch, 0.7f);
+ ImGui::TableSetupColumn("Qty", ImGuiTableColumnFlags_WidthStretch, 0.8f);
+ ImGui::TableSetupColumn("Price", ImGuiTableColumnFlags_WidthStretch, 0.8f);
+ ImGui::TableSetupColumn("Status", ImGuiTableColumnFlags_WidthStretch, 0.7f);
+ ImGui::TableSetupColumn("Action", ImGuiTableColumnFlags_WidthStretch, 0.6f);
+ ImGui::TableSetupScrollFreeze(0, 1);
+ ImGui::PushStyleColor(ImGuiCol_TableHeaderBg, BG_DARKEST);
+ ImGui::TableHeadersRow();
+ ImGui::PopStyleColor();
+
+ char buf[32];
+ for (auto& ord : live_orders_) {
+ ImGui::TableNextRow();
+ ImGui::PushID(ord.id.c_str());
+
+ ImGui::TableSetColumnIndex(0);
+ ImGui::TextColored(TEXT_PRIMARY, "%s", ord.symbol.c_str());
+
+ ImGui::TableSetColumnIndex(1);
+ ImVec4 side_col = (ord.side == "buy") ? MARKET_GREEN : MARKET_RED;
+ ImGui::TextColored(side_col, "%s", ord.side == "buy" ? "BUY" : "SELL");
+
+ ImGui::TableSetColumnIndex(2);
+ ImGui::TextColored(TEXT_SECONDARY, "%s", ord.type.c_str());
+
+ ImGui::TableSetColumnIndex(3);
+ std::snprintf(buf, sizeof(buf), "%.4f", ord.quantity);
+ ImGui::TextColored(TEXT_SECONDARY, "%s", buf);
+
+ ImGui::TableSetColumnIndex(4);
+ if (ord.price > 0.0) {
+ std::snprintf(buf, sizeof(buf), "%.2f", ord.price);
+ ImGui::TextColored(TEXT_PRIMARY, "%s", buf);
+ } else {
+ ImGui::TextColored(TEXT_DIM, "MKT");
+ }
+
+ ImGui::TableSetColumnIndex(5);
+ ImVec4 status_col = TEXT_DIM;
+ if (ord.status == "open") status_col = WARNING;
+ else if (ord.status == "closed" || ord.status == "filled") status_col = MARKET_GREEN;
+ else if (ord.status == "canceled" || ord.status == "cancelled") status_col = MARKET_RED;
+ ImGui::TextColored(status_col, "%s", ord.status.c_str());
+
+ ImGui::TableSetColumnIndex(6);
+ if (ord.status == "open") {
+ ImGui::PushStyleColor(ImGuiCol_Button, ImVec4(0.5f, 0.1f, 0.1f, 0.8f));
+ ImGui::PushStyleColor(ImGuiCol_Text, MARKET_RED);
+ if (ImGui::SmallButton("Cancel")) {
+ cancel_order(ord.id);
+ }
+ ImGui::PopStyleColor(2);
+ }
+
+ ImGui::PopID();
+ }
+
+ ImGui::EndTable();
+ }
+ return;
+ }
+
+ std::lock_guard<std::mutex> lock(data_mutex_);
+
+ if (!portfolio_loaded_) {
+ theme::LoadingSpinner("Loading orders...");
+ return;
+ }
+
+ if (orders_.empty()) {
+ ImGui::TextColored(TEXT_DIM, "No orders");
+ return;
+ }
+
+ ImGuiTableFlags flags = ImGuiTableFlags_RowBg | ImGuiTableFlags_BordersInnerH |
+ ImGuiTableFlags_SizingStretchProp | ImGuiTableFlags_ScrollY;
+
+ if (ImGui::BeginTable("##orders", 7, flags)) {
+ ImGui::TableSetupColumn("Symbol", ImGuiTableColumnFlags_WidthStretch, 1.0f);
+ ImGui::TableSetupColumn("Side", ImGuiTableColumnFlags_WidthStretch, 0.5f);
+ ImGui::TableSetupColumn("Type", ImGuiTableColumnFlags_WidthStretch, 0.7f);
+ ImGui::TableSetupColumn("Qty", ImGuiTableColumnFlags_WidthStretch, 0.8f);
+ ImGui::TableSetupColumn("Price", ImGuiTableColumnFlags_WidthStretch, 0.8f);
+ ImGui::TableSetupColumn("Status", ImGuiTableColumnFlags_WidthStretch, 0.7f);
+ ImGui::TableSetupColumn("Action", ImGuiTableColumnFlags_WidthStretch, 0.6f);
+ ImGui::TableSetupScrollFreeze(0, 1);
+ ImGui::PushStyleColor(ImGuiCol_TableHeaderBg, BG_DARKEST);
+ ImGui::TableHeadersRow();
+ ImGui::PopStyleColor();
+
+ char buf[32];
+ for (auto& ord : orders_) {
+ ImGui::TableNextRow();
+ ImGui::PushID(ord.id.c_str());
+
+ ImGui::TableSetColumnIndex(0);
+ ImGui::TextColored(TEXT_PRIMARY, "%s", ord.symbol.c_str());
+
+ ImGui::TableSetColumnIndex(1);
+ ImVec4 side_col = (ord.side == "buy") ? MARKET_GREEN : MARKET_RED;
+ ImGui::TextColored(side_col, "%s", ord.side == "buy" ? "BUY" : "SELL");
+
+ ImGui::TableSetColumnIndex(2);
+ ImGui::TextColored(TEXT_SECONDARY, "%s", ord.order_type.c_str());
+
+ ImGui::TableSetColumnIndex(3);
+ std::snprintf(buf, sizeof(buf), "%.4f", ord.quantity);
+ ImGui::TextColored(TEXT_SECONDARY, "%s", buf);
+
+ ImGui::TableSetColumnIndex(4);
+ if (ord.price.has_value()) {
+ std::snprintf(buf, sizeof(buf), "%.2f", *ord.price);
+ ImGui::TextColored(TEXT_PRIMARY, "%s", buf);
+ } else {
+ ImGui::TextColored(TEXT_DIM, "MKT");
+ }
+
+ ImGui::TableSetColumnIndex(5);
+ ImVec4 status_col = TEXT_DIM;
+ if (ord.status == "pending") status_col = WARNING;
+ else if (ord.status == "filled") status_col = MARKET_GREEN;
+ else if (ord.status == "cancelled") status_col = MARKET_RED;
+ ImGui::TextColored(status_col, "%s", ord.status.c_str());
+
+ ImGui::TableSetColumnIndex(6);
+ if (ord.status == "pending") {
+ ImGui::PushStyleColor(ImGuiCol_Button, ImVec4(0.5f, 0.1f, 0.1f, 0.8f));
+ ImGui::PushStyleColor(ImGuiCol_Text, MARKET_RED);
+ if (ImGui::SmallButton("Cancel")) {
+ cancel_order(ord.id);
+ }
+ ImGui::PopStyleColor(2);
+ }
+
+ ImGui::PopID();
+ }
+
+ ImGui::EndTable();
+ }
+}
+
+void CryptoTradingScreen::render_history_tab() {
+ bool is_live = (trading_mode_ == TradingMode::Live);
+ ImGui::TextColored(is_live ? ImVec4(0.9f, 0.2f, 0.2f, 1.0f) : ImVec4(0.0f, 0.7f, 0.3f, 1.0f),
+ is_live ? "[LIVE HISTORY]" : "[PAPER HISTORY]");
+
+ if (is_live) {
+ if (!has_credentials_) {
+ ImGui::TextColored(TEXT_DIM, "API credentials required.");
+ return;
+ }
+
+ std::lock_guard<std::mutex> lock(data_mutex_);
+
+ if (live_trades_fetching_) {
+ theme::LoadingSpinner("Fetching trade history...");
+ return;
+ }
+
+ if (live_trades_.empty()) {
+ ImGui::TextColored(TEXT_DIM, "No trade history on %s", exchange_id_.c_str());
+ // Trigger initial fetch
+ if (!live_data_loaded_) {
+ live_data_loaded_ = true;
+ async_fetch_live_trades();
+ }
+ return;
+ }
+
+ ImGuiTableFlags flags = ImGuiTableFlags_RowBg | ImGuiTableFlags_BordersInnerH |
+ ImGuiTableFlags_SizingStretchProp | ImGuiTableFlags_ScrollY;
+
+ if (ImGui::BeginTable("##live_trades_hist", 6, flags)) {
+ ImGui::TableSetupColumn("Symbol", ImGuiTableColumnFlags_WidthStretch, 1.0f);
+ ImGui::TableSetupColumn("Side", ImGuiTableColumnFlags_WidthStretch, 0.5f);
+ ImGui::TableSetupColumn("Price", ImGuiTableColumnFlags_WidthStretch, 0.8f);
+ ImGui::TableSetupColumn("Qty", ImGuiTableColumnFlags_WidthStretch, 0.8f);
+ ImGui::TableSetupColumn("Fee", ImGuiTableColumnFlags_WidthStretch, 0.6f);
+ ImGui::TableSetupColumn("Time", ImGuiTableColumnFlags_WidthStretch, 1.2f);
+ ImGui::TableSetupScrollFreeze(0, 1);
+ ImGui::PushStyleColor(ImGuiCol_TableHeaderBg, BG_DARKEST);
+ ImGui::TableHeadersRow();
+ ImGui::PopStyleColor();
+
+ char buf[32];
+ for (const auto& t : live_trades_) {
+ ImGui::TableNextRow();
+
+ ImGui::TableSetColumnIndex(0);
+ ImGui::TextColored(TEXT_PRIMARY, "%s", t.symbol.c_str());
+
+ ImGui::TableSetColumnIndex(1);
+ ImVec4 side_col = (t.side == "buy") ? MARKET_GREEN : MARKET_RED;
+ ImGui::TextColored(side_col, "%s", t.side == "buy" ? "BUY" : "SELL");
+
+ ImGui::TableSetColumnIndex(2);
+ std::snprintf(buf, sizeof(buf), "%.2f", t.price);
+ ImGui::TextColored(TEXT_SECONDARY, "%s", buf);
+
+ ImGui::TableSetColumnIndex(3);
+ std::snprintf(buf, sizeof(buf), "%.4f", t.quantity);
+ ImGui::TextColored(TEXT_SECONDARY, "%s", buf);
+
+ ImGui::TableSetColumnIndex(4);
+ std::snprintf(buf, sizeof(buf), "%.4f", t.fee);
+ ImGui::TextColored(TEXT_DIM, "%s", buf);
+
+ ImGui::TableSetColumnIndex(5);
+ ImGui::TextColored(TEXT_DIM, "%s", t.timestamp.c_str());
+ }
+
+ ImGui::EndTable();
+ }
+ return;
+ }
+
+ std::lock_guard<std::mutex> lock(data_mutex_);
+
+ if (!portfolio_loaded_) {
+ theme::LoadingSpinner("Loading history...");
+ return;
+ }
+
+ if (trades_.empty()) {
+ ImGui::TextColored(TEXT_DIM, "No trade history");
+ return;
+ }
+
+ ImGuiTableFlags flags = ImGuiTableFlags_RowBg | ImGuiTableFlags_BordersInnerH |
+ ImGuiTableFlags_SizingStretchProp | ImGuiTableFlags_ScrollY;
+
+ if (ImGui::BeginTable("##history", 6, flags)) {
+ ImGui::TableSetupColumn("Symbol", ImGuiTableColumnFlags_WidthStretch, 1.0f);
+ ImGui::TableSetupColumn("Side", ImGuiTableColumnFlags_WidthStretch, 0.5f);
+ ImGui::TableSetupColumn("Price", ImGuiTableColumnFlags_WidthStretch, 0.8f);
+ ImGui::TableSetupColumn("Qty", ImGuiTableColumnFlags_WidthStretch, 0.7f);
+ ImGui::TableSetupColumn("Fee", ImGuiTableColumnFlags_WidthStretch, 0.6f);
+ ImGui::TableSetupColumn("PnL", ImGuiTableColumnFlags_WidthStretch, 0.8f);
+ ImGui::TableSetupScrollFreeze(0, 1);
+ ImGui::PushStyleColor(ImGuiCol_TableHeaderBg, BG_DARKEST);
+ ImGui::TableHeadersRow();
+ ImGui::PopStyleColor();
+
+ char buf[32];
+ for (auto& t : trades_) {
+ ImGui::TableNextRow();
+
+ ImGui::TableSetColumnIndex(0);
+ ImGui::TextColored(TEXT_PRIMARY, "%s", t.symbol.c_str());
+
+ ImGui::TableSetColumnIndex(1);
+ ImVec4 side_col = (t.side == "buy") ? MARKET_GREEN : MARKET_RED;
+ ImGui::TextColored(side_col, "%s", t.side == "buy" ? "BUY" : "SELL");
+
+ ImGui::TableSetColumnIndex(2);
+ std::snprintf(buf, sizeof(buf), "%.2f", t.price);
+ ImGui::TextColored(TEXT_SECONDARY, "%s", buf);
+
+ ImGui::TableSetColumnIndex(3);
+ std::snprintf(buf, sizeof(buf), "%.4f", t.quantity);
+ ImGui::TextColored(TEXT_SECONDARY, "%s", buf);
+
+ ImGui::TableSetColumnIndex(4);
+ std::snprintf(buf, sizeof(buf), "%.4f", t.fee);
+ ImGui::TextColored(TEXT_DIM, "%s", buf);
+
+ ImGui::TableSetColumnIndex(5);
+ ImVec4 pnl_col = t.pnl >= 0 ? MARKET_GREEN : MARKET_RED;
+ std::snprintf(buf, sizeof(buf), "%s%.2f", t.pnl >= 0 ? "+" : "", t.pnl);
+ ImGui::TextColored(pnl_col, "%s", buf);
+ }
+
+ ImGui::EndTable();
+ }
+}
+
+void CryptoTradingScreen::render_stats_tab() {
+ bool is_live = (trading_mode_ == TradingMode::Live);
+ ImGui::TextColored(is_live ? ImVec4(0.9f, 0.2f, 0.2f, 1.0f) : ImVec4(0.0f, 0.7f, 0.3f, 1.0f),
+ is_live ? "[LIVE STATS]" : "[PAPER STATS]");
+
+ if (is_live) {
+ ImGui::TextColored(TEXT_DIM, "Live statistics not available yet.");
+ return;
+ }
+
+ std::lock_guard<std::mutex> lock(data_mutex_);
+ char buf[32];
+
+ if (!portfolio_loaded_) {
+ theme::LoadingSpinner("Loading stats...");
+ return;
+ }
+
+ ImGui::Columns(2, "##stats_cols", false);
+
+ // Compute unrealized PnL from open positions
+ double unrealized_pnl = 0.0;
+ for (const auto& pos : positions_) {
+ unrealized_pnl += pos.unrealized_pnl;
+ }
+
+ ImGui::TextColored(TEXT_DIM, "Realized PnL");
+ ImVec4 pnl_col = stats_.total_pnl >= 0 ? MARKET_GREEN : MARKET_RED;
+ std::snprintf(buf, sizeof(buf), "%s%.2f", stats_.total_pnl >= 0 ? "+" : "", stats_.total_pnl);
+ ImGui::TextColored(pnl_col, "%s", buf);
+ ImGui::Spacing();
+
+ ImGui::TextColored(TEXT_DIM, "Unrealized PnL");
+ ImVec4 upnl_col = unrealized_pnl >= 0 ? MARKET_GREEN : MARKET_RED;
+ std::snprintf(buf, sizeof(buf), "%s%.2f", unrealized_pnl >= 0 ? "+" : "", unrealized_pnl);
+ ImGui::TextColored(upnl_col, "%s", buf);
+ ImGui::Spacing();
+
+ ImGui::TextColored(TEXT_DIM, "Win Rate");
+ std::snprintf(buf, sizeof(buf), "%.1f%%", stats_.win_rate);
+ ImGui::TextColored(TEXT_PRIMARY, "%s", buf);
+ ImGui::Spacing();
+
+ ImGui::TextColored(TEXT_DIM, "Total Trades");
+ std::snprintf(buf, sizeof(buf), "%lld", (long long)stats_.total_trades);
+ ImGui::TextColored(TEXT_PRIMARY, "%s", buf);
+ ImGui::Spacing();
+
+ ImGui::TextColored(TEXT_DIM, "Balance");
+ std::snprintf(buf, sizeof(buf), "%.2f", portfolio_.balance);
+ ImGui::TextColored(TEXT_PRIMARY, "%s", buf);
+
+ ImGui::NextColumn();
+
+ ImGui::TextColored(TEXT_DIM, "Winning");
+ std::snprintf(buf, sizeof(buf), "%lld", (long long)stats_.winning_trades);
+ ImGui::TextColored(MARKET_GREEN, "%s", buf);
+ ImGui::Spacing();
+
+ ImGui::TextColored(TEXT_DIM, "Losing");
+ std::snprintf(buf, sizeof(buf), "%lld", (long long)stats_.losing_trades);
+ ImGui::TextColored(MARKET_RED, "%s", buf);
+ ImGui::Spacing();
+
+ ImGui::TextColored(TEXT_DIM, "Largest Win");
+ std::snprintf(buf, sizeof(buf), "+%.2f", stats_.largest_win);
+ ImGui::TextColored(MARKET_GREEN, "%s", buf);
+ ImGui::Spacing();
+
+ ImGui::TextColored(TEXT_DIM, "Largest Loss");
+ std::snprintf(buf, sizeof(buf), "%.2f", stats_.largest_loss);
+ ImGui::TextColored(MARKET_RED, "%s", buf);
+
+ ImGui::Columns(1);
+
+ ImGui::Spacing();
+ ImGui::Separator();
+ ImGui::Spacing();
+ ImGui::PushStyleColor(ImGuiCol_Button, ImVec4(0.5f, 0.1f, 0.1f, 1.0f));
+ if (ImGui::Button("Reset Portfolio", ImVec2(-1, 0))) {
+ portfolio_ = trading::pt_reset_portfolio(portfolio_id_);
+ refresh_portfolio_data();
+ LOG_INFO(TAG, "Portfolio reset");
+ }
+ ImGui::PopStyleColor();
+}
+
+// ============================================================================
+// Trades tab — Time & Sales feed
+// ============================================================================
+void CryptoTradingScreen::render_trades_tab() {
+ std::lock_guard<std::mutex> lock(data_mutex_);
+
+ if (recent_trades_.empty()) {
+ if (trades_fetching_) {
+ ImGui::TextColored(TEXT_DIM, "Loading trades...");
+ } else {
+ ImGui::TextColored(TEXT_DIM, "No trades yet");
+ }
+ return;
+ }
+
+ ImGuiTableFlags flags = ImGuiTableFlags_RowBg | ImGuiTableFlags_BordersInnerH |
+ ImGuiTableFlags_SizingStretchProp | ImGuiTableFlags_ScrollY;
+
+ if (ImGui::BeginTable("##trades_feed", 4, flags)) {
+ ImGui::TableSetupColumn("Time", ImGuiTableColumnFlags_WidthStretch, 1.0f);
+ ImGui::TableSetupColumn("Side", ImGuiTableColumnFlags_WidthStretch, 0.5f);
+ ImGui::TableSetupColumn("Price", ImGuiTableColumnFlags_WidthStretch, 1.0f);
+ ImGui::TableSetupColumn("Amount", ImGuiTableColumnFlags_WidthStretch, 0.8f);
+ ImGui::TableSetupScrollFreeze(0, 1);
+ ImGui::PushStyleColor(ImGuiCol_TableHeaderBg, BG_DARKEST);
+ ImGui::TableHeadersRow();
+ ImGui::PopStyleColor();
+
+ char buf[32];
+ for (const auto& t : recent_trades_) {
+ ImGui::TableNextRow();
+
+ ImGui::TableSetColumnIndex(0);
+ time_t ts = t.timestamp / 1000;
+ struct tm tm_buf{};
+#ifdef _WIN32
+ localtime_s(&tm_buf, &ts);
+#else
+ localtime_r(&ts, &tm_buf);
+#endif
+ std::snprintf(buf, sizeof(buf), "%02d:%02d:%02d", tm_buf.tm_hour, tm_buf.tm_min, tm_buf.tm_sec);
+ ImGui::TextColored(TEXT_DIM, "%s", buf);
+
+ ImGui::TableSetColumnIndex(1);
+ ImVec4 col = (t.side == "buy") ? MARKET_GREEN : MARKET_RED;
+ ImGui::TextColored(col, "%s", t.side == "buy" ? "BUY" : "SELL");
+
+ ImGui::TableSetColumnIndex(2);
+ std::snprintf(buf, sizeof(buf), "%.2f", t.price);
+ ImGui::TextColored(col, "%s", buf);
+
+ ImGui::TableSetColumnIndex(3);
+ std::snprintf(buf, sizeof(buf), "%.4f", t.amount);
+ ImGui::TextColored(TEXT_SECONDARY, "%s", buf);
+ }
+
+ ImGui::EndTable();
+ }
+}
+
+void CryptoTradingScreen::async_fetch_trades() {
+ if (trades_fetching_) return;
+ trades_fetching_ = true;
+
+ const std::string sym = selected_symbol_;
+ launch_async(std::thread([this, sym]() {
+ try {
+ auto trades = trading::ExchangeService::instance().fetch_trades(sym, 100);
+ std::lock_guard<std::mutex> lock(data_mutex_);
+ recent_trades_.clear();
+ for (const auto& t : trades) {
+ recent_trades_.push_back({t.id, t.side, t.price, t.amount, t.timestamp});
+ }
+ } catch (const std::exception& e) {
+ LOG_ERROR("CryptoTrading", "Failed to fetch trades: %s", e.what());
+ }
+ trades_fetching_ = false;
+ }));
+}
+
+// ============================================================================
+// Market Info tab — funding rate, open interest, fees
+// ============================================================================
+void CryptoTradingScreen::render_market_info_tab() {
+ std::lock_guard<std::mutex> lock(data_mutex_);
+ char buf[64];
+
+ if (!market_info_.has_data) {
+ if (market_info_fetching_) {
+ ImGui::TextColored(TEXT_DIM, "Loading market info...");
+ } else {
+ // Not yet fetched — show a trigger hint
+ ImGui::TextColored(TEXT_DIM, "Fetching market info...");
+ }
+ return;
+ }
+
+ ImGui::Columns(2, "##mktinfo_cols", false);
+
+ // --- Fees (always available for any symbol) ---
+ ImGui::TextColored(TEXT_DIM, "Maker Fee");
+ if (market_info_.maker_fee > 0.0) {
+ std::snprintf(buf, sizeof(buf), "%.4f%%", market_info_.maker_fee * 100.0);
+ ImGui::TextColored(TEXT_PRIMARY, "%s", buf);
+ } else {
+ ImGui::TextColored(TEXT_DIM, "N/A");
+ }
+ ImGui::Spacing();
+
+ ImGui::TextColored(TEXT_DIM, "Taker Fee");
+ if (market_info_.taker_fee > 0.0) {
+ std::snprintf(buf, sizeof(buf), "%.4f%%", market_info_.taker_fee * 100.0);
+ ImGui::TextColored(TEXT_PRIMARY, "%s", buf);
+ } else {
+ ImGui::TextColored(TEXT_DIM, "N/A");
+ }
+ ImGui::Spacing();
+
+ // --- Perp-only fields (show N/A for spot) ---
+ ImGui::TextColored(TEXT_DIM, "Funding Rate");
+ if (market_info_.funding_rate != 0.0) {
+ std::snprintf(buf, sizeof(buf), "%.4f%%", market_info_.funding_rate * 100.0);
+ ImVec4 fr_col = market_info_.funding_rate >= 0 ? MARKET_GREEN : MARKET_RED;
+ ImGui::TextColored(fr_col, "%s", buf);
+ } else {
+ ImGui::TextColored(TEXT_DIM, "N/A (spot)");
+ }
+ ImGui::Spacing();
+
+ ImGui::TextColored(TEXT_DIM, "Mark Price");
+ if (market_info_.mark_price > 0.0) {
+ std::snprintf(buf, sizeof(buf), "%.4f", market_info_.mark_price);
+ ImGui::TextColored(TEXT_PRIMARY, "%s", buf);
+ } else {
+ ImGui::TextColored(TEXT_DIM, "N/A (spot)");
+ }
+ ImGui::Spacing();
+
+ ImGui::TextColored(TEXT_DIM, "Index Price");
+ if (market_info_.index_price > 0.0) {
+ std::snprintf(buf, sizeof(buf), "%.4f", market_info_.index_price);
+ ImGui::TextColored(TEXT_PRIMARY, "%s", buf);
+ } else {
+ ImGui::TextColored(TEXT_DIM, "N/A (spot)");
+ }
+
+ ImGui::NextColumn();
+
+ ImGui::TextColored(TEXT_DIM, "Open Interest");
+ if (market_info_.open_interest > 0.0) {
+ std::snprintf(buf, sizeof(buf), "%.2f", market_info_.open_interest);
+ ImGui::TextColored(TEXT_PRIMARY, "%s", buf);
+ } else {
+ ImGui::TextColored(TEXT_DIM, "N/A (spot)");
+ }
+ ImGui::Spacing();
+
+ ImGui::TextColored(TEXT_DIM, "OI Value (USD)");
+ if (market_info_.open_interest_value > 0.0) {
+ const double oi_val = market_info_.open_interest_value;
+ if (oi_val > 1e9) std::snprintf(buf, sizeof(buf), "%.2fB", oi_val / 1e9);
+ else if (oi_val > 1e6) std::snprintf(buf, sizeof(buf), "%.2fM", oi_val / 1e6);
+ else std::snprintf(buf, sizeof(buf), "%.0f", oi_val);
+ ImGui::TextColored(TEXT_PRIMARY, "%s", buf);
+ } else {
+ ImGui::TextColored(TEXT_DIM, "N/A (spot)");
+ }
+ ImGui::Spacing();
+
+ if (market_info_.next_funding_time > 0) {
+ ImGui::TextColored(TEXT_DIM, "Next Funding");
+ const int64_t now_ms = std::chrono::duration_cast<std::chrono::milliseconds>(
+ std::chrono::system_clock::now().time_since_epoch()).count();
+ const int64_t diff_s = (market_info_.next_funding_time - now_ms) / 1000;
+ if (diff_s > 0) {
+ const int h = static_cast<int>(diff_s / 3600);
+ const int m = static_cast<int>((diff_s % 3600) / 60);
+ std::snprintf(buf, sizeof(buf), "%dh %dm", h, m);
+ } else {
+ std::snprintf(buf, sizeof(buf), "Now");
+ }
+ ImGui::TextColored(TEXT_PRIMARY, "%s", buf);
+ }
+
+ ImGui::Columns(1);
+
+ // Refresh hint
+ ImGui::Spacing();
+ ImGui::TextColored(TEXT_DIM, "(refreshes every %.0fs)", MARKET_INFO_INTERVAL);
+}
+
+void CryptoTradingScreen::async_fetch_market_info() {
+ if (market_info_fetching_) return;
+ market_info_fetching_ = true;
+
+ const std::string sym = selected_symbol_;
+ launch_async(std::thread([this, sym]() {
+ auto& svc = trading::ExchangeService::instance();
+
+ // Fetch funding rate + OI (perp only — scripts return nulls gracefully for spot)
+ const auto fr = svc.fetch_funding_rate(sym);
+ const auto oi = svc.fetch_open_interest(sym);
+
+ // Fetch trading fees — always available for any symbol on any exchange.
+ // fetch_trading_fees.py with a symbol arg returns: {"symbol":..., "maker":..., "taker":...}
+ double maker_fee = 0.0;
+ double taker_fee = 0.0;
+ try {
+ const auto fees_j = svc.fetch_trading_fees(sym);
+ if (fees_j.contains("data")) {
+ const auto& d = fees_j["data"];
+ if (d.contains("maker") && !d["maker"].is_null())
+ maker_fee = d["maker"].get<double>();
+ if (d.contains("taker") && !d["taker"].is_null())
+ taker_fee = d["taker"].get<double>();
+ }
+ } catch (const std::exception& e) {
+ LOG_DEBUG(TAG, "Trading fees fetch failed: %s", e.what());
+ }
+
+ {
+ std::lock_guard<std::mutex> lock(data_mutex_);
+ market_info_.funding_rate = fr.funding_rate;
+ market_info_.mark_price = fr.mark_price;
+ market_info_.index_price = fr.index_price;
+ market_info_.next_funding_time = fr.next_funding_timestamp;
+ market_info_.open_interest = oi.open_interest;
+ market_info_.open_interest_value = oi.open_interest_value;
+ market_info_.maker_fee = maker_fee;
+ market_info_.taker_fee = taker_fee;
+ market_info_.has_data = true; // always mark ready after fetch attempt
+ }
+ market_info_fetching_ = false;
+ }));
+}
+
+} // namespace fincept::crypto
diff --git a/fincept-cpp/src/screens/crypto_trading/crypto_chart.cpp b/fincept-cpp/src/screens/crypto_trading/crypto_chart.cpp
new file mode 100644
index 000000000..f3b3cb901
--- /dev/null
+++ b/fincept-cpp/src/screens/crypto_trading/crypto_chart.cpp
@@ -0,0 +1,378 @@
+#include "crypto_trading_screen.h"
+#include "crypto_internal.h"
+#include "ui/theme.h"
+#include "trading/exchange_service.h"
+#include "core/logger.h"
+#include <imgui.h>
+#include <cstdio>
+#include <cmath>
+
+namespace fincept::crypto {
+
+using namespace theme::colors;
+
+void CryptoTradingScreen::render_chart_area(float w, float h) {
+ ImGui::PushStyleColor(ImGuiCol_ChildBg, BG_DARK);
+ ImGui::BeginChild("##crypto_chart", ImVec2(w, h), true);
+
+ // Header: CHART label + symbol + WS indicator
+ ImGui::TextColored(ACCENT, "CHART");
+ ImGui::SameLine(0, 8);
+ ImGui::TextColored(TEXT_DIM, "%s", selected_symbol_.c_str());
+
+ ImGui::SameLine(0, 8);
+ bool ws_ok = trading::ExchangeService::instance().is_ws_connected();
+ ImGui::TextColored(ws_ok ? MARKET_GREEN : WARNING, ws_ok ? "[WS LIVE]" : "[REST]");
+
+ ImGui::SameLine(0, 16);
+
+ // Timeframe buttons
+ static const char* timeframes[] = {"1m", "5m", "15m", "1h", "4h", "1d"};
+ for (int i = 0; i < 6; i++) {
+ if (i > 0) ImGui::SameLine(0, 2);
+ bool active = (i == selected_timeframe_);
+ ImGui::PushStyleColor(ImGuiCol_Button, active ? ACCENT_DIM : BG_WIDGET);
+ ImGui::PushStyleColor(ImGuiCol_Text, active ? TEXT_PRIMARY : TEXT_DIM);
+ if (ImGui::SmallButton(timeframes[i])) {
+ if (selected_timeframe_ != i) {
+ selected_timeframe_ = i;
+ candle_timeframe_ = timeframes[i];
+ // Re-fetch candles for new timeframe
+ candles_loading_ = true;
+ candles_fetching_ = true;
+ const std::string sym = selected_symbol_;
+ std::string tf = candle_timeframe_;
+ launch_async(std::thread([this, sym, tf]() {
+ try {
+ auto ohlcv = trading::ExchangeService::instance().fetch_ohlcv(sym, tf, OHLCV_FETCH_COUNT);
+ LOG_INFO(TAG, "<<< OHLCV %s received: %d candles", tf.c_str(), (int)ohlcv.size());
+ {
+ std::lock_guard<std::mutex> lock(data_mutex_);
+ candles_ = std::move(ohlcv);
+ }
+ candles_loading_ = false;
+ candles_fetching_ = false;
+ success_count_++;
+ } catch (const std::exception& e) {
+ LOG_ERROR(TAG, "<<< OHLCV fetch failed: %s", e.what());
+ candles_loading_ = false;
+ candles_fetching_ = false;
+ error_count_++;
+ }
+ }));
+ }
+ }
+ ImGui::PopStyleColor(2);
+ }
+
+ // Candle count
+ {
+ std::lock_guard<std::mutex> lock(data_mutex_);
+ ImGui::SameLine(0, 12);
+ ImGui::TextColored(TEXT_DIM, "[%d candles]", (int)candles_.size());
+ }
+
+ ImGui::Separator();
+
+ float chart_w = ImGui::GetContentRegionAvail().x;
+ float chart_h = ImGui::GetContentRegionAvail().y;
+
+ std::lock_guard<std::mutex> lock(data_mutex_);
+ if (chart_h > 60 && !candles_.empty()) {
+ ImVec2 p = ImGui::GetCursorScreenPos();
+ render_candlestick_chart(p, chart_w, chart_h);
+ ImGui::Dummy(ImVec2(chart_w, chart_h));
+ } else if (candles_loading_) {
+ ImGui::Dummy(ImVec2(0, 20));
+ theme::LoadingSpinner("Loading OHLCV data...");
+ } else if (chart_h > 60 && current_ticker_.last > 0) {
+ // No candle data yet but have ticker — show price placeholder
+ ImVec2 p = ImGui::GetCursorScreenPos();
+ ImDrawList* dl = ImGui::GetWindowDrawList();
+ char price_text[64];
+ std::snprintf(price_text, sizeof(price_text), "%.2f", current_ticker_.last);
+ ImVec2 text_size = ImGui::CalcTextSize(price_text);
+ ImVec2 text_pos(p.x + (chart_w - text_size.x) / 2, p.y + (chart_h - text_size.y) / 2);
+ dl->AddText(text_pos, ImGui::ColorConvertFloat4ToU32(TEXT_PRIMARY), price_text);
+ ImGui::Dummy(ImVec2(chart_w, chart_h));
+ } else {
+ ImGui::Dummy(ImVec2(0, 20));
+ theme::LoadingSpinner("Loading chart data...");
+ }
+
+ ImGui::EndChild();
+ ImGui::PopStyleColor();
+}
+
+// ============================================================================
+// Candlestick Chart — renders OHLCV candles via ImDrawList
+// ============================================================================
+void CryptoTradingScreen::render_candlestick_chart(ImVec2 origin, float chart_w, float chart_h) {
+ ImDrawList* dl = ImGui::GetWindowDrawList();
+
+ // Colors
+ ImU32 grid_col = ImGui::ColorConvertFloat4ToU32(ImVec4(0.15f, 0.15f, 0.17f, 1.0f));
+ ImU32 green = ImGui::ColorConvertFloat4ToU32(ImVec4(0.0f, 0.8f, 0.4f, 1.0f));
+ ImU32 red = ImGui::ColorConvertFloat4ToU32(ImVec4(0.9f, 0.2f, 0.2f, 1.0f));
+ ImU32 green_dim = ImGui::ColorConvertFloat4ToU32(ImVec4(0.0f, 0.6f, 0.3f, 0.6f));
+ ImU32 red_dim = ImGui::ColorConvertFloat4ToU32(ImVec4(0.7f, 0.15f, 0.15f, 0.6f));
+ ImU32 text_col = ImGui::ColorConvertFloat4ToU32(TEXT_DIM);
+ ImU32 crosshair_col = ImGui::ColorConvertFloat4ToU32(ImVec4(0.4f, 0.4f, 0.5f, 0.5f));
+
+ // Reserve right margin for price axis
+ float price_axis_w = 70.0f;
+ float plot_w = chart_w - price_axis_w;
+ if (plot_w < 50) plot_w = chart_w;
+
+ // Determine how many candles fit
+ float candle_width = 6.0f;
+ float candle_gap = 2.0f;
+ float candle_step = candle_width + candle_gap;
+ int max_visible = (int)(plot_w / candle_step);
+ if (max_visible < 5) max_visible = 5;
+
+ // Get visible range (show most recent candles)
+ int total = (int)candles_.size();
+ int start_idx = total > max_visible ? total - max_visible : 0;
+ int visible_count = total - start_idx;
+ if (visible_count <= 0) return;
+
+ // Find price range
+ double price_high = -1e18;
+ double price_low = 1e18;
+ for (int i = start_idx; i < total; i++) {
+ const auto& c = candles_[i];
+ if (c.high > price_high) price_high = c.high;
+ if (c.low < price_low) price_low = c.low;
+ }
+
+ // Add 2% padding
+ double range = price_high - price_low;
+ if (range < 0.01) range = 1.0;
+ double padding = range * 0.02;
+ price_high += padding;
+ price_low -= padding;
+ range = price_high - price_low;
+
+ // Helper: price to Y coordinate
+ auto price_to_y = [&](double price) -> float {
+ return origin.y + chart_h * (1.0f - (float)((price - price_low) / range));
+ };
+
+ // Draw grid lines (horizontal)
+ int grid_lines = 5;
+ for (int i = 0; i <= grid_lines; i++) {
+ float y = origin.y + chart_h * i / (float)grid_lines;
+ dl->AddLine(ImVec2(origin.x, y), ImVec2(origin.x + plot_w, y), grid_col);
+
+ // Price labels on right axis
+ if (plot_w < chart_w) {
+ double price = price_high - (range * i / grid_lines);
+ char label[32];
+ if (price >= 1000)
+ std::snprintf(label, sizeof(label), "%.1f", price);
+ else if (price >= 1)
+ std::snprintf(label, sizeof(label), "%.2f", price);
+ else
+ std::snprintf(label, sizeof(label), "%.4f", price);
+ dl->AddText(ImVec2(origin.x + plot_w + 4, y - 6), text_col, label);
+ }
+ }
+
+ // Draw vertical grid lines
+ int v_grid = 6;
+ for (int i = 1; i < v_grid; i++) {
+ float x = origin.x + plot_w * i / (float)v_grid;
+ dl->AddLine(ImVec2(x, origin.y), ImVec2(x, origin.y + chart_h), grid_col);
+ }
+
+ // Draw candles
+ float x_start = origin.x + plot_w - visible_count * candle_step;
+
+ for (int i = 0; i < visible_count; i++) {
+ const auto& c = candles_[start_idx + i];
+ float cx = x_start + i * candle_step + candle_width * 0.5f;
+
+ bool bullish = c.close >= c.open;
+ ImU32 body_col = bullish ? green : red;
+ ImU32 wick_col = bullish ? green_dim : red_dim;
+
+ // Wick (high-low line)
+ float wick_x = cx;
+ float wick_top = price_to_y(c.high);
+ float wick_bot = price_to_y(c.low);
+ dl->AddLine(ImVec2(wick_x, wick_top), ImVec2(wick_x, wick_bot), wick_col, 1.0f);
+
+ // Body (open-close rect)
+ float body_top = price_to_y(bullish ? c.close : c.open);
+ float body_bot = price_to_y(bullish ? c.open : c.close);
+ float body_min_h = 1.0f;
+ if (body_bot - body_top < body_min_h) {
+ body_bot = body_top + body_min_h;
+ }
+
+ float body_left = cx - candle_width * 0.5f;
+ float body_right = cx + candle_width * 0.5f;
+ dl->AddRectFilled(ImVec2(body_left, body_top), ImVec2(body_right, body_bot), body_col);
+ }
+
+ // Volume bars at bottom (subtle, 15% of chart height)
+ double vol_max = 0;
+ for (int i = start_idx; i < total; i++) {
+ if (candles_[i].volume > vol_max) vol_max = candles_[i].volume;
+ }
+
+ if (vol_max > 0) {
+ float vol_zone = chart_h * 0.15f;
+ float vol_base = origin.y + chart_h;
+
+ for (int i = 0; i < visible_count; i++) {
+ const auto& c = candles_[start_idx + i];
+ float cx = x_start + i * candle_step + candle_width * 0.5f;
+ float vol_h = (float)(c.volume / vol_max) * vol_zone;
+ bool bullish = c.close >= c.open;
+
+ ImU32 vol_col = bullish
+ ? ImGui::ColorConvertFloat4ToU32(ImVec4(0.0f, 0.5f, 0.25f, 0.3f))
+ : ImGui::ColorConvertFloat4ToU32(ImVec4(0.5f, 0.1f, 0.1f, 0.3f));
+
+ float body_left = cx - candle_width * 0.5f;
+ float body_right = cx + candle_width * 0.5f;
+ dl->AddRectFilled(ImVec2(body_left, vol_base - vol_h),
+ ImVec2(body_right, vol_base), vol_col);
+ }
+ }
+
+ // Current price line
+ if (current_ticker_.last > 0 && current_ticker_.last >= price_low && current_ticker_.last <= price_high) {
+ float y = price_to_y(current_ticker_.last);
+ ImU32 price_line_col = ImGui::ColorConvertFloat4ToU32(
+ current_ticker_.change >= 0 ? MARKET_GREEN : MARKET_RED);
+
+ // Dashed line effect
+ float dash_len = 6.0f;
+ for (float x = origin.x; x < origin.x + plot_w; x += dash_len * 2) {
+ float end = x + dash_len;
+ if (end > origin.x + plot_w) end = origin.x + plot_w;
+ dl->AddLine(ImVec2(x, y), ImVec2(end, y), price_line_col, 1.0f);
+ }
+
+ // Price tag on right
+ if (plot_w < chart_w) {
+ char tag[32];
+ if (current_ticker_.last >= 1000)
+ std::snprintf(tag, sizeof(tag), "%.1f", current_ticker_.last);
+ else
+ std::snprintf(tag, sizeof(tag), "%.2f", current_ticker_.last);
+
+ ImVec2 tag_size = ImGui::CalcTextSize(tag);
+ float tag_x = origin.x + plot_w + 2;
+ float tag_y = y - tag_size.y * 0.5f;
+ dl->AddRectFilled(ImVec2(tag_x, tag_y - 1),
+ ImVec2(tag_x + tag_size.x + 6, tag_y + tag_size.y + 1),
+ price_line_col);
+ dl->AddText(ImVec2(tag_x + 3, tag_y),
+ ImGui::ColorConvertFloat4ToU32(ImVec4(1, 1, 1, 1)), tag);
+ }
+ }
+
+ // Crosshair on hover
+ ImVec2 mouse = ImGui::GetMousePos();
+ if (mouse.x >= origin.x && mouse.x <= origin.x + plot_w &&
+ mouse.y >= origin.y && mouse.y <= origin.y + chart_h) {
+
+ dl->AddLine(ImVec2(origin.x, mouse.y), ImVec2(origin.x + plot_w, mouse.y), crosshair_col);
+ dl->AddLine(ImVec2(mouse.x, origin.y), ImVec2(mouse.x, origin.y + chart_h), crosshair_col);
+
+ // Price at cursor Y
+ double hover_price = price_high - range * ((mouse.y - origin.y) / chart_h);
+ char hover_label[32];
+ std::snprintf(hover_label, sizeof(hover_label), "%.2f", hover_price);
+ dl->AddText(ImVec2(origin.x + plot_w + 4, mouse.y - 6),
+ ImGui::ColorConvertFloat4ToU32(TEXT_PRIMARY), hover_label);
+ }
+}
+
+// ============================================================================
+// Bottom Panel — Positions / Orders / History / Stats
+// ============================================================================
+void CryptoTradingScreen::render_bottom_panel(float w, float h) {
+ ImGui::PushStyleColor(ImGuiCol_ChildBg, BG_PANEL);
+ ImGui::BeginChild("##crypto_bottom", ImVec2(w, h), true);
+
+ struct TabDef { const char* label; BottomTab tab; };
+ static const TabDef tabs[] = {
+ {"Positions", BottomTab::Positions},
+ {"Orders", BottomTab::Orders},
+ {"History", BottomTab::History},
+ {"Trades", BottomTab::Trades},
+ {"Market Info", BottomTab::MarketInfo},
+ {"Stats", BottomTab::Stats},
+ };
+
+ for (int i = 0; i < 6; i++) {
+ if (i > 0) ImGui::SameLine(0, 2);
+ bool active = (bottom_tab_ == tabs[i].tab);
+ ImGui::PushStyleColor(ImGuiCol_Button, active ? ACCENT_BG : ImVec4(0, 0, 0, 0));
+ ImGui::PushStyleColor(ImGuiCol_Text, active ? ACCENT : TEXT_DIM);
+ if (ImGui::SmallButton(tabs[i].label)) {
+ bottom_tab_ = tabs[i].tab;
+ }
+ ImGui::PopStyleColor(2);
+ }
+
+ // Count badges
+ {
+ std::lock_guard<std::mutex> lock(data_mutex_);
+ ImGui::SameLine(0, 8);
+
+ if (trading_mode_ == TradingMode::Live && has_credentials_) {
+ if (!live_positions_.empty()) {
+ char badge[16];
+ std::snprintf(badge, sizeof(badge), "[%d pos]", (int)live_positions_.size());
+ ImGui::TextColored(ACCENT, "%s", badge);
+ ImGui::SameLine(0, 4);
+ }
+ int open_count = 0;
+ for (auto& o : live_orders_) if (o.status == "open") open_count++;
+ if (open_count > 0) {
+ char badge[16];
+ std::snprintf(badge, sizeof(badge), "[%d ord]", open_count);
+ ImGui::TextColored(WARNING, "%s", badge);
+ }
+ } else if (trading_mode_ == TradingMode::Paper) {
+ if (!positions_.empty()) {
+ char badge[16];
+ std::snprintf(badge, sizeof(badge), "[%d pos]", (int)positions_.size());
+ ImGui::TextColored(ACCENT, "%s", badge);
+ ImGui::SameLine(0, 4);
+ }
+ int pending = 0;
+ for (auto& o : orders_) if (o.status == "pending") pending++;
+ if (pending > 0) {
+ char badge[16];
+ std::snprintf(badge, sizeof(badge), "[%d ord]", pending);
+ ImGui::TextColored(WARNING, "%s", badge);
+ }
+ }
+ }
+
+ ImGui::Separator();
+
+ ImGui::BeginChild("##bottom_content", ImVec2(0, 0), false);
+ switch (bottom_tab_) {
+ case BottomTab::Positions: render_positions_tab(); break;
+ case BottomTab::Orders: render_orders_tab(); break;
+ case BottomTab::History: render_history_tab(); break;
+ case BottomTab::Trades: render_trades_tab(); break;
+ case BottomTab::MarketInfo: render_market_info_tab(); break;
+ case BottomTab::Stats: render_stats_tab(); break;
+ }
+ ImGui::EndChild();
+
+ ImGui::EndChild();
+ ImGui::PopStyleColor();
+}
+
+
+} // namespace fincept::crypto
diff --git a/fincept-cpp/src/screens/crypto_trading/crypto_credentials.cpp b/fincept-cpp/src/screens/crypto_trading/crypto_credentials.cpp
new file mode 100644
index 000000000..498e0d91a
--- /dev/null
+++ b/fincept-cpp/src/screens/crypto_trading/crypto_credentials.cpp
@@ -0,0 +1,183 @@
+#include "crypto_trading_screen.h"
+#include "crypto_internal.h"
+#include "ui/theme.h"
+#include "trading/exchange_service.h"
+#include "storage/database.h"
+#include "core/logger.h"
+#include <imgui.h>
+#include <cstring>
+
+namespace fincept::crypto {
+
+using namespace theme::colors;
+
+
+void CryptoTradingScreen::load_exchange_credentials() {
+ std::string service = "exchange_" + exchange_id_;
+ auto opt = db::ops::get_credential_by_service(service);
+ if (opt) {
+ std::strncpy(cred_api_key_, opt->api_key.value_or("").c_str(), sizeof(cred_api_key_) - 1);
+ std::strncpy(cred_api_secret_, opt->api_secret.value_or("").c_str(), sizeof(cred_api_secret_) - 1);
+ std::strncpy(cred_password_, opt->password.value_or("").c_str(), sizeof(cred_password_) - 1);
+
+ has_credentials_ = (cred_api_key_[0] != '\0' && cred_api_secret_[0] != '\0');
+
+ // Push to ExchangeService
+ if (has_credentials_) {
+ trading::ExchangeCredentials ec;
+ ec.api_key = cred_api_key_;
+ ec.secret = cred_api_secret_;
+ ec.password = cred_password_;
+ trading::ExchangeService::instance().set_credentials(ec);
+ }
+ } else {
+ cred_api_key_[0] = '\0';
+ cred_api_secret_[0] = '\0';
+ cred_password_[0] = '\0';
+ has_credentials_ = false;
+ }
+ credentials_loaded_ = true;
+}
+
+void CryptoTradingScreen::save_exchange_credentials() {
+ std::string service = "exchange_" + exchange_id_;
+
+ db::Credential c;
+ c.service_name = service;
+ c.api_key = std::string(cred_api_key_);
+ c.api_secret = std::string(cred_api_secret_);
+ c.password = std::string(cred_password_);
+ db::ops::save_credential(c);
+
+ has_credentials_ = (cred_api_key_[0] != '\0' && cred_api_secret_[0] != '\0');
+
+ // Push to ExchangeService
+ if (has_credentials_) {
+ trading::ExchangeCredentials ec;
+ ec.api_key = cred_api_key_;
+ ec.secret = cred_api_secret_;
+ ec.password = cred_password_;
+ trading::ExchangeService::instance().set_credentials(ec);
+
+ // Trigger initial live data fetch
+ if (trading_mode_ == TradingMode::Live) {
+ async_fetch_live_balance();
+ async_fetch_live_positions();
+ async_fetch_live_orders();
+ }
+ }
+
+ LOG_INFO(TAG, "Credentials saved for %s (has_key=%d)", exchange_id_.c_str(), has_credentials_);
+}
+
+bool CryptoTradingScreen::has_credentials() const {
+ return has_credentials_;
+}
+
+void CryptoTradingScreen::render_credentials_popup() {
+ if (!show_credentials_popup_) return;
+
+ ImGui::SetNextWindowSize(ImVec2(420, 320), ImGuiCond_FirstUseEver);
+ if (ImGui::Begin("Exchange API Credentials", &show_credentials_popup_,
+ ImGuiWindowFlags_NoCollapse | ImGuiWindowFlags_NoDocking)) {
+
+ // Exchange name header
+ char header[128];
+ std::snprintf(header, sizeof(header), "Configure API Key for: %s", exchange_id_.c_str());
+ ImGui::TextColored(ACCENT, "%s", header);
+ ImGui::Separator();
+ ImGui::Spacing();
+
+ float input_w = ImGui::GetContentRegionAvail().x - 16;
+
+ // API Key
+ ImGui::TextColored(TEXT_DIM, "API Key");
+ ImGui::PushItemWidth(input_w);
+ ImGui::PushStyleColor(ImGuiCol_FrameBg, BG_INPUT);
+ ImGui::InputText("##cred_api_key", cred_api_key_, sizeof(cred_api_key_));
+ ImGui::PopStyleColor();
+ ImGui::PopItemWidth();
+
+ ImGui::Spacing();
+
+ // API Secret
+ ImGui::TextColored(TEXT_DIM, "API Secret");
+ ImGui::PushItemWidth(input_w);
+ ImGui::PushStyleColor(ImGuiCol_FrameBg, BG_INPUT);
+ ImGui::InputText("##cred_api_secret", cred_api_secret_, sizeof(cred_api_secret_),
+ ImGuiInputTextFlags_Password);
+ ImGui::PopStyleColor();
+ ImGui::PopItemWidth();
+
+ ImGui::Spacing();
+
+ // Password (for exchanges that require it: OKX, Kucoin, etc.)
+ bool needs_password = (exchange_id_ == "okx" || exchange_id_ == "kucoin" ||
+ exchange_id_ == "gate" || exchange_id_ == "bitget");
+ if (needs_password) {
+ ImGui::TextColored(TEXT_DIM, "Passphrase / Password");
+ ImGui::PushItemWidth(input_w);
+ ImGui::PushStyleColor(ImGuiCol_FrameBg, BG_INPUT);
+ ImGui::InputText("##cred_password", cred_password_, sizeof(cred_password_),
+ ImGuiInputTextFlags_Password);
+ ImGui::PopStyleColor();
+ ImGui::PopItemWidth();
+ ImGui::Spacing();
+ }
+
+ // Status
+ if (has_credentials_) {
+ ImGui::TextColored(MARKET_GREEN, "Credentials configured");
+ } else {
+ ImGui::TextColored(TEXT_DIM, "No credentials stored for this exchange");
+ }
+
+ ImGui::Spacing();
+ ImGui::Separator();
+ ImGui::Spacing();
+
+ // Buttons
+ float btn_w = (input_w - 12) / 3;
+
+ ImGui::PushStyleColor(ImGuiCol_Button, ImVec4(0.0f, 0.5f, 0.25f, 1.0f));
+ ImGui::PushStyleColor(ImGuiCol_Text, TEXT_PRIMARY);
+ if (ImGui::Button("Save", ImVec2(btn_w, 28))) {
+ save_exchange_credentials();
+ show_credentials_popup_ = false;
+ }
+ ImGui::PopStyleColor(2);
+
+ ImGui::SameLine(0, 6);
+
+ ImGui::PushStyleColor(ImGuiCol_Button, ImVec4(0.5f, 0.1f, 0.1f, 1.0f));
+ ImGui::PushStyleColor(ImGuiCol_Text, TEXT_PRIMARY);
+ if (ImGui::Button("Clear", ImVec2(btn_w, 28))) {
+ cred_api_key_[0] = '\0';
+ cred_api_secret_[0] = '\0';
+ cred_password_[0] = '\0';
+ save_exchange_credentials();
+ has_credentials_ = false;
+ }
+ ImGui::PopStyleColor(2);
+
+ ImGui::SameLine(0, 6);
+
+ ImGui::PushStyleColor(ImGuiCol_Button, BG_WIDGET);
+ ImGui::PushStyleColor(ImGuiCol_Text, TEXT_DIM);
+ if (ImGui::Button("Cancel", ImVec2(btn_w, 28))) {
+ show_credentials_popup_ = false;
+ }
+ ImGui::PopStyleColor(2);
+
+ ImGui::Spacing();
+
+ // Security note
+ ImGui::PushStyleColor(ImGuiCol_Text, TEXT_DIM);
+ ImGui::TextWrapped("Credentials are stored encrypted in the local database. "
+ "Use read-only API keys when possible.");
+ ImGui::PopStyleColor();
+ }
+ ImGui::End();
+}
+
+} // namespace fincept::crypto
diff --git a/fincept-cpp/src/screens/crypto_trading/crypto_internal.h b/fincept-cpp/src/screens/crypto_trading/crypto_internal.h
new file mode 100644
index 000000000..2df26b2fd
--- /dev/null
+++ b/fincept-cpp/src/screens/crypto_trading/crypto_internal.h
@@ -0,0 +1,32 @@
+#pragma once
+// crypto_internal.h — private shared constants for crypto_trading translation units.
+// Include ONLY from crypto_trading/*.cpp files.
+
+namespace fincept::crypto {
+
+static constexpr const char* TAG = "CryptoTrading";
+
+// Named constants (ES.45: avoid magic numbers)
+static constexpr int OHLCV_FETCH_COUNT = 200;
+static constexpr double DEFAULT_PAPER_BALANCE = 100000.0;
+static constexpr int PORTFOLIO_CLEANUP_THRESH = 10;
+static constexpr float TICKER_POLL_INTERVAL = 3.0f;
+static constexpr float ORDERBOOK_POLL_INTERVAL = 3.0f;
+static constexpr float WATCHLIST_POLL_INTERVAL = 15.0f;
+static constexpr float PORTFOLIO_REFRESH_INTERVAL = 1.5f;
+static constexpr float MARKET_INFO_INTERVAL = 30.0f;
+static constexpr int PRICE_FEED_POLL_SEC = 3;
+static constexpr int WS_MAX_WATCHLIST_SYMBOLS = 10;
+static constexpr int MAX_CANDLE_BUFFER = 500;
+static constexpr int PORTFOLIO_CLEANUP_TRADE_LIMIT = 1;
+
+// Order book analytics constants
+static constexpr double OB_IMBALANCE_BUY_THRESHOLD = 0.30;
+static constexpr double OB_IMBALANCE_SELL_THRESHOLD = -0.30;
+static constexpr double OB_RISE_BUY_THRESHOLD = 0.15;
+static constexpr double OB_RISE_SELL_THRESHOLD = -0.15;
+static constexpr int OB_MAX_TICK_HISTORY = 3600;
+static constexpr int OB_TICK_CAPTURE_MS = 1000;
+static constexpr int OB_MAX_OB_DISPLAY_LEVELS = 12;
+
+} // namespace fincept::crypto
diff --git a/fincept-cpp/src/screens/crypto_trading/crypto_lifecycle.cpp b/fincept-cpp/src/screens/crypto_trading/crypto_lifecycle.cpp
new file mode 100644
index 000000000..32ba6c55e
--- /dev/null
+++ b/fincept-cpp/src/screens/crypto_trading/crypto_lifecycle.cpp
@@ -0,0 +1,772 @@
+#include "crypto_trading_screen.h"
+#include "crypto_internal.h"
+#include "ui/yoga_helpers.h"
+#include "ui/theme.h"
+#include "trading/paper_trading.h"
+#include "trading/order_matcher.h"
+#include "core/logger.h"
+#include "core/notification.h"
+#include <imgui.h>
+#include <cstdio>
+#include <cstring>
+#include <cmath>
+#include <ctime>
+#include <algorithm>
+#include <chrono>
+#include <thread>
+
+namespace fincept::crypto {
+
+using namespace theme::colors;
+
+// ============================================================================
+std::vector<std::string> CryptoTradingScreen::default_watchlist_symbols() {
+ return {
+ "BTC/USDT", "ETH/USDT", "BNB/USDT", "SOL/USDT", "XRP/USDT",
+ "ADA/USDT", "DOGE/USDT", "AVAX/USDT", "DOT/USDT", "MATIC/USDT",
+ "LINK/USDT", "UNI/USDT", "ATOM/USDT", "LTC/USDT", "FIL/USDT",
+ "APT/USDT", "ARB/USDT", "OP/USDT", "NEAR/USDT", "SUI/USDT",
+ };
+}
+
+// ============================================================================
+// Destructor
+// ============================================================================
+CryptoTradingScreen::~CryptoTradingScreen() {
+ LOG_INFO(TAG, "Shutting down");
+ join_pending_threads(); // wait for in-flight fetches before tearing down (CP.26)
+
+ auto& svc = trading::ExchangeService::instance();
+ if (ws_started_) {
+ svc.stop_ws_stream();
+ ws_started_ = false;
+ }
+ if (ws_price_cb_id_ >= 0) svc.remove_price_callback(ws_price_cb_id_);
+ if (ws_ob_cb_id_ >= 0) svc.remove_orderbook_callback(ws_ob_cb_id_);
+ if (ws_candle_cb_id_ >= 0) svc.remove_candle_callback(ws_candle_cb_id_);
+ if (ws_trade_cb_id_ >= 0) svc.remove_trade_callback(ws_trade_cb_id_);
+}
+
+// ============================================================================
+// Thread lifecycle — RAII tracked async threads (CP.26: no detach)
+// ============================================================================
+void CryptoTradingScreen::launch_async(std::thread t) {
+ std::lock_guard<std::mutex> lock(threads_mutex_);
+ // Prune already-finished threads to keep the vector bounded
+ async_threads_.erase(
+ std::remove_if(async_threads_.begin(), async_threads_.end(),
+ [](std::thread& th) { return !th.joinable(); }),
+ async_threads_.end());
+ async_threads_.push_back(std::move(t));
+}
+
+void CryptoTradingScreen::join_pending_threads() {
+ std::lock_guard<std::mutex> lock(threads_mutex_);
+ for (auto& t : async_threads_) {
+ if (t.joinable()) t.join();
+ }
+ async_threads_.clear();
+}
+
+// ============================================================================
+// Initialization — fast, no blocking network calls
+// ============================================================================
+void CryptoTradingScreen::init() {
+ LOG_INFO(TAG, "=== INIT START ===");
+
+ // Ensure exchange_id has a value
+ if (exchange_id_.empty()) {
+ exchange_id_ = "binance";
+ LOG_INFO(TAG, "exchange_id_ was empty, defaulting to binance");
+ }
+ if (selected_symbol_.empty()) {
+ selected_symbol_ = "BTC/USDT";
+ }
+
+ // Set up exchange
+ auto& svc = trading::ExchangeService::instance();
+ svc.set_exchange(exchange_id_);
+ LOG_INFO(TAG, "Exchange set to: %s", exchange_id_.c_str());
+
+ // Load stored API credentials for this exchange (if any)
+ load_exchange_credentials();
+
+ // Build watchlist entries
+ auto symbols = default_watchlist_symbols();
+ watchlist_.clear();
+ for (auto& s : symbols) {
+ WatchlistEntry e;
+ e.symbol = s;
+ watchlist_.push_back(e);
+ }
+ LOG_INFO(TAG, "Watchlist initialized with %d symbols", (int)watchlist_.size());
+
+ // Create or load paper trading portfolio (DB only, fast)
+ load_portfolio();
+
+ // Register portfolio with exchange service so position prices get updated
+ if (!portfolio_id_.empty()) {
+ svc.watch_symbol(selected_symbol_, portfolio_id_);
+ // Also watch all symbols that have open positions
+ for (const auto& pos : positions_) {
+ if (pos.symbol != selected_symbol_) {
+ svc.watch_symbol(pos.symbol, portfolio_id_);
+ }
+ }
+ }
+
+ // Start the price feed for watched symbols (drives OrderMatcher + position updates)
+ if (!svc.is_feed_running()) {
+ svc.start_price_feed(PRICE_FEED_POLL_SEC);
+ }
+
+ // Fetch available exchanges from ccxt (async, non-blocking)
+ if (!exchanges_loaded_ && !exchanges_fetching_) {
+ exchanges_fetching_ = true;
+ launch_async(std::thread([this]() {
+ try {
+ auto ids = trading::ExchangeService::instance().list_exchange_ids();
+ LOG_INFO(TAG, "Loaded %d exchange IDs from ccxt", (int)ids.size());
+ std::lock_guard<std::mutex> lock(data_mutex_);
+ available_exchanges_ = std::move(ids);
+ exchanges_loaded_ = true;
+ } catch (const std::exception& e) {
+ LOG_ERROR(TAG, "Failed to load exchange IDs: %s", e.what());
+ }
+ exchanges_fetching_ = false;
+ }));
+ }
+
+ initialized_ = true;
+ LOG_INFO(TAG, "=== INIT COMPLETE === (portfolio_id=%s, balance=%.2f)",
+ portfolio_id_.c_str(), portfolio_.balance);
+
+ // Kick off initial REST fetches (fast initial data while WS connects)
+ LOG_INFO(TAG, "Starting async data fetches...");
+ ticker_loading_ = true;
+ ob_loading_ = true;
+ async_refresh_ticker();
+ async_refresh_orderbook();
+ async_refresh_watchlist_prices();
+
+ // Fetch initial OHLCV candles via REST
+ candles_loading_ = true;
+ candles_fetching_ = true;
+ const std::string sym = selected_symbol_;
+ launch_async(std::thread([this, sym]() {
+ try {
+ auto ohlcv = trading::ExchangeService::instance().fetch_ohlcv(sym, "1m", OHLCV_FETCH_COUNT);
+ LOG_INFO(TAG, "<<< Initial OHLCV received: %d candles", (int)ohlcv.size());
+ {
+ std::lock_guard<std::mutex> lock(data_mutex_);
+ candles_ = std::move(ohlcv);
+ }
+ candles_loading_ = false;
+ candles_fetching_ = false;
+ success_count_++;
+ } catch (const std::exception& e) {
+ LOG_ERROR(TAG, "<<< OHLCV fetch failed: %s", e.what());
+ candles_loading_ = false;
+ candles_fetching_ = false;
+ error_count_++;
+ }
+ }));
+
+ // Start WebSocket streaming for real-time updates
+ // restart_ws_stream() handles callback registration + stream start
+ restart_ws_stream();
+
+ // Fetch initial trades and market info via REST
+ async_fetch_trades();
+ async_fetch_market_info();
+}
+
+void CryptoTradingScreen::load_portfolio() {
+ LOG_INFO(TAG, "Loading paper trading portfolio for exchange: %s", exchange_id_.c_str());
+
+ try {
+ // Reset state so stale data from previous exchange doesn't leak
+ portfolio_id_.clear();
+ portfolio_ = {};
+ positions_.clear();
+ orders_.clear();
+ trades_.clear();
+ stats_ = {};
+ portfolio_loaded_ = false;
+
+ // Find portfolio scoped to this exchange
+ auto found = trading::pt_find_portfolio("Crypto Paper Trading", exchange_id_);
+ if (found) {
+ portfolio_ = *found;
+ portfolio_id_ = found->id;
+ LOG_INFO(TAG, "Using existing portfolio: %s (exchange=%s, balance=%.2f)",
+ portfolio_id_.c_str(), exchange_id_.c_str(), portfolio_.balance);
+ }
+
+ // Create if not found for this exchange
+ if (portfolio_id_.empty()) {
+ portfolio_ = trading::pt_create_portfolio(
+ "Crypto Paper Trading", DEFAULT_PAPER_BALANCE, "USDT",
+ 1.0, "cross", 0.001, exchange_id_);
+ portfolio_id_ = portfolio_.id;
+ LOG_INFO(TAG, "Created new portfolio: %s (exchange=%s, balance=%.2f)",
+ portfolio_id_.c_str(), exchange_id_.c_str(), portfolio_.balance);
+ }
+
+ // Load positions, orders, trades, stats from DB
+ positions_ = trading::pt_get_positions(portfolio_id_);
+ orders_ = trading::pt_get_orders(portfolio_id_);
+ trades_ = trading::pt_get_trades(portfolio_id_, 50);
+ stats_ = trading::pt_get_stats(portfolio_id_);
+ portfolio_loaded_ = true;
+
+ LOG_INFO(TAG, "Portfolio data loaded: %d positions, %d orders, %d trades",
+ (int)positions_.size(), (int)orders_.size(), (int)trades_.size());
+ } catch (const std::exception& e) {
+ LOG_ERROR(TAG, "Failed to load portfolio: %s", e.what());
+ last_error_ = std::string("Portfolio load failed: ") + e.what();
+ error_count_++;
+ }
+}
+
+// ============================================================================
+// Exchange & symbol switching — proper lifecycle management
+// ============================================================================
+
+void CryptoTradingScreen::clear_market_data() {
+ std::lock_guard<std::mutex> lock(data_mutex_);
+ current_ticker_ = {};
+ ob_bids_.clear();
+ ob_asks_.clear();
+ ob_spread_ = 0.0;
+ ob_spread_pct_ = 0.0;
+ candles_.clear();
+ recent_trades_.clear();
+ market_info_ = {};
+ for (auto& w : watchlist_) {
+ w.price = 0.0;
+ w.change = 0.0;
+ w.change_pct = 0.0;
+ w.volume = 0.0;
+ w.has_data = false;
+ }
+ last_error_.clear();
+ error_count_ = 0;
+ success_count_ = 0;
+}
+
+void CryptoTradingScreen::restart_ws_stream() {
+ auto& svc = trading::ExchangeService::instance();
+
+ // Tear down existing WS
+ if (ws_started_) {
+ svc.stop_ws_stream();
+ ws_started_ = false;
+ }
+
+ // Remove old callbacks
+ if (ws_price_cb_id_ >= 0) { svc.remove_price_callback(ws_price_cb_id_); ws_price_cb_id_ = -1; }
+ if (ws_ob_cb_id_ >= 0) { svc.remove_orderbook_callback(ws_ob_cb_id_); ws_ob_cb_id_ = -1; }
+ if (ws_candle_cb_id_ >= 0) { svc.remove_candle_callback(ws_candle_cb_id_); ws_candle_cb_id_ = -1; }
+ if (ws_trade_cb_id_ >= 0) { svc.remove_trade_callback(ws_trade_cb_id_); ws_trade_cb_id_ = -1; }
+
+ // Re-register callbacks (same as in init())
+ ws_price_cb_id_ = svc.on_price_update([this](const std::string& symbol, const trading::TickerData& ticker) {
+ std::lock_guard<std::mutex> lock(data_mutex_);
+ if (symbol == selected_symbol_) {
+ current_ticker_ = ticker;
+ ticker_loading_ = false;
+ }
+ for (auto& w : watchlist_) {
+ if (w.symbol == symbol) {
+ w.price = ticker.last;
+ w.change = ticker.change;
+ w.change_pct = ticker.percentage;
+ w.volume = ticker.base_volume;
+ w.has_data = true;
+ break;
+ }
+ }
+ last_data_update_ = time(nullptr);
+ });
+
+ ws_ob_cb_id_ = svc.on_orderbook_update([this](const std::string& symbol, const trading::OrderBookData& ob) {
+ if (symbol != selected_symbol_) return;
+ std::lock_guard<std::mutex> lock(data_mutex_);
+
+ // Parse bids/asks into cumulative levels
+ ob_bids_.clear();
+ ob_asks_.clear();
+ {
+ double cum = 0;
+ for (const auto& [price, amount] : ob.bids) {
+ cum += amount;
+ ob_bids_.push_back({price, amount, cum});
+ }
+ }
+ {
+ double cum = 0;
+ for (const auto& [price, amount] : ob.asks) {
+ cum += amount;
+ ob_asks_.push_back({price, amount, cum});
+ }
+ }
+ ob_spread_ = ob.spread;
+ ob_spread_pct_ = ob.spread_pct;
+ ob_loading_ = false;
+ last_data_update_ = time(nullptr);
+
+ // --- Tick history capture (throttled to OB_TICK_CAPTURE_MS) ---
+ // Feeds Imbalance and Signals view modes with computed analytics.
+ const int64_t now_ms = std::chrono::duration_cast<std::chrono::milliseconds>(
+ std::chrono::steady_clock::now().time_since_epoch()).count();
+
+ if (now_ms - last_tick_capture_ms_ >= static_cast<int64_t>(OB_TICK_CAPTURE_MS)) {
+ last_tick_capture_ms_ = now_ms;
+
+ TickSnapshot snap;
+ snap.timestamp = now_ms;
+ snap.best_bid = ob.best_bid;
+ snap.best_ask = ob.best_ask;
+
+ // Top-3 quantities from each side for weighted imbalance
+ for (int i = 0; i < 3 && i < static_cast<int>(ob_bids_.size()); ++i)
+ snap.bid_qty[i] = ob_bids_[i].amount;
+ for (int i = 0; i < 3 && i < static_cast<int>(ob_asks_.size()); ++i)
+ snap.ask_qty[i] = ob_asks_[i].amount;
+
+ // Weighted imbalance: 50/30/20 top-3 levels (SGX formula, from Tauri impl)
+ const double wBid = 50.0 * snap.bid_qty[0] + 30.0 * snap.bid_qty[1] + 20.0 * snap.bid_qty[2];
+ const double wAsk = 50.0 * snap.ask_qty[0] + 30.0 * snap.ask_qty[1] + 20.0 * snap.ask_qty[2];
+ snap.imbalance = (wBid + wAsk > 0.0) ? (wBid - wAsk) / (wBid + wAsk) : 0.0;
+
+ // 60-second rise ratio: find oldest tick within 60s window
+ const int64_t cutoff_60 = now_ms - 60000;
+ snap.rise_ratio_60 = 0.0;
+ for (int i = static_cast<int>(tick_history_.size()) - 1; i >= 0; --i) {
+ if (tick_history_[i].timestamp <= cutoff_60 && tick_history_[i].best_ask > 0.0) {
+ snap.rise_ratio_60 = ((ob.best_ask - tick_history_[i].best_ask)
+ / tick_history_[i].best_ask) * 100.0;
+ break;
+ }
+ }
+
+ tick_history_.push_back(snap);
+ if (static_cast<int>(tick_history_.size()) > OB_MAX_TICK_HISTORY)
+ tick_history_.erase(tick_history_.begin());
+ }
+ });
+
+ ws_candle_cb_id_ = svc.on_candle_update([this](const std::string& symbol, const trading::Candle& candle) {
+ if (symbol != selected_symbol_) return;
+ std::lock_guard<std::mutex> lock(data_mutex_);
+ if (!candles_.empty() && candles_.back().timestamp == candle.timestamp) {
+ candles_.back() = candle;
+ } else {
+ candles_.push_back(candle);
+ if (candles_.size() > MAX_CANDLE_BUFFER) candles_.erase(candles_.begin());
+ }
+ });
+
+ ws_trade_cb_id_ = svc.on_trade_update([this](const std::string& symbol, const trading::TradeData& trade) {
+ if (symbol != selected_symbol_) return;
+ std::lock_guard<std::mutex> lock(data_mutex_);
+ recent_trades_.insert(recent_trades_.begin(), TradeEntry{
+ trade.id, trade.side, trade.price, trade.amount, trade.timestamp
+ });
+ if ((int)recent_trades_.size() > MAX_TRADES) recent_trades_.resize(MAX_TRADES);
+ });
+
+ // Start new WS stream — cap to top N symbols to limit concurrent WS subscriptions.
+ // Primary symbol is always first; remaining slots filled from watchlist in order.
+ // Callbacks capture `this` — selected_symbol_ is read at invocation time,
+ // so symbol switches (via set_ws_primary_symbol) take effect automatically
+ // without restarting these callbacks.
+ std::vector<std::string> all_symbols;
+ all_symbols.reserve(WS_MAX_WATCHLIST_SYMBOLS + 1);
+ all_symbols.push_back(selected_symbol_);
+ for (const auto& w : watchlist_) {
+ if ((int)all_symbols.size() >= WS_MAX_WATCHLIST_SYMBOLS) break;
+ if (w.symbol != selected_symbol_) all_symbols.push_back(w.symbol);
+ }
+
+ try {
+ svc.start_ws_stream(selected_symbol_, all_symbols);
+ ws_started_ = true;
+ LOG_INFO(TAG, "WS stream restarted for %s + %d symbols on %s",
+ selected_symbol_.c_str(), (int)all_symbols.size(), exchange_id_.c_str());
+ } catch (const std::exception& e) {
+ LOG_ERROR(TAG, "Failed to restart WS: %s", e.what());
+ last_error_ = std::string("WS restart failed: ") + e.what();
+ }
+}
+
+void CryptoTradingScreen::switch_exchange(const std::string& exchange_id) {
+ if (exchange_id == exchange_id_) return;
+
+ LOG_INFO(TAG, "Switching exchange: %s -> %s", exchange_id_.c_str(), exchange_id.c_str());
+
+ // Stop price feed before switching (it uses the old exchange)
+ auto& svc = trading::ExchangeService::instance();
+ svc.stop_price_feed();
+
+ // Update exchange
+ exchange_id_ = exchange_id;
+ svc.set_exchange(exchange_id);
+
+ // Invalidate search cache — new exchange has different markets
+ search_markets_loaded_ = false;
+ search_cache_exchange_.clear();
+ all_markets_.clear();
+ search_results_.clear();
+
+ // Load credentials for the new exchange
+ load_exchange_credentials();
+ live_data_loaded_ = false;
+
+ // Clear all stale market data from previous exchange
+ clear_market_data();
+
+ // Swap portfolio — each exchange gets its own isolated paper portfolio
+ // Unwatch symbols from old portfolio first
+ if (!portfolio_id_.empty()) {
+ svc.unwatch_symbol(selected_symbol_, portfolio_id_);
+ for (const auto& pos : positions_) {
+ svc.unwatch_symbol(pos.symbol, portfolio_id_);
+ }
+ trading::OrderMatcher::instance().clear_portfolio_orders(portfolio_id_);
+ }
+ load_portfolio();
+
+ // Reset loading states
+ ticker_loading_ = true;
+ ob_loading_ = true;
+ candles_loading_ = true;
+
+ // Re-watch the selected symbol with the NEW portfolio
+ if (!portfolio_id_.empty()) {
+ svc.watch_symbol(selected_symbol_, portfolio_id_);
+ for (const auto& pos : positions_) {
+ if (pos.symbol != selected_symbol_) {
+ svc.watch_symbol(pos.symbol, portfolio_id_);
+ }
+ }
+ }
+ svc.start_price_feed(PRICE_FEED_POLL_SEC);
+
+ // Restart WebSocket stream for new exchange
+ restart_ws_stream();
+
+ // Kick off REST fetches for immediate data
+ async_refresh_ticker();
+ async_refresh_orderbook();
+ async_refresh_watchlist_prices();
+ async_fetch_trades();
+ async_fetch_market_info();
+
+ // Fetch fresh candles
+ candles_fetching_ = true;
+ const std::string sym = selected_symbol_;
+ launch_async(std::thread([this, sym]() {
+ try {
+ auto ohlcv = trading::ExchangeService::instance().fetch_ohlcv(sym, "1m", OHLCV_FETCH_COUNT);
+ {
+ std::lock_guard<std::mutex> lock(data_mutex_);
+ candles_ = std::move(ohlcv);
+ }
+ candles_loading_ = false;
+ candles_fetching_ = false;
+ } catch (const std::exception& e) {
+ LOG_ERROR(TAG, "OHLCV fetch failed on exchange switch: %s", e.what());
+ candles_loading_ = false;
+ candles_fetching_ = false;
+ }
+ }));
+
+ LOG_INFO(TAG, "Exchange switch complete: %s", exchange_id.c_str());
+}
+
+void CryptoTradingScreen::switch_symbol(const std::string& symbol) {
+ if (symbol == selected_symbol_) return;
+
+ LOG_INFO(TAG, "Switching symbol: %s -> %s", selected_symbol_.c_str(), symbol.c_str());
+
+ selected_symbol_ = symbol;
+
+ // Clear symbol-specific data (keep watchlist prices intact)
+ {
+ std::lock_guard<std::mutex> lock(data_mutex_);
+ current_ticker_ = {};
+ ob_bids_.clear();
+ ob_asks_.clear();
+ ob_spread_ = 0.0;
+ ob_spread_pct_ = 0.0;
+ candles_.clear();
+ recent_trades_.clear();
+ market_info_ = {};
+ }
+
+ ticker_loading_ = true;
+ ob_loading_ = true;
+ candles_loading_ = true;
+
+ // Watch new symbol for paper trading price updates
+ if (!portfolio_id_.empty()) {
+ trading::ExchangeService::instance().watch_symbol(symbol, portfolio_id_);
+ }
+
+ // Tell ExchangeService the new primary — WS subprocess stays alive,
+ // callbacks filter on selected_symbol_ (member read at invocation time)
+ // so they automatically route to the new symbol without a subprocess restart.
+ trading::ExchangeService::instance().set_ws_primary_symbol(symbol);
+
+ // Serve from price cache immediately — eliminates blank ticker on switch
+ {
+ const auto cached = trading::ExchangeService::instance().get_cached_price(symbol);
+ if (cached.last > 0.0) {
+ std::lock_guard<std::mutex> lock(data_mutex_);
+ current_ticker_ = cached;
+ ticker_loading_ = false;
+ LOG_INFO(TAG, "Showing cached price for %s: %.4f", symbol.c_str(), cached.last);
+ }
+ }
+
+ // REST fetches to fill data not yet in cache (orderbook, candles, trades, market info)
+ async_refresh_ticker();
+ async_refresh_orderbook();
+ async_fetch_trades();
+ async_fetch_market_info();
+
+ // Fetch OHLCV candles for new symbol
+ candles_fetching_ = true;
+ const std::string sym = symbol;
+ launch_async(std::thread([this, sym]() {
+ try {
+ auto ohlcv = trading::ExchangeService::instance().fetch_ohlcv(
+ sym, candle_timeframe_, OHLCV_FETCH_COUNT);
+ {
+ std::lock_guard<std::mutex> lock(data_mutex_);
+ candles_ = std::move(ohlcv);
+ }
+ candles_loading_ = false;
+ candles_fetching_ = false;
+ } catch (const std::exception& e) {
+ LOG_ERROR(TAG, "OHLCV fetch failed on symbol switch: %s", e.what());
+ candles_loading_ = false;
+ candles_fetching_ = false;
+ }
+ }));
+}
+
+// ============================================================================
+// Async data fetchers — run in detached threads
+// ============================================================================
+void CryptoTradingScreen::async_refresh_ticker() {
+ if (ticker_fetching_) {
+ LOG_DEBUG(TAG, "Ticker fetch already in flight, skipping");
+ return;
+ }
+
+ ticker_fetching_ = true;
+ ticker_loading_ = true;
+ const std::string symbol = selected_symbol_;
+ LOG_INFO(TAG, ">>> Fetching ticker for %s...", symbol.c_str());
+
+ launch_async(std::thread([this, symbol]() {
+ try {
+ auto ticker = trading::ExchangeService::instance().fetch_ticker(symbol);
+
+ LOG_INFO(TAG, "<<< Ticker received: %s last=%.2f bid=%.2f ask=%.2f change=%.2f%%",
+ ticker.symbol.c_str(), ticker.last, ticker.bid, ticker.ask, ticker.percentage);
+
+ {
+ std::lock_guard<std::mutex> lock(data_mutex_);
+ current_ticker_ = ticker;
+
+ // Also update the watchlist entry
+ for (auto& w : watchlist_) {
+ if (w.symbol == symbol) {
+ w.price = ticker.last;
+ w.change = ticker.change;
+ w.change_pct = ticker.percentage;
+ w.volume = ticker.base_volume;
+ w.has_data = true;
+ break;
+ }
+ }
+ }
+
+ ticker_loading_ = false;
+ ticker_fetching_ = false;
+ success_count_++;
+ last_data_update_ = time(nullptr);
+ } catch (const std::exception& e) {
+ LOG_ERROR(TAG, "<<< Ticker fetch FAILED for %s: %s", symbol.c_str(), e.what());
+ ticker_loading_ = false;
+ ticker_fetching_ = false;
+ last_error_ = std::string("Ticker: ") + e.what();
+ error_count_++;
+ }
+ }));
+}
+
+void CryptoTradingScreen::async_refresh_orderbook() {
+ if (ob_fetching_) {
+ LOG_DEBUG(TAG, "Orderbook fetch already in flight, skipping");
+ return;
+ }
+
+ ob_fetching_ = true;
+ ob_loading_ = true;
+ const std::string symbol = selected_symbol_;
+ LOG_INFO(TAG, ">>> Fetching orderbook for %s...", symbol.c_str());
+
+ launch_async(std::thread([this, symbol]() {
+ try {
+ auto ob = trading::ExchangeService::instance().fetch_orderbook(symbol, 15);
+
+ LOG_INFO(TAG, "<<< Orderbook received: %s bids=%d asks=%d spread=%.4f (%.4f%%)",
+ ob.symbol.c_str(), (int)ob.bids.size(), (int)ob.asks.size(),
+ ob.spread, ob.spread_pct);
+
+ {
+ std::lock_guard<std::mutex> lock(data_mutex_);
+ ob_bids_.clear();
+ ob_asks_.clear();
+
+ double cum = 0;
+ for (auto& [price, amount] : ob.bids) {
+ cum += amount;
+ ob_bids_.push_back({price, amount, cum});
+ }
+
+ cum = 0;
+ for (auto& [price, amount] : ob.asks) {
+ cum += amount;
+ ob_asks_.push_back({price, amount, cum});
+ }
+
+ ob_spread_ = ob.spread;
+ ob_spread_pct_ = ob.spread_pct;
+ }
+
+ ob_loading_ = false;
+ ob_fetching_ = false;
+ success_count_++;
+ last_data_update_ = time(nullptr);
+ } catch (const std::exception& e) {
+ LOG_ERROR(TAG, "<<< Orderbook fetch FAILED for %s: %s", symbol.c_str(), e.what());
+ ob_loading_ = false;
+ ob_fetching_ = false;
+ last_error_ = std::string("Orderbook: ") + e.what();
+ error_count_++;
+ }
+ }));
+}
+
+void CryptoTradingScreen::async_refresh_watchlist_prices() {
+ if (wl_fetching_) {
+ LOG_DEBUG(TAG, "Watchlist price fetch already in flight, skipping");
+ return;
+ }
+
+ wl_fetching_ = true;
+
+ // Collect symbols
+ std::vector<std::string> symbols;
+ {
+ std::lock_guard<std::mutex> lock(data_mutex_);
+ for (auto& w : watchlist_) {
+ symbols.push_back(w.symbol);
+ }
+ }
+
+ LOG_INFO(TAG, ">>> Fetching watchlist prices for %d symbols...", (int)symbols.size());
+
+ launch_async(std::thread([this, symbols]() {
+ try {
+ auto tickers = trading::ExchangeService::instance().fetch_tickers(symbols);
+
+ LOG_INFO(TAG, "<<< Watchlist prices received: %d tickers", (int)tickers.size());
+
+ {
+ std::lock_guard<std::mutex> lock(data_mutex_);
+ for (auto& ticker : tickers) {
+ for (auto& w : watchlist_) {
+ if (w.symbol == ticker.symbol) {
+ w.price = ticker.last;
+ w.change = ticker.change;
+ w.change_pct = ticker.percentage;
+ w.volume = ticker.base_volume;
+ w.has_data = true;
+
+ LOG_DEBUG(TAG, " WL %s: $%.2f (%.2f%%)",
+ w.symbol.c_str(), w.price, w.change_pct);
+ break;
+ }
+ }
+
+ // Update current ticker if it matches selected symbol
+ if (ticker.symbol == selected_symbol_) {
+ current_ticker_ = ticker;
+ }
+ }
+ }
+
+ wl_fetching_ = false;
+ success_count_++;
+ last_data_update_ = time(nullptr);
+ } catch (const std::exception& e) {
+ LOG_ERROR(TAG, "<<< Watchlist price fetch FAILED: %s", e.what());
+ wl_fetching_ = false;
+ last_error_ = std::string("Watchlist: ") + e.what();
+ error_count_++;
+ }
+ }));
+}
+
+void CryptoTradingScreen::refresh_portfolio_data() {
+ if (portfolio_id_.empty()) return;
+
+ try {
+ // Update position mark-to-market prices using current ticker data
+ double last_price = current_ticker_.last;
+ if (last_price > 0) {
+ trading::pt_update_position_price(portfolio_id_, selected_symbol_, last_price);
+ }
+
+ // Also update prices for positions in other symbols from the price cache
+ auto& svc = trading::ExchangeService::instance();
+ for (const auto& pos : positions_) {
+ if (pos.symbol == selected_symbol_) continue;
+ auto cached = svc.get_cached_price(pos.symbol);
+ if (cached.last > 0) {
+ trading::pt_update_position_price(portfolio_id_, pos.symbol, cached.last);
+ }
+ }
+
+ // Check SL/TP triggers for all open positions
+ {
+ auto& matcher = trading::OrderMatcher::instance();
+ if (last_price > 0)
+ matcher.check_sl_tp_triggers(portfolio_id_, selected_symbol_, last_price);
+ for (const auto& pos : positions_) {
+ if (pos.symbol == selected_symbol_) continue;
+ const auto cached = svc.get_cached_price(pos.symbol);
+ if (cached.last > 0)
+ matcher.check_sl_tp_triggers(portfolio_id_, pos.symbol, cached.last);
+ }
+ }
+
+ std::lock_guard<std::mutex> lock(data_mutex_);
+ portfolio_ = trading::pt_get_portfolio(portfolio_id_);
+ positions_ = trading::pt_get_positions(portfolio_id_);
+ orders_ = trading::pt_get_orders(portfolio_id_);
+ trades_ = trading::pt_get_trades(portfolio_id_, 50);
+ stats_ = trading::pt_get_stats(portfolio_id_);
+ } catch (const std::exception& e) {
+ LOG_ERROR(TAG, "Portfolio refresh failed: %s", e.what());
+ }
+}
+
+} // namespace fincept::crypto
diff --git a/fincept-cpp/src/screens/crypto_trading/crypto_order_actions.cpp b/fincept-cpp/src/screens/crypto_trading/crypto_order_actions.cpp
new file mode 100644
index 000000000..e61cf742a
--- /dev/null
+++ b/fincept-cpp/src/screens/crypto_trading/crypto_order_actions.cpp
@@ -0,0 +1,403 @@
+#include "crypto_trading_screen.h"
+#include "crypto_internal.h"
+#include "ui/theme.h"
+#include "trading/exchange_service.h"
+#include "trading/paper_trading.h"
+#include "trading/order_matcher.h"
+#include "core/logger.h"
+#include "core/notification.h"
+#include <imgui.h>
+#include <cstdio>
+#include <cstring>
+#include <thread>
+
+namespace fincept::crypto {
+
+using namespace theme::colors;
+
+void CryptoTradingScreen::submit_order() {
+ order_form_.error.clear();
+ order_form_.success.clear();
+
+ bool is_live = (trading_mode_ == TradingMode::Live);
+ LOG_INFO(TAG, "Submitting %s order: symbol=%s side=%d type=%d qty='%s' price='%s'",
+ is_live ? "LIVE" : "PAPER",
+ selected_symbol_.c_str(), order_form_.side_idx, order_form_.type_idx,
+ order_form_.quantity_buf, order_form_.price_buf);
+
+ // Live mode guard — require credentials
+ if (is_live) {
+ if (!has_credentials_) {
+ order_form_.error = "API credentials required. Click 'API' button to configure.";
+ order_form_.msg_timer = 5.0f;
+ return;
+ }
+ LOG_INFO(TAG, "Live order being routed to %s exchange API", exchange_id_.c_str());
+ }
+
+ // Parse quantity
+ double qty = 0;
+ try {
+ qty = std::stod(order_form_.quantity_buf);
+ } catch (...) {
+ order_form_.error = "Invalid quantity";
+ order_form_.msg_timer = 5.0f;
+ LOG_ERROR(TAG, "Invalid quantity: '%s'", order_form_.quantity_buf);
+ return;
+ }
+ if (qty <= 0) {
+ order_form_.error = "Quantity must be > 0";
+ order_form_.msg_timer = 5.0f;
+ return;
+ }
+
+ static const char* type_strs[] = {"market", "limit", "stop", "stop_limit"};
+ std::string order_type = type_strs[order_form_.type_idx];
+ std::string side = order_form_.side_idx == 0 ? "buy" : "sell";
+
+ std::optional<double> price;
+ std::optional<double> stop_price;
+
+ // For market orders, use current ticker price as reference for margin calculation
+ if (order_form_.type_idx == 0) {
+ double ref = (side == "buy") ? current_ticker_.ask : current_ticker_.bid;
+ if (ref <= 0) ref = current_ticker_.last;
+ if (ref <= 0) {
+ order_form_.error = "No market price available yet";
+ order_form_.msg_timer = 5.0f;
+ LOG_ERROR(TAG, "Market order rejected: no price data");
+ return;
+ }
+ price = ref;
+ }
+
+ if (order_form_.type_idx == 1 || order_form_.type_idx == 3) {
+ try {
+ double p = std::stod(order_form_.price_buf);
+ if (p <= 0) {
+ order_form_.error = "Price must be > 0";
+ order_form_.msg_timer = 5.0f;
+ return;
+ }
+ price = p;
+ } catch (...) {
+ order_form_.error = "Invalid price";
+ order_form_.msg_timer = 5.0f;
+ return;
+ }
+ }
+
+ if (order_form_.type_idx >= 2) {
+ try {
+ double sp = std::stod(order_form_.stop_price_buf);
+ if (sp <= 0) {
+ order_form_.error = "Stop price must be > 0";
+ order_form_.msg_timer = 5.0f;
+ return;
+ }
+ stop_price = sp;
+ } catch (...) {
+ order_form_.error = "Invalid stop price";
+ order_form_.msg_timer = 5.0f;
+ return;
+ }
+ }
+
+ // Fee-inclusive balance check for paper BUY orders (ES.45: named values not magic)
+ if (trading_mode_ == TradingMode::Paper && side == "buy" && price.has_value()) {
+ const bool is_maker = (order_form_.type_idx == 1); // limit → maker
+ const double effective_fee = market_info_.has_data
+ ? (is_maker ? market_info_.maker_fee : market_info_.taker_fee)
+ : 0.001; // fallback 0.1% if fees not yet loaded
+ const double notional = qty * price.value();
+ const double total_incl = notional * (1.0 + effective_fee);
+ if (total_incl > portfolio_.balance) {
+ char buf[128];
+ std::snprintf(buf, sizeof(buf),
+ "Insufficient balance ($%.2f avail, $%.2f needed incl. fee)",
+ portfolio_.balance, total_incl);
+ order_form_.error = buf;
+ order_form_.msg_timer = 5.0f;
+ return;
+ }
+ }
+
+ try {
+ if (trading_mode_ == TradingMode::Live) {
+ // Live trading — route through exchange API on background thread
+ order_submitting_.store(true);
+ const std::string sym = selected_symbol_;
+ std::string pid = portfolio_id_;
+ launch_async(std::thread([this, sym, side, order_type, qty, price, pid]() {
+ try {
+ auto& svc = trading::ExchangeService::instance();
+ auto result = svc.place_order(sym, side, order_type, qty,
+ price.value_or(0.0));
+ LOG_INFO(TAG, "Live order placed: %s", result.dump(2).c_str());
+ core::notify::send("Order Placed",
+ sym + " " + side + " " + std::to_string(qty),
+ core::NotifyLevel::Success);
+ {
+ std::lock_guard<std::mutex> lock(data_mutex_);
+ order_form_.success = "Live order sent!";
+ order_form_.msg_timer = 3.0f;
+ }
+ trading::ExchangeService::instance().watch_symbol(sym, pid);
+ refresh_portfolio_data();
+ } catch (const std::exception& e) {
+ std::lock_guard<std::mutex> lock(data_mutex_);
+ order_form_.error = e.what();
+ order_form_.msg_timer = 5.0f;
+ LOG_ERROR(TAG, "Live order FAILED: %s", e.what());
+ core::notify::send("Order Failed", e.what(), core::NotifyLevel::Error);
+ }
+ order_submitting_.store(false);
+ }));
+ // Clear form immediately
+ order_form_.quantity_buf[0] = '\0';
+ order_form_.price_buf[0] = '\0';
+ order_form_.stop_price_buf[0] = '\0';
+ order_form_.sl_price_buf[0] = '\0';
+ order_form_.tp_price_buf[0] = '\0';
+ return; // skip the rest — thread handles result
+ } else {
+ // Paper trading
+ auto order = trading::pt_place_order(
+ portfolio_id_, selected_symbol_, side, order_type,
+ qty, price, stop_price, order_form_.reduce_only);
+
+ LOG_INFO(TAG, "Order created: id=%s type=%s side=%s qty=%.6f",
+ order.id.c_str(), order_type.c_str(), side.c_str(), qty);
+
+ // For market orders, immediately fill at current price
+ if (order_type == "market" && current_ticker_.last > 0) {
+ double fill_price = side == "buy" ? current_ticker_.ask : current_ticker_.bid;
+ if (fill_price <= 0) fill_price = current_ticker_.last;
+ LOG_INFO(TAG, "Market order fill at %.2f", fill_price);
+ trading::pt_fill_order(order.id, fill_price);
+ {
+ char msg[128];
+ std::snprintf(msg, sizeof(msg), "%s %s %.4f @ %.2f",
+ side == "buy" ? "BUY" : "SELL",
+ selected_symbol_.c_str(), qty, fill_price);
+ core::notify::send("Order Filled", msg, core::NotifyLevel::Success);
+ }
+ } else {
+ trading::OrderMatcher::instance().add_order(order);
+ LOG_INFO(TAG, "Order added to matcher");
+ }
+
+ // Register SL/TP triggers if provided
+ {
+ const double sl = (order_form_.sl_price_buf[0] != '\0')
+ ? std::atof(order_form_.sl_price_buf) : 0.0;
+ const double tp = (order_form_.tp_price_buf[0] != '\0')
+ ? std::atof(order_form_.tp_price_buf) : 0.0;
+ if ((sl > 0.0 || tp > 0.0) && !order.id.empty()) {
+ trading::OrderMatcher::instance().set_sl_tp(
+ portfolio_id_, selected_symbol_, order.id, sl, tp);
+ }
+ }
+
+ order_form_.success = "Order placed: " + order.id.substr(0, 8);
+ order_form_.msg_timer = 3.0f;
+ }
+
+ // Ensure the traded symbol is watched for price updates
+ trading::ExchangeService::instance().watch_symbol(selected_symbol_, portfolio_id_);
+
+ // Clear form
+ order_form_.quantity_buf[0] = '\0';
+ order_form_.price_buf[0] = '\0';
+ order_form_.stop_price_buf[0] = '\0';
+ order_form_.sl_price_buf[0] = '\0';
+ order_form_.tp_price_buf[0] = '\0';
+
+ // Refresh portfolio data immediately
+ refresh_portfolio_data();
+ } catch (const std::exception& e) {
+ order_form_.error = e.what();
+ order_form_.msg_timer = 5.0f;
+ LOG_ERROR(TAG, "Order FAILED: %s", e.what());
+ }
+}
+
+void CryptoTradingScreen::cancel_order(const std::string& order_id) {
+ if (trading_mode_ == TradingMode::Live) {
+ // Live cancel — route through exchange API
+ LOG_INFO(TAG, "Cancelling live order: %s on %s", order_id.c_str(), exchange_id_.c_str());
+ const std::string sym = selected_symbol_;
+ launch_async(std::thread([this, order_id, sym]() {
+ try {
+ auto& svc = trading::ExchangeService::instance();
+ auto result = svc.cancel_order(order_id, sym);
+ LOG_INFO(TAG, "Live order cancelled: %s", result.dump(2).c_str());
+ // Refresh live orders
+ async_fetch_live_orders();
+ } catch (const std::exception& e) {
+ LOG_ERROR(TAG, "Live cancel failed: %s", e.what());
+ std::lock_guard<std::mutex> lock(data_mutex_);
+ order_form_.error = std::string("Cancel failed: ") + e.what();
+ order_form_.msg_timer = 5.0f;
+ }
+ }));
+ return;
+ }
+
+ // Paper cancel
+ LOG_INFO(TAG, "Cancelling paper order: %s", order_id.c_str());
+ try {
+ trading::pt_cancel_order(order_id);
+ trading::OrderMatcher::instance().remove_order(order_id);
+ refresh_portfolio_data();
+ LOG_INFO(TAG, "Order cancelled: %s", order_id.c_str());
+ } catch (const std::exception& e) {
+ LOG_ERROR(TAG, "Cancel failed: %s", e.what());
+ }
+}
+
+// ============================================================================
+// Live trading data fetchers — call exchange API via ExchangeService
+// ============================================================================
+
+void CryptoTradingScreen::async_fetch_live_positions() {
+ if (live_positions_fetching_ || !has_credentials_) return;
+ live_positions_fetching_ = true;
+
+ launch_async(std::thread([this]() {
+ try {
+ auto& svc = trading::ExchangeService::instance();
+ auto result = svc.fetch_positions_live();
+ if (result.value("success", false) && result.contains("data")) {
+ std::lock_guard<std::mutex> lock(data_mutex_);
+ live_positions_.clear();
+ auto& positions = result["data"]["positions"];
+ if (positions.is_array()) {
+ for (const auto& p : positions) {
+ LivePosition pos;
+ pos.symbol = p.value("symbol", "");
+ pos.side = p.value("side", "long");
+ pos.quantity = std::abs(p.value("contracts", p.value("contractSize", 0.0)));
+ if (pos.quantity == 0.0) pos.quantity = std::abs(p.value("amount", 0.0));
+ pos.entry_price = p.value("entryPrice", 0.0);
+ pos.current_price = p.value("markPrice", p.value("liquidationPrice", 0.0));
+ pos.unrealized_pnl = p.value("unrealizedPnl", 0.0);
+ pos.leverage = p.value("leverage", 1.0);
+ if (pos.quantity > 0.0) {
+ live_positions_.push_back(pos);
+ }
+ }
+ }
+ live_data_loaded_ = true;
+ }
+ } catch (const std::exception& e) {
+ LOG_ERROR(TAG, "Live positions fetch failed: %s", e.what());
+ }
+ live_positions_fetching_ = false;
+ }));
+}
+
+void CryptoTradingScreen::async_fetch_live_orders() {
+ if (live_orders_fetching_ || !has_credentials_) return;
+ live_orders_fetching_ = true;
+
+ launch_async(std::thread([this]() {
+ try {
+ auto& svc = trading::ExchangeService::instance();
+ auto result = svc.fetch_open_orders_live();
+ if (result.value("success", false) && result.contains("data")) {
+ std::lock_guard<std::mutex> lock(data_mutex_);
+ live_orders_.clear();
+ auto& orders = result["data"]["orders"];
+ if (orders.is_array()) {
+ for (const auto& o : orders) {
+ LiveOrder ord;
+ ord.id = o.value("id", "");
+ ord.symbol = o.value("symbol", "");
+ ord.side = o.value("side", "");
+ ord.type = o.value("type", "");
+ ord.status = o.value("status", "");
+ ord.quantity = o.value("amount", 0.0);
+ ord.price = o.value("price", 0.0);
+ ord.filled_qty = o.value("filled", 0.0);
+ ord.timestamp = o.value("datetime", "");
+ live_orders_.push_back(ord);
+ }
+ }
+ }
+ } catch (const std::exception& e) {
+ LOG_ERROR(TAG, "Live orders fetch failed: %s", e.what());
+ }
+ live_orders_fetching_ = false;
+ }));
+}
+
+void CryptoTradingScreen::async_fetch_live_balance() {
+ if (live_balance_fetching_ || !has_credentials_) return;
+ live_balance_fetching_ = true;
+
+ launch_async(std::thread([this]() {
+ try {
+ auto& svc = trading::ExchangeService::instance();
+ auto result = svc.fetch_balance();
+ if (result.value("success", false) && result.contains("data")) {
+ std::lock_guard<std::mutex> lock(data_mutex_);
+ auto& bal = result["data"];
+ // ccxt returns balance as {free: {USDT: x}, used: {USDT: x}, total: {USDT: x}}
+ if (bal.contains("total") && bal["total"].is_object()) {
+ live_equity_ = bal["total"].value("USDT", bal["total"].value("USD", 0.0));
+ }
+ if (bal.contains("free") && bal["free"].is_object()) {
+ live_balance_ = bal["free"].value("USDT", bal["free"].value("USD", 0.0));
+ }
+ if (bal.contains("used") && bal["used"].is_object()) {
+ live_used_margin_ = bal["used"].value("USDT", bal["used"].value("USD", 0.0));
+ }
+ }
+ } catch (const std::exception& e) {
+ LOG_ERROR(TAG, "Live balance fetch failed: %s", e.what());
+ }
+ live_balance_fetching_ = false;
+ }));
+}
+
+void CryptoTradingScreen::async_fetch_live_trades() {
+ if (live_trades_fetching_ || !has_credentials_) return;
+ live_trades_fetching_ = true;
+
+ const std::string sym = selected_symbol_;
+ launch_async(std::thread([this, sym]() {
+ try {
+ auto& svc = trading::ExchangeService::instance();
+ auto result = svc.fetch_my_trades_live(sym, 50);
+ if (result.value("success", false) && result.contains("data")) {
+ std::lock_guard<std::mutex> lock(data_mutex_);
+ live_trades_.clear();
+ auto& trades = result["data"]["trades"];
+ if (trades.is_array()) {
+ for (const auto& t : trades) {
+ LiveTrade tr;
+ tr.id = t.value("id", "");
+ tr.symbol = t.value("symbol", sym);
+ tr.side = t.value("side", "");
+ tr.price = t.value("price", 0.0);
+ tr.quantity = t.value("amount", 0.0);
+ // fee can be an object {cost: x, currency: y} or a number
+ if (t.contains("fee") && t["fee"].is_object()) {
+ tr.fee = t["fee"].value("cost", 0.0);
+ } else {
+ tr.fee = t.value("fee", 0.0);
+ }
+ tr.timestamp = t.value("datetime", "");
+ live_trades_.push_back(tr);
+ }
+ }
+ }
+ } catch (const std::exception& e) {
+ LOG_ERROR(TAG, "Live trades fetch failed: %s", e.what());
+ }
+ live_trades_fetching_ = false;
+ }));
+}
+
+} // namespace fincept::crypto
diff --git a/fincept-cpp/src/screens/crypto_trading/crypto_order_entry.cpp b/fincept-cpp/src/screens/crypto_trading/crypto_order_entry.cpp
new file mode 100644
index 000000000..21a3b8b39
--- /dev/null
+++ b/fincept-cpp/src/screens/crypto_trading/crypto_order_entry.cpp
@@ -0,0 +1,605 @@
+#include "crypto_trading_screen.h"
+#include "crypto_internal.h"
+#include "ui/theme.h"
+#include "trading/exchange_service.h"
+#include "core/logger.h"
+#include <imgui.h>
+#include <cstdio>
+#include <cmath>
+
+namespace fincept::crypto {
+
+using namespace theme::colors;
+
+void CryptoTradingScreen::render_order_entry(float w, float h) {
+ ImGui::PushStyleColor(ImGuiCol_ChildBg, BG_PANEL);
+ ImGui::BeginChild("##crypto_order_entry", ImVec2(w, h), true);
+
+ // Mode indicator
+ bool is_paper = (trading_mode_ == TradingMode::Paper);
+ ImGui::TextColored(ACCENT, "ORDER ENTRY");
+ ImGui::SameLine(0, 6);
+ if (is_paper) {
+ ImGui::TextColored(ImVec4(0.0f, 0.7f, 0.3f, 1.0f), "[PAPER]");
+ } else {
+ ImGui::TextColored(ImVec4(0.9f, 0.2f, 0.2f, 1.0f), "[LIVE]");
+ }
+ ImGui::Separator();
+
+ float input_w = w - 24;
+
+ // Side: Buy / Sell
+ ImGui::TextColored(TEXT_DIM, "Side");
+ {
+ float btn_w = (input_w - 4) / 2;
+ bool is_buy = (order_form_.side_idx == 0);
+
+ ImGui::PushStyleColor(ImGuiCol_Button, is_buy ? ImVec4(0.0f, 0.55f, 0.25f, 1.0f) : BG_WIDGET);
+ ImGui::PushStyleColor(ImGuiCol_Text, is_buy ? TEXT_PRIMARY : TEXT_DIM);
+ if (ImGui::Button("BUY", ImVec2(btn_w, 0))) order_form_.side_idx = 0;
+ ImGui::PopStyleColor(2);
+
+ ImGui::SameLine(0, 4);
+
+ bool is_sell = (order_form_.side_idx == 1);
+ ImGui::PushStyleColor(ImGuiCol_Button, is_sell ? ImVec4(0.65f, 0.1f, 0.1f, 1.0f) : BG_WIDGET);
+ ImGui::PushStyleColor(ImGuiCol_Text, is_sell ? TEXT_PRIMARY : TEXT_DIM);
+ if (ImGui::Button("SELL", ImVec2(btn_w, 0))) order_form_.side_idx = 1;
+ ImGui::PopStyleColor(2);
+ }
+
+ ImGui::Spacing();
+
+ // Order type
+ ImGui::TextColored(TEXT_DIM, "Type");
+ ImGui::PushItemWidth(input_w);
+ ImGui::PushStyleColor(ImGuiCol_FrameBg, BG_INPUT);
+ static const char* types[] = {"Market", "Limit", "Stop", "Stop Limit"};
+ ImGui::Combo("##order_type", &order_form_.type_idx, types, 4);
+ ImGui::PopStyleColor();
+ ImGui::PopItemWidth();
+
+ ImGui::Spacing();
+
+ // Quantity
+ ImGui::TextColored(TEXT_DIM, "Quantity");
+ ImGui::PushItemWidth(input_w);
+ ImGui::PushStyleColor(ImGuiCol_FrameBg, BG_INPUT);
+ ImGui::InputText("##qty", order_form_.quantity_buf, sizeof(order_form_.quantity_buf),
+ ImGuiInputTextFlags_CharsDecimal);
+ ImGui::PopStyleColor();
+ ImGui::PopItemWidth();
+
+ // Quick quantity buttons
+ {
+ float btn_w = (input_w - 12) / 4;
+ const char* pcts[] = {"25%", "50%", "75%", "100%"};
+ float pct_vals[] = {0.25f, 0.50f, 0.75f, 1.00f};
+ for (int i = 0; i < 4; i++) {
+ if (i > 0) ImGui::SameLine(0, 4);
+ ImGui::PushStyleColor(ImGuiCol_Button, BG_WIDGET);
+ ImGui::PushStyleColor(ImGuiCol_Text, TEXT_DIM);
+ if (ImGui::Button(pcts[i], ImVec2(btn_w, 0))) {
+ if (current_ticker_.last > 0 && portfolio_.balance > 0) {
+ double max_qty = (portfolio_.balance * pct_vals[i]) / current_ticker_.last;
+ std::snprintf(order_form_.quantity_buf, sizeof(order_form_.quantity_buf),
+ "%.6f", max_qty);
+ }
+ }
+ ImGui::PopStyleColor(2);
+ }
+ }
+
+ ImGui::Spacing();
+
+ // Price (for limit/stop orders)
+ if (order_form_.type_idx >= 1) {
+ ImGui::TextColored(TEXT_DIM, "Price");
+ ImGui::PushItemWidth(input_w);
+ ImGui::PushStyleColor(ImGuiCol_FrameBg, BG_INPUT);
+ ImGui::InputText("##price", order_form_.price_buf, sizeof(order_form_.price_buf),
+ ImGuiInputTextFlags_CharsDecimal);
+ ImGui::PopStyleColor();
+ ImGui::PopItemWidth();
+ }
+
+ // Stop price (for stop/stoplimit)
+ if (order_form_.type_idx >= 2) {
+ ImGui::TextColored(TEXT_DIM, "Stop Price");
+ ImGui::PushItemWidth(input_w);
+ ImGui::PushStyleColor(ImGuiCol_FrameBg, BG_INPUT);
+ ImGui::InputText("##stop_price", order_form_.stop_price_buf, sizeof(order_form_.stop_price_buf),
+ ImGuiInputTextFlags_CharsDecimal);
+ ImGui::PopStyleColor();
+ ImGui::PopItemWidth();
+ }
+
+ // Stop Loss / Take Profit — optional risk management, non-Market orders only
+ if (order_form_.type_idx != 0) {
+ ImGui::Spacing();
+ ImGui::PushStyleColor(ImGuiCol_Text, TEXT_DIM);
+ ImGui::Text("-- Risk Mgmt (optional) --");
+ ImGui::PopStyleColor();
+
+ ImGui::TextColored(TEXT_DIM, "Stop Loss");
+ ImGui::PushItemWidth(input_w);
+ ImGui::PushStyleColor(ImGuiCol_FrameBg, BG_INPUT);
+ ImGui::InputText("##sl_price", order_form_.sl_price_buf, sizeof(order_form_.sl_price_buf),
+ ImGuiInputTextFlags_CharsDecimal);
+ ImGui::PopStyleColor();
+ ImGui::PopItemWidth();
+
+ ImGui::TextColored(TEXT_DIM, "Take Profit");
+ ImGui::PushItemWidth(input_w);
+ ImGui::PushStyleColor(ImGuiCol_FrameBg, BG_INPUT);
+ ImGui::InputText("##tp_price", order_form_.tp_price_buf, sizeof(order_form_.tp_price_buf),
+ ImGuiInputTextFlags_CharsDecimal);
+ ImGui::PopStyleColor();
+ ImGui::PopItemWidth();
+ }
+
+ ImGui::Spacing();
+
+ // Reduce only checkbox
+ ImGui::Checkbox("Reduce Only", &order_form_.reduce_only);
+
+ ImGui::Spacing();
+
+ // --- Fee Estimation (shown when market info has loaded and notional > 0) ---
+ if (market_info_.has_data) {
+ const double qty = std::atof(order_form_.quantity_buf);
+ // Market orders use last ticker price; limit/stop orders use entered price
+ const double price = (order_form_.type_idx == 0)
+ ? current_ticker_.last
+ : std::atof(order_form_.price_buf);
+
+ if (qty > 0.0 && price > 0.0) {
+ // Limit orders go on the book → maker fee; all others fill immediately → taker fee
+ const bool is_maker = (order_form_.type_idx == 1);
+ const double effective_fee = is_maker ? market_info_.maker_fee : market_info_.taker_fee;
+ const double notional = qty * price;
+ const double fee_amount = notional * effective_fee;
+ const double total_incl = notional + fee_amount;
+
+ ImGui::Separator();
+ {
+ char buf[64];
+ std::snprintf(buf, sizeof(buf), "Fee(%.2f%% %s)",
+ effective_fee * 100.0, is_maker ? "mkr" : "tkr");
+ ImGui::PushStyleColor(ImGuiCol_Text, TEXT_DIM);
+ ImGui::Text("%s", buf);
+ ImGui::SameLine(input_w - 72);
+ std::snprintf(buf, sizeof(buf), "%.4f", fee_amount);
+ ImGui::Text("%s", buf);
+
+ ImGui::Text("Total w/fee");
+ ImGui::SameLine(input_w - 72);
+ std::snprintf(buf, sizeof(buf), "%.2f", total_incl);
+ ImGui::Text("%s", buf);
+ ImGui::PopStyleColor();
+ }
+ ImGui::Separator();
+ }
+ }
+
+ ImGui::Spacing();
+
+ // Submit button — clearly labeled with mode
+ {
+ bool is_buy = (order_form_.side_idx == 0);
+ ImVec4 btn_col = is_buy ? ImVec4(0.0f, 0.55f, 0.25f, 1.0f) : ImVec4(0.65f, 0.1f, 0.1f, 1.0f);
+
+ // Show base symbol without quote (e.g., "BTC" not "BTC/USDT")
+ std::string base_sym = selected_symbol_;
+ auto slash_pos = base_sym.find('/');
+ if (slash_pos != std::string::npos) base_sym = base_sym.substr(0, slash_pos);
+
+ char label[64];
+ if (is_paper) {
+ std::snprintf(label, sizeof(label), "%s %s (Paper)",
+ is_buy ? "BUY" : "SELL", base_sym.c_str());
+ } else {
+ std::snprintf(label, sizeof(label), "%s %s (LIVE)",
+ is_buy ? "BUY" : "SELL", base_sym.c_str());
+ // Add red border for live orders as a safety indicator
+ btn_col = is_buy ? ImVec4(0.0f, 0.4f, 0.2f, 1.0f) : ImVec4(0.6f, 0.05f, 0.05f, 1.0f);
+ }
+
+ ImGui::PushStyleColor(ImGuiCol_Button, btn_col);
+ ImGui::PushStyleColor(ImGuiCol_ButtonHovered, ImVec4(btn_col.x + 0.1f, btn_col.y + 0.1f, btn_col.z + 0.1f, 1.0f));
+ ImGui::PushStyleColor(ImGuiCol_Text, TEXT_PRIMARY);
+ if (order_submitting_.load()) {
+ ImGui::Button("Submitting...", ImVec2(input_w, 28));
+ } else if (ImGui::Button(label, ImVec2(input_w, 28))) {
+ submit_order();
+ }
+ ImGui::PopStyleColor(3);
+
+ // Warning for live mode
+ if (!is_paper) {
+ ImGui::TextColored(ImVec4(0.9f, 0.5f, 0.1f, 1.0f), "Real money at risk!");
+ }
+ }
+
+ // Error / Success messages
+ if (!order_form_.error.empty()) {
+ ImGui::TextColored(MARKET_RED, "%s", order_form_.error.c_str());
+ }
+ if (!order_form_.success.empty()) {
+ ImGui::TextColored(MARKET_GREEN, "%s", order_form_.success.c_str());
+ }
+
+ ImGui::EndChild();
+ ImGui::PopStyleColor();
+}
+
+// ============================================================================
+// Order Book — right panel bottom
+// ============================================================================
+void CryptoTradingScreen::render_orderbook(float w, float h) {
+ ImGui::PushStyleColor(ImGuiCol_ChildBg, BG_PANEL);
+ ImGui::BeginChild("##crypto_orderbook", ImVec2(w, h), true);
+
+ // Title + spread
+ ImGui::TextColored(ACCENT, "ORDER BOOK");
+ {
+ std::lock_guard<std::mutex> lock(data_mutex_);
+ if (ob_spread_ > 0) {
+ ImGui::SameLine();
+ char spread_buf[32];
+ std::snprintf(spread_buf, sizeof(spread_buf), "Spread:%.2f(%.3f%%)", ob_spread_, ob_spread_pct_);
+ ImGui::TextColored(TEXT_DIM, "%s", spread_buf);
+ }
+ }
+ if (ob_fetching_) {
+ ImGui::SameLine();
+ ImGui::TextColored(WARNING, "[*]");
+ }
+
+ // Mode switcher — 4 segmented buttons
+ {
+ struct ModeBtn { const char* label; ObViewMode mode; };
+ static constexpr ModeBtn k_modes[] = {
+ {"OB", ObViewMode::Book},
+ {"VOL", ObViewMode::Volume},
+ {"IMBAL", ObViewMode::Imbalance},
+ {"SIG", ObViewMode::Signals},
+ };
+ const float btn_w = (w - 28.0f) / 4.0f;
+ ImGui::SameLine(0, 6);
+ for (int i = 0; i < 4; ++i) {
+ if (i > 0) ImGui::SameLine(0, 2);
+ const bool active = (ob_view_mode_ == k_modes[i].mode);
+ ImGui::PushStyleColor(ImGuiCol_Button,
+ active ? ImVec4(0.2f, 0.4f, 0.7f, 1.0f) : BG_WIDGET);
+ ImGui::PushStyleColor(ImGuiCol_Text,
+ active ? TEXT_PRIMARY : TEXT_DIM);
+ if (ImGui::SmallButton(k_modes[i].label))
+ ob_view_mode_ = k_modes[i].mode;
+ ImGui::PopStyleColor(2);
+ }
+ }
+
+ ImGui::Separator();
+
+ // Empty state guard
+ {
+ std::lock_guard<std::mutex> lock(data_mutex_);
+ if (ob_asks_.empty() && ob_bids_.empty()) {
+ if (ob_loading_) {
+ theme::LoadingSpinner("Loading order book...");
+ } else {
+ ImGui::TextColored(TEXT_DIM, "No order book data");
+ }
+ ImGui::EndChild();
+ ImGui::PopStyleColor();
+ return;
+ }
+ }
+
+ // Dispatch to active mode renderer
+ switch (ob_view_mode_) {
+ case ObViewMode::Book: render_ob_mode_book(w); break;
+ case ObViewMode::Volume: render_ob_mode_volume(w); break;
+ case ObViewMode::Imbalance: render_ob_mode_imbalance(w); break;
+ case ObViewMode::Signals: render_ob_mode_signals(w); break;
+ }
+
+ ImGui::EndChild();
+ ImGui::PopStyleColor();
+}
+
+// ----------------------------------------------------------------------------
+// OB Mode: Book — price / amount / cumulative depth bars (default view)
+// ----------------------------------------------------------------------------
+void CryptoTradingScreen::render_ob_mode_book(float w) {
+ std::lock_guard<std::mutex> lock(data_mutex_);
+
+ const float avail_h = ImGui::GetContentRegionAvail().y;
+ const float half_h = avail_h / 2.0f;
+ const float col_w = (w - 24.0f) / 3.0f;
+
+ double max_cum = 1.0;
+ if (!ob_bids_.empty()) max_cum = std::max(max_cum, ob_bids_.back().cumulative);
+ if (!ob_asks_.empty()) max_cum = std::max(max_cum, ob_asks_.back().cumulative);
+
+ ImGui::PushStyleColor(ImGuiCol_Text, TEXT_DIM);
+ ImGui::Text("PRICE");
+ ImGui::SameLine(col_w + 4); ImGui::Text("AMOUNT");
+ ImGui::SameLine(col_w * 2 + 8); ImGui::Text("TOTAL");
+ ImGui::PopStyleColor();
+
+ // Asks — lowest ask nearest spread
+ ImGui::BeginChild("##ob_asks_book", ImVec2(0, half_h - 12), false);
+ {
+ char buf[32];
+ const int start = std::max(0, static_cast<int>(ob_asks_.size()) - OB_MAX_OB_DISPLAY_LEVELS);
+ for (int i = start; i < static_cast<int>(ob_asks_.size()); ++i) {
+ const auto& lvl = ob_asks_[i];
+ ImVec2 p = ImGui::GetCursorScreenPos();
+ const float row_w = ImGui::GetContentRegionAvail().x;
+ const float bar_w = static_cast<float>(lvl.cumulative / max_cum) * row_w;
+ ImGui::GetWindowDrawList()->AddRectFilled(
+ ImVec2(p.x + row_w - bar_w, p.y),
+ ImVec2(p.x + row_w, p.y + ImGui::GetTextLineHeight()),
+ ImGui::ColorConvertFloat4ToU32(ImVec4(0.6f, 0.1f, 0.1f, 0.15f)));
+ std::snprintf(buf, sizeof(buf), "%.2f", lvl.price);
+ ImGui::TextColored(MARKET_RED, "%s", buf);
+ ImGui::SameLine(col_w + 4);
+ std::snprintf(buf, sizeof(buf), "%.4f", lvl.amount);
+ ImGui::TextColored(TEXT_SECONDARY, "%s", buf);
+ ImGui::SameLine(col_w * 2 + 8);
+ std::snprintf(buf, sizeof(buf), "%.4f", lvl.cumulative);
+ ImGui::TextColored(TEXT_DIM, "%s", buf);
+ }
+ }
+ ImGui::EndChild();
+
+ ImGui::PushStyleColor(ImGuiCol_Separator, BORDER_BRIGHT);
+ ImGui::Separator();
+ ImGui::PopStyleColor();
+
+ // Bids — highest to lowest
+ ImGui::BeginChild("##ob_bids_book", ImVec2(0, 0), false);
+ {
+ char buf[32];
+ const int count = std::min(static_cast<int>(ob_bids_.size()), OB_MAX_OB_DISPLAY_LEVELS);
+ for (int i = 0; i < count; ++i) {
+ const auto& lvl = ob_bids_[i];
+ ImVec2 p = ImGui::GetCursorScreenPos();
+ const float row_w = ImGui::GetContentRegionAvail().x;
+ const float bar_w = static_cast<float>(lvl.cumulative / max_cum) * row_w;
+ ImGui::GetWindowDrawList()->AddRectFilled(
+ ImVec2(p.x + row_w - bar_w, p.y),
+ ImVec2(p.x + row_w, p.y + ImGui::GetTextLineHeight()),
+ ImGui::ColorConvertFloat4ToU32(ImVec4(0.0f, 0.5f, 0.2f, 0.15f)));
+ std::snprintf(buf, sizeof(buf), "%.2f", lvl.price);
+ ImGui::TextColored(MARKET_GREEN, "%s", buf);
+ ImGui::SameLine(col_w + 4);
+ std::snprintf(buf, sizeof(buf), "%.4f", lvl.amount);
+ ImGui::TextColored(TEXT_SECONDARY, "%s", buf);
+ ImGui::SameLine(col_w * 2 + 8);
+ std::snprintf(buf, sizeof(buf), "%.4f", lvl.cumulative);
+ ImGui::TextColored(TEXT_DIM, "%s", buf);
+ }
+ }
+ ImGui::EndChild();
+}
+
+// ----------------------------------------------------------------------------
+// OB Mode: Volume — price / amount / % share of total book
+// ----------------------------------------------------------------------------
+void CryptoTradingScreen::render_ob_mode_volume(float w) {
+ std::lock_guard<std::mutex> lock(data_mutex_);
+
+ const float col_w = (w - 24.0f) / 3.0f;
+
+ double total_vol = 0.0;
+ for (const auto& lvl : ob_asks_) total_vol += lvl.amount;
+ for (const auto& lvl : ob_bids_) total_vol += lvl.amount;
+ if (total_vol <= 0.0) total_vol = 1.0;
+
+ // Normaliser: each bar fills to its share of the avg-level volume
+ const double avg_lvl_vol = total_vol / static_cast<double>(OB_MAX_OB_DISPLAY_LEVELS * 2);
+
+ ImGui::PushStyleColor(ImGuiCol_Text, TEXT_DIM);
+ ImGui::Text("PRICE");
+ ImGui::SameLine(col_w + 4); ImGui::Text("AMOUNT");
+ ImGui::SameLine(col_w * 2 + 8); ImGui::Text("VOL%");
+ ImGui::PopStyleColor();
+
+ const float avail_h = ImGui::GetContentRegionAvail().y;
+ const float half_h = avail_h / 2.0f;
+
+ ImGui::BeginChild("##ob_asks_vol", ImVec2(0, half_h - 12), false);
+ {
+ char buf[32];
+ const int start = std::max(0, static_cast<int>(ob_asks_.size()) - OB_MAX_OB_DISPLAY_LEVELS);
+ for (int i = start; i < static_cast<int>(ob_asks_.size()); ++i) {
+ const auto& lvl = ob_asks_[i];
+ const double vol_pct = (lvl.amount / total_vol) * 100.0;
+ ImVec2 p = ImGui::GetCursorScreenPos();
+ const float row_w = ImGui::GetContentRegionAvail().x;
+ const float bar_w = std::min(static_cast<float>(lvl.amount / (avg_lvl_vol * 2.0)) * row_w, row_w);
+ ImGui::GetWindowDrawList()->AddRectFilled(
+ ImVec2(p.x, p.y),
+ ImVec2(p.x + bar_w, p.y + ImGui::GetTextLineHeight()),
+ ImGui::ColorConvertFloat4ToU32(ImVec4(0.6f, 0.1f, 0.1f, 0.20f)));
+ std::snprintf(buf, sizeof(buf), "%.2f", lvl.price);
+ ImGui::TextColored(MARKET_RED, "%s", buf);
+ ImGui::SameLine(col_w + 4);
+ std::snprintf(buf, sizeof(buf), "%.4f", lvl.amount);
+ ImGui::TextColored(TEXT_SECONDARY, "%s", buf);
+ ImGui::SameLine(col_w * 2 + 8);
+ std::snprintf(buf, sizeof(buf), "%.2f%%", vol_pct);
+ ImGui::TextColored(TEXT_DIM, "%s", buf);
+ }
+ }
+ ImGui::EndChild();
+
+ ImGui::PushStyleColor(ImGuiCol_Separator, BORDER_BRIGHT);
+ ImGui::Separator();
+ ImGui::PopStyleColor();
+
+ ImGui::BeginChild("##ob_bids_vol", ImVec2(0, 0), false);
+ {
+ char buf[32];
+ const int count = std::min(static_cast<int>(ob_bids_.size()), OB_MAX_OB_DISPLAY_LEVELS);
+ for (int i = 0; i < count; ++i) {
+ const auto& lvl = ob_bids_[i];
+ const double vol_pct = (lvl.amount / total_vol) * 100.0;
+ ImVec2 p = ImGui::GetCursorScreenPos();
+ const float row_w = ImGui::GetContentRegionAvail().x;
+ const float bar_w = std::min(static_cast<float>(lvl.amount / (avg_lvl_vol * 2.0)) * row_w, row_w);
+ ImGui::GetWindowDrawList()->AddRectFilled(
+ ImVec2(p.x, p.y),
+ ImVec2(p.x + bar_w, p.y + ImGui::GetTextLineHeight()),
+ ImGui::ColorConvertFloat4ToU32(ImVec4(0.0f, 0.5f, 0.2f, 0.20f)));
+ std::snprintf(buf, sizeof(buf), "%.2f", lvl.price);
+ ImGui::TextColored(MARKET_GREEN, "%s", buf);
+ ImGui::SameLine(col_w + 4);
+ std::snprintf(buf, sizeof(buf), "%.4f", lvl.amount);
+ ImGui::TextColored(TEXT_SECONDARY, "%s", buf);
+ ImGui::SameLine(col_w * 2 + 8);
+ std::snprintf(buf, sizeof(buf), "%.2f%%", vol_pct);
+ ImGui::TextColored(TEXT_DIM, "%s", buf);
+ }
+ }
+ ImGui::EndChild();
+}
+
+// ----------------------------------------------------------------------------
+// OB Mode: Imbalance — weighted bid/ask ratio gauge + per-level table
+// ----------------------------------------------------------------------------
+void CryptoTradingScreen::render_ob_mode_imbalance(float w) {
+ std::lock_guard<std::mutex> lock(data_mutex_);
+
+ if (tick_history_.empty()) {
+ ImGui::TextColored(TEXT_DIM, "Collecting data...");
+ return;
+ }
+
+ const auto& latest = tick_history_.back();
+ const double imbalance = latest.imbalance;
+
+ // Imbalance value + colour
+ {
+ char buf[48];
+ std::snprintf(buf, sizeof(buf), "Imbalance: %+.3f", imbalance);
+ const ImVec4 col = (imbalance > OB_IMBALANCE_BUY_THRESHOLD) ? MARKET_GREEN :
+ (imbalance < OB_IMBALANCE_SELL_THRESHOLD) ? MARKET_RED :
+ TEXT_SECONDARY;
+ ImGui::TextColored(col, "%s", buf);
+ }
+
+ // Horizontal bid/ask weight bar
+ {
+ const float bar_total_w = w - 24.0f;
+ const float bid_frac = static_cast<float>((imbalance + 1.0) / 2.0);
+ ImVec2 p = ImGui::GetCursorScreenPos();
+ constexpr float bar_h = 8.0f;
+ ImDrawList* dl = ImGui::GetWindowDrawList();
+ dl->AddRectFilled(p, ImVec2(p.x + bar_total_w * bid_frac, p.y + bar_h),
+ ImGui::ColorConvertFloat4ToU32(ImVec4(0.0f, 0.55f, 0.25f, 0.8f)));
+ dl->AddRectFilled(ImVec2(p.x + bar_total_w * bid_frac, p.y),
+ ImVec2(p.x + bar_total_w, p.y + bar_h),
+ ImGui::ColorConvertFloat4ToU32(ImVec4(0.65f, 0.1f, 0.1f, 0.8f)));
+ ImGui::Dummy(ImVec2(bar_total_w, bar_h + 2.0f));
+ }
+
+ ImGui::Spacing();
+
+ // Per-level breakdown
+ static constexpr float k_weights[3] = {50.0f, 30.0f, 20.0f};
+ ImGui::PushStyleColor(ImGuiCol_Text, TEXT_DIM);
+ ImGui::Text("LVL WT BID QTY ASK QTY IMBAL");
+ ImGui::PopStyleColor();
+ ImGui::Separator();
+
+ for (int i = 0; i < 3; ++i) {
+ const double bq = latest.bid_qty[i];
+ const double aq = latest.ask_qty[i];
+ const double wB = k_weights[i] * bq;
+ const double wA = k_weights[i] * aq;
+ const double lvl_imbal = (wB + wA > 0.0) ? (wB - wA) / (wB + wA) : 0.0;
+ const ImVec4 col = (lvl_imbal > 0.1) ? MARKET_GREEN :
+ (lvl_imbal < -0.1) ? MARKET_RED : TEXT_SECONDARY;
+ char row[96];
+ std::snprintf(row, sizeof(row), " L%d %3.0f%% %9.4f %9.4f %+.3f",
+ i + 1, k_weights[i], bq, aq, lvl_imbal);
+ ImGui::TextColored(col, "%s", row);
+ }
+
+ ImGui::Spacing();
+ ImGui::Separator();
+
+ {
+ char buf[48];
+ std::snprintf(buf, sizeof(buf), "60s rise: %+.3f%%", latest.rise_ratio_60);
+ ImGui::TextColored(latest.rise_ratio_60 >= 0.0 ? MARKET_GREEN : MARKET_RED, "%s", buf);
+ }
+}
+
+// ----------------------------------------------------------------------------
+// OB Mode: Signals — BUY/SELL/NEUTRAL badge from imbalance + rise ratio
+// ----------------------------------------------------------------------------
+void CryptoTradingScreen::render_ob_mode_signals(float w) {
+ std::lock_guard<std::mutex> lock(data_mutex_);
+
+ if (tick_history_.empty()) {
+ ImGui::TextColored(TEXT_DIM, "Collecting data... (~5s)");
+ return;
+ }
+
+ const auto& latest = tick_history_.back();
+ const double imbalance = latest.imbalance;
+ const double rise_60 = latest.rise_ratio_60;
+
+ const bool is_buy = (imbalance > OB_IMBALANCE_BUY_THRESHOLD && rise_60 > OB_RISE_BUY_THRESHOLD);
+ const bool is_sell = (imbalance < OB_IMBALANCE_SELL_THRESHOLD && rise_60 < OB_RISE_SELL_THRESHOLD);
+
+ // Signal badge (styled as non-interactive button for visual weight)
+ {
+ const char* label = is_buy ? " BUY " : (is_sell ? " SELL " : " NEUTRAL ");
+ const ImVec4 bg = is_buy ? ImVec4(0.0f, 0.55f, 0.25f, 1.0f) :
+ is_sell ? ImVec4(0.65f, 0.1f, 0.1f, 1.0f) :
+ ImVec4(0.3f, 0.3f, 0.3f, 1.0f);
+ ImGui::PushStyleColor(ImGuiCol_Button, bg);
+ ImGui::PushStyleColor(ImGuiCol_ButtonHovered, bg);
+ ImGui::PushStyleColor(ImGuiCol_Text, TEXT_PRIMARY);
+ ImGui::Button(label, ImVec2(w - 24.0f, 28.0f));
+ ImGui::PopStyleColor(3);
+ }
+
+ ImGui::Spacing();
+
+ // Metrics table
+ ImGui::PushStyleColor(ImGuiCol_Text, TEXT_DIM);
+ ImGui::Text("Imbalance Rise 60s Thresholds");
+ ImGui::PopStyleColor();
+ ImGui::Separator();
+
+ {
+ char buf[64];
+ std::snprintf(buf, sizeof(buf), "%+.3f", imbalance);
+ ImGui::TextColored(imbalance >= 0.0 ? MARKET_GREEN : MARKET_RED, "%s", buf);
+ ImGui::SameLine(80);
+ std::snprintf(buf, sizeof(buf), "%+.3f%%", rise_60);
+ ImGui::TextColored(rise_60 >= 0.0 ? MARKET_GREEN : MARKET_RED, "%s", buf);
+ ImGui::SameLine(160);
+ ImGui::TextColored(TEXT_DIM, "B>%.2f|S<%.2f",
+ OB_IMBALANCE_BUY_THRESHOLD, OB_IMBALANCE_SELL_THRESHOLD);
+ }
+
+ ImGui::Spacing();
+ ImGui::Separator();
+
+ {
+ char buf[48];
+ std::snprintf(buf, sizeof(buf), "History: %d/%d ticks",
+ static_cast<int>(tick_history_.size()), OB_MAX_TICK_HISTORY);
+ ImGui::TextColored(TEXT_DIM, "%s", buf);
+ }
+}
+
+} // namespace fincept::crypto
diff --git a/fincept-cpp/src/screens/crypto_trading/crypto_screen.cpp b/fincept-cpp/src/screens/crypto_trading/crypto_screen.cpp
new file mode 100644
index 000000000..0fb8d3561
--- /dev/null
+++ b/fincept-cpp/src/screens/crypto_trading/crypto_screen.cpp
@@ -0,0 +1,460 @@
+#include "crypto_trading_screen.h"
+#include "crypto_internal.h"
+#include "ui/yoga_helpers.h"
+#include "ui/theme.h"
+#include "trading/exchange_service.h"
+#include "core/logger.h"
+#include <imgui.h>
+#include <cstdio>
+#include <algorithm>
+
+namespace fincept::crypto {
+
+using namespace theme::colors;
+
+void CryptoTradingScreen::render() {
+ if (!initialized_) init();
+
+ // Handle deferred symbol switch (set from search results while holding data_mutex_)
+ if (!pending_symbol_switch_.empty()) {
+ std::string sym = pending_symbol_switch_;
+ pending_symbol_switch_.clear();
+ switch_symbol(sym);
+ }
+
+ ui::ScreenFrame frame("##crypto_trading", ImVec2(0, 0), BG_DARKEST);
+ if (!frame.begin()) { frame.end(); return; }
+
+ float W = frame.width();
+ float H = frame.height();
+
+ // Vertical stack: top_nav(28) + ticker_bar(36) + main_area(flex) + status(22)
+ auto vstack = ui::vstack_layout(W, H, {28, 36, -1, 22});
+
+ render_top_nav(W, vstack.heights[0]);
+ render_ticker_bar(W, vstack.heights[1]);
+
+ // Main area — three-panel horizontal layout
+ float main_h = vstack.heights[2];
+ {
+ auto panels = ui::three_panel_layout(W, main_h, 15, 22, 180, 280, 300, 4);
+
+ ImGui::BeginChild("##crypto_left", ImVec2(panels.left_w, panels.left_h), false);
+ render_watchlist(panels.left_w, panels.left_h);
+ ImGui::EndChild();
+
+ ImGui::SameLine(0, panels.gap);
+
+ ImGui::BeginChild("##crypto_center", ImVec2(panels.center_w, panels.center_h), false);
+ {
+ float chart_h = panels.center_h * 0.55f;
+ float bottom_h = panels.center_h - chart_h - 4;
+
+ render_chart_area(panels.center_w, chart_h);
+ ImGui::Dummy(ImVec2(0, 4));
+ render_bottom_panel(panels.center_w, bottom_h);
+ }
+ ImGui::EndChild();
+
+ if (panels.right_w > 0) {
+ ImGui::SameLine(0, panels.gap);
+
+ ImGui::BeginChild("##crypto_right", ImVec2(panels.right_w, panels.right_h), false);
+ {
+ float entry_h = panels.right_h * 0.45f;
+ float book_h = panels.right_h - entry_h - 4;
+
+ render_order_entry(panels.right_w, entry_h);
+ ImGui::Dummy(ImVec2(0, 4));
+ render_orderbook(panels.right_w, book_h);
+ }
+ ImGui::EndChild();
+ }
+ }
+
+ render_status_bar(W, vstack.heights[3]);
+
+ // Credentials popup (rendered outside frame to overlay properly)
+ render_credentials_popup();
+
+ frame.end();
+
+ // Periodic refreshes — WS handles ticker/orderbook/candles in real-time,
+ // polling is fallback only (long intervals)
+ float dt = ImGui::GetIO().DeltaTime;
+ portfolio_timer_ += dt;
+
+ bool ws_ok = trading::ExchangeService::instance().is_ws_connected();
+ if (!ws_ok) {
+ // WS not connected — fall back to faster REST polling
+ ticker_timer_ += dt;
+ ob_timer_ += dt;
+ wl_timer_ += dt;
+
+ if (ticker_timer_ >= TICKER_POLL_INTERVAL) {
+ ticker_timer_ = 0;
+ async_refresh_ticker();
+ }
+ if (ob_timer_ >= ORDERBOOK_POLL_INTERVAL) {
+ ob_timer_ = 0;
+ async_refresh_orderbook();
+ }
+ if (wl_timer_ >= WATCHLIST_POLL_INTERVAL) {
+ wl_timer_ = 0;
+ async_refresh_watchlist_prices();
+ }
+ }
+
+ if (portfolio_timer_ >= PORTFOLIO_REFRESH_INTERVAL) {
+ portfolio_timer_ = 0;
+ refresh_portfolio_data();
+ }
+
+ // Live data refresh (positions, orders, balance from exchange API)
+ if (trading_mode_ == TradingMode::Live && has_credentials_) {
+ live_data_timer_ += dt;
+ if (live_data_timer_ >= LIVE_DATA_REFRESH_INTERVAL) {
+ live_data_timer_ = 0;
+ async_fetch_live_positions();
+ async_fetch_live_orders();
+ async_fetch_live_balance();
+ }
+ }
+
+ // Market info refresh (every 30s)
+ market_info_timer_ += dt;
+ if (market_info_timer_ >= MARKET_INFO_INTERVAL) {
+ market_info_timer_ = 0;
+ async_fetch_market_info();
+ }
+
+ // Clear success/error messages after timeout
+ if (order_form_.msg_timer > 0) {
+ order_form_.msg_timer -= dt;
+ if (order_form_.msg_timer <= 0) {
+ order_form_.error.clear();
+ order_form_.success.clear();
+ }
+ }
+}
+
+// ============================================================================
+// Top Navigation Bar
+// ============================================================================
+void CryptoTradingScreen::render_top_nav(float w, float h) {
+ ImGui::PushStyleColor(ImGuiCol_ChildBg, BG_DARK);
+ ImGui::BeginChild("##crypto_topnav", ImVec2(w, h), true);
+
+ ImGui::TextColored(ACCENT, "CRYPTO");
+ ImGui::SameLine(0, 4);
+ ImGui::TextColored(TEXT_PRIMARY, "TRADING");
+ ImGui::SameLine(0, 12);
+ ImGui::TextColored(BORDER_BRIGHT, "|");
+ ImGui::SameLine(0, 12);
+
+ // Exchange selector — dynamic list from ccxt (with search filter)
+ ImGui::TextColored(TEXT_DIM, "Exchange:");
+ ImGui::SameLine(0, 4);
+ ImGui::PushItemWidth(140);
+ ImGui::PushStyleColor(ImGuiCol_FrameBg, BG_INPUT);
+
+ if (exchanges_loaded_) {
+ if (ImGui::BeginCombo("##exchange", exchange_id_.c_str())) {
+ ImGui::PushItemWidth(-1);
+ ImGui::InputTextWithHint("##ex_filter", "Filter...",
+ exchange_filter_, sizeof(exchange_filter_));
+ ImGui::PopItemWidth();
+ ImGui::Separator();
+
+ std::string filter(exchange_filter_);
+ for (auto& c : filter) c = (char)std::tolower((unsigned char)c);
+
+ std::lock_guard<std::mutex> lock(data_mutex_);
+ for (const auto& ex_id : available_exchanges_) {
+ if (!filter.empty() && ex_id.find(filter) == std::string::npos)
+ continue;
+ bool selected = (ex_id == exchange_id_);
+ if (ImGui::Selectable(ex_id.c_str(), selected)) {
+ switch_exchange(ex_id);
+ exchange_filter_[0] = '\0';
+ }
+ if (selected) ImGui::SetItemDefaultFocus();
+ }
+ ImGui::EndCombo();
+ }
+ } else {
+ ImGui::BeginDisabled();
+ if (ImGui::BeginCombo("##exchange",
+ exchanges_fetching_ ? "Loading..." : exchange_id_.c_str())) {
+ ImGui::EndCombo();
+ }
+ ImGui::EndDisabled();
+ }
+
+ ImGui::PopStyleColor();
+ ImGui::PopItemWidth();
+
+ // API key indicator + settings button
+ ImGui::SameLine(0, 6);
+ if (has_credentials_) {
+ ImGui::TextColored(MARKET_GREEN, "[KEY]");
+ } else {
+ ImGui::TextColored(TEXT_DIM, "[NO KEY]");
+ }
+ ImGui::SameLine(0, 4);
+ ImGui::PushStyleColor(ImGuiCol_Button, BG_WIDGET);
+ ImGui::PushStyleColor(ImGuiCol_Text, TEXT_DIM);
+ if (ImGui::SmallButton("API")) {
+ show_credentials_popup_ = true;
+ // Pre-fill from DB if we have stored credentials
+ load_exchange_credentials();
+ }
+ ImGui::PopStyleColor(2);
+
+ ImGui::SameLine(0, 12);
+ ImGui::TextColored(BORDER_BRIGHT, "|");
+ ImGui::SameLine(0, 12);
+
+ // Trading mode toggle
+ bool is_paper = (trading_mode_ == TradingMode::Paper);
+ ImGui::PushStyleColor(ImGuiCol_Button, is_paper ? ImVec4(0.0f, 0.5f, 0.2f, 1.0f) : BG_WIDGET);
+ ImGui::PushStyleColor(ImGuiCol_Text, is_paper ? TEXT_PRIMARY : TEXT_DIM);
+ if (ImGui::SmallButton("PAPER")) trading_mode_ = TradingMode::Paper;
+ ImGui::PopStyleColor(2);
+
+ ImGui::SameLine(0, 4);
+
+ bool is_live = (trading_mode_ == TradingMode::Live);
+ ImGui::PushStyleColor(ImGuiCol_Button, is_live ? ImVec4(0.7f, 0.1f, 0.1f, 1.0f) : BG_WIDGET);
+ ImGui::PushStyleColor(ImGuiCol_Text, is_live ? TEXT_PRIMARY : TEXT_DIM);
+ if (ImGui::SmallButton("LIVE")) {
+ trading_mode_ = TradingMode::Live;
+ // Trigger initial live data fetch when switching to live mode
+ if (has_credentials_ && !live_data_loaded_) {
+ async_fetch_live_balance();
+ async_fetch_live_positions();
+ async_fetch_live_orders();
+ }
+ }
+ ImGui::PopStyleColor(2);
+
+ // Right side: mode badge + balance
+ float balance_w = 280;
+ float avail = ImGui::GetContentRegionAvail().x;
+ if (avail > balance_w + 20) {
+ ImGui::SameLine(ImGui::GetCursorPosX() + avail - balance_w);
+ if (is_paper) {
+ ImGui::TextColored(ImVec4(0.0f, 0.7f, 0.3f, 1.0f), "PAPER");
+ } else {
+ ImGui::TextColored(ImVec4(0.9f, 0.2f, 0.2f, 1.0f), "LIVE");
+ }
+ ImGui::SameLine(0, 8);
+ ImGui::TextColored(TEXT_DIM, "Balance:");
+ ImGui::SameLine(0, 4);
+ char bal_buf[32];
+ if (is_paper) {
+ std::snprintf(bal_buf, sizeof(bal_buf), "%.2f %s", portfolio_.balance, portfolio_.currency.c_str());
+ } else if (has_credentials_ && live_equity_ > 0.0) {
+ std::snprintf(bal_buf, sizeof(bal_buf), "%.2f USDT", live_equity_);
+ } else {
+ std::snprintf(bal_buf, sizeof(bal_buf), "-- (Live)");
+ }
+ ImGui::TextColored(MARKET_GREEN, "%s", bal_buf);
+ }
+
+ ImGui::EndChild();
+ ImGui::PopStyleColor();
+}
+
+// ============================================================================
+// Ticker Bar — selected symbol price info
+// ============================================================================
+void CryptoTradingScreen::render_ticker_bar(float w, float h) {
+ ImGui::PushStyleColor(ImGuiCol_ChildBg, BG_PANEL);
+ ImGui::BeginChild("##crypto_ticker", ImVec2(w, h), true);
+
+ // Symbol
+ ImGui::SetWindowFontScale(1.2f);
+ ImGui::TextColored(TEXT_PRIMARY, "%s", selected_symbol_.c_str());
+ ImGui::SetWindowFontScale(1.0f);
+
+ ImGui::SameLine(0, 16);
+
+ double price = current_ticker_.last;
+
+ if (price <= 0 && ticker_loading_) {
+ theme::LoadingSpinner("Loading...");
+ ImGui::EndChild();
+ ImGui::PopStyleColor();
+ return;
+ }
+
+ if (price <= 0) {
+ ImGui::TextColored(TEXT_DIM, "Waiting for data...");
+ ImGui::EndChild();
+ ImGui::PopStyleColor();
+ return;
+ }
+
+ // Price
+ char buf[64];
+ bool positive = current_ticker_.change >= 0;
+ ImVec4 chg_col = positive ? MARKET_GREEN : MARKET_RED;
+
+ if (price > 1.0)
+ std::snprintf(buf, sizeof(buf), "%.2f", price);
+ else
+ std::snprintf(buf, sizeof(buf), "%.6f", price);
+
+ ImGui::SetWindowFontScale(1.1f);
+ ImGui::TextColored(chg_col, "%s", buf);
+ ImGui::SetWindowFontScale(1.0f);
+
+ ImGui::SameLine(0, 16);
+
+ // Change
+ std::snprintf(buf, sizeof(buf), "%s%.2f (%s%.2f%%)",
+ positive ? "+" : "", current_ticker_.change,
+ positive ? "+" : "", current_ticker_.percentage);
+ ImGui::TextColored(chg_col, "%s", buf);
+
+ ImGui::SameLine(0, 24);
+ ImGui::TextColored(BORDER_BRIGHT, "|");
+
+ // High / Low
+ ImGui::SameLine(0, 12);
+ ImGui::TextColored(TEXT_DIM, "H:");
+ ImGui::SameLine(0, 4);
+ std::snprintf(buf, sizeof(buf), "%.2f", current_ticker_.high);
+ ImGui::TextColored(TEXT_SECONDARY, "%s", buf);
+
+ ImGui::SameLine(0, 8);
+ ImGui::TextColored(TEXT_DIM, "L:");
+ ImGui::SameLine(0, 4);
+ std::snprintf(buf, sizeof(buf), "%.2f", current_ticker_.low);
+ ImGui::TextColored(TEXT_SECONDARY, "%s", buf);
+
+ ImGui::SameLine(0, 12);
+ ImGui::TextColored(BORDER_BRIGHT, "|");
+
+ // Volume
+ ImGui::SameLine(0, 12);
+ ImGui::TextColored(TEXT_DIM, "Vol:");
+ ImGui::SameLine(0, 4);
+ double vol = current_ticker_.base_volume;
+ if (vol >= 1e9)
+ std::snprintf(buf, sizeof(buf), "%.2fB", vol / 1e9);
+ else if (vol >= 1e6)
+ std::snprintf(buf, sizeof(buf), "%.2fM", vol / 1e6);
+ else if (vol >= 1e3)
+ std::snprintf(buf, sizeof(buf), "%.2fK", vol / 1e3);
+ else
+ std::snprintf(buf, sizeof(buf), "%.2f", vol);
+ ImGui::TextColored(TEXT_SECONDARY, "%s", buf);
+
+ ImGui::SameLine(0, 12);
+ ImGui::TextColored(BORDER_BRIGHT, "|");
+
+ // Bid / Ask
+ ImGui::SameLine(0, 12);
+ ImGui::TextColored(TEXT_DIM, "Bid:");
+ ImGui::SameLine(0, 4);
+ std::snprintf(buf, sizeof(buf), "%.2f", current_ticker_.bid);
+ ImGui::TextColored(MARKET_GREEN, "%s", buf);
+
+ ImGui::SameLine(0, 8);
+ ImGui::TextColored(TEXT_DIM, "Ask:");
+ ImGui::SameLine(0, 4);
+ std::snprintf(buf, sizeof(buf), "%.2f", current_ticker_.ask);
+ ImGui::TextColored(MARKET_RED, "%s", buf);
+
+ // Loading indicator
+ if (ticker_fetching_) {
+ ImGui::SameLine(0, 8);
+ ImGui::TextColored(WARNING, "[*]");
+ }
+
+ ImGui::EndChild();
+ ImGui::PopStyleColor();
+}
+
+void CryptoTradingScreen::render_status_bar(float w, float h) {
+ ImGui::PushStyleColor(ImGuiCol_ChildBg, BG_DARKEST);
+ ImGui::BeginChild("##crypto_status", ImVec2(w, h), true);
+
+ // Connection status
+ bool ws_live = trading::ExchangeService::instance().is_ws_connected();
+ bool has_data = (current_ticker_.last > 0);
+ ImGui::TextColored(ws_live ? MARKET_GREEN : (has_data ? WARNING : MARKET_RED), "[*]");
+ ImGui::SameLine(0, 4);
+ ImGui::TextColored(TEXT_DIM, "%s", ws_live ? "WS LIVE" : (has_data ? "REST" : "NO DATA"));
+
+ ImGui::SameLine(0, 12);
+ ImGui::TextColored(BORDER_BRIGHT, "|");
+ ImGui::SameLine(0, 12);
+
+ // Exchange
+ ImGui::TextColored(TEXT_DIM, "Exchange:");
+ ImGui::SameLine(0, 4);
+ ImGui::TextColored(TEXT_SECONDARY, "%s", exchange_id_.c_str());
+
+ ImGui::SameLine(0, 12);
+ ImGui::TextColored(BORDER_BRIGHT, "|");
+ ImGui::SameLine(0, 12);
+
+ // Mode
+ bool is_paper = (trading_mode_ == TradingMode::Paper);
+ ImGui::TextColored(TEXT_DIM, "Mode:");
+ ImGui::SameLine(0, 4);
+ ImGui::TextColored(is_paper ? WARNING : MARKET_RED, "%s", is_paper ? "PAPER" : "LIVE");
+
+ ImGui::SameLine(0, 12);
+ ImGui::TextColored(BORDER_BRIGHT, "|");
+ ImGui::SameLine(0, 12);
+
+ // Stats
+ ImGui::TextColored(TEXT_DIM, "OK:%d ERR:%d", success_count_, error_count_);
+
+ // Async status
+ ImGui::SameLine(0, 12);
+ ImGui::TextColored(BORDER_BRIGHT, "|");
+ ImGui::SameLine(0, 12);
+
+ if (ticker_fetching_ || ob_fetching_ || wl_fetching_) {
+ ImGui::TextColored(WARNING, "FETCHING");
+ if (ticker_fetching_) { ImGui::SameLine(0, 4); ImGui::TextColored(TEXT_DIM, "[T]"); }
+ if (ob_fetching_) { ImGui::SameLine(0, 4); ImGui::TextColored(TEXT_DIM, "[OB]"); }
+ if (wl_fetching_) { ImGui::SameLine(0, 4); ImGui::TextColored(TEXT_DIM, "[WL]"); }
+ } else {
+ ImGui::TextColored(TEXT_DIM, "IDLE");
+ }
+
+ // Last error (if any)
+ if (!last_error_.empty()) {
+ ImGui::SameLine(0, 12);
+ ImGui::TextColored(BORDER_BRIGHT, "|");
+ ImGui::SameLine(0, 12);
+ // Truncate error for status bar
+ std::string err_short = last_error_.substr(0, 60);
+ ImGui::TextColored(MARKET_RED, "%s", err_short.c_str());
+ }
+
+ // Right side: last update time
+ if (last_data_update_ > 0) {
+ time_t now = time(nullptr);
+ int elapsed = (int)difftime(now, last_data_update_);
+ char time_buf[32];
+ std::snprintf(time_buf, sizeof(time_buf), "Updated %ds ago", elapsed);
+ float time_w = ImGui::CalcTextSize(time_buf).x + 8;
+ float avail = ImGui::GetContentRegionAvail().x;
+ if (avail > time_w) {
+ ImGui::SameLine(ImGui::GetCursorPosX() + avail - time_w);
+ ImGui::TextColored(TEXT_DIM, "%s", time_buf);
+ }
+ }
+
+ ImGui::EndChild();
+ ImGui::PopStyleColor();
+}
+
+} // namespace fincept::crypto
diff --git a/fincept-cpp/src/screens/crypto_trading/crypto_trading_screen.cpp b/fincept-cpp/src/screens/crypto_trading/crypto_trading_screen.cpp
index 60706fe6c..9a91501f3 100644
--- a/fincept-cpp/src/screens/crypto_trading/crypto_trading_screen.cpp
+++ b/fincept-cpp/src/screens/crypto_trading/crypto_trading_screen.cpp
@@ -1,3789 +1,10 @@
-#include "crypto_trading_screen.h"
-#include "ui/yoga_helpers.h"
-#include "ui/theme.h"
-#include "trading/paper_trading.h"
-#include "trading/order_matcher.h"
-#include "core/logger.h"
-#include "core/notification.h"
-#include <imgui.h>
-#include <cstdio>
-#include <cstring>
-#include <cmath>
-#include <ctime>
-#include <algorithm>
-#include <chrono>
-#include <thread>
-
-namespace fincept::crypto {
-
-using namespace theme::colors;
-static constexpr const char* TAG = "CryptoTrading";
-
-// Named constants (ES.45: avoid magic numbers)
-static constexpr int OHLCV_FETCH_COUNT = 200;
-static constexpr double DEFAULT_PAPER_BALANCE = 100000.0;
-static constexpr int PORTFOLIO_CLEANUP_THRESH = 10;
-static constexpr float TICKER_POLL_INTERVAL = 3.0f; // seconds (REST fallback)
-static constexpr float ORDERBOOK_POLL_INTERVAL = 3.0f;
-static constexpr float WATCHLIST_POLL_INTERVAL = 15.0f;
-static constexpr float PORTFOLIO_REFRESH_INTERVAL = 1.5f;
-static constexpr float MARKET_INFO_INTERVAL = 30.0f;
-static constexpr int PRICE_FEED_POLL_SEC = 3;
-static constexpr int WS_MAX_WATCHLIST_SYMBOLS = 10; // cap WS subscriptions
-static constexpr int MAX_CANDLE_BUFFER = 500; // rolling candle window
-static constexpr int PORTFOLIO_CLEANUP_TRADE_LIMIT = 1; // min trades to keep portfolio
-
-// Order book analytics constants (ported from Tauri CryptoOrderBook.tsx)
-static constexpr double OB_IMBALANCE_BUY_THRESHOLD = 0.30; // signal=BUY if imbalance > this
-static constexpr double OB_IMBALANCE_SELL_THRESHOLD = -0.30; // signal=SELL if imbalance < this
-static constexpr double OB_RISE_BUY_THRESHOLD = 0.15; // % 60s rise required for BUY signal
-static constexpr double OB_RISE_SELL_THRESHOLD = -0.15; // % 60s rise required for SELL signal
-static constexpr int OB_MAX_TICK_HISTORY = 3600; // 1 hour at 1 snapshot/sec
-static constexpr int OB_TICK_CAPTURE_MS = 1000; // ms between tick snapshots
-static constexpr int OB_MAX_OB_DISPLAY_LEVELS = 12; // visible rows per side
-
-// ============================================================================
-// Default watchlist — top crypto pairs
-// ============================================================================
-std::vector<std::string> CryptoTradingScreen::default_watchlist_symbols() {
- return {
- "BTC/USDT", "ETH/USDT", "BNB/USDT", "SOL/USDT", "XRP/USDT",
- "ADA/USDT", "DOGE/USDT", "AVAX/USDT", "DOT/USDT", "MATIC/USDT",
- "LINK/USDT", "UNI/USDT", "ATOM/USDT", "LTC/USDT", "FIL/USDT",
- "APT/USDT", "ARB/USDT", "OP/USDT", "NEAR/USDT", "SUI/USDT",
- };
-}
-
-// ============================================================================
-// Destructor
-// ============================================================================
-CryptoTradingScreen::~CryptoTradingScreen() {
- LOG_INFO(TAG, "Shutting down");
- join_pending_threads(); // wait for in-flight fetches before tearing down (CP.26)
-
- auto& svc = trading::ExchangeService::instance();
- if (ws_started_) {
- svc.stop_ws_stream();
- ws_started_ = false;
- }
- if (ws_price_cb_id_ >= 0) svc.remove_price_callback(ws_price_cb_id_);
- if (ws_ob_cb_id_ >= 0) svc.remove_orderbook_callback(ws_ob_cb_id_);
- if (ws_candle_cb_id_ >= 0) svc.remove_candle_callback(ws_candle_cb_id_);
- if (ws_trade_cb_id_ >= 0) svc.remove_trade_callback(ws_trade_cb_id_);
-}
-
-// ============================================================================
-// Thread lifecycle — RAII tracked async threads (CP.26: no detach)
-// ============================================================================
-void CryptoTradingScreen::launch_async(std::thread t) {
- std::lock_guard<std::mutex> lock(threads_mutex_);
- // Prune already-finished threads to keep the vector bounded
- async_threads_.erase(
- std::remove_if(async_threads_.begin(), async_threads_.end(),
- [](std::thread& th) { return !th.joinable(); }),
- async_threads_.end());
- async_threads_.push_back(std::move(t));
-}
-
-void CryptoTradingScreen::join_pending_threads() {
- std::lock_guard<std::mutex> lock(threads_mutex_);
- for (auto& t : async_threads_) {
- if (t.joinable()) t.join();
- }
- async_threads_.clear();
-}
-
-// ============================================================================
-// Initialization — fast, no blocking network calls
-// ============================================================================
-void CryptoTradingScreen::init() {
- LOG_INFO(TAG, "=== INIT START ===");
-
- // Ensure exchange_id has a value
- if (exchange_id_.empty()) {
- exchange_id_ = "binance";
- LOG_INFO(TAG, "exchange_id_ was empty, defaulting to binance");
- }
- if (selected_symbol_.empty()) {
- selected_symbol_ = "BTC/USDT";
- }
-
- // Set up exchange
- auto& svc = trading::ExchangeService::instance();
- svc.set_exchange(exchange_id_);
- LOG_INFO(TAG, "Exchange set to: %s", exchange_id_.c_str());
-
- // Load stored API credentials for this exchange (if any)
- load_exchange_credentials();
-
- // Build watchlist entries
- auto symbols = default_watchlist_symbols();
- watchlist_.clear();
- for (auto& s : symbols) {
- WatchlistEntry e;
- e.symbol = s;
- watchlist_.push_back(e);
- }
- LOG_INFO(TAG, "Watchlist initialized with %d symbols", (int)watchlist_.size());
-
- // Create or load paper trading portfolio (DB only, fast)
- load_portfolio();
-
- // Register portfolio with exchange service so position prices get updated
- if (!portfolio_id_.empty()) {
- svc.watch_symbol(selected_symbol_, portfolio_id_);
- // Also watch all symbols that have open positions
- for (const auto& pos : positions_) {
- if (pos.symbol != selected_symbol_) {
- svc.watch_symbol(pos.symbol, portfolio_id_);
- }
- }
- }
-
- // Start the price feed for watched symbols (drives OrderMatcher + position updates)
- if (!svc.is_feed_running()) {
- svc.start_price_feed(PRICE_FEED_POLL_SEC);
- }
-
- // Fetch available exchanges from ccxt (async, non-blocking)
- if (!exchanges_loaded_ && !exchanges_fetching_) {
- exchanges_fetching_ = true;
- launch_async(std::thread([this]() {
- try {
- auto ids = trading::ExchangeService::instance().list_exchange_ids();
- LOG_INFO(TAG, "Loaded %d exchange IDs from ccxt", (int)ids.size());
- std::lock_guard<std::mutex> lock(data_mutex_);
- available_exchanges_ = std::move(ids);
- exchanges_loaded_ = true;
- } catch (const std::exception& e) {
- LOG_ERROR(TAG, "Failed to load exchange IDs: %s", e.what());
- }
- exchanges_fetching_ = false;
- }));
- }
-
- initialized_ = true;
- LOG_INFO(TAG, "=== INIT COMPLETE === (portfolio_id=%s, balance=%.2f)",
- portfolio_id_.c_str(), portfolio_.balance);
-
- // Kick off initial REST fetches (fast initial data while WS connects)
- LOG_INFO(TAG, "Starting async data fetches...");
- ticker_loading_ = true;
- ob_loading_ = true;
- async_refresh_ticker();
- async_refresh_orderbook();
- async_refresh_watchlist_prices();
-
- // Fetch initial OHLCV candles via REST
- candles_loading_ = true;
- candles_fetching_ = true;
- const std::string sym = selected_symbol_;
- launch_async(std::thread([this, sym]() {
- try {
- auto ohlcv = trading::ExchangeService::instance().fetch_ohlcv(sym, "1m", OHLCV_FETCH_COUNT);
- LOG_INFO(TAG, "<<< Initial OHLCV received: %d candles", (int)ohlcv.size());
- {
- std::lock_guard<std::mutex> lock(data_mutex_);
- candles_ = std::move(ohlcv);
- }
- candles_loading_ = false;
- candles_fetching_ = false;
- success_count_++;
- } catch (const std::exception& e) {
- LOG_ERROR(TAG, "<<< OHLCV fetch failed: %s", e.what());
- candles_loading_ = false;
- candles_fetching_ = false;
- error_count_++;
- }
- }));
-
- // Start WebSocket streaming for real-time updates
- // restart_ws_stream() handles callback registration + stream start
- restart_ws_stream();
-
- // Fetch initial trades and market info via REST
- async_fetch_trades();
- async_fetch_market_info();
-}
-
-void CryptoTradingScreen::load_portfolio() {
- LOG_INFO(TAG, "Loading paper trading portfolio for exchange: %s", exchange_id_.c_str());
-
- try {
- // Reset state so stale data from previous exchange doesn't leak
- portfolio_id_.clear();
- portfolio_ = {};
- positions_.clear();
- orders_.clear();
- trades_.clear();
- stats_ = {};
- portfolio_loaded_ = false;
-
- // Find portfolio scoped to this exchange
- auto found = trading::pt_find_portfolio("Crypto Paper Trading", exchange_id_);
- if (found) {
- portfolio_ = *found;
- portfolio_id_ = found->id;
- LOG_INFO(TAG, "Using existing portfolio: %s (exchange=%s, balance=%.2f)",
- portfolio_id_.c_str(), exchange_id_.c_str(), portfolio_.balance);
- }
-
- // Create if not found for this exchange
- if (portfolio_id_.empty()) {
- portfolio_ = trading::pt_create_portfolio(
- "Crypto Paper Trading", DEFAULT_PAPER_BALANCE, "USDT",
- 1.0, "cross", 0.001, exchange_id_);
- portfolio_id_ = portfolio_.id;
- LOG_INFO(TAG, "Created new portfolio: %s (exchange=%s, balance=%.2f)",
- portfolio_id_.c_str(), exchange_id_.c_str(), portfolio_.balance);
- }
-
- // Load positions, orders, trades, stats from DB
- positions_ = trading::pt_get_positions(portfolio_id_);
- orders_ = trading::pt_get_orders(portfolio_id_);
- trades_ = trading::pt_get_trades(portfolio_id_, 50);
- stats_ = trading::pt_get_stats(portfolio_id_);
- portfolio_loaded_ = true;
-
- LOG_INFO(TAG, "Portfolio data loaded: %d positions, %d orders, %d trades",
- (int)positions_.size(), (int)orders_.size(), (int)trades_.size());
- } catch (const std::exception& e) {
- LOG_ERROR(TAG, "Failed to load portfolio: %s", e.what());
- last_error_ = std::string("Portfolio load failed: ") + e.what();
- error_count_++;
- }
-}
-
-// ============================================================================
-// Exchange & symbol switching — proper lifecycle management
-// ============================================================================
-
-void CryptoTradingScreen::clear_market_data() {
- std::lock_guard<std::mutex> lock(data_mutex_);
- current_ticker_ = {};
- ob_bids_.clear();
- ob_asks_.clear();
- ob_spread_ = 0.0;
- ob_spread_pct_ = 0.0;
- candles_.clear();
- recent_trades_.clear();
- market_info_ = {};
- for (auto& w : watchlist_) {
- w.price = 0.0;
- w.change = 0.0;
- w.change_pct = 0.0;
- w.volume = 0.0;
- w.has_data = false;
- }
- last_error_.clear();
- error_count_ = 0;
- success_count_ = 0;
-}
-
-void CryptoTradingScreen::restart_ws_stream() {
- auto& svc = trading::ExchangeService::instance();
-
- // Tear down existing WS
- if (ws_started_) {
- svc.stop_ws_stream();
- ws_started_ = false;
- }
-
- // Remove old callbacks
- if (ws_price_cb_id_ >= 0) { svc.remove_price_callback(ws_price_cb_id_); ws_price_cb_id_ = -1; }
- if (ws_ob_cb_id_ >= 0) { svc.remove_orderbook_callback(ws_ob_cb_id_); ws_ob_cb_id_ = -1; }
- if (ws_candle_cb_id_ >= 0) { svc.remove_candle_callback(ws_candle_cb_id_); ws_candle_cb_id_ = -1; }
- if (ws_trade_cb_id_ >= 0) { svc.remove_trade_callback(ws_trade_cb_id_); ws_trade_cb_id_ = -1; }
-
- // Re-register callbacks (same as in init())
- ws_price_cb_id_ = svc.on_price_update([this](const std::string& symbol, const trading::TickerData& ticker) {
- std::lock_guard<std::mutex> lock(data_mutex_);
- if (symbol == selected_symbol_) {
- current_ticker_ = ticker;
- ticker_loading_ = false;
- }
- for (auto& w : watchlist_) {
- if (w.symbol == symbol) {
- w.price = ticker.last;
- w.change = ticker.change;
- w.change_pct = ticker.percentage;
- w.volume = ticker.base_volume;
- w.has_data = true;
- break;
- }
- }
- last_data_update_ = time(nullptr);
- });
-
- ws_ob_cb_id_ = svc.on_orderbook_update([this](const std::string& symbol, const trading::OrderBookData& ob) {
- if (symbol != selected_symbol_) return;
- std::lock_guard<std::mutex> lock(data_mutex_);
-
- // Parse bids/asks into cumulative levels
- ob_bids_.clear();
- ob_asks_.clear();
- {
- double cum = 0;
- for (const auto& [price, amount] : ob.bids) {
- cum += amount;
- ob_bids_.push_back({price, amount, cum});
- }
- }
- {
- double cum = 0;
- for (const auto& [price, amount] : ob.asks) {
- cum += amount;
- ob_asks_.push_back({price, amount, cum});
- }
- }
- ob_spread_ = ob.spread;
- ob_spread_pct_ = ob.spread_pct;
- ob_loading_ = false;
- last_data_update_ = time(nullptr);
-
- // --- Tick history capture (throttled to OB_TICK_CAPTURE_MS) ---
- // Feeds Imbalance and Signals view modes with computed analytics.
- const int64_t now_ms = std::chrono::duration_cast<std::chrono::milliseconds>(
- std::chrono::steady_clock::now().time_since_epoch()).count();
-
- if (now_ms - last_tick_capture_ms_ >= static_cast<int64_t>(OB_TICK_CAPTURE_MS)) {
- last_tick_capture_ms_ = now_ms;
-
- TickSnapshot snap;
- snap.timestamp = now_ms;
- snap.best_bid = ob.best_bid;
- snap.best_ask = ob.best_ask;
-
- // Top-3 quantities from each side for weighted imbalance
- for (int i = 0; i < 3 && i < static_cast<int>(ob_bids_.size()); ++i)
- snap.bid_qty[i] = ob_bids_[i].amount;
- for (int i = 0; i < 3 && i < static_cast<int>(ob_asks_.size()); ++i)
- snap.ask_qty[i] = ob_asks_[i].amount;
-
- // Weighted imbalance: 50/30/20 top-3 levels (SGX formula, from Tauri impl)
- const double wBid = 50.0 * snap.bid_qty[0] + 30.0 * snap.bid_qty[1] + 20.0 * snap.bid_qty[2];
- const double wAsk = 50.0 * snap.ask_qty[0] + 30.0 * snap.ask_qty[1] + 20.0 * snap.ask_qty[2];
- snap.imbalance = (wBid + wAsk > 0.0) ? (wBid - wAsk) / (wBid + wAsk) : 0.0;
-
- // 60-second rise ratio: find oldest tick within 60s window
- const int64_t cutoff_60 = now_ms - 60000;
- snap.rise_ratio_60 = 0.0;
- for (int i = static_cast<int>(tick_history_.size()) - 1; i >= 0; --i) {
- if (tick_history_[i].timestamp <= cutoff_60 && tick_history_[i].best_ask > 0.0) {
- snap.rise_ratio_60 = ((ob.best_ask - tick_history_[i].best_ask)
- / tick_history_[i].best_ask) * 100.0;
- break;
- }
- }
-
- tick_history_.push_back(snap);
- if (static_cast<int>(tick_history_.size()) > OB_MAX_TICK_HISTORY)
- tick_history_.erase(tick_history_.begin());
- }
- });
-
- ws_candle_cb_id_ = svc.on_candle_update([this](const std::string& symbol, const trading::Candle& candle) {
- if (symbol != selected_symbol_) return;
- std::lock_guard<std::mutex> lock(data_mutex_);
- if (!candles_.empty() && candles_.back().timestamp == candle.timestamp) {
- candles_.back() = candle;
- } else {
- candles_.push_back(candle);
- if (candles_.size() > MAX_CANDLE_BUFFER) candles_.erase(candles_.begin());
- }
- });
-
- ws_trade_cb_id_ = svc.on_trade_update([this](const std::string& symbol, const trading::TradeData& trade) {
- if (symbol != selected_symbol_) return;
- std::lock_guard<std::mutex> lock(data_mutex_);
- recent_trades_.insert(recent_trades_.begin(), TradeEntry{
- trade.id, trade.side, trade.price, trade.amount, trade.timestamp
- });
- if ((int)recent_trades_.size() > MAX_TRADES) recent_trades_.resize(MAX_TRADES);
- });
-
- // Start new WS stream — cap to top N symbols to limit concurrent WS subscriptions.
- // Primary symbol is always first; remaining slots filled from watchlist in order.
- // Callbacks capture `this` — selected_symbol_ is read at invocation time,
- // so symbol switches (via set_ws_primary_symbol) take effect automatically
- // without restarting these callbacks.
- std::vector<std::string> all_symbols;
- all_symbols.reserve(WS_MAX_WATCHLIST_SYMBOLS + 1);
- all_symbols.push_back(selected_symbol_);
- for (const auto& w : watchlist_) {
- if ((int)all_symbols.size() >= WS_MAX_WATCHLIST_SYMBOLS) break;
- if (w.symbol != selected_symbol_) all_symbols.push_back(w.symbol);
- }
-
- try {
- svc.start_ws_stream(selected_symbol_, all_symbols);
- ws_started_ = true;
- LOG_INFO(TAG, "WS stream restarted for %s + %d symbols on %s",
- selected_symbol_.c_str(), (int)all_symbols.size(), exchange_id_.c_str());
- } catch (const std::exception& e) {
- LOG_ERROR(TAG, "Failed to restart WS: %s", e.what());
- last_error_ = std::string("WS restart failed: ") + e.what();
- }
-}
-
-void CryptoTradingScreen::switch_exchange(const std::string& exchange_id) {
- if (exchange_id == exchange_id_) return;
-
- LOG_INFO(TAG, "Switching exchange: %s -> %s", exchange_id_.c_str(), exchange_id.c_str());
-
- // Stop price feed before switching (it uses the old exchange)
- auto& svc = trading::ExchangeService::instance();
- svc.stop_price_feed();
-
- // Update exchange
- exchange_id_ = exchange_id;
- svc.set_exchange(exchange_id);
-
- // Invalidate search cache — new exchange has different markets
- search_markets_loaded_ = false;
- search_cache_exchange_.clear();
- all_markets_.clear();
- search_results_.clear();
-
- // Load credentials for the new exchange
- load_exchange_credentials();
- live_data_loaded_ = false;
-
- // Clear all stale market data from previous exchange
- clear_market_data();
-
- // Swap portfolio — each exchange gets its own isolated paper portfolio
- // Unwatch symbols from old portfolio first
- if (!portfolio_id_.empty()) {
- svc.unwatch_symbol(selected_symbol_, portfolio_id_);
- for (const auto& pos : positions_) {
- svc.unwatch_symbol(pos.symbol, portfolio_id_);
- }
- trading::OrderMatcher::instance().clear_portfolio_orders(portfolio_id_);
- }
- load_portfolio();
-
- // Reset loading states
- ticker_loading_ = true;
- ob_loading_ = true;
- candles_loading_ = true;
-
- // Re-watch the selected symbol with the NEW portfolio
- if (!portfolio_id_.empty()) {
- svc.watch_symbol(selected_symbol_, portfolio_id_);
- for (const auto& pos : positions_) {
- if (pos.symbol != selected_symbol_) {
- svc.watch_symbol(pos.symbol, portfolio_id_);
- }
- }
- }
- svc.start_price_feed(PRICE_FEED_POLL_SEC);
-
- // Restart WebSocket stream for new exchange
- restart_ws_stream();
-
- // Kick off REST fetches for immediate data
- async_refresh_ticker();
- async_refresh_orderbook();
- async_refresh_watchlist_prices();
- async_fetch_trades();
- async_fetch_market_info();
-
- // Fetch fresh candles
- candles_fetching_ = true;
- const std::string sym = selected_symbol_;
- launch_async(std::thread([this, sym]() {
- try {
- auto ohlcv = trading::ExchangeService::instance().fetch_ohlcv(sym, "1m", OHLCV_FETCH_COUNT);
- {
- std::lock_guard<std::mutex> lock(data_mutex_);
- candles_ = std::move(ohlcv);
- }
- candles_loading_ = false;
- candles_fetching_ = false;
- } catch (const std::exception& e) {
- LOG_ERROR(TAG, "OHLCV fetch failed on exchange switch: %s", e.what());
- candles_loading_ = false;
- candles_fetching_ = false;
- }
- }));
-
- LOG_INFO(TAG, "Exchange switch complete: %s", exchange_id.c_str());
-}
-
-void CryptoTradingScreen::switch_symbol(const std::string& symbol) {
- if (symbol == selected_symbol_) return;
-
- LOG_INFO(TAG, "Switching symbol: %s -> %s", selected_symbol_.c_str(), symbol.c_str());
-
- selected_symbol_ = symbol;
-
- // Clear symbol-specific data (keep watchlist prices intact)
- {
- std::lock_guard<std::mutex> lock(data_mutex_);
- current_ticker_ = {};
- ob_bids_.clear();
- ob_asks_.clear();
- ob_spread_ = 0.0;
- ob_spread_pct_ = 0.0;
- candles_.clear();
- recent_trades_.clear();
- market_info_ = {};
- }
-
- ticker_loading_ = true;
- ob_loading_ = true;
- candles_loading_ = true;
-
- // Watch new symbol for paper trading price updates
- if (!portfolio_id_.empty()) {
- trading::ExchangeService::instance().watch_symbol(symbol, portfolio_id_);
- }
-
- // Tell ExchangeService the new primary — WS subprocess stays alive,
- // callbacks filter on selected_symbol_ (member read at invocation time)
- // so they automatically route to the new symbol without a subprocess restart.
- trading::ExchangeService::instance().set_ws_primary_symbol(symbol);
-
- // Serve from price cache immediately — eliminates blank ticker on switch
- {
- const auto cached = trading::ExchangeService::instance().get_cached_price(symbol);
- if (cached.last > 0.0) {
- std::lock_guard<std::mutex> lock(data_mutex_);
- current_ticker_ = cached;
- ticker_loading_ = false;
- LOG_INFO(TAG, "Showing cached price for %s: %.4f", symbol.c_str(), cached.last);
- }
- }
-
- // REST fetches to fill data not yet in cache (orderbook, candles, trades, market info)
- async_refresh_ticker();
- async_refresh_orderbook();
- async_fetch_trades();
- async_fetch_market_info();
-
- // Fetch OHLCV candles for new symbol
- candles_fetching_ = true;
- const std::string sym = symbol;
- launch_async(std::thread([this, sym]() {
- try {
- auto ohlcv = trading::ExchangeService::instance().fetch_ohlcv(
- sym, candle_timeframe_, OHLCV_FETCH_COUNT);
- {
- std::lock_guard<std::mutex> lock(data_mutex_);
- candles_ = std::move(ohlcv);
- }
- candles_loading_ = false;
- candles_fetching_ = false;
- } catch (const std::exception& e) {
- LOG_ERROR(TAG, "OHLCV fetch failed on symbol switch: %s", e.what());
- candles_loading_ = false;
- candles_fetching_ = false;
- }
- }));
-}
-
-// ============================================================================
-// Async data fetchers — run in detached threads
-// ============================================================================
-void CryptoTradingScreen::async_refresh_ticker() {
- if (ticker_fetching_) {
- LOG_DEBUG(TAG, "Ticker fetch already in flight, skipping");
- return;
- }
-
- ticker_fetching_ = true;
- ticker_loading_ = true;
- const std::string symbol = selected_symbol_;
- LOG_INFO(TAG, ">>> Fetching ticker for %s...", symbol.c_str());
-
- launch_async(std::thread([this, symbol]() {
- try {
- auto ticker = trading::ExchangeService::instance().fetch_ticker(symbol);
-
- LOG_INFO(TAG, "<<< Ticker received: %s last=%.2f bid=%.2f ask=%.2f change=%.2f%%",
- ticker.symbol.c_str(), ticker.last, ticker.bid, ticker.ask, ticker.percentage);
-
- {
- std::lock_guard<std::mutex> lock(data_mutex_);
- current_ticker_ = ticker;
-
- // Also update the watchlist entry
- for (auto& w : watchlist_) {
- if (w.symbol == symbol) {
- w.price = ticker.last;
- w.change = ticker.change;
- w.change_pct = ticker.percentage;
- w.volume = ticker.base_volume;
- w.has_data = true;
- break;
- }
- }
- }
-
- ticker_loading_ = false;
- ticker_fetching_ = false;
- success_count_++;
- last_data_update_ = time(nullptr);
- } catch (const std::exception& e) {
- LOG_ERROR(TAG, "<<< Ticker fetch FAILED for %s: %s", symbol.c_str(), e.what());
- ticker_loading_ = false;
- ticker_fetching_ = false;
- last_error_ = std::string("Ticker: ") + e.what();
- error_count_++;
- }
- }));
-}
-
-void CryptoTradingScreen::async_refresh_orderbook() {
- if (ob_fetching_) {
- LOG_DEBUG(TAG, "Orderbook fetch already in flight, skipping");
- return;
- }
-
- ob_fetching_ = true;
- ob_loading_ = true;
- const std::string symbol = selected_symbol_;
- LOG_INFO(TAG, ">>> Fetching orderbook for %s...", symbol.c_str());
-
- launch_async(std::thread([this, symbol]() {
- try {
- auto ob = trading::ExchangeService::instance().fetch_orderbook(symbol, 15);
-
- LOG_INFO(TAG, "<<< Orderbook received: %s bids=%d asks=%d spread=%.4f (%.4f%%)",
- ob.symbol.c_str(), (int)ob.bids.size(), (int)ob.asks.size(),
- ob.spread, ob.spread_pct);
-
- {
- std::lock_guard<std::mutex> lock(data_mutex_);
- ob_bids_.clear();
- ob_asks_.clear();
-
- double cum = 0;
- for (auto& [price, amount] : ob.bids) {
- cum += amount;
- ob_bids_.push_back({price, amount, cum});
- }
-
- cum = 0;
- for (auto& [price, amount] : ob.asks) {
- cum += amount;
- ob_asks_.push_back({price, amount, cum});
- }
-
- ob_spread_ = ob.spread;
- ob_spread_pct_ = ob.spread_pct;
- }
-
- ob_loading_ = false;
- ob_fetching_ = false;
- success_count_++;
- last_data_update_ = time(nullptr);
- } catch (const std::exception& e) {
- LOG_ERROR(TAG, "<<< Orderbook fetch FAILED for %s: %s", symbol.c_str(), e.what());
- ob_loading_ = false;
- ob_fetching_ = false;
- last_error_ = std::string("Orderbook: ") + e.what();
- error_count_++;
- }
- }));
-}
-
-void CryptoTradingScreen::async_refresh_watchlist_prices() {
- if (wl_fetching_) {
- LOG_DEBUG(TAG, "Watchlist price fetch already in flight, skipping");
- return;
- }
-
- wl_fetching_ = true;
-
- // Collect symbols
- std::vector<std::string> symbols;
- {
- std::lock_guard<std::mutex> lock(data_mutex_);
- for (auto& w : watchlist_) {
- symbols.push_back(w.symbol);
- }
- }
-
- LOG_INFO(TAG, ">>> Fetching watchlist prices for %d symbols...", (int)symbols.size());
-
- launch_async(std::thread([this, symbols]() {
- try {
- auto tickers = trading::ExchangeService::instance().fetch_tickers(symbols);
-
- LOG_INFO(TAG, "<<< Watchlist prices received: %d tickers", (int)tickers.size());
-
- {
- std::lock_guard<std::mutex> lock(data_mutex_);
- for (auto& ticker : tickers) {
- for (auto& w : watchlist_) {
- if (w.symbol == ticker.symbol) {
- w.price = ticker.last;
- w.change = ticker.change;
- w.change_pct = ticker.percentage;
- w.volume = ticker.base_volume;
- w.has_data = true;
-
- LOG_DEBUG(TAG, " WL %s: $%.2f (%.2f%%)",
- w.symbol.c_str(), w.price, w.change_pct);
- break;
- }
- }
-
- // Update current ticker if it matches selected symbol
- if (ticker.symbol == selected_symbol_) {
- current_ticker_ = ticker;
- }
- }
- }
-
- wl_fetching_ = false;
- success_count_++;
- last_data_update_ = time(nullptr);
- } catch (const std::exception& e) {
- LOG_ERROR(TAG, "<<< Watchlist price fetch FAILED: %s", e.what());
- wl_fetching_ = false;
- last_error_ = std::string("Watchlist: ") + e.what();
- error_count_++;
- }
- }));
-}
-
-void CryptoTradingScreen::refresh_portfolio_data() {
- if (portfolio_id_.empty()) return;
-
- try {
- // Update position mark-to-market prices using current ticker data
- double last_price = current_ticker_.last;
- if (last_price > 0) {
- trading::pt_update_position_price(portfolio_id_, selected_symbol_, last_price);
- }
-
- // Also update prices for positions in other symbols from the price cache
- auto& svc = trading::ExchangeService::instance();
- for (const auto& pos : positions_) {
- if (pos.symbol == selected_symbol_) continue;
- auto cached = svc.get_cached_price(pos.symbol);
- if (cached.last > 0) {
- trading::pt_update_position_price(portfolio_id_, pos.symbol, cached.last);
- }
- }
-
- // Check SL/TP triggers for all open positions
- {
- auto& matcher = trading::OrderMatcher::instance();
- if (last_price > 0)
- matcher.check_sl_tp_triggers(portfolio_id_, selected_symbol_, last_price);
- for (const auto& pos : positions_) {
- if (pos.symbol == selected_symbol_) continue;
- const auto cached = svc.get_cached_price(pos.symbol);
- if (cached.last > 0)
- matcher.check_sl_tp_triggers(portfolio_id_, pos.symbol, cached.last);
- }
- }
-
- std::lock_guard<std::mutex> lock(data_mutex_);
- portfolio_ = trading::pt_get_portfolio(portfolio_id_);
- positions_ = trading::pt_get_positions(portfolio_id_);
- orders_ = trading::pt_get_orders(portfolio_id_);
- trades_ = trading::pt_get_trades(portfolio_id_, 50);
- stats_ = trading::pt_get_stats(portfolio_id_);
- } catch (const std::exception& e) {
- LOG_ERROR(TAG, "Portfolio refresh failed: %s", e.what());
- }
-}
-
-// ============================================================================
-// Main render — Yoga-based responsive layout
-// ============================================================================
-void CryptoTradingScreen::render() {
- if (!initialized_) init();
-
- // Handle deferred symbol switch (set from search results while holding data_mutex_)
- if (!pending_symbol_switch_.empty()) {
- std::string sym = pending_symbol_switch_;
- pending_symbol_switch_.clear();
- switch_symbol(sym);
- }
-
- ui::ScreenFrame frame("##crypto_trading", ImVec2(0, 0), BG_DARKEST);
- if (!frame.begin()) { frame.end(); return; }
-
- float W = frame.width();
- float H = frame.height();
-
- // Vertical stack: top_nav(28) + ticker_bar(36) + main_area(flex) + status(22)
- auto vstack = ui::vstack_layout(W, H, {28, 36, -1, 22});
-
- render_top_nav(W, vstack.heights[0]);
- render_ticker_bar(W, vstack.heights[1]);
-
- // Main area — three-panel horizontal layout
- float main_h = vstack.heights[2];
- {
- auto panels = ui::three_panel_layout(W, main_h, 15, 22, 180, 280, 300, 4);
-
- ImGui::BeginChild("##crypto_left", ImVec2(panels.left_w, panels.left_h), false);
- render_watchlist(panels.left_w, panels.left_h);
- ImGui::EndChild();
-
- ImGui::SameLine(0, panels.gap);
-
- ImGui::BeginChild("##crypto_center", ImVec2(panels.center_w, panels.center_h), false);
- {
- float chart_h = panels.center_h * 0.55f;
- float bottom_h = panels.center_h - chart_h - 4;
-
- render_chart_area(panels.center_w, chart_h);
- ImGui::Dummy(ImVec2(0, 4));
- render_bottom_panel(panels.center_w, bottom_h);
- }
- ImGui::EndChild();
-
- if (panels.right_w > 0) {
- ImGui::SameLine(0, panels.gap);
-
- ImGui::BeginChild("##crypto_right", ImVec2(panels.right_w, panels.right_h), false);
- {
- float entry_h = panels.right_h * 0.45f;
- float book_h = panels.right_h - entry_h - 4;
-
- render_order_entry(panels.right_w, entry_h);
- ImGui::Dummy(ImVec2(0, 4));
- render_orderbook(panels.right_w, book_h);
- }
- ImGui::EndChild();
- }
- }
-
- render_status_bar(W, vstack.heights[3]);
-
- // Credentials popup (rendered outside frame to overlay properly)
- render_credentials_popup();
-
- frame.end();
-
- // Periodic refreshes — WS handles ticker/orderbook/candles in real-time,
- // polling is fallback only (long intervals)
- float dt = ImGui::GetIO().DeltaTime;
- portfolio_timer_ += dt;
-
- bool ws_ok = trading::ExchangeService::instance().is_ws_connected();
- if (!ws_ok) {
- // WS not connected — fall back to faster REST polling
- ticker_timer_ += dt;
- ob_timer_ += dt;
- wl_timer_ += dt;
-
- if (ticker_timer_ >= TICKER_POLL_INTERVAL) {
- ticker_timer_ = 0;
- async_refresh_ticker();
- }
- if (ob_timer_ >= ORDERBOOK_POLL_INTERVAL) {
- ob_timer_ = 0;
- async_refresh_orderbook();
- }
- if (wl_timer_ >= WATCHLIST_POLL_INTERVAL) {
- wl_timer_ = 0;
- async_refresh_watchlist_prices();
- }
- }
-
- if (portfolio_timer_ >= PORTFOLIO_REFRESH_INTERVAL) {
- portfolio_timer_ = 0;
- refresh_portfolio_data();
- }
-
- // Live data refresh (positions, orders, balance from exchange API)
- if (trading_mode_ == TradingMode::Live && has_credentials_) {
- live_data_timer_ += dt;
- if (live_data_timer_ >= LIVE_DATA_REFRESH_INTERVAL) {
- live_data_timer_ = 0;
- async_fetch_live_positions();
- async_fetch_live_orders();
- async_fetch_live_balance();
- }
- }
-
- // Market info refresh (every 30s)
- market_info_timer_ += dt;
- if (market_info_timer_ >= MARKET_INFO_INTERVAL) {
- market_info_timer_ = 0;
- async_fetch_market_info();
- }
-
- // Clear success/error messages after timeout
- if (order_form_.msg_timer > 0) {
- order_form_.msg_timer -= dt;
- if (order_form_.msg_timer <= 0) {
- order_form_.error.clear();
- order_form_.success.clear();
- }
- }
-}
-
-// ============================================================================
-// Top Navigation Bar
-// ============================================================================
-void CryptoTradingScreen::render_top_nav(float w, float h) {
- ImGui::PushStyleColor(ImGuiCol_ChildBg, BG_DARK);
- ImGui::BeginChild("##crypto_topnav", ImVec2(w, h), true);
-
- ImGui::TextColored(ACCENT, "CRYPTO");
- ImGui::SameLine(0, 4);
- ImGui::TextColored(TEXT_PRIMARY, "TRADING");
- ImGui::SameLine(0, 12);
- ImGui::TextColored(BORDER_BRIGHT, "|");
- ImGui::SameLine(0, 12);
-
- // Exchange selector — dynamic list from ccxt (with search filter)
- ImGui::TextColored(TEXT_DIM, "Exchange:");
- ImGui::SameLine(0, 4);
- ImGui::PushItemWidth(140);
- ImGui::PushStyleColor(ImGuiCol_FrameBg, BG_INPUT);
-
- if (exchanges_loaded_) {
- if (ImGui::BeginCombo("##exchange", exchange_id_.c_str())) {
- ImGui::PushItemWidth(-1);
- ImGui::InputTextWithHint("##ex_filter", "Filter...",
- exchange_filter_, sizeof(exchange_filter_));
- ImGui::PopItemWidth();
- ImGui::Separator();
-
- std::string filter(exchange_filter_);
- for (auto& c : filter) c = (char)std::tolower((unsigned char)c);
-
- std::lock_guard<std::mutex> lock(data_mutex_);
- for (const auto& ex_id : available_exchanges_) {
- if (!filter.empty() && ex_id.find(filter) == std::string::npos)
- continue;
- bool selected = (ex_id == exchange_id_);
- if (ImGui::Selectable(ex_id.c_str(), selected)) {
- switch_exchange(ex_id);
- exchange_filter_[0] = '\0';
- }
- if (selected) ImGui::SetItemDefaultFocus();
- }
- ImGui::EndCombo();
- }
- } else {
- ImGui::BeginDisabled();
- if (ImGui::BeginCombo("##exchange",
- exchanges_fetching_ ? "Loading..." : exchange_id_.c_str())) {
- ImGui::EndCombo();
- }
- ImGui::EndDisabled();
- }
-
- ImGui::PopStyleColor();
- ImGui::PopItemWidth();
-
- // API key indicator + settings button
- ImGui::SameLine(0, 6);
- if (has_credentials_) {
- ImGui::TextColored(MARKET_GREEN, "[KEY]");
- } else {
- ImGui::TextColored(TEXT_DIM, "[NO KEY]");
- }
- ImGui::SameLine(0, 4);
- ImGui::PushStyleColor(ImGuiCol_Button, BG_WIDGET);
- ImGui::PushStyleColor(ImGuiCol_Text, TEXT_DIM);
- if (ImGui::SmallButton("API")) {
- show_credentials_popup_ = true;
- // Pre-fill from DB if we have stored credentials
- load_exchange_credentials();
- }
- ImGui::PopStyleColor(2);
-
- ImGui::SameLine(0, 12);
- ImGui::TextColored(BORDER_BRIGHT, "|");
- ImGui::SameLine(0, 12);
-
- // Trading mode toggle
- bool is_paper = (trading_mode_ == TradingMode::Paper);
- ImGui::PushStyleColor(ImGuiCol_Button, is_paper ? ImVec4(0.0f, 0.5f, 0.2f, 1.0f) : BG_WIDGET);
- ImGui::PushStyleColor(ImGuiCol_Text, is_paper ? TEXT_PRIMARY : TEXT_DIM);
- if (ImGui::SmallButton("PAPER")) trading_mode_ = TradingMode::Paper;
- ImGui::PopStyleColor(2);
-
- ImGui::SameLine(0, 4);
-
- bool is_live = (trading_mode_ == TradingMode::Live);
- ImGui::PushStyleColor(ImGuiCol_Button, is_live ? ImVec4(0.7f, 0.1f, 0.1f, 1.0f) : BG_WIDGET);
- ImGui::PushStyleColor(ImGuiCol_Text, is_live ? TEXT_PRIMARY : TEXT_DIM);
- if (ImGui::SmallButton("LIVE")) {
- trading_mode_ = TradingMode::Live;
- // Trigger initial live data fetch when switching to live mode
- if (has_credentials_ && !live_data_loaded_) {
- async_fetch_live_balance();
- async_fetch_live_positions();
- async_fetch_live_orders();
- }
- }
- ImGui::PopStyleColor(2);
-
- // Right side: mode badge + balance
- float balance_w = 280;
- float avail = ImGui::GetContentRegionAvail().x;
- if (avail > balance_w + 20) {
- ImGui::SameLine(ImGui::GetCursorPosX() + avail - balance_w);
- if (is_paper) {
- ImGui::TextColored(ImVec4(0.0f, 0.7f, 0.3f, 1.0f), "PAPER");
- } else {
- ImGui::TextColored(ImVec4(0.9f, 0.2f, 0.2f, 1.0f), "LIVE");
- }
- ImGui::SameLine(0, 8);
- ImGui::TextColored(TEXT_DIM, "Balance:");
- ImGui::SameLine(0, 4);
- char bal_buf[32];
- if (is_paper) {
- std::snprintf(bal_buf, sizeof(bal_buf), "%.2f %s", portfolio_.balance, portfolio_.currency.c_str());
- } else if (has_credentials_ && live_equity_ > 0.0) {
- std::snprintf(bal_buf, sizeof(bal_buf), "%.2f USDT", live_equity_);
- } else {
- std::snprintf(bal_buf, sizeof(bal_buf), "-- (Live)");
- }
- ImGui::TextColored(MARKET_GREEN, "%s", bal_buf);
- }
-
- ImGui::EndChild();
- ImGui::PopStyleColor();
-}
-
-// ============================================================================
-// Ticker Bar — selected symbol price info
-// ============================================================================
-void CryptoTradingScreen::render_ticker_bar(float w, float h) {
- ImGui::PushStyleColor(ImGuiCol_ChildBg, BG_PANEL);
- ImGui::BeginChild("##crypto_ticker", ImVec2(w, h), true);
-
- // Symbol
- ImGui::SetWindowFontScale(1.2f);
- ImGui::TextColored(TEXT_PRIMARY, "%s", selected_symbol_.c_str());
- ImGui::SetWindowFontScale(1.0f);
-
- ImGui::SameLine(0, 16);
-
- double price = current_ticker_.last;
-
- if (price <= 0 && ticker_loading_) {
- theme::LoadingSpinner("Loading...");
- ImGui::EndChild();
- ImGui::PopStyleColor();
- return;
- }
-
- if (price <= 0) {
- ImGui::TextColored(TEXT_DIM, "Waiting for data...");
- ImGui::EndChild();
- ImGui::PopStyleColor();
- return;
- }
-
- // Price
- char buf[64];
- bool positive = current_ticker_.change >= 0;
- ImVec4 chg_col = positive ? MARKET_GREEN : MARKET_RED;
-
- if (price > 1.0)
- std::snprintf(buf, sizeof(buf), "%.2f", price);
- else
- std::snprintf(buf, sizeof(buf), "%.6f", price);
-
- ImGui::SetWindowFontScale(1.1f);
- ImGui::TextColored(chg_col, "%s", buf);
- ImGui::SetWindowFontScale(1.0f);
-
- ImGui::SameLine(0, 16);
-
- // Change
- std::snprintf(buf, sizeof(buf), "%s%.2f (%s%.2f%%)",
- positive ? "+" : "", current_ticker_.change,
- positive ? "+" : "", current_ticker_.percentage);
- ImGui::TextColored(chg_col, "%s", buf);
-
- ImGui::SameLine(0, 24);
- ImGui::TextColored(BORDER_BRIGHT, "|");
-
- // High / Low
- ImGui::SameLine(0, 12);
- ImGui::TextColored(TEXT_DIM, "H:");
- ImGui::SameLine(0, 4);
- std::snprintf(buf, sizeof(buf), "%.2f", current_ticker_.high);
- ImGui::TextColored(TEXT_SECONDARY, "%s", buf);
-
- ImGui::SameLine(0, 8);
- ImGui::TextColored(TEXT_DIM, "L:");
- ImGui::SameLine(0, 4);
- std::snprintf(buf, sizeof(buf), "%.2f", current_ticker_.low);
- ImGui::TextColored(TEXT_SECONDARY, "%s", buf);
-
- ImGui::SameLine(0, 12);
- ImGui::TextColored(BORDER_BRIGHT, "|");
-
- // Volume
- ImGui::SameLine(0, 12);
- ImGui::TextColored(TEXT_DIM, "Vol:");
- ImGui::SameLine(0, 4);
- double vol = current_ticker_.base_volume;
- if (vol >= 1e9)
- std::snprintf(buf, sizeof(buf), "%.2fB", vol / 1e9);
- else if (vol >= 1e6)
- std::snprintf(buf, sizeof(buf), "%.2fM", vol / 1e6);
- else if (vol >= 1e3)
- std::snprintf(buf, sizeof(buf), "%.2fK", vol / 1e3);
- else
- std::snprintf(buf, sizeof(buf), "%.2f", vol);
- ImGui::TextColored(TEXT_SECONDARY, "%s", buf);
-
- ImGui::SameLine(0, 12);
- ImGui::TextColored(BORDER_BRIGHT, "|");
-
- // Bid / Ask
- ImGui::SameLine(0, 12);
- ImGui::TextColored(TEXT_DIM, "Bid:");
- ImGui::SameLine(0, 4);
- std::snprintf(buf, sizeof(buf), "%.2f", current_ticker_.bid);
- ImGui::TextColored(MARKET_GREEN, "%s", buf);
-
- ImGui::SameLine(0, 8);
- ImGui::TextColored(TEXT_DIM, "Ask:");
- ImGui::SameLine(0, 4);
- std::snprintf(buf, sizeof(buf), "%.2f", current_ticker_.ask);
- ImGui::TextColored(MARKET_RED, "%s", buf);
-
- // Loading indicator
- if (ticker_fetching_) {
- ImGui::SameLine(0, 8);
- ImGui::TextColored(WARNING, "[*]");
- }
-
- ImGui::EndChild();
- ImGui::PopStyleColor();
-}
-
-// ============================================================================
-// Watchlist — left panel
-// ============================================================================
-void CryptoTradingScreen::render_watchlist(float w, float h) {
- ImGui::PushStyleColor(ImGuiCol_ChildBg, BG_PANEL);
- ImGui::BeginChild("##crypto_watchlist", ImVec2(w, h), true);
-
- // Header
- ImGui::TextColored(ACCENT, "WATCHLIST");
- ImGui::SameLine();
-
- int loaded = 0;
- {
- std::lock_guard<std::mutex> lock(data_mutex_);
- for (auto& w : watchlist_) if (w.has_data) loaded++;
- }
- ImGui::TextColored(TEXT_DIM, "(%d/%d)", loaded, (int)watchlist_.size());
-
- if (wl_fetching_) {
- ImGui::SameLine();
- ImGui::TextColored(WARNING, "[*]");
- }
-
- // Search / Filter field
- ImGui::PushItemWidth(-1);
- ImGui::PushStyleColor(ImGuiCol_FrameBg, BG_INPUT);
- bool search_changed = ImGui::InputTextWithHint("##wl_filter", "Search symbol...",
- watchlist_filter_, sizeof(watchlist_filter_));
- ImGui::PopStyleColor();
- ImGui::PopItemWidth();
-
- std::string filter_str(watchlist_filter_);
- for (auto& c : filter_str) c = (char)std::toupper((unsigned char)c);
-
- // Fetch exchange markets for search (lazy, cached per exchange)
- if (search_changed && filter_str.length() >= 2 && !search_fetching_) {
- // Load markets if not cached for this exchange
- if (search_cache_exchange_ != exchange_id_ || !search_markets_loaded_) {
- search_fetching_ = true;
- std::string ex_id = exchange_id_;
- launch_async(std::thread([this, ex_id]() {
- try {
- auto markets = trading::ExchangeService::instance().fetch_markets("spot");
- LOG_INFO(TAG, "Loaded %d markets for search from %s",
- (int)markets.size(), ex_id.c_str());
- std::lock_guard<std::mutex> lock(data_mutex_);
- all_markets_ = std::move(markets);
- search_cache_exchange_ = ex_id;
- search_markets_loaded_ = true;
- } catch (const std::exception& e) {
- LOG_ERROR(TAG, "Failed to load markets for search: %s", e.what());
- }
- search_fetching_ = false;
- }));
- }
- }
-
- // Build search results from cached markets
- bool has_search = filter_str.length() >= 2 && search_markets_loaded_;
- std::vector<trading::MarketInfo> filtered_markets;
- if (has_search) {
- std::lock_guard<std::mutex> lock(data_mutex_);
- int count = 0;
- for (const auto& m : all_markets_) {
- if (!m.active) continue;
- std::string sym_upper = m.symbol;
- for (auto& c : sym_upper) c = (char)std::toupper((unsigned char)c);
- if (sym_upper.find(filter_str) != std::string::npos) {
- // Skip if already in watchlist
- bool in_wl = false;
- for (const auto& w : watchlist_) {
- if (w.symbol == m.symbol) { in_wl = true; break; }
- }
- if (!in_wl) {
- filtered_markets.push_back(m);
- if (++count >= 20) break; // limit results
- }
- }
- }
- }
-
- ImGui::Separator();
-
- // Scrollable list
- ImGui::BeginChild("##wl_scroll", ImVec2(0, 0), false);
-
- char buf[64];
- std::lock_guard<std::mutex> lock(data_mutex_);
-
- // --- Watchlist entries ---
- for (int i = 0; i < (int)watchlist_.size(); i++) {
- auto& entry = watchlist_[i];
-
- // Filter check
- if (!filter_str.empty()) {
- std::string sym_upper = entry.symbol;
- for (auto& c : sym_upper) c = (char)std::toupper((unsigned char)c);
- if (sym_upper.find(filter_str) == std::string::npos) continue;
- }
-
- bool is_selected = (entry.symbol == selected_symbol_);
- ImGui::PushID(i);
-
- ImGui::PushStyleColor(ImGuiCol_Header, BG_WIDGET);
- ImGui::PushStyleColor(ImGuiCol_HeaderHovered, BG_HOVER);
-
- if (ImGui::Selectable("##wl_sel", is_selected, ImGuiSelectableFlags_SpanAllColumns, ImVec2(0, 22))) {
- watchlist_selected_ = i;
- switch_symbol(entry.symbol);
- }
-
- ImGui::PopStyleColor(2);
-
- // Draw content over the selectable
- ImGui::SameLine(4);
-
- // Symbol name (truncate base only)
- std::string base = entry.symbol;
- auto slash = base.find('/');
- if (slash != std::string::npos) base = base.substr(0, slash);
- ImGui::TextColored(TEXT_PRIMARY, "%s", base.c_str());
-
- if (entry.has_data) {
- // Price on right
- if (entry.price > 1.0)
- std::snprintf(buf, sizeof(buf), "%.2f", entry.price);
- else if (entry.price > 0.01)
- std::snprintf(buf, sizeof(buf), "%.4f", entry.price);
- else
- std::snprintf(buf, sizeof(buf), "%.6f", entry.price);
-
- ImVec4 col = entry.change_pct >= 0 ? MARKET_GREEN : MARKET_RED;
-
- // Change % next to symbol
- ImGui::SameLine(0, 4);
- char pct_buf[16];
- std::snprintf(pct_buf, sizeof(pct_buf), "%.1f%%", entry.change_pct);
- ImGui::TextColored(col, "%s", pct_buf);
-
- // Price on far right
- float price_w = ImGui::CalcTextSize(buf).x;
- float avail = ImGui::GetContentRegionAvail().x;
- if (avail > price_w + 4) {
- ImGui::SameLine(w - price_w - 16);
- ImGui::TextColored(col, "%s", buf);
- }
- } else {
- float avail = ImGui::GetContentRegionAvail().x;
- if (avail > 20) {
- ImGui::SameLine(w - 30);
- ImGui::TextColored(TEXT_DIM, "...");
- }
- }
-
- ImGui::PopID();
- }
-
- // --- Exchange search results (symbols not in watchlist) ---
- if (!filtered_markets.empty()) {
- ImGui::Separator();
- ImGui::TextColored(TEXT_DIM, "Exchange results:");
- ImGui::Spacing();
-
- for (int i = 0; i < (int)filtered_markets.size(); i++) {
- const auto& m = filtered_markets[i];
- ImGui::PushID(10000 + i);
-
- ImGui::PushStyleColor(ImGuiCol_Header, ImVec4(0.1f, 0.15f, 0.2f, 1.0f));
- ImGui::PushStyleColor(ImGuiCol_HeaderHovered, BG_HOVER);
-
- if (ImGui::Selectable("##search_sel", false, ImGuiSelectableFlags_SpanAllColumns, ImVec2(0, 22))) {
- // Add to watchlist
- WatchlistEntry new_entry;
- new_entry.symbol = m.symbol;
- watchlist_.push_back(new_entry);
- watchlist_selected_ = (int)watchlist_.size() - 1;
- LOG_INFO(TAG, "Added %s to watchlist from search", m.symbol.c_str());
-
- // Clear search field
- watchlist_filter_[0] = '\0';
-
- // Defer symbol switch — we hold data_mutex_ here,
- // switch_symbol() will run in the render loop next frame
- pending_symbol_switch_ = m.symbol;
- }
-
- ImGui::PopStyleColor(2);
-
- ImGui::SameLine(4);
-
- // Show base/quote
- std::string base = m.base;
- ImGui::TextColored(ACCENT, "%s", base.c_str());
- ImGui::SameLine(0, 2);
- ImGui::TextColored(TEXT_DIM, "/%s", m.quote.c_str());
-
- // Type on right
- float type_w = ImGui::CalcTextSize(m.type.c_str()).x;
- float avail = ImGui::GetContentRegionAvail().x;
- if (avail > type_w + 4) {
- ImGui::SameLine(w - type_w - 16);
- ImGui::TextColored(TEXT_DIM, "%s", m.type.c_str());
- }
-
- ImGui::PopID();
- }
- } else if (filter_str.length() >= 2 && search_fetching_) {
- ImGui::Separator();
- ImGui::TextColored(TEXT_DIM, "Searching...");
- } else if (filter_str.length() >= 2 && search_markets_loaded_ && filtered_markets.empty()) {
- // Check if all matches are in watchlist already
- bool any_watchlist_match = false;
- for (const auto& w : watchlist_) {
- std::string sym_upper = w.symbol;
- for (auto& c : sym_upper) c = (char)std::toupper((unsigned char)c);
- if (sym_upper.find(filter_str) != std::string::npos) {
- any_watchlist_match = true;
- break;
- }
- }
- if (!any_watchlist_match) {
- ImGui::Separator();
- ImGui::TextColored(TEXT_DIM, "No results");
- }
- }
-
- ImGui::EndChild();
- ImGui::EndChild();
- ImGui::PopStyleColor();
-}
-
-// ============================================================================
-// Chart Area (placeholder)
-// ============================================================================
-void CryptoTradingScreen::render_chart_area(float w, float h) {
- ImGui::PushStyleColor(ImGuiCol_ChildBg, BG_DARK);
- ImGui::BeginChild("##crypto_chart", ImVec2(w, h), true);
-
- // Header: CHART label + symbol + WS indicator
- ImGui::TextColored(ACCENT, "CHART");
- ImGui::SameLine(0, 8);
- ImGui::TextColored(TEXT_DIM, "%s", selected_symbol_.c_str());
-
- ImGui::SameLine(0, 8);
- bool ws_ok = trading::ExchangeService::instance().is_ws_connected();
- ImGui::TextColored(ws_ok ? MARKET_GREEN : WARNING, ws_ok ? "[WS LIVE]" : "[REST]");
-
- ImGui::SameLine(0, 16);
-
- // Timeframe buttons
- static const char* timeframes[] = {"1m", "5m", "15m", "1h", "4h", "1d"};
- for (int i = 0; i < 6; i++) {
- if (i > 0) ImGui::SameLine(0, 2);
- bool active = (i == selected_timeframe_);
- ImGui::PushStyleColor(ImGuiCol_Button, active ? ACCENT_DIM : BG_WIDGET);
- ImGui::PushStyleColor(ImGuiCol_Text, active ? TEXT_PRIMARY : TEXT_DIM);
- if (ImGui::SmallButton(timeframes[i])) {
- if (selected_timeframe_ != i) {
- selected_timeframe_ = i;
- candle_timeframe_ = timeframes[i];
- // Re-fetch candles for new timeframe
- candles_loading_ = true;
- candles_fetching_ = true;
- const std::string sym = selected_symbol_;
- std::string tf = candle_timeframe_;
- launch_async(std::thread([this, sym, tf]() {
- try {
- auto ohlcv = trading::ExchangeService::instance().fetch_ohlcv(sym, tf, OHLCV_FETCH_COUNT);
- LOG_INFO(TAG, "<<< OHLCV %s received: %d candles", tf.c_str(), (int)ohlcv.size());
- {
- std::lock_guard<std::mutex> lock(data_mutex_);
- candles_ = std::move(ohlcv);
- }
- candles_loading_ = false;
- candles_fetching_ = false;
- success_count_++;
- } catch (const std::exception& e) {
- LOG_ERROR(TAG, "<<< OHLCV fetch failed: %s", e.what());
- candles_loading_ = false;
- candles_fetching_ = false;
- error_count_++;
- }
- }));
- }
- }
- ImGui::PopStyleColor(2);
- }
-
- // Candle count
- {
- std::lock_guard<std::mutex> lock(data_mutex_);
- ImGui::SameLine(0, 12);
- ImGui::TextColored(TEXT_DIM, "[%d candles]", (int)candles_.size());
- }
-
- ImGui::Separator();
-
- float chart_w = ImGui::GetContentRegionAvail().x;
- float chart_h = ImGui::GetContentRegionAvail().y;
-
- std::lock_guard<std::mutex> lock(data_mutex_);
- if (chart_h > 60 && !candles_.empty()) {
- ImVec2 p = ImGui::GetCursorScreenPos();
- render_candlestick_chart(p, chart_w, chart_h);
- ImGui::Dummy(ImVec2(chart_w, chart_h));
- } else if (candles_loading_) {
- ImGui::Dummy(ImVec2(0, 20));
- theme::LoadingSpinner("Loading OHLCV data...");
- } else if (chart_h > 60 && current_ticker_.last > 0) {
- // No candle data yet but have ticker — show price placeholder
- ImVec2 p = ImGui::GetCursorScreenPos();
- ImDrawList* dl = ImGui::GetWindowDrawList();
- char price_text[64];
- std::snprintf(price_text, sizeof(price_text), "%.2f", current_ticker_.last);
- ImVec2 text_size = ImGui::CalcTextSize(price_text);
- ImVec2 text_pos(p.x + (chart_w - text_size.x) / 2, p.y + (chart_h - text_size.y) / 2);
- dl->AddText(text_pos, ImGui::ColorConvertFloat4ToU32(TEXT_PRIMARY), price_text);
- ImGui::Dummy(ImVec2(chart_w, chart_h));
- } else {
- ImGui::Dummy(ImVec2(0, 20));
- theme::LoadingSpinner("Loading chart data...");
- }
-
- ImGui::EndChild();
- ImGui::PopStyleColor();
-}
-
-// ============================================================================
-// Candlestick Chart — renders OHLCV candles via ImDrawList
-// ============================================================================
-void CryptoTradingScreen::render_candlestick_chart(ImVec2 origin, float chart_w, float chart_h) {
- ImDrawList* dl = ImGui::GetWindowDrawList();
-
- // Colors
- ImU32 grid_col = ImGui::ColorConvertFloat4ToU32(ImVec4(0.15f, 0.15f, 0.17f, 1.0f));
- ImU32 green = ImGui::ColorConvertFloat4ToU32(ImVec4(0.0f, 0.8f, 0.4f, 1.0f));
- ImU32 red = ImGui::ColorConvertFloat4ToU32(ImVec4(0.9f, 0.2f, 0.2f, 1.0f));
- ImU32 green_dim = ImGui::ColorConvertFloat4ToU32(ImVec4(0.0f, 0.6f, 0.3f, 0.6f));
- ImU32 red_dim = ImGui::ColorConvertFloat4ToU32(ImVec4(0.7f, 0.15f, 0.15f, 0.6f));
- ImU32 text_col = ImGui::ColorConvertFloat4ToU32(TEXT_DIM);
- ImU32 crosshair_col = ImGui::ColorConvertFloat4ToU32(ImVec4(0.4f, 0.4f, 0.5f, 0.5f));
-
- // Reserve right margin for price axis
- float price_axis_w = 70.0f;
- float plot_w = chart_w - price_axis_w;
- if (plot_w < 50) plot_w = chart_w;
-
- // Determine how many candles fit
- float candle_width = 6.0f;
- float candle_gap = 2.0f;
- float candle_step = candle_width + candle_gap;
- int max_visible = (int)(plot_w / candle_step);
- if (max_visible < 5) max_visible = 5;
-
- // Get visible range (show most recent candles)
- int total = (int)candles_.size();
- int start_idx = total > max_visible ? total - max_visible : 0;
- int visible_count = total - start_idx;
- if (visible_count <= 0) return;
-
- // Find price range
- double price_high = -1e18;
- double price_low = 1e18;
- for (int i = start_idx; i < total; i++) {
- const auto& c = candles_[i];
- if (c.high > price_high) price_high = c.high;
- if (c.low < price_low) price_low = c.low;
- }
-
- // Add 2% padding
- double range = price_high - price_low;
- if (range < 0.01) range = 1.0;
- double padding = range * 0.02;
- price_high += padding;
- price_low -= padding;
- range = price_high - price_low;
-
- // Helper: price to Y coordinate
- auto price_to_y = [&](double price) -> float {
- return origin.y + chart_h * (1.0f - (float)((price - price_low) / range));
- };
-
- // Draw grid lines (horizontal)
- int grid_lines = 5;
- for (int i = 0; i <= grid_lines; i++) {
- float y = origin.y + chart_h * i / (float)grid_lines;
- dl->AddLine(ImVec2(origin.x, y), ImVec2(origin.x + plot_w, y), grid_col);
-
- // Price labels on right axis
- if (plot_w < chart_w) {
- double price = price_high - (range * i / grid_lines);
- char label[32];
- if (price >= 1000)
- std::snprintf(label, sizeof(label), "%.1f", price);
- else if (price >= 1)
- std::snprintf(label, sizeof(label), "%.2f", price);
- else
- std::snprintf(label, sizeof(label), "%.4f", price);
- dl->AddText(ImVec2(origin.x + plot_w + 4, y - 6), text_col, label);
- }
- }
-
- // Draw vertical grid lines
- int v_grid = 6;
- for (int i = 1; i < v_grid; i++) {
- float x = origin.x + plot_w * i / (float)v_grid;
- dl->AddLine(ImVec2(x, origin.y), ImVec2(x, origin.y + chart_h), grid_col);
- }
-
- // Draw candles
- float x_start = origin.x + plot_w - visible_count * candle_step;
-
- for (int i = 0; i < visible_count; i++) {
- const auto& c = candles_[start_idx + i];
- float cx = x_start + i * candle_step + candle_width * 0.5f;
-
- bool bullish = c.close >= c.open;
- ImU32 body_col = bullish ? green : red;
- ImU32 wick_col = bullish ? green_dim : red_dim;
-
- // Wick (high-low line)
- float wick_x = cx;
- float wick_top = price_to_y(c.high);
- float wick_bot = price_to_y(c.low);
- dl->AddLine(ImVec2(wick_x, wick_top), ImVec2(wick_x, wick_bot), wick_col, 1.0f);
-
- // Body (open-close rect)
- float body_top = price_to_y(bullish ? c.close : c.open);
- float body_bot = price_to_y(bullish ? c.open : c.close);
- float body_min_h = 1.0f;
- if (body_bot - body_top < body_min_h) {
- body_bot = body_top + body_min_h;
- }
-
- float body_left = cx - candle_width * 0.5f;
- float body_right = cx + candle_width * 0.5f;
- dl->AddRectFilled(ImVec2(body_left, body_top), ImVec2(body_right, body_bot), body_col);
- }
-
- // Volume bars at bottom (subtle, 15% of chart height)
- double vol_max = 0;
- for (int i = start_idx; i < total; i++) {
- if (candles_[i].volume > vol_max) vol_max = candles_[i].volume;
- }
-
- if (vol_max > 0) {
- float vol_zone = chart_h * 0.15f;
- float vol_base = origin.y + chart_h;
-
- for (int i = 0; i < visible_count; i++) {
- const auto& c = candles_[start_idx + i];
- float cx = x_start + i * candle_step + candle_width * 0.5f;
- float vol_h = (float)(c.volume / vol_max) * vol_zone;
- bool bullish = c.close >= c.open;
-
- ImU32 vol_col = bullish
- ? ImGui::ColorConvertFloat4ToU32(ImVec4(0.0f, 0.5f, 0.25f, 0.3f))
- : ImGui::ColorConvertFloat4ToU32(ImVec4(0.5f, 0.1f, 0.1f, 0.3f));
-
- float body_left = cx - candle_width * 0.5f;
- float body_right = cx + candle_width * 0.5f;
- dl->AddRectFilled(ImVec2(body_left, vol_base - vol_h),
- ImVec2(body_right, vol_base), vol_col);
- }
- }
-
- // Current price line
- if (current_ticker_.last > 0 && current_ticker_.last >= price_low && current_ticker_.last <= price_high) {
- float y = price_to_y(current_ticker_.last);
- ImU32 price_line_col = ImGui::ColorConvertFloat4ToU32(
- current_ticker_.change >= 0 ? MARKET_GREEN : MARKET_RED);
-
- // Dashed line effect
- float dash_len = 6.0f;
- for (float x = origin.x; x < origin.x + plot_w; x += dash_len * 2) {
- float end = x + dash_len;
- if (end > origin.x + plot_w) end = origin.x + plot_w;
- dl->AddLine(ImVec2(x, y), ImVec2(end, y), price_line_col, 1.0f);
- }
-
- // Price tag on right
- if (plot_w < chart_w) {
- char tag[32];
- if (current_ticker_.last >= 1000)
- std::snprintf(tag, sizeof(tag), "%.1f", current_ticker_.last);
- else
- std::snprintf(tag, sizeof(tag), "%.2f", current_ticker_.last);
-
- ImVec2 tag_size = ImGui::CalcTextSize(tag);
- float tag_x = origin.x + plot_w + 2;
- float tag_y = y - tag_size.y * 0.5f;
- dl->AddRectFilled(ImVec2(tag_x, tag_y - 1),
- ImVec2(tag_x + tag_size.x + 6, tag_y + tag_size.y + 1),
- price_line_col);
- dl->AddText(ImVec2(tag_x + 3, tag_y),
- ImGui::ColorConvertFloat4ToU32(ImVec4(1, 1, 1, 1)), tag);
- }
- }
-
- // Crosshair on hover
- ImVec2 mouse = ImGui::GetMousePos();
- if (mouse.x >= origin.x && mouse.x <= origin.x + plot_w &&
- mouse.y >= origin.y && mouse.y <= origin.y + chart_h) {
-
- dl->AddLine(ImVec2(origin.x, mouse.y), ImVec2(origin.x + plot_w, mouse.y), crosshair_col);
- dl->AddLine(ImVec2(mouse.x, origin.y), ImVec2(mouse.x, origin.y + chart_h), crosshair_col);
-
- // Price at cursor Y
- double hover_price = price_high - range * ((mouse.y - origin.y) / chart_h);
- char hover_label[32];
- std::snprintf(hover_label, sizeof(hover_label), "%.2f", hover_price);
- dl->AddText(ImVec2(origin.x + plot_w + 4, mouse.y - 6),
- ImGui::ColorConvertFloat4ToU32(TEXT_PRIMARY), hover_label);
- }
-}
-
-// ============================================================================
-// Bottom Panel — Positions / Orders / History / Stats
-// ============================================================================
-void CryptoTradingScreen::render_bottom_panel(float w, float h) {
- ImGui::PushStyleColor(ImGuiCol_ChildBg, BG_PANEL);
- ImGui::BeginChild("##crypto_bottom", ImVec2(w, h), true);
-
- struct TabDef { const char* label; BottomTab tab; };
- static const TabDef tabs[] = {
- {"Positions", BottomTab::Positions},
- {"Orders", BottomTab::Orders},
- {"History", BottomTab::History},
- {"Trades", BottomTab::Trades},
- {"Market Info", BottomTab::MarketInfo},
- {"Stats", BottomTab::Stats},
- };
-
- for (int i = 0; i < 6; i++) {
- if (i > 0) ImGui::SameLine(0, 2);
- bool active = (bottom_tab_ == tabs[i].tab);
- ImGui::PushStyleColor(ImGuiCol_Button, active ? ACCENT_BG : ImVec4(0, 0, 0, 0));
- ImGui::PushStyleColor(ImGuiCol_Text, active ? ACCENT : TEXT_DIM);
- if (ImGui::SmallButton(tabs[i].label)) {
- bottom_tab_ = tabs[i].tab;
- }
- ImGui::PopStyleColor(2);
- }
-
- // Count badges
- {
- std::lock_guard<std::mutex> lock(data_mutex_);
- ImGui::SameLine(0, 8);
-
- if (trading_mode_ == TradingMode::Live && has_credentials_) {
- if (!live_positions_.empty()) {
- char badge[16];
- std::snprintf(badge, sizeof(badge), "[%d pos]", (int)live_positions_.size());
- ImGui::TextColored(ACCENT, "%s", badge);
- ImGui::SameLine(0, 4);
- }
- int open_count = 0;
- for (auto& o : live_orders_) if (o.status == "open") open_count++;
- if (open_count > 0) {
- char badge[16];
- std::snprintf(badge, sizeof(badge), "[%d ord]", open_count);
- ImGui::TextColored(WARNING, "%s", badge);
- }
- } else if (trading_mode_ == TradingMode::Paper) {
- if (!positions_.empty()) {
- char badge[16];
- std::snprintf(badge, sizeof(badge), "[%d pos]", (int)positions_.size());
- ImGui::TextColored(ACCENT, "%s", badge);
- ImGui::SameLine(0, 4);
- }
- int pending = 0;
- for (auto& o : orders_) if (o.status == "pending") pending++;
- if (pending > 0) {
- char badge[16];
- std::snprintf(badge, sizeof(badge), "[%d ord]", pending);
- ImGui::TextColored(WARNING, "%s", badge);
- }
- }
- }
-
- ImGui::Separator();
-
- ImGui::BeginChild("##bottom_content", ImVec2(0, 0), false);
- switch (bottom_tab_) {
- case BottomTab::Positions: render_positions_tab(); break;
- case BottomTab::Orders: render_orders_tab(); break;
- case BottomTab::History: render_history_tab(); break;
- case BottomTab::Trades: render_trades_tab(); break;
- case BottomTab::MarketInfo: render_market_info_tab(); break;
- case BottomTab::Stats: render_stats_tab(); break;
- }
- ImGui::EndChild();
-
- ImGui::EndChild();
- ImGui::PopStyleColor();
-}
-
-void CryptoTradingScreen::render_positions_tab() {
- bool is_live = (trading_mode_ == TradingMode::Live);
-
- // Mode label
- ImGui::TextColored(is_live ? ImVec4(0.9f, 0.2f, 0.2f, 1.0f) : ImVec4(0.0f, 0.7f, 0.3f, 1.0f),
- is_live ? "[LIVE POSITIONS]" : "[PAPER POSITIONS]");
-
- if (is_live) {
- if (!has_credentials_) {
- ImGui::TextColored(TEXT_DIM, "API credentials required for live trading.");
- ImGui::SameLine(0, 8);
- ImGui::PushStyleColor(ImGuiCol_Button, ACCENT_BG);
- if (ImGui::SmallButton("Configure API Key")) {
- show_credentials_popup_ = true;
- load_exchange_credentials();
- }
- ImGui::PopStyleColor();
- return;
- }
-
- std::lock_guard<std::mutex> lock(data_mutex_);
-
- if (live_positions_fetching_) {
- theme::LoadingSpinner("Fetching positions...");
- return;
- }
-
- if (live_positions_.empty()) {
- ImGui::TextColored(TEXT_DIM, "No open positions on %s", exchange_id_.c_str());
- return;
- }
-
- ImGuiTableFlags flags = ImGuiTableFlags_RowBg | ImGuiTableFlags_BordersInnerH |
- ImGuiTableFlags_SizingStretchProp | ImGuiTableFlags_ScrollY;
-
- if (ImGui::BeginTable("##live_positions", 7, flags)) {
- ImGui::TableSetupColumn("Symbol", ImGuiTableColumnFlags_WidthStretch, 1.2f);
- ImGui::TableSetupColumn("Side", ImGuiTableColumnFlags_WidthStretch, 0.6f);
- ImGui::TableSetupColumn("Qty", ImGuiTableColumnFlags_WidthStretch, 0.8f);
- ImGui::TableSetupColumn("Entry", ImGuiTableColumnFlags_WidthStretch, 1.0f);
- ImGui::TableSetupColumn("Current", ImGuiTableColumnFlags_WidthStretch, 1.0f);
- ImGui::TableSetupColumn("PnL", ImGuiTableColumnFlags_WidthStretch, 1.0f);
- ImGui::TableSetupColumn("Lev", ImGuiTableColumnFlags_WidthStretch, 0.5f);
- ImGui::TableSetupScrollFreeze(0, 1);
- ImGui::PushStyleColor(ImGuiCol_TableHeaderBg, BG_DARKEST);
- ImGui::TableHeadersRow();
- ImGui::PopStyleColor();
-
- char buf[32];
- for (const auto& pos : live_positions_) {
- ImGui::TableNextRow();
-
- ImGui::TableSetColumnIndex(0);
- ImGui::TextColored(TEXT_PRIMARY, "%s", pos.symbol.c_str());
-
- ImGui::TableSetColumnIndex(1);
- ImVec4 side_col = (pos.side == "long") ? MARKET_GREEN : MARKET_RED;
- ImGui::TextColored(side_col, "%s", pos.side == "long" ? "LONG" : "SHORT");
-
- ImGui::TableSetColumnIndex(2);
- std::snprintf(buf, sizeof(buf), "%.4f", pos.quantity);
- ImGui::TextColored(TEXT_SECONDARY, "%s", buf);
-
- ImGui::TableSetColumnIndex(3);
- std::snprintf(buf, sizeof(buf), "%.2f", pos.entry_price);
- ImGui::TextColored(TEXT_SECONDARY, "%s", buf);
-
- ImGui::TableSetColumnIndex(4);
- std::snprintf(buf, sizeof(buf), "%.2f", pos.current_price);
- ImGui::TextColored(TEXT_PRIMARY, "%s", buf);
-
- ImGui::TableSetColumnIndex(5);
- ImVec4 pnl_col = pos.unrealized_pnl >= 0 ? MARKET_GREEN : MARKET_RED;
- std::snprintf(buf, sizeof(buf), "%s%.2f",
- pos.unrealized_pnl >= 0 ? "+" : "", pos.unrealized_pnl);
- ImGui::TextColored(pnl_col, "%s", buf);
-
- ImGui::TableSetColumnIndex(6);
- std::snprintf(buf, sizeof(buf), "%.0fx", pos.leverage);
- ImGui::TextColored(TEXT_DIM, "%s", buf);
- }
-
- ImGui::EndTable();
- }
- return;
- }
-
- // Paper mode — show simulated positions
- std::lock_guard<std::mutex> lock(data_mutex_);
-
- if (!portfolio_loaded_) {
- theme::LoadingSpinner("Loading portfolio...");
- return;
- }
-
- if (positions_.empty()) {
- ImGui::TextColored(TEXT_DIM, "No open positions");
- return;
- }
-
- ImGuiTableFlags flags = ImGuiTableFlags_RowBg | ImGuiTableFlags_BordersInnerH |
- ImGuiTableFlags_SizingStretchProp | ImGuiTableFlags_ScrollY;
-
- if (ImGui::BeginTable("##positions", 7, flags)) {
- ImGui::TableSetupColumn("Symbol", ImGuiTableColumnFlags_WidthStretch, 1.2f);
- ImGui::TableSetupColumn("Side", ImGuiTableColumnFlags_WidthStretch, 0.6f);
- ImGui::TableSetupColumn("Qty", ImGuiTableColumnFlags_WidthStretch, 0.8f);
- ImGui::TableSetupColumn("Entry", ImGuiTableColumnFlags_WidthStretch, 1.0f);
- ImGui::TableSetupColumn("Current", ImGuiTableColumnFlags_WidthStretch, 1.0f);
- ImGui::TableSetupColumn("PnL", ImGuiTableColumnFlags_WidthStretch, 1.0f);
- ImGui::TableSetupColumn("Lev", ImGuiTableColumnFlags_WidthStretch, 0.5f);
- ImGui::TableSetupScrollFreeze(0, 1);
- ImGui::PushStyleColor(ImGuiCol_TableHeaderBg, BG_DARKEST);
- ImGui::TableHeadersRow();
- ImGui::PopStyleColor();
-
- char buf[32];
- for (auto& pos : positions_) {
- ImGui::TableNextRow();
-
- ImGui::TableSetColumnIndex(0);
- ImGui::TextColored(TEXT_PRIMARY, "%s", pos.symbol.c_str());
-
- ImGui::TableSetColumnIndex(1);
- ImVec4 side_col = (pos.side == "long") ? MARKET_GREEN : MARKET_RED;
- ImGui::TextColored(side_col, "%s", pos.side == "long" ? "LONG" : "SHORT");
-
- ImGui::TableSetColumnIndex(2);
- std::snprintf(buf, sizeof(buf), "%.4f", pos.quantity);
- ImGui::TextColored(TEXT_SECONDARY, "%s", buf);
-
- ImGui::TableSetColumnIndex(3);
- std::snprintf(buf, sizeof(buf), "%.2f", pos.entry_price);
- ImGui::TextColored(TEXT_SECONDARY, "%s", buf);
-
- ImGui::TableSetColumnIndex(4);
- std::snprintf(buf, sizeof(buf), "%.2f", pos.current_price);
- ImGui::TextColored(TEXT_PRIMARY, "%s", buf);
-
- ImGui::TableSetColumnIndex(5);
- ImVec4 pnl_col = pos.unrealized_pnl >= 0 ? MARKET_GREEN : MARKET_RED;
- std::snprintf(buf, sizeof(buf), "%s%.2f",
- pos.unrealized_pnl >= 0 ? "+" : "", pos.unrealized_pnl);
- ImGui::TextColored(pnl_col, "%s", buf);
-
- ImGui::TableSetColumnIndex(6);
- std::snprintf(buf, sizeof(buf), "%.0fx", pos.leverage);
- ImGui::TextColored(TEXT_DIM, "%s", buf);
- }
-
- ImGui::EndTable();
- }
-}
-
-void CryptoTradingScreen::render_orders_tab() {
- bool is_live = (trading_mode_ == TradingMode::Live);
-
- ImGui::TextColored(is_live ? ImVec4(0.9f, 0.2f, 0.2f, 1.0f) : ImVec4(0.0f, 0.7f, 0.3f, 1.0f),
- is_live ? "[LIVE ORDERS]" : "[PAPER ORDERS]");
-
- if (is_live) {
- if (!has_credentials_) {
- ImGui::TextColored(TEXT_DIM, "API credentials required.");
- ImGui::SameLine(0, 8);
- ImGui::PushStyleColor(ImGuiCol_Button, ACCENT_BG);
- if (ImGui::SmallButton("Configure##orders")) {
- show_credentials_popup_ = true;
- load_exchange_credentials();
- }
- ImGui::PopStyleColor();
- return;
- }
-
- std::lock_guard<std::mutex> lock(data_mutex_);
-
- if (live_orders_fetching_) {
- theme::LoadingSpinner("Fetching orders...");
- return;
- }
-
- if (live_orders_.empty()) {
- ImGui::TextColored(TEXT_DIM, "No open orders on %s", exchange_id_.c_str());
- return;
- }
-
- ImGuiTableFlags flags = ImGuiTableFlags_RowBg | ImGuiTableFlags_BordersInnerH |
- ImGuiTableFlags_SizingStretchProp | ImGuiTableFlags_ScrollY;
-
- if (ImGui::BeginTable("##live_orders", 7, flags)) {
- ImGui::TableSetupColumn("Symbol", ImGuiTableColumnFlags_WidthStretch, 1.0f);
- ImGui::TableSetupColumn("Side", ImGuiTableColumnFlags_WidthStretch, 0.5f);
- ImGui::TableSetupColumn("Type", ImGuiTableColumnFlags_WidthStretch, 0.7f);
- ImGui::TableSetupColumn("Qty", ImGuiTableColumnFlags_WidthStretch, 0.8f);
- ImGui::TableSetupColumn("Price", ImGuiTableColumnFlags_WidthStretch, 0.8f);
- ImGui::TableSetupColumn("Status", ImGuiTableColumnFlags_WidthStretch, 0.7f);
- ImGui::TableSetupColumn("Action", ImGuiTableColumnFlags_WidthStretch, 0.6f);
- ImGui::TableSetupScrollFreeze(0, 1);
- ImGui::PushStyleColor(ImGuiCol_TableHeaderBg, BG_DARKEST);
- ImGui::TableHeadersRow();
- ImGui::PopStyleColor();
-
- char buf[32];
- for (auto& ord : live_orders_) {
- ImGui::TableNextRow();
- ImGui::PushID(ord.id.c_str());
-
- ImGui::TableSetColumnIndex(0);
- ImGui::TextColored(TEXT_PRIMARY, "%s", ord.symbol.c_str());
-
- ImGui::TableSetColumnIndex(1);
- ImVec4 side_col = (ord.side == "buy") ? MARKET_GREEN : MARKET_RED;
- ImGui::TextColored(side_col, "%s", ord.side == "buy" ? "BUY" : "SELL");
-
- ImGui::TableSetColumnIndex(2);
- ImGui::TextColored(TEXT_SECONDARY, "%s", ord.type.c_str());
-
- ImGui::TableSetColumnIndex(3);
- std::snprintf(buf, sizeof(buf), "%.4f", ord.quantity);
- ImGui::TextColored(TEXT_SECONDARY, "%s", buf);
-
- ImGui::TableSetColumnIndex(4);
- if (ord.price > 0.0) {
- std::snprintf(buf, sizeof(buf), "%.2f", ord.price);
- ImGui::TextColored(TEXT_PRIMARY, "%s", buf);
- } else {
- ImGui::TextColored(TEXT_DIM, "MKT");
- }
-
- ImGui::TableSetColumnIndex(5);
- ImVec4 status_col = TEXT_DIM;
- if (ord.status == "open") status_col = WARNING;
- else if (ord.status == "closed" || ord.status == "filled") status_col = MARKET_GREEN;
- else if (ord.status == "canceled" || ord.status == "cancelled") status_col = MARKET_RED;
- ImGui::TextColored(status_col, "%s", ord.status.c_str());
-
- ImGui::TableSetColumnIndex(6);
- if (ord.status == "open") {
- ImGui::PushStyleColor(ImGuiCol_Button, ImVec4(0.5f, 0.1f, 0.1f, 0.8f));
- ImGui::PushStyleColor(ImGuiCol_Text, MARKET_RED);
- if (ImGui::SmallButton("Cancel")) {
- cancel_order(ord.id);
- }
- ImGui::PopStyleColor(2);
- }
-
- ImGui::PopID();
- }
-
- ImGui::EndTable();
- }
- return;
- }
-
- std::lock_guard<std::mutex> lock(data_mutex_);
-
- if (!portfolio_loaded_) {
- theme::LoadingSpinner("Loading orders...");
- return;
- }
-
- if (orders_.empty()) {
- ImGui::TextColored(TEXT_DIM, "No orders");
- return;
- }
-
- ImGuiTableFlags flags = ImGuiTableFlags_RowBg | ImGuiTableFlags_BordersInnerH |
- ImGuiTableFlags_SizingStretchProp | ImGuiTableFlags_ScrollY;
-
- if (ImGui::BeginTable("##orders", 7, flags)) {
- ImGui::TableSetupColumn("Symbol", ImGuiTableColumnFlags_WidthStretch, 1.0f);
- ImGui::TableSetupColumn("Side", ImGuiTableColumnFlags_WidthStretch, 0.5f);
- ImGui::TableSetupColumn("Type", ImGuiTableColumnFlags_WidthStretch, 0.7f);
- ImGui::TableSetupColumn("Qty", ImGuiTableColumnFlags_WidthStretch, 0.8f);
- ImGui::TableSetupColumn("Price", ImGuiTableColumnFlags_WidthStretch, 0.8f);
- ImGui::TableSetupColumn("Status", ImGuiTableColumnFlags_WidthStretch, 0.7f);
- ImGui::TableSetupColumn("Action", ImGuiTableColumnFlags_WidthStretch, 0.6f);
- ImGui::TableSetupScrollFreeze(0, 1);
- ImGui::PushStyleColor(ImGuiCol_TableHeaderBg, BG_DARKEST);
- ImGui::TableHeadersRow();
- ImGui::PopStyleColor();
-
- char buf[32];
- for (auto& ord : orders_) {
- ImGui::TableNextRow();
- ImGui::PushID(ord.id.c_str());
-
- ImGui::TableSetColumnIndex(0);
- ImGui::TextColored(TEXT_PRIMARY, "%s", ord.symbol.c_str());
-
- ImGui::TableSetColumnIndex(1);
- ImVec4 side_col = (ord.side == "buy") ? MARKET_GREEN : MARKET_RED;
- ImGui::TextColored(side_col, "%s", ord.side == "buy" ? "BUY" : "SELL");
-
- ImGui::TableSetColumnIndex(2);
- ImGui::TextColored(TEXT_SECONDARY, "%s", ord.order_type.c_str());
-
- ImGui::TableSetColumnIndex(3);
- std::snprintf(buf, sizeof(buf), "%.4f", ord.quantity);
- ImGui::TextColored(TEXT_SECONDARY, "%s", buf);
-
- ImGui::TableSetColumnIndex(4);
- if (ord.price.has_value()) {
- std::snprintf(buf, sizeof(buf), "%.2f", *ord.price);
- ImGui::TextColored(TEXT_PRIMARY, "%s", buf);
- } else {
- ImGui::TextColored(TEXT_DIM, "MKT");
- }
-
- ImGui::TableSetColumnIndex(5);
- ImVec4 status_col = TEXT_DIM;
- if (ord.status == "pending") status_col = WARNING;
- else if (ord.status == "filled") status_col = MARKET_GREEN;
- else if (ord.status == "cancelled") status_col = MARKET_RED;
- ImGui::TextColored(status_col, "%s", ord.status.c_str());
-
- ImGui::TableSetColumnIndex(6);
- if (ord.status == "pending") {
- ImGui::PushStyleColor(ImGuiCol_Button, ImVec4(0.5f, 0.1f, 0.1f, 0.8f));
- ImGui::PushStyleColor(ImGuiCol_Text, MARKET_RED);
- if (ImGui::SmallButton("Cancel")) {
- cancel_order(ord.id);
- }
- ImGui::PopStyleColor(2);
- }
-
- ImGui::PopID();
- }
-
- ImGui::EndTable();
- }
-}
-
-void CryptoTradingScreen::render_history_tab() {
- bool is_live = (trading_mode_ == TradingMode::Live);
- ImGui::TextColored(is_live ? ImVec4(0.9f, 0.2f, 0.2f, 1.0f) : ImVec4(0.0f, 0.7f, 0.3f, 1.0f),
- is_live ? "[LIVE HISTORY]" : "[PAPER HISTORY]");
-
- if (is_live) {
- if (!has_credentials_) {
- ImGui::TextColored(TEXT_DIM, "API credentials required.");
- return;
- }
-
- std::lock_guard<std::mutex> lock(data_mutex_);
-
- if (live_trades_fetching_) {
- theme::LoadingSpinner("Fetching trade history...");
- return;
- }
-
- if (live_trades_.empty()) {
- ImGui::TextColored(TEXT_DIM, "No trade history on %s", exchange_id_.c_str());
- // Trigger initial fetch
- if (!live_data_loaded_) {
- live_data_loaded_ = true;
- async_fetch_live_trades();
- }
- return;
- }
-
- ImGuiTableFlags flags = ImGuiTableFlags_RowBg | ImGuiTableFlags_BordersInnerH |
- ImGuiTableFlags_SizingStretchProp | ImGuiTableFlags_ScrollY;
-
- if (ImGui::BeginTable("##live_trades_hist", 6, flags)) {
- ImGui::TableSetupColumn("Symbol", ImGuiTableColumnFlags_WidthStretch, 1.0f);
- ImGui::TableSetupColumn("Side", ImGuiTableColumnFlags_WidthStretch, 0.5f);
- ImGui::TableSetupColumn("Price", ImGuiTableColumnFlags_WidthStretch, 0.8f);
- ImGui::TableSetupColumn("Qty", ImGuiTableColumnFlags_WidthStretch, 0.8f);
- ImGui::TableSetupColumn("Fee", ImGuiTableColumnFlags_WidthStretch, 0.6f);
- ImGui::TableSetupColumn("Time", ImGuiTableColumnFlags_WidthStretch, 1.2f);
- ImGui::TableSetupScrollFreeze(0, 1);
- ImGui::PushStyleColor(ImGuiCol_TableHeaderBg, BG_DARKEST);
- ImGui::TableHeadersRow();
- ImGui::PopStyleColor();
-
- char buf[32];
- for (const auto& t : live_trades_) {
- ImGui::TableNextRow();
-
- ImGui::TableSetColumnIndex(0);
- ImGui::TextColored(TEXT_PRIMARY, "%s", t.symbol.c_str());
-
- ImGui::TableSetColumnIndex(1);
- ImVec4 side_col = (t.side == "buy") ? MARKET_GREEN : MARKET_RED;
- ImGui::TextColored(side_col, "%s", t.side == "buy" ? "BUY" : "SELL");
-
- ImGui::TableSetColumnIndex(2);
- std::snprintf(buf, sizeof(buf), "%.2f", t.price);
- ImGui::TextColored(TEXT_SECONDARY, "%s", buf);
-
- ImGui::TableSetColumnIndex(3);
- std::snprintf(buf, sizeof(buf), "%.4f", t.quantity);
- ImGui::TextColored(TEXT_SECONDARY, "%s", buf);
-
- ImGui::TableSetColumnIndex(4);
- std::snprintf(buf, sizeof(buf), "%.4f", t.fee);
- ImGui::TextColored(TEXT_DIM, "%s", buf);
-
- ImGui::TableSetColumnIndex(5);
- ImGui::TextColored(TEXT_DIM, "%s", t.timestamp.c_str());
- }
-
- ImGui::EndTable();
- }
- return;
- }
-
- std::lock_guard<std::mutex> lock(data_mutex_);
-
- if (!portfolio_loaded_) {
- theme::LoadingSpinner("Loading history...");
- return;
- }
-
- if (trades_.empty()) {
- ImGui::TextColored(TEXT_DIM, "No trade history");
- return;
- }
-
- ImGuiTableFlags flags = ImGuiTableFlags_RowBg | ImGuiTableFlags_BordersInnerH |
- ImGuiTableFlags_SizingStretchProp | ImGuiTableFlags_ScrollY;
-
- if (ImGui::BeginTable("##history", 6, flags)) {
- ImGui::TableSetupColumn("Symbol", ImGuiTableColumnFlags_WidthStretch, 1.0f);
- ImGui::TableSetupColumn("Side", ImGuiTableColumnFlags_WidthStretch, 0.5f);
- ImGui::TableSetupColumn("Price", ImGuiTableColumnFlags_WidthStretch, 0.8f);
- ImGui::TableSetupColumn("Qty", ImGuiTableColumnFlags_WidthStretch, 0.7f);
- ImGui::TableSetupColumn("Fee", ImGuiTableColumnFlags_WidthStretch, 0.6f);
- ImGui::TableSetupColumn("PnL", ImGuiTableColumnFlags_WidthStretch, 0.8f);
- ImGui::TableSetupScrollFreeze(0, 1);
- ImGui::PushStyleColor(ImGuiCol_TableHeaderBg, BG_DARKEST);
- ImGui::TableHeadersRow();
- ImGui::PopStyleColor();
-
- char buf[32];
- for (auto& t : trades_) {
- ImGui::TableNextRow();
-
- ImGui::TableSetColumnIndex(0);
- ImGui::TextColored(TEXT_PRIMARY, "%s", t.symbol.c_str());
-
- ImGui::TableSetColumnIndex(1);
- ImVec4 side_col = (t.side == "buy") ? MARKET_GREEN : MARKET_RED;
- ImGui::TextColored(side_col, "%s", t.side == "buy" ? "BUY" : "SELL");
-
- ImGui::TableSetColumnIndex(2);
- std::snprintf(buf, sizeof(buf), "%.2f", t.price);
- ImGui::TextColored(TEXT_SECONDARY, "%s", buf);
-
- ImGui::TableSetColumnIndex(3);
- std::snprintf(buf, sizeof(buf), "%.4f", t.quantity);
- ImGui::TextColored(TEXT_SECONDARY, "%s", buf);
-
- ImGui::TableSetColumnIndex(4);
- std::snprintf(buf, sizeof(buf), "%.4f", t.fee);
- ImGui::TextColored(TEXT_DIM, "%s", buf);
-
- ImGui::TableSetColumnIndex(5);
- ImVec4 pnl_col = t.pnl >= 0 ? MARKET_GREEN : MARKET_RED;
- std::snprintf(buf, sizeof(buf), "%s%.2f", t.pnl >= 0 ? "+" : "", t.pnl);
- ImGui::TextColored(pnl_col, "%s", buf);
- }
-
- ImGui::EndTable();
- }
-}
-
-void CryptoTradingScreen::render_stats_tab() {
- bool is_live = (trading_mode_ == TradingMode::Live);
- ImGui::TextColored(is_live ? ImVec4(0.9f, 0.2f, 0.2f, 1.0f) : ImVec4(0.0f, 0.7f, 0.3f, 1.0f),
- is_live ? "[LIVE STATS]" : "[PAPER STATS]");
-
- if (is_live) {
- ImGui::TextColored(TEXT_DIM, "Live statistics not available yet.");
- return;
- }
-
- std::lock_guard<std::mutex> lock(data_mutex_);
- char buf[32];
-
- if (!portfolio_loaded_) {
- theme::LoadingSpinner("Loading stats...");
- return;
- }
-
- ImGui::Columns(2, "##stats_cols", false);
-
- // Compute unrealized PnL from open positions
- double unrealized_pnl = 0.0;
- for (const auto& pos : positions_) {
- unrealized_pnl += pos.unrealized_pnl;
- }
-
- ImGui::TextColored(TEXT_DIM, "Realized PnL");
- ImVec4 pnl_col = stats_.total_pnl >= 0 ? MARKET_GREEN : MARKET_RED;
- std::snprintf(buf, sizeof(buf), "%s%.2f", stats_.total_pnl >= 0 ? "+" : "", stats_.total_pnl);
- ImGui::TextColored(pnl_col, "%s", buf);
- ImGui::Spacing();
-
- ImGui::TextColored(TEXT_DIM, "Unrealized PnL");
- ImVec4 upnl_col = unrealized_pnl >= 0 ? MARKET_GREEN : MARKET_RED;
- std::snprintf(buf, sizeof(buf), "%s%.2f", unrealized_pnl >= 0 ? "+" : "", unrealized_pnl);
- ImGui::TextColored(upnl_col, "%s", buf);
- ImGui::Spacing();
-
- ImGui::TextColored(TEXT_DIM, "Win Rate");
- std::snprintf(buf, sizeof(buf), "%.1f%%", stats_.win_rate);
- ImGui::TextColored(TEXT_PRIMARY, "%s", buf);
- ImGui::Spacing();
-
- ImGui::TextColored(TEXT_DIM, "Total Trades");
- std::snprintf(buf, sizeof(buf), "%lld", (long long)stats_.total_trades);
- ImGui::TextColored(TEXT_PRIMARY, "%s", buf);
- ImGui::Spacing();
-
- ImGui::TextColored(TEXT_DIM, "Balance");
- std::snprintf(buf, sizeof(buf), "%.2f", portfolio_.balance);
- ImGui::TextColored(TEXT_PRIMARY, "%s", buf);
-
- ImGui::NextColumn();
-
- ImGui::TextColored(TEXT_DIM, "Winning");
- std::snprintf(buf, sizeof(buf), "%lld", (long long)stats_.winning_trades);
- ImGui::TextColored(MARKET_GREEN, "%s", buf);
- ImGui::Spacing();
-
- ImGui::TextColored(TEXT_DIM, "Losing");
- std::snprintf(buf, sizeof(buf), "%lld", (long long)stats_.losing_trades);
- ImGui::TextColored(MARKET_RED, "%s", buf);
- ImGui::Spacing();
-
- ImGui::TextColored(TEXT_DIM, "Largest Win");
- std::snprintf(buf, sizeof(buf), "+%.2f", stats_.largest_win);
- ImGui::TextColored(MARKET_GREEN, "%s", buf);
- ImGui::Spacing();
-
- ImGui::TextColored(TEXT_DIM, "Largest Loss");
- std::snprintf(buf, sizeof(buf), "%.2f", stats_.largest_loss);
- ImGui::TextColored(MARKET_RED, "%s", buf);
-
- ImGui::Columns(1);
-
- ImGui::Spacing();
- ImGui::Separator();
- ImGui::Spacing();
- ImGui::PushStyleColor(ImGuiCol_Button, ImVec4(0.5f, 0.1f, 0.1f, 1.0f));
- if (ImGui::Button("Reset Portfolio", ImVec2(-1, 0))) {
- portfolio_ = trading::pt_reset_portfolio(portfolio_id_);
- refresh_portfolio_data();
- LOG_INFO(TAG, "Portfolio reset");
- }
- ImGui::PopStyleColor();
-}
-
-// ============================================================================
-// Trades tab — Time & Sales feed
-// ============================================================================
-void CryptoTradingScreen::render_trades_tab() {
- std::lock_guard<std::mutex> lock(data_mutex_);
-
- if (recent_trades_.empty()) {
- if (trades_fetching_) {
- ImGui::TextColored(TEXT_DIM, "Loading trades...");
- } else {
- ImGui::TextColored(TEXT_DIM, "No trades yet");
- }
- return;
- }
-
- ImGuiTableFlags flags = ImGuiTableFlags_RowBg | ImGuiTableFlags_BordersInnerH |
- ImGuiTableFlags_SizingStretchProp | ImGuiTableFlags_ScrollY;
-
- if (ImGui::BeginTable("##trades_feed", 4, flags)) {
- ImGui::TableSetupColumn("Time", ImGuiTableColumnFlags_WidthStretch, 1.0f);
- ImGui::TableSetupColumn("Side", ImGuiTableColumnFlags_WidthStretch, 0.5f);
- ImGui::TableSetupColumn("Price", ImGuiTableColumnFlags_WidthStretch, 1.0f);
- ImGui::TableSetupColumn("Amount", ImGuiTableColumnFlags_WidthStretch, 0.8f);
- ImGui::TableSetupScrollFreeze(0, 1);
- ImGui::PushStyleColor(ImGuiCol_TableHeaderBg, BG_DARKEST);
- ImGui::TableHeadersRow();
- ImGui::PopStyleColor();
-
- char buf[32];
- for (const auto& t : recent_trades_) {
- ImGui::TableNextRow();
-
- ImGui::TableSetColumnIndex(0);
- time_t ts = t.timestamp / 1000;
- struct tm tm_buf{};
-#ifdef _WIN32
- localtime_s(&tm_buf, &ts);
-#else
- localtime_r(&ts, &tm_buf);
-#endif
- std::snprintf(buf, sizeof(buf), "%02d:%02d:%02d", tm_buf.tm_hour, tm_buf.tm_min, tm_buf.tm_sec);
- ImGui::TextColored(TEXT_DIM, "%s", buf);
-
- ImGui::TableSetColumnIndex(1);
- ImVec4 col = (t.side == "buy") ? MARKET_GREEN : MARKET_RED;
- ImGui::TextColored(col, "%s", t.side == "buy" ? "BUY" : "SELL");
-
- ImGui::TableSetColumnIndex(2);
- std::snprintf(buf, sizeof(buf), "%.2f", t.price);
- ImGui::TextColored(col, "%s", buf);
-
- ImGui::TableSetColumnIndex(3);
- std::snprintf(buf, sizeof(buf), "%.4f", t.amount);
- ImGui::TextColored(TEXT_SECONDARY, "%s", buf);
- }
-
- ImGui::EndTable();
- }
-}
-
-void CryptoTradingScreen::async_fetch_trades() {
- if (trades_fetching_) return;
- trades_fetching_ = true;
-
- const std::string sym = selected_symbol_;
- launch_async(std::thread([this, sym]() {
- try {
- auto trades = trading::ExchangeService::instance().fetch_trades(sym, 100);
- std::lock_guard<std::mutex> lock(data_mutex_);
- recent_trades_.clear();
- for (const auto& t : trades) {
- recent_trades_.push_back({t.id, t.side, t.price, t.amount, t.timestamp});
- }
- } catch (const std::exception& e) {
- LOG_ERROR("CryptoTrading", "Failed to fetch trades: %s", e.what());
- }
- trades_fetching_ = false;
- }));
-}
-
-// ============================================================================
-// Market Info tab — funding rate, open interest, fees
-// ============================================================================
-void CryptoTradingScreen::render_market_info_tab() {
- std::lock_guard<std::mutex> lock(data_mutex_);
- char buf[64];
-
- if (!market_info_.has_data) {
- if (market_info_fetching_) {
- ImGui::TextColored(TEXT_DIM, "Loading market info...");
- } else {
- // Not yet fetched — show a trigger hint
- ImGui::TextColored(TEXT_DIM, "Fetching market info...");
- }
- return;
- }
-
- ImGui::Columns(2, "##mktinfo_cols", false);
-
- // --- Fees (always available for any symbol) ---
- ImGui::TextColored(TEXT_DIM, "Maker Fee");
- if (market_info_.maker_fee > 0.0) {
- std::snprintf(buf, sizeof(buf), "%.4f%%", market_info_.maker_fee * 100.0);
- ImGui::TextColored(TEXT_PRIMARY, "%s", buf);
- } else {
- ImGui::TextColored(TEXT_DIM, "N/A");
- }
- ImGui::Spacing();
-
- ImGui::TextColored(TEXT_DIM, "Taker Fee");
- if (market_info_.taker_fee > 0.0) {
- std::snprintf(buf, sizeof(buf), "%.4f%%", market_info_.taker_fee * 100.0);
- ImGui::TextColored(TEXT_PRIMARY, "%s", buf);
- } else {
- ImGui::TextColored(TEXT_DIM, "N/A");
- }
- ImGui::Spacing();
-
- // --- Perp-only fields (show N/A for spot) ---
- ImGui::TextColored(TEXT_DIM, "Funding Rate");
- if (market_info_.funding_rate != 0.0) {
- std::snprintf(buf, sizeof(buf), "%.4f%%", market_info_.funding_rate * 100.0);
- ImVec4 fr_col = market_info_.funding_rate >= 0 ? MARKET_GREEN : MARKET_RED;
- ImGui::TextColored(fr_col, "%s", buf);
- } else {
- ImGui::TextColored(TEXT_DIM, "N/A (spot)");
- }
- ImGui::Spacing();
-
- ImGui::TextColored(TEXT_DIM, "Mark Price");
- if (market_info_.mark_price > 0.0) {
- std::snprintf(buf, sizeof(buf), "%.4f", market_info_.mark_price);
- ImGui::TextColored(TEXT_PRIMARY, "%s", buf);
- } else {
- ImGui::TextColored(TEXT_DIM, "N/A (spot)");
- }
- ImGui::Spacing();
-
- ImGui::TextColored(TEXT_DIM, "Index Price");
- if (market_info_.index_price > 0.0) {
- std::snprintf(buf, sizeof(buf), "%.4f", market_info_.index_price);
- ImGui::TextColored(TEXT_PRIMARY, "%s", buf);
- } else {
- ImGui::TextColored(TEXT_DIM, "N/A (spot)");
- }
-
- ImGui::NextColumn();
-
- ImGui::TextColored(TEXT_DIM, "Open Interest");
- if (market_info_.open_interest > 0.0) {
- std::snprintf(buf, sizeof(buf), "%.2f", market_info_.open_interest);
- ImGui::TextColored(TEXT_PRIMARY, "%s", buf);
- } else {
- ImGui::TextColored(TEXT_DIM, "N/A (spot)");
- }
- ImGui::Spacing();
-
- ImGui::TextColored(TEXT_DIM, "OI Value (USD)");
- if (market_info_.open_interest_value > 0.0) {
- const double oi_val = market_info_.open_interest_value;
- if (oi_val > 1e9) std::snprintf(buf, sizeof(buf), "%.2fB", oi_val / 1e9);
- else if (oi_val > 1e6) std::snprintf(buf, sizeof(buf), "%.2fM", oi_val / 1e6);
- else std::snprintf(buf, sizeof(buf), "%.0f", oi_val);
- ImGui::TextColored(TEXT_PRIMARY, "%s", buf);
- } else {
- ImGui::TextColored(TEXT_DIM, "N/A (spot)");
- }
- ImGui::Spacing();
-
- if (market_info_.next_funding_time > 0) {
- ImGui::TextColored(TEXT_DIM, "Next Funding");
- const int64_t now_ms = std::chrono::duration_cast<std::chrono::milliseconds>(
- std::chrono::system_clock::now().time_since_epoch()).count();
- const int64_t diff_s = (market_info_.next_funding_time - now_ms) / 1000;
- if (diff_s > 0) {
- const int h = static_cast<int>(diff_s / 3600);
- const int m = static_cast<int>((diff_s % 3600) / 60);
- std::snprintf(buf, sizeof(buf), "%dh %dm", h, m);
- } else {
- std::snprintf(buf, sizeof(buf), "Now");
- }
- ImGui::TextColored(TEXT_PRIMARY, "%s", buf);
- }
-
- ImGui::Columns(1);
-
- // Refresh hint
- ImGui::Spacing();
- ImGui::TextColored(TEXT_DIM, "(refreshes every %.0fs)", MARKET_INFO_INTERVAL);
-}
-
-void CryptoTradingScreen::async_fetch_market_info() {
- if (market_info_fetching_) return;
- market_info_fetching_ = true;
-
- const std::string sym = selected_symbol_;
- launch_async(std::thread([this, sym]() {
- auto& svc = trading::ExchangeService::instance();
-
- // Fetch funding rate + OI (perp only — scripts return nulls gracefully for spot)
- const auto fr = svc.fetch_funding_rate(sym);
- const auto oi = svc.fetch_open_interest(sym);
-
- // Fetch trading fees — always available for any symbol on any exchange.
- // fetch_trading_fees.py with a symbol arg returns: {"symbol":..., "maker":..., "taker":...}
- double maker_fee = 0.0;
- double taker_fee = 0.0;
- try {
- const auto fees_j = svc.fetch_trading_fees(sym);
- if (fees_j.contains("data")) {
- const auto& d = fees_j["data"];
- if (d.contains("maker") && !d["maker"].is_null())
- maker_fee = d["maker"].get<double>();
- if (d.contains("taker") && !d["taker"].is_null())
- taker_fee = d["taker"].get<double>();
- }
- } catch (const std::exception& e) {
- LOG_DEBUG(TAG, "Trading fees fetch failed: %s", e.what());
- }
-
- {
- std::lock_guard<std::mutex> lock(data_mutex_);
- market_info_.funding_rate = fr.funding_rate;
- market_info_.mark_price = fr.mark_price;
- market_info_.index_price = fr.index_price;
- market_info_.next_funding_time = fr.next_funding_timestamp;
- market_info_.open_interest = oi.open_interest;
- market_info_.open_interest_value = oi.open_interest_value;
- market_info_.maker_fee = maker_fee;
- market_info_.taker_fee = taker_fee;
- market_info_.has_data = true; // always mark ready after fetch attempt
- }
- market_info_fetching_ = false;
- }));
-}
-
-// ============================================================================
-// Order Entry — right panel top
-// ============================================================================
-void CryptoTradingScreen::render_order_entry(float w, float h) {
- ImGui::PushStyleColor(ImGuiCol_ChildBg, BG_PANEL);
- ImGui::BeginChild("##crypto_order_entry", ImVec2(w, h), true);
-
- // Mode indicator
- bool is_paper = (trading_mode_ == TradingMode::Paper);
- ImGui::TextColored(ACCENT, "ORDER ENTRY");
- ImGui::SameLine(0, 6);
- if (is_paper) {
- ImGui::TextColored(ImVec4(0.0f, 0.7f, 0.3f, 1.0f), "[PAPER]");
- } else {
- ImGui::TextColored(ImVec4(0.9f, 0.2f, 0.2f, 1.0f), "[LIVE]");
- }
- ImGui::Separator();
-
- float input_w = w - 24;
-
- // Side: Buy / Sell
- ImGui::TextColored(TEXT_DIM, "Side");
- {
- float btn_w = (input_w - 4) / 2;
- bool is_buy = (order_form_.side_idx == 0);
-
- ImGui::PushStyleColor(ImGuiCol_Button, is_buy ? ImVec4(0.0f, 0.55f, 0.25f, 1.0f) : BG_WIDGET);
- ImGui::PushStyleColor(ImGuiCol_Text, is_buy ? TEXT_PRIMARY : TEXT_DIM);
- if (ImGui::Button("BUY", ImVec2(btn_w, 0))) order_form_.side_idx = 0;
- ImGui::PopStyleColor(2);
-
- ImGui::SameLine(0, 4);
-
- bool is_sell = (order_form_.side_idx == 1);
- ImGui::PushStyleColor(ImGuiCol_Button, is_sell ? ImVec4(0.65f, 0.1f, 0.1f, 1.0f) : BG_WIDGET);
- ImGui::PushStyleColor(ImGuiCol_Text, is_sell ? TEXT_PRIMARY : TEXT_DIM);
- if (ImGui::Button("SELL", ImVec2(btn_w, 0))) order_form_.side_idx = 1;
- ImGui::PopStyleColor(2);
- }
-
- ImGui::Spacing();
-
- // Order type
- ImGui::TextColored(TEXT_DIM, "Type");
- ImGui::PushItemWidth(input_w);
- ImGui::PushStyleColor(ImGuiCol_FrameBg, BG_INPUT);
- static const char* types[] = {"Market", "Limit", "Stop", "Stop Limit"};
- ImGui::Combo("##order_type", &order_form_.type_idx, types, 4);
- ImGui::PopStyleColor();
- ImGui::PopItemWidth();
-
- ImGui::Spacing();
-
- // Quantity
- ImGui::TextColored(TEXT_DIM, "Quantity");
- ImGui::PushItemWidth(input_w);
- ImGui::PushStyleColor(ImGuiCol_FrameBg, BG_INPUT);
- ImGui::InputText("##qty", order_form_.quantity_buf, sizeof(order_form_.quantity_buf),
- ImGuiInputTextFlags_CharsDecimal);
- ImGui::PopStyleColor();
- ImGui::PopItemWidth();
-
- // Quick quantity buttons
- {
- float btn_w = (input_w - 12) / 4;
- const char* pcts[] = {"25%", "50%", "75%", "100%"};
- float pct_vals[] = {0.25f, 0.50f, 0.75f, 1.00f};
- for (int i = 0; i < 4; i++) {
- if (i > 0) ImGui::SameLine(0, 4);
- ImGui::PushStyleColor(ImGuiCol_Button, BG_WIDGET);
- ImGui::PushStyleColor(ImGuiCol_Text, TEXT_DIM);
- if (ImGui::Button(pcts[i], ImVec2(btn_w, 0))) {
- if (current_ticker_.last > 0 && portfolio_.balance > 0) {
- double max_qty = (portfolio_.balance * pct_vals[i]) / current_ticker_.last;
- std::snprintf(order_form_.quantity_buf, sizeof(order_form_.quantity_buf),
- "%.6f", max_qty);
- }
- }
- ImGui::PopStyleColor(2);
- }
- }
-
- ImGui::Spacing();
-
- // Price (for limit/stop orders)
- if (order_form_.type_idx >= 1) {
- ImGui::TextColored(TEXT_DIM, "Price");
- ImGui::PushItemWidth(input_w);
- ImGui::PushStyleColor(ImGuiCol_FrameBg, BG_INPUT);
- ImGui::InputText("##price", order_form_.price_buf, sizeof(order_form_.price_buf),
- ImGuiInputTextFlags_CharsDecimal);
- ImGui::PopStyleColor();
- ImGui::PopItemWidth();
- }
-
- // Stop price (for stop/stoplimit)
- if (order_form_.type_idx >= 2) {
- ImGui::TextColored(TEXT_DIM, "Stop Price");
- ImGui::PushItemWidth(input_w);
- ImGui::PushStyleColor(ImGuiCol_FrameBg, BG_INPUT);
- ImGui::InputText("##stop_price", order_form_.stop_price_buf, sizeof(order_form_.stop_price_buf),
- ImGuiInputTextFlags_CharsDecimal);
- ImGui::PopStyleColor();
- ImGui::PopItemWidth();
- }
-
- // Stop Loss / Take Profit — optional risk management, non-Market orders only
- if (order_form_.type_idx != 0) {
- ImGui::Spacing();
- ImGui::PushStyleColor(ImGuiCol_Text, TEXT_DIM);
- ImGui::Text("-- Risk Mgmt (optional) --");
- ImGui::PopStyleColor();
-
- ImGui::TextColored(TEXT_DIM, "Stop Loss");
- ImGui::PushItemWidth(input_w);
- ImGui::PushStyleColor(ImGuiCol_FrameBg, BG_INPUT);
- ImGui::InputText("##sl_price", order_form_.sl_price_buf, sizeof(order_form_.sl_price_buf),
- ImGuiInputTextFlags_CharsDecimal);
- ImGui::PopStyleColor();
- ImGui::PopItemWidth();
-
- ImGui::TextColored(TEXT_DIM, "Take Profit");
- ImGui::PushItemWidth(input_w);
- ImGui::PushStyleColor(ImGuiCol_FrameBg, BG_INPUT);
- ImGui::InputText("##tp_price", order_form_.tp_price_buf, sizeof(order_form_.tp_price_buf),
- ImGuiInputTextFlags_CharsDecimal);
- ImGui::PopStyleColor();
- ImGui::PopItemWidth();
- }
-
- ImGui::Spacing();
-
- // Reduce only checkbox
- ImGui::Checkbox("Reduce Only", &order_form_.reduce_only);
-
- ImGui::Spacing();
-
- // --- Fee Estimation (shown when market info has loaded and notional > 0) ---
- if (market_info_.has_data) {
- const double qty = std::atof(order_form_.quantity_buf);
- // Market orders use last ticker price; limit/stop orders use entered price
- const double price = (order_form_.type_idx == 0)
- ? current_ticker_.last
- : std::atof(order_form_.price_buf);
-
- if (qty > 0.0 && price > 0.0) {
- // Limit orders go on the book → maker fee; all others fill immediately → taker fee
- const bool is_maker = (order_form_.type_idx == 1);
- const double effective_fee = is_maker ? market_info_.maker_fee : market_info_.taker_fee;
- const double notional = qty * price;
- const double fee_amount = notional * effective_fee;
- const double total_incl = notional + fee_amount;
-
- ImGui::Separator();
- {
- char buf[64];
- std::snprintf(buf, sizeof(buf), "Fee(%.2f%% %s)",
- effective_fee * 100.0, is_maker ? "mkr" : "tkr");
- ImGui::PushStyleColor(ImGuiCol_Text, TEXT_DIM);
- ImGui::Text("%s", buf);
- ImGui::SameLine(input_w - 72);
- std::snprintf(buf, sizeof(buf), "%.4f", fee_amount);
- ImGui::Text("%s", buf);
-
- ImGui::Text("Total w/fee");
- ImGui::SameLine(input_w - 72);
- std::snprintf(buf, sizeof(buf), "%.2f", total_incl);
- ImGui::Text("%s", buf);
- ImGui::PopStyleColor();
- }
- ImGui::Separator();
- }
- }
-
- ImGui::Spacing();
-
- // Submit button — clearly labeled with mode
- {
- bool is_buy = (order_form_.side_idx == 0);
- ImVec4 btn_col = is_buy ? ImVec4(0.0f, 0.55f, 0.25f, 1.0f) : ImVec4(0.65f, 0.1f, 0.1f, 1.0f);
-
- // Show base symbol without quote (e.g., "BTC" not "BTC/USDT")
- std::string base_sym = selected_symbol_;
- auto slash_pos = base_sym.find('/');
- if (slash_pos != std::string::npos) base_sym = base_sym.substr(0, slash_pos);
-
- char label[64];
- if (is_paper) {
- std::snprintf(label, sizeof(label), "%s %s (Paper)",
- is_buy ? "BUY" : "SELL", base_sym.c_str());
- } else {
- std::snprintf(label, sizeof(label), "%s %s (LIVE)",
- is_buy ? "BUY" : "SELL", base_sym.c_str());
- // Add red border for live orders as a safety indicator
- btn_col = is_buy ? ImVec4(0.0f, 0.4f, 0.2f, 1.0f) : ImVec4(0.6f, 0.05f, 0.05f, 1.0f);
- }
-
- ImGui::PushStyleColor(ImGuiCol_Button, btn_col);
- ImGui::PushStyleColor(ImGuiCol_ButtonHovered, ImVec4(btn_col.x + 0.1f, btn_col.y + 0.1f, btn_col.z + 0.1f, 1.0f));
- ImGui::PushStyleColor(ImGuiCol_Text, TEXT_PRIMARY);
- if (order_submitting_.load()) {
- ImGui::Button("Submitting...", ImVec2(input_w, 28));
- } else if (ImGui::Button(label, ImVec2(input_w, 28))) {
- submit_order();
- }
- ImGui::PopStyleColor(3);
-
- // Warning for live mode
- if (!is_paper) {
- ImGui::TextColored(ImVec4(0.9f, 0.5f, 0.1f, 1.0f), "Real money at risk!");
- }
- }
-
- // Error / Success messages
- if (!order_form_.error.empty()) {
- ImGui::TextColored(MARKET_RED, "%s", order_form_.error.c_str());
- }
- if (!order_form_.success.empty()) {
- ImGui::TextColored(MARKET_GREEN, "%s", order_form_.success.c_str());
- }
-
- ImGui::EndChild();
- ImGui::PopStyleColor();
-}
-
-// ============================================================================
-// Order Book — right panel bottom
-// ============================================================================
-void CryptoTradingScreen::render_orderbook(float w, float h) {
- ImGui::PushStyleColor(ImGuiCol_ChildBg, BG_PANEL);
- ImGui::BeginChild("##crypto_orderbook", ImVec2(w, h), true);
-
- // Title + spread
- ImGui::TextColored(ACCENT, "ORDER BOOK");
- {
- std::lock_guard<std::mutex> lock(data_mutex_);
- if (ob_spread_ > 0) {
- ImGui::SameLine();
- char spread_buf[32];
- std::snprintf(spread_buf, sizeof(spread_buf), "Spread:%.2f(%.3f%%)", ob_spread_, ob_spread_pct_);
- ImGui::TextColored(TEXT_DIM, "%s", spread_buf);
- }
- }
- if (ob_fetching_) {
- ImGui::SameLine();
- ImGui::TextColored(WARNING, "[*]");
- }
-
- // Mode switcher — 4 segmented buttons
- {
- struct ModeBtn { const char* label; ObViewMode mode; };
- static constexpr ModeBtn k_modes[] = {
- {"OB", ObViewMode::Book},
- {"VOL", ObViewMode::Volume},
- {"IMBAL", ObViewMode::Imbalance},
- {"SIG", ObViewMode::Signals},
- };
- const float btn_w = (w - 28.0f) / 4.0f;
- ImGui::SameLine(0, 6);
- for (int i = 0; i < 4; ++i) {
- if (i > 0) ImGui::SameLine(0, 2);
- const bool active = (ob_view_mode_ == k_modes[i].mode);
- ImGui::PushStyleColor(ImGuiCol_Button,
- active ? ImVec4(0.2f, 0.4f, 0.7f, 1.0f) : BG_WIDGET);
- ImGui::PushStyleColor(ImGuiCol_Text,
- active ? TEXT_PRIMARY : TEXT_DIM);
- if (ImGui::SmallButton(k_modes[i].label))
- ob_view_mode_ = k_modes[i].mode;
- ImGui::PopStyleColor(2);
- }
- }
-
- ImGui::Separator();
-
- // Empty state guard
- {
- std::lock_guard<std::mutex> lock(data_mutex_);
- if (ob_asks_.empty() && ob_bids_.empty()) {
- if (ob_loading_) {
- theme::LoadingSpinner("Loading order book...");
- } else {
- ImGui::TextColored(TEXT_DIM, "No order book data");
- }
- ImGui::EndChild();
- ImGui::PopStyleColor();
- return;
- }
- }
-
- // Dispatch to active mode renderer
- switch (ob_view_mode_) {
- case ObViewMode::Book: render_ob_mode_book(w); break;
- case ObViewMode::Volume: render_ob_mode_volume(w); break;
- case ObViewMode::Imbalance: render_ob_mode_imbalance(w); break;
- case ObViewMode::Signals: render_ob_mode_signals(w); break;
- }
-
- ImGui::EndChild();
- ImGui::PopStyleColor();
-}
-
-// ----------------------------------------------------------------------------
-// OB Mode: Book — price / amount / cumulative depth bars (default view)
-// ----------------------------------------------------------------------------
-void CryptoTradingScreen::render_ob_mode_book(float w) {
- std::lock_guard<std::mutex> lock(data_mutex_);
-
- const float avail_h = ImGui::GetContentRegionAvail().y;
- const float half_h = avail_h / 2.0f;
- const float col_w = (w - 24.0f) / 3.0f;
-
- double max_cum = 1.0;
- if (!ob_bids_.empty()) max_cum = std::max(max_cum, ob_bids_.back().cumulative);
- if (!ob_asks_.empty()) max_cum = std::max(max_cum, ob_asks_.back().cumulative);
-
- ImGui::PushStyleColor(ImGuiCol_Text, TEXT_DIM);
- ImGui::Text("PRICE");
- ImGui::SameLine(col_w + 4); ImGui::Text("AMOUNT");
- ImGui::SameLine(col_w * 2 + 8); ImGui::Text("TOTAL");
- ImGui::PopStyleColor();
-
- // Asks — lowest ask nearest spread
- ImGui::BeginChild("##ob_asks_book", ImVec2(0, half_h - 12), false);
- {
- char buf[32];
- const int start = std::max(0, static_cast<int>(ob_asks_.size()) - OB_MAX_OB_DISPLAY_LEVELS);
- for (int i = start; i < static_cast<int>(ob_asks_.size()); ++i) {
- const auto& lvl = ob_asks_[i];
- ImVec2 p = ImGui::GetCursorScreenPos();
- const float row_w = ImGui::GetContentRegionAvail().x;
- const float bar_w = static_cast<float>(lvl.cumulative / max_cum) * row_w;
- ImGui::GetWindowDrawList()->AddRectFilled(
- ImVec2(p.x + row_w - bar_w, p.y),
- ImVec2(p.x + row_w, p.y + ImGui::GetTextLineHeight()),
- ImGui::ColorConvertFloat4ToU32(ImVec4(0.6f, 0.1f, 0.1f, 0.15f)));
- std::snprintf(buf, sizeof(buf), "%.2f", lvl.price);
- ImGui::TextColored(MARKET_RED, "%s", buf);
- ImGui::SameLine(col_w + 4);
- std::snprintf(buf, sizeof(buf), "%.4f", lvl.amount);
- ImGui::TextColored(TEXT_SECONDARY, "%s", buf);
- ImGui::SameLine(col_w * 2 + 8);
- std::snprintf(buf, sizeof(buf), "%.4f", lvl.cumulative);
- ImGui::TextColored(TEXT_DIM, "%s", buf);
- }
- }
- ImGui::EndChild();
-
- ImGui::PushStyleColor(ImGuiCol_Separator, BORDER_BRIGHT);
- ImGui::Separator();
- ImGui::PopStyleColor();
-
- // Bids — highest to lowest
- ImGui::BeginChild("##ob_bids_book", ImVec2(0, 0), false);
- {
- char buf[32];
- const int count = std::min(static_cast<int>(ob_bids_.size()), OB_MAX_OB_DISPLAY_LEVELS);
- for (int i = 0; i < count; ++i) {
- const auto& lvl = ob_bids_[i];
- ImVec2 p = ImGui::GetCursorScreenPos();
- const float row_w = ImGui::GetContentRegionAvail().x;
- const float bar_w = static_cast<float>(lvl.cumulative / max_cum) * row_w;
- ImGui::GetWindowDrawList()->AddRectFilled(
- ImVec2(p.x + row_w - bar_w, p.y),
- ImVec2(p.x + row_w, p.y + ImGui::GetTextLineHeight()),
- ImGui::ColorConvertFloat4ToU32(ImVec4(0.0f, 0.5f, 0.2f, 0.15f)));
- std::snprintf(buf, sizeof(buf), "%.2f", lvl.price);
- ImGui::TextColored(MARKET_GREEN, "%s", buf);
- ImGui::SameLine(col_w + 4);
- std::snprintf(buf, sizeof(buf), "%.4f", lvl.amount);
- ImGui::TextColored(TEXT_SECONDARY, "%s", buf);
- ImGui::SameLine(col_w * 2 + 8);
- std::snprintf(buf, sizeof(buf), "%.4f", lvl.cumulative);
- ImGui::TextColored(TEXT_DIM, "%s", buf);
- }
- }
- ImGui::EndChild();
-}
-
-// ----------------------------------------------------------------------------
-// OB Mode: Volume — price / amount / % share of total book
-// ----------------------------------------------------------------------------
-void CryptoTradingScreen::render_ob_mode_volume(float w) {
- std::lock_guard<std::mutex> lock(data_mutex_);
-
- const float col_w = (w - 24.0f) / 3.0f;
-
- double total_vol = 0.0;
- for (const auto& lvl : ob_asks_) total_vol += lvl.amount;
- for (const auto& lvl : ob_bids_) total_vol += lvl.amount;
- if (total_vol <= 0.0) total_vol = 1.0;
-
- // Normaliser: each bar fills to its share of the avg-level volume
- const double avg_lvl_vol = total_vol / static_cast<double>(OB_MAX_OB_DISPLAY_LEVELS * 2);
-
- ImGui::PushStyleColor(ImGuiCol_Text, TEXT_DIM);
- ImGui::Text("PRICE");
- ImGui::SameLine(col_w + 4); ImGui::Text("AMOUNT");
- ImGui::SameLine(col_w * 2 + 8); ImGui::Text("VOL%");
- ImGui::PopStyleColor();
-
- const float avail_h = ImGui::GetContentRegionAvail().y;
- const float half_h = avail_h / 2.0f;
-
- ImGui::BeginChild("##ob_asks_vol", ImVec2(0, half_h - 12), false);
- {
- char buf[32];
- const int start = std::max(0, static_cast<int>(ob_asks_.size()) - OB_MAX_OB_DISPLAY_LEVELS);
- for (int i = start; i < static_cast<int>(ob_asks_.size()); ++i) {
- const auto& lvl = ob_asks_[i];
- const double vol_pct = (lvl.amount / total_vol) * 100.0;
- ImVec2 p = ImGui::GetCursorScreenPos();
- const float row_w = ImGui::GetContentRegionAvail().x;
- const float bar_w = std::min(static_cast<float>(lvl.amount / (avg_lvl_vol * 2.0)) * row_w, row_w);
- ImGui::GetWindowDrawList()->AddRectFilled(
- ImVec2(p.x, p.y),
- ImVec2(p.x + bar_w, p.y + ImGui::GetTextLineHeight()),
- ImGui::ColorConvertFloat4ToU32(ImVec4(0.6f, 0.1f, 0.1f, 0.20f)));
- std::snprintf(buf, sizeof(buf), "%.2f", lvl.price);
- ImGui::TextColored(MARKET_RED, "%s", buf);
- ImGui::SameLine(col_w + 4);
- std::snprintf(buf, sizeof(buf), "%.4f", lvl.amount);
- ImGui::TextColored(TEXT_SECONDARY, "%s", buf);
- ImGui::SameLine(col_w * 2 + 8);
- std::snprintf(buf, sizeof(buf), "%.2f%%", vol_pct);
- ImGui::TextColored(TEXT_DIM, "%s", buf);
- }
- }
- ImGui::EndChild();
-
- ImGui::PushStyleColor(ImGuiCol_Separator, BORDER_BRIGHT);
- ImGui::Separator();
- ImGui::PopStyleColor();
-
- ImGui::BeginChild("##ob_bids_vol", ImVec2(0, 0), false);
- {
- char buf[32];
- const int count = std::min(static_cast<int>(ob_bids_.size()), OB_MAX_OB_DISPLAY_LEVELS);
- for (int i = 0; i < count; ++i) {
- const auto& lvl = ob_bids_[i];
- const double vol_pct = (lvl.amount / total_vol) * 100.0;
- ImVec2 p = ImGui::GetCursorScreenPos();
- const float row_w = ImGui::GetContentRegionAvail().x;
- const float bar_w = std::min(static_cast<float>(lvl.amount / (avg_lvl_vol * 2.0)) * row_w, row_w);
- ImGui::GetWindowDrawList()->AddRectFilled(
- ImVec2(p.x, p.y),
- ImVec2(p.x + bar_w, p.y + ImGui::GetTextLineHeight()),
- ImGui::ColorConvertFloat4ToU32(ImVec4(0.0f, 0.5f, 0.2f, 0.20f)));
- std::snprintf(buf, sizeof(buf), "%.2f", lvl.price);
- ImGui::TextColored(MARKET_GREEN, "%s", buf);
- ImGui::SameLine(col_w + 4);
- std::snprintf(buf, sizeof(buf), "%.4f", lvl.amount);
- ImGui::TextColored(TEXT_SECONDARY, "%s", buf);
- ImGui::SameLine(col_w * 2 + 8);
- std::snprintf(buf, sizeof(buf), "%.2f%%", vol_pct);
- ImGui::TextColored(TEXT_DIM, "%s", buf);
- }
- }
- ImGui::EndChild();
-}
-
-// ----------------------------------------------------------------------------
-// OB Mode: Imbalance — weighted bid/ask ratio gauge + per-level table
-// ----------------------------------------------------------------------------
-void CryptoTradingScreen::render_ob_mode_imbalance(float w) {
- std::lock_guard<std::mutex> lock(data_mutex_);
-
- if (tick_history_.empty()) {
- ImGui::TextColored(TEXT_DIM, "Collecting data...");
- return;
- }
-
- const auto& latest = tick_history_.back();
- const double imbalance = latest.imbalance;
-
- // Imbalance value + colour
- {
- char buf[48];
- std::snprintf(buf, sizeof(buf), "Imbalance: %+.3f", imbalance);
- const ImVec4 col = (imbalance > OB_IMBALANCE_BUY_THRESHOLD) ? MARKET_GREEN :
- (imbalance < OB_IMBALANCE_SELL_THRESHOLD) ? MARKET_RED :
- TEXT_SECONDARY;
- ImGui::TextColored(col, "%s", buf);
- }
-
- // Horizontal bid/ask weight bar
- {
- const float bar_total_w = w - 24.0f;
- const float bid_frac = static_cast<float>((imbalance + 1.0) / 2.0);
- ImVec2 p = ImGui::GetCursorScreenPos();
- constexpr float bar_h = 8.0f;
- ImDrawList* dl = ImGui::GetWindowDrawList();
- dl->AddRectFilled(p, ImVec2(p.x + bar_total_w * bid_frac, p.y + bar_h),
- ImGui::ColorConvertFloat4ToU32(ImVec4(0.0f, 0.55f, 0.25f, 0.8f)));
- dl->AddRectFilled(ImVec2(p.x + bar_total_w * bid_frac, p.y),
- ImVec2(p.x + bar_total_w, p.y + bar_h),
- ImGui::ColorConvertFloat4ToU32(ImVec4(0.65f, 0.1f, 0.1f, 0.8f)));
- ImGui::Dummy(ImVec2(bar_total_w, bar_h + 2.0f));
- }
-
- ImGui::Spacing();
-
- // Per-level breakdown
- static constexpr float k_weights[3] = {50.0f, 30.0f, 20.0f};
- ImGui::PushStyleColor(ImGuiCol_Text, TEXT_DIM);
- ImGui::Text("LVL WT BID QTY ASK QTY IMBAL");
- ImGui::PopStyleColor();
- ImGui::Separator();
-
- for (int i = 0; i < 3; ++i) {
- const double bq = latest.bid_qty[i];
- const double aq = latest.ask_qty[i];
- const double wB = k_weights[i] * bq;
- const double wA = k_weights[i] * aq;
- const double lvl_imbal = (wB + wA > 0.0) ? (wB - wA) / (wB + wA) : 0.0;
- const ImVec4 col = (lvl_imbal > 0.1) ? MARKET_GREEN :
- (lvl_imbal < -0.1) ? MARKET_RED : TEXT_SECONDARY;
- char row[96];
- std::snprintf(row, sizeof(row), " L%d %3.0f%% %9.4f %9.4f %+.3f",
- i + 1, k_weights[i], bq, aq, lvl_imbal);
- ImGui::TextColored(col, "%s", row);
- }
-
- ImGui::Spacing();
- ImGui::Separator();
-
- {
- char buf[48];
- std::snprintf(buf, sizeof(buf), "60s rise: %+.3f%%", latest.rise_ratio_60);
- ImGui::TextColored(latest.rise_ratio_60 >= 0.0 ? MARKET_GREEN : MARKET_RED, "%s", buf);
- }
-}
-
-// ----------------------------------------------------------------------------
-// OB Mode: Signals — BUY/SELL/NEUTRAL badge from imbalance + rise ratio
-// ----------------------------------------------------------------------------
-void CryptoTradingScreen::render_ob_mode_signals(float w) {
- std::lock_guard<std::mutex> lock(data_mutex_);
-
- if (tick_history_.empty()) {
- ImGui::TextColored(TEXT_DIM, "Collecting data... (~5s)");
- return;
- }
-
- const auto& latest = tick_history_.back();
- const double imbalance = latest.imbalance;
- const double rise_60 = latest.rise_ratio_60;
-
- const bool is_buy = (imbalance > OB_IMBALANCE_BUY_THRESHOLD && rise_60 > OB_RISE_BUY_THRESHOLD);
- const bool is_sell = (imbalance < OB_IMBALANCE_SELL_THRESHOLD && rise_60 < OB_RISE_SELL_THRESHOLD);
-
- // Signal badge (styled as non-interactive button for visual weight)
- {
- const char* label = is_buy ? " BUY " : (is_sell ? " SELL " : " NEUTRAL ");
- const ImVec4 bg = is_buy ? ImVec4(0.0f, 0.55f, 0.25f, 1.0f) :
- is_sell ? ImVec4(0.65f, 0.1f, 0.1f, 1.0f) :
- ImVec4(0.3f, 0.3f, 0.3f, 1.0f);
- ImGui::PushStyleColor(ImGuiCol_Button, bg);
- ImGui::PushStyleColor(ImGuiCol_ButtonHovered, bg);
- ImGui::PushStyleColor(ImGuiCol_Text, TEXT_PRIMARY);
- ImGui::Button(label, ImVec2(w - 24.0f, 28.0f));
- ImGui::PopStyleColor(3);
- }
-
- ImGui::Spacing();
-
- // Metrics table
- ImGui::PushStyleColor(ImGuiCol_Text, TEXT_DIM);
- ImGui::Text("Imbalance Rise 60s Thresholds");
- ImGui::PopStyleColor();
- ImGui::Separator();
-
- {
- char buf[64];
- std::snprintf(buf, sizeof(buf), "%+.3f", imbalance);
- ImGui::TextColored(imbalance >= 0.0 ? MARKET_GREEN : MARKET_RED, "%s", buf);
- ImGui::SameLine(80);
- std::snprintf(buf, sizeof(buf), "%+.3f%%", rise_60);
- ImGui::TextColored(rise_60 >= 0.0 ? MARKET_GREEN : MARKET_RED, "%s", buf);
- ImGui::SameLine(160);
- ImGui::TextColored(TEXT_DIM, "B>%.2f|S<%.2f",
- OB_IMBALANCE_BUY_THRESHOLD, OB_IMBALANCE_SELL_THRESHOLD);
- }
-
- ImGui::Spacing();
- ImGui::Separator();
-
- {
- char buf[48];
- std::snprintf(buf, sizeof(buf), "History: %d/%d ticks",
- static_cast<int>(tick_history_.size()), OB_MAX_TICK_HISTORY);
- ImGui::TextColored(TEXT_DIM, "%s", buf);
- }
-}
-
-// ============================================================================
-// Status Bar — shows connection, errors, debug info
-// ============================================================================
-void CryptoTradingScreen::render_status_bar(float w, float h) {
- ImGui::PushStyleColor(ImGuiCol_ChildBg, BG_DARKEST);
- ImGui::BeginChild("##crypto_status", ImVec2(w, h), true);
-
- // Connection status
- bool ws_live = trading::ExchangeService::instance().is_ws_connected();
- bool has_data = (current_ticker_.last > 0);
- ImGui::TextColored(ws_live ? MARKET_GREEN : (has_data ? WARNING : MARKET_RED), "[*]");
- ImGui::SameLine(0, 4);
- ImGui::TextColored(TEXT_DIM, "%s", ws_live ? "WS LIVE" : (has_data ? "REST" : "NO DATA"));
-
- ImGui::SameLine(0, 12);
- ImGui::TextColored(BORDER_BRIGHT, "|");
- ImGui::SameLine(0, 12);
-
- // Exchange
- ImGui::TextColored(TEXT_DIM, "Exchange:");
- ImGui::SameLine(0, 4);
- ImGui::TextColored(TEXT_SECONDARY, "%s", exchange_id_.c_str());
-
- ImGui::SameLine(0, 12);
- ImGui::TextColored(BORDER_BRIGHT, "|");
- ImGui::SameLine(0, 12);
-
- // Mode
- bool is_paper = (trading_mode_ == TradingMode::Paper);
- ImGui::TextColored(TEXT_DIM, "Mode:");
- ImGui::SameLine(0, 4);
- ImGui::TextColored(is_paper ? WARNING : MARKET_RED, "%s", is_paper ? "PAPER" : "LIVE");
-
- ImGui::SameLine(0, 12);
- ImGui::TextColored(BORDER_BRIGHT, "|");
- ImGui::SameLine(0, 12);
-
- // Stats
- ImGui::TextColored(TEXT_DIM, "OK:%d ERR:%d", success_count_, error_count_);
-
- // Async status
- ImGui::SameLine(0, 12);
- ImGui::TextColored(BORDER_BRIGHT, "|");
- ImGui::SameLine(0, 12);
-
- if (ticker_fetching_ || ob_fetching_ || wl_fetching_) {
- ImGui::TextColored(WARNING, "FETCHING");
- if (ticker_fetching_) { ImGui::SameLine(0, 4); ImGui::TextColored(TEXT_DIM, "[T]"); }
- if (ob_fetching_) { ImGui::SameLine(0, 4); ImGui::TextColored(TEXT_DIM, "[OB]"); }
- if (wl_fetching_) { ImGui::SameLine(0, 4); ImGui::TextColored(TEXT_DIM, "[WL]"); }
- } else {
- ImGui::TextColored(TEXT_DIM, "IDLE");
- }
-
- // Last error (if any)
- if (!last_error_.empty()) {
- ImGui::SameLine(0, 12);
- ImGui::TextColored(BORDER_BRIGHT, "|");
- ImGui::SameLine(0, 12);
- // Truncate error for status bar
- std::string err_short = last_error_.substr(0, 60);
- ImGui::TextColored(MARKET_RED, "%s", err_short.c_str());
- }
-
- // Right side: last update time
- if (last_data_update_ > 0) {
- time_t now = time(nullptr);
- int elapsed = (int)difftime(now, last_data_update_);
- char time_buf[32];
- std::snprintf(time_buf, sizeof(time_buf), "Updated %ds ago", elapsed);
- float time_w = ImGui::CalcTextSize(time_buf).x + 8;
- float avail = ImGui::GetContentRegionAvail().x;
- if (avail > time_w) {
- ImGui::SameLine(ImGui::GetCursorPosX() + avail - time_w);
- ImGui::TextColored(TEXT_DIM, "%s", time_buf);
- }
- }
-
- ImGui::EndChild();
- ImGui::PopStyleColor();
-}
-
-// ============================================================================
-// Order submission
-// ============================================================================
-void CryptoTradingScreen::submit_order() {
- order_form_.error.clear();
- order_form_.success.clear();
-
- bool is_live = (trading_mode_ == TradingMode::Live);
- LOG_INFO(TAG, "Submitting %s order: symbol=%s side=%d type=%d qty='%s' price='%s'",
- is_live ? "LIVE" : "PAPER",
- selected_symbol_.c_str(), order_form_.side_idx, order_form_.type_idx,
- order_form_.quantity_buf, order_form_.price_buf);
-
- // Live mode guard — require credentials
- if (is_live) {
- if (!has_credentials_) {
- order_form_.error = "API credentials required. Click 'API' button to configure.";
- order_form_.msg_timer = 5.0f;
- return;
- }
- LOG_INFO(TAG, "Live order being routed to %s exchange API", exchange_id_.c_str());
- }
-
- // Parse quantity
- double qty = 0;
- try {
- qty = std::stod(order_form_.quantity_buf);
- } catch (...) {
- order_form_.error = "Invalid quantity";
- order_form_.msg_timer = 5.0f;
- LOG_ERROR(TAG, "Invalid quantity: '%s'", order_form_.quantity_buf);
- return;
- }
- if (qty <= 0) {
- order_form_.error = "Quantity must be > 0";
- order_form_.msg_timer = 5.0f;
- return;
- }
-
- static const char* type_strs[] = {"market", "limit", "stop", "stop_limit"};
- std::string order_type = type_strs[order_form_.type_idx];
- std::string side = order_form_.side_idx == 0 ? "buy" : "sell";
-
- std::optional<double> price;
- std::optional<double> stop_price;
-
- // For market orders, use current ticker price as reference for margin calculation
- if (order_form_.type_idx == 0) {
- double ref = (side == "buy") ? current_ticker_.ask : current_ticker_.bid;
- if (ref <= 0) ref = current_ticker_.last;
- if (ref <= 0) {
- order_form_.error = "No market price available yet";
- order_form_.msg_timer = 5.0f;
- LOG_ERROR(TAG, "Market order rejected: no price data");
- return;
- }
- price = ref;
- }
-
- if (order_form_.type_idx == 1 || order_form_.type_idx == 3) {
- try {
- double p = std::stod(order_form_.price_buf);
- if (p <= 0) {
- order_form_.error = "Price must be > 0";
- order_form_.msg_timer = 5.0f;
- return;
- }
- price = p;
- } catch (...) {
- order_form_.error = "Invalid price";
- order_form_.msg_timer = 5.0f;
- return;
- }
- }
-
- if (order_form_.type_idx >= 2) {
- try {
- double sp = std::stod(order_form_.stop_price_buf);
- if (sp <= 0) {
- order_form_.error = "Stop price must be > 0";
- order_form_.msg_timer = 5.0f;
- return;
- }
- stop_price = sp;
- } catch (...) {
- order_form_.error = "Invalid stop price";
- order_form_.msg_timer = 5.0f;
- return;
- }
- }
-
- // Fee-inclusive balance check for paper BUY orders (ES.45: named values not magic)
- if (trading_mode_ == TradingMode::Paper && side == "buy" && price.has_value()) {
- const bool is_maker = (order_form_.type_idx == 1); // limit → maker
- const double effective_fee = market_info_.has_data
- ? (is_maker ? market_info_.maker_fee : market_info_.taker_fee)
- : 0.001; // fallback 0.1% if fees not yet loaded
- const double notional = qty * price.value();
- const double total_incl = notional * (1.0 + effective_fee);
- if (total_incl > portfolio_.balance) {
- char buf[128];
- std::snprintf(buf, sizeof(buf),
- "Insufficient balance ($%.2f avail, $%.2f needed incl. fee)",
- portfolio_.balance, total_incl);
- order_form_.error = buf;
- order_form_.msg_timer = 5.0f;
- return;
- }
- }
-
- try {
- if (trading_mode_ == TradingMode::Live) {
- // Live trading — route through exchange API on background thread
- order_submitting_.store(true);
- const std::string sym = selected_symbol_;
- std::string pid = portfolio_id_;
- launch_async(std::thread([this, sym, side, order_type, qty, price, pid]() {
- try {
- auto& svc = trading::ExchangeService::instance();
- auto result = svc.place_order(sym, side, order_type, qty,
- price.value_or(0.0));
- LOG_INFO(TAG, "Live order placed: %s", result.dump(2).c_str());
- core::notify::send("Order Placed",
- sym + " " + side + " " + std::to_string(qty),
- core::NotifyLevel::Success);
- {
- std::lock_guard<std::mutex> lock(data_mutex_);
- order_form_.success = "Live order sent!";
- order_form_.msg_timer = 3.0f;
- }
- trading::ExchangeService::instance().watch_symbol(sym, pid);
- refresh_portfolio_data();
- } catch (const std::exception& e) {
- std::lock_guard<std::mutex> lock(data_mutex_);
- order_form_.error = e.what();
- order_form_.msg_timer = 5.0f;
- LOG_ERROR(TAG, "Live order FAILED: %s", e.what());
- core::notify::send("Order Failed", e.what(), core::NotifyLevel::Error);
- }
- order_submitting_.store(false);
- }));
- // Clear form immediately
- order_form_.quantity_buf[0] = '\0';
- order_form_.price_buf[0] = '\0';
- order_form_.stop_price_buf[0] = '\0';
- order_form_.sl_price_buf[0] = '\0';
- order_form_.tp_price_buf[0] = '\0';
- return; // skip the rest — thread handles result
- } else {
- // Paper trading
- auto order = trading::pt_place_order(
- portfolio_id_, selected_symbol_, side, order_type,
- qty, price, stop_price, order_form_.reduce_only);
-
- LOG_INFO(TAG, "Order created: id=%s type=%s side=%s qty=%.6f",
- order.id.c_str(), order_type.c_str(), side.c_str(), qty);
-
- // For market orders, immediately fill at current price
- if (order_type == "market" && current_ticker_.last > 0) {
- double fill_price = side == "buy" ? current_ticker_.ask : current_ticker_.bid;
- if (fill_price <= 0) fill_price = current_ticker_.last;
- LOG_INFO(TAG, "Market order fill at %.2f", fill_price);
- trading::pt_fill_order(order.id, fill_price);
- {
- char msg[128];
- std::snprintf(msg, sizeof(msg), "%s %s %.4f @ %.2f",
- side == "buy" ? "BUY" : "SELL",
- selected_symbol_.c_str(), qty, fill_price);
- core::notify::send("Order Filled", msg, core::NotifyLevel::Success);
- }
- } else {
- trading::OrderMatcher::instance().add_order(order);
- LOG_INFO(TAG, "Order added to matcher");
- }
-
- // Register SL/TP triggers if provided
- {
- const double sl = (order_form_.sl_price_buf[0] != '\0')
- ? std::atof(order_form_.sl_price_buf) : 0.0;
- const double tp = (order_form_.tp_price_buf[0] != '\0')
- ? std::atof(order_form_.tp_price_buf) : 0.0;
- if ((sl > 0.0 || tp > 0.0) && !order.id.empty()) {
- trading::OrderMatcher::instance().set_sl_tp(
- portfolio_id_, selected_symbol_, order.id, sl, tp);
- }
- }
-
- order_form_.success = "Order placed: " + order.id.substr(0, 8);
- order_form_.msg_timer = 3.0f;
- }
-
- // Ensure the traded symbol is watched for price updates
- trading::ExchangeService::instance().watch_symbol(selected_symbol_, portfolio_id_);
-
- // Clear form
- order_form_.quantity_buf[0] = '\0';
- order_form_.price_buf[0] = '\0';
- order_form_.stop_price_buf[0] = '\0';
- order_form_.sl_price_buf[0] = '\0';
- order_form_.tp_price_buf[0] = '\0';
-
- // Refresh portfolio data immediately
- refresh_portfolio_data();
- } catch (const std::exception& e) {
- order_form_.error = e.what();
- order_form_.msg_timer = 5.0f;
- LOG_ERROR(TAG, "Order FAILED: %s", e.what());
- }
-}
-
-void CryptoTradingScreen::cancel_order(const std::string& order_id) {
- if (trading_mode_ == TradingMode::Live) {
- // Live cancel — route through exchange API
- LOG_INFO(TAG, "Cancelling live order: %s on %s", order_id.c_str(), exchange_id_.c_str());
- const std::string sym = selected_symbol_;
- launch_async(std::thread([this, order_id, sym]() {
- try {
- auto& svc = trading::ExchangeService::instance();
- auto result = svc.cancel_order(order_id, sym);
- LOG_INFO(TAG, "Live order cancelled: %s", result.dump(2).c_str());
- // Refresh live orders
- async_fetch_live_orders();
- } catch (const std::exception& e) {
- LOG_ERROR(TAG, "Live cancel failed: %s", e.what());
- std::lock_guard<std::mutex> lock(data_mutex_);
- order_form_.error = std::string("Cancel failed: ") + e.what();
- order_form_.msg_timer = 5.0f;
- }
- }));
- return;
- }
-
- // Paper cancel
- LOG_INFO(TAG, "Cancelling paper order: %s", order_id.c_str());
- try {
- trading::pt_cancel_order(order_id);
- trading::OrderMatcher::instance().remove_order(order_id);
- refresh_portfolio_data();
- LOG_INFO(TAG, "Order cancelled: %s", order_id.c_str());
- } catch (const std::exception& e) {
- LOG_ERROR(TAG, "Cancel failed: %s", e.what());
- }
-}
-
-// ============================================================================
-// Live trading data fetchers — call exchange API via ExchangeService
-// ============================================================================
-
-void CryptoTradingScreen::async_fetch_live_positions() {
- if (live_positions_fetching_ || !has_credentials_) return;
- live_positions_fetching_ = true;
-
- launch_async(std::thread([this]() {
- try {
- auto& svc = trading::ExchangeService::instance();
- auto result = svc.fetch_positions_live();
- if (result.value("success", false) && result.contains("data")) {
- std::lock_guard<std::mutex> lock(data_mutex_);
- live_positions_.clear();
- auto& positions = result["data"]["positions"];
- if (positions.is_array()) {
- for (const auto& p : positions) {
- LivePosition pos;
- pos.symbol = p.value("symbol", "");
- pos.side = p.value("side", "long");
- pos.quantity = std::abs(p.value("contracts", p.value("contractSize", 0.0)));
- if (pos.quantity == 0.0) pos.quantity = std::abs(p.value("amount", 0.0));
- pos.entry_price = p.value("entryPrice", 0.0);
- pos.current_price = p.value("markPrice", p.value("liquidationPrice", 0.0));
- pos.unrealized_pnl = p.value("unrealizedPnl", 0.0);
- pos.leverage = p.value("leverage", 1.0);
- if (pos.quantity > 0.0) {
- live_positions_.push_back(pos);
- }
- }
- }
- live_data_loaded_ = true;
- }
- } catch (const std::exception& e) {
- LOG_ERROR(TAG, "Live positions fetch failed: %s", e.what());
- }
- live_positions_fetching_ = false;
- }));
-}
-
-void CryptoTradingScreen::async_fetch_live_orders() {
- if (live_orders_fetching_ || !has_credentials_) return;
- live_orders_fetching_ = true;
-
- launch_async(std::thread([this]() {
- try {
- auto& svc = trading::ExchangeService::instance();
- auto result = svc.fetch_open_orders_live();
- if (result.value("success", false) && result.contains("data")) {
- std::lock_guard<std::mutex> lock(data_mutex_);
- live_orders_.clear();
- auto& orders = result["data"]["orders"];
- if (orders.is_array()) {
- for (const auto& o : orders) {
- LiveOrder ord;
- ord.id = o.value("id", "");
- ord.symbol = o.value("symbol", "");
- ord.side = o.value("side", "");
- ord.type = o.value("type", "");
- ord.status = o.value("status", "");
- ord.quantity = o.value("amount", 0.0);
- ord.price = o.value("price", 0.0);
- ord.filled_qty = o.value("filled", 0.0);
- ord.timestamp = o.value("datetime", "");
- live_orders_.push_back(ord);
- }
- }
- }
- } catch (const std::exception& e) {
- LOG_ERROR(TAG, "Live orders fetch failed: %s", e.what());
- }
- live_orders_fetching_ = false;
- }));
-}
-
-void CryptoTradingScreen::async_fetch_live_balance() {
- if (live_balance_fetching_ || !has_credentials_) return;
- live_balance_fetching_ = true;
-
- launch_async(std::thread([this]() {
- try {
- auto& svc = trading::ExchangeService::instance();
- auto result = svc.fetch_balance();
- if (result.value("success", false) && result.contains("data")) {
- std::lock_guard<std::mutex> lock(data_mutex_);
- auto& bal = result["data"];
- // ccxt returns balance as {free: {USDT: x}, used: {USDT: x}, total: {USDT: x}}
- if (bal.contains("total") && bal["total"].is_object()) {
- live_equity_ = bal["total"].value("USDT", bal["total"].value("USD", 0.0));
- }
- if (bal.contains("free") && bal["free"].is_object()) {
- live_balance_ = bal["free"].value("USDT", bal["free"].value("USD", 0.0));
- }
- if (bal.contains("used") && bal["used"].is_object()) {
- live_used_margin_ = bal["used"].value("USDT", bal["used"].value("USD", 0.0));
- }
- }
- } catch (const std::exception& e) {
- LOG_ERROR(TAG, "Live balance fetch failed: %s", e.what());
- }
- live_balance_fetching_ = false;
- }));
-}
-
-void CryptoTradingScreen::async_fetch_live_trades() {
- if (live_trades_fetching_ || !has_credentials_) return;
- live_trades_fetching_ = true;
-
- const std::string sym = selected_symbol_;
- launch_async(std::thread([this, sym]() {
- try {
- auto& svc = trading::ExchangeService::instance();
- auto result = svc.fetch_my_trades_live(sym, 50);
- if (result.value("success", false) && result.contains("data")) {
- std::lock_guard<std::mutex> lock(data_mutex_);
- live_trades_.clear();
- auto& trades = result["data"]["trades"];
- if (trades.is_array()) {
- for (const auto& t : trades) {
- LiveTrade tr;
- tr.id = t.value("id", "");
- tr.symbol = t.value("symbol", sym);
- tr.side = t.value("side", "");
- tr.price = t.value("price", 0.0);
- tr.quantity = t.value("amount", 0.0);
- // fee can be an object {cost: x, currency: y} or a number
- if (t.contains("fee") && t["fee"].is_object()) {
- tr.fee = t["fee"].value("cost", 0.0);
- } else {
- tr.fee = t.value("fee", 0.0);
- }
- tr.timestamp = t.value("datetime", "");
- live_trades_.push_back(tr);
- }
- }
- }
- } catch (const std::exception& e) {
- LOG_ERROR(TAG, "Live trades fetch failed: %s", e.what());
- }
- live_trades_fetching_ = false;
- }));
-}
-
-// ============================================================================
-// Credential Management — store/load API keys per exchange
-// ============================================================================
-
-void CryptoTradingScreen::load_exchange_credentials() {
- std::string service = "exchange_" + exchange_id_;
- auto opt = db::ops::get_credential_by_service(service);
- if (opt) {
- std::strncpy(cred_api_key_, opt->api_key.value_or("").c_str(), sizeof(cred_api_key_) - 1);
- std::strncpy(cred_api_secret_, opt->api_secret.value_or("").c_str(), sizeof(cred_api_secret_) - 1);
- std::strncpy(cred_password_, opt->password.value_or("").c_str(), sizeof(cred_password_) - 1);
-
- has_credentials_ = (cred_api_key_[0] != '\0' && cred_api_secret_[0] != '\0');
-
- // Push to ExchangeService
- if (has_credentials_) {
- trading::ExchangeCredentials ec;
- ec.api_key = cred_api_key_;
- ec.secret = cred_api_secret_;
- ec.password = cred_password_;
- trading::ExchangeService::instance().set_credentials(ec);
- }
- } else {
- cred_api_key_[0] = '\0';
- cred_api_secret_[0] = '\0';
- cred_password_[0] = '\0';
- has_credentials_ = false;
- }
- credentials_loaded_ = true;
-}
-
-void CryptoTradingScreen::save_exchange_credentials() {
- std::string service = "exchange_" + exchange_id_;
-
- db::Credential c;
- c.service_name = service;
- c.api_key = std::string(cred_api_key_);
- c.api_secret = std::string(cred_api_secret_);
- c.password = std::string(cred_password_);
- db::ops::save_credential(c);
-
- has_credentials_ = (cred_api_key_[0] != '\0' && cred_api_secret_[0] != '\0');
-
- // Push to ExchangeService
- if (has_credentials_) {
- trading::ExchangeCredentials ec;
- ec.api_key = cred_api_key_;
- ec.secret = cred_api_secret_;
- ec.password = cred_password_;
- trading::ExchangeService::instance().set_credentials(ec);
-
- // Trigger initial live data fetch
- if (trading_mode_ == TradingMode::Live) {
- async_fetch_live_balance();
- async_fetch_live_positions();
- async_fetch_live_orders();
- }
- }
-
- LOG_INFO(TAG, "Credentials saved for %s (has_key=%d)", exchange_id_.c_str(), has_credentials_);
-}
-
-bool CryptoTradingScreen::has_credentials() const {
- return has_credentials_;
-}
-
-void CryptoTradingScreen::render_credentials_popup() {
- if (!show_credentials_popup_) return;
-
- ImGui::SetNextWindowSize(ImVec2(420, 320), ImGuiCond_FirstUseEver);
- if (ImGui::Begin("Exchange API Credentials", &show_credentials_popup_,
- ImGuiWindowFlags_NoCollapse | ImGuiWindowFlags_NoDocking)) {
-
- // Exchange name header
- char header[128];
- std::snprintf(header, sizeof(header), "Configure API Key for: %s", exchange_id_.c_str());
- ImGui::TextColored(ACCENT, "%s", header);
- ImGui::Separator();
- ImGui::Spacing();
-
- float input_w = ImGui::GetContentRegionAvail().x - 16;
-
- // API Key
- ImGui::TextColored(TEXT_DIM, "API Key");
- ImGui::PushItemWidth(input_w);
- ImGui::PushStyleColor(ImGuiCol_FrameBg, BG_INPUT);
- ImGui::InputText("##cred_api_key", cred_api_key_, sizeof(cred_api_key_));
- ImGui::PopStyleColor();
- ImGui::PopItemWidth();
-
- ImGui::Spacing();
-
- // API Secret
- ImGui::TextColored(TEXT_DIM, "API Secret");
- ImGui::PushItemWidth(input_w);
- ImGui::PushStyleColor(ImGuiCol_FrameBg, BG_INPUT);
- ImGui::InputText("##cred_api_secret", cred_api_secret_, sizeof(cred_api_secret_),
- ImGuiInputTextFlags_Password);
- ImGui::PopStyleColor();
- ImGui::PopItemWidth();
-
- ImGui::Spacing();
-
- // Password (for exchanges that require it: OKX, Kucoin, etc.)
- bool needs_password = (exchange_id_ == "okx" || exchange_id_ == "kucoin" ||
- exchange_id_ == "gate" || exchange_id_ == "bitget");
- if (needs_password) {
- ImGui::TextColored(TEXT_DIM, "Passphrase / Password");
- ImGui::PushItemWidth(input_w);
- ImGui::PushStyleColor(ImGuiCol_FrameBg, BG_INPUT);
- ImGui::InputText("##cred_password", cred_password_, sizeof(cred_password_),
- ImGuiInputTextFlags_Password);
- ImGui::PopStyleColor();
- ImGui::PopItemWidth();
- ImGui::Spacing();
- }
-
- // Status
- if (has_credentials_) {
- ImGui::TextColored(MARKET_GREEN, "Credentials configured");
- } else {
- ImGui::TextColored(TEXT_DIM, "No credentials stored for this exchange");
- }
-
- ImGui::Spacing();
- ImGui::Separator();
- ImGui::Spacing();
-
- // Buttons
- float btn_w = (input_w - 12) / 3;
-
- ImGui::PushStyleColor(ImGuiCol_Button, ImVec4(0.0f, 0.5f, 0.25f, 1.0f));
- ImGui::PushStyleColor(ImGuiCol_Text, TEXT_PRIMARY);
- if (ImGui::Button("Save", ImVec2(btn_w, 28))) {
- save_exchange_credentials();
- show_credentials_popup_ = false;
- }
- ImGui::PopStyleColor(2);
-
- ImGui::SameLine(0, 6);
-
- ImGui::PushStyleColor(ImGuiCol_Button, ImVec4(0.5f, 0.1f, 0.1f, 1.0f));
- ImGui::PushStyleColor(ImGuiCol_Text, TEXT_PRIMARY);
- if (ImGui::Button("Clear", ImVec2(btn_w, 28))) {
- cred_api_key_[0] = '\0';
- cred_api_secret_[0] = '\0';
- cred_password_[0] = '\0';
- save_exchange_credentials();
- has_credentials_ = false;
- }
- ImGui::PopStyleColor(2);
-
- ImGui::SameLine(0, 6);
-
- ImGui::PushStyleColor(ImGuiCol_Button, BG_WIDGET);
- ImGui::PushStyleColor(ImGuiCol_Text, TEXT_DIM);
- if (ImGui::Button("Cancel", ImVec2(btn_w, 28))) {
- show_credentials_popup_ = false;
- }
- ImGui::PopStyleColor(2);
-
- ImGui::Spacing();
-
- // Security note
- ImGui::PushStyleColor(ImGuiCol_Text, TEXT_DIM);
- ImGui::TextWrapped("Credentials are stored encrypted in the local database. "
- "Use read-only API keys when possible.");
- ImGui::PopStyleColor();
- }
- ImGui::End();
-}
-
-} // namespace fincept::crypto
+// crypto_trading_screen.cpp — split into focused files.
+// This file is intentionally empty; all implementations live in:
+// crypto_lifecycle.cpp — init, destructor, exchange/symbol switching, WS, data fetch
+// crypto_screen.cpp — render(), render_top_nav, render_ticker_bar, render_status_bar
+// crypto_watchlist.cpp — render_watchlist
+// crypto_chart.cpp — render_chart_area, render_candlestick_chart, render_bottom_panel
+// crypto_bottom_tabs.cpp — positions/orders/history/stats/trades/market_info tabs
+// crypto_order_entry.cpp — render_order_entry, render_orderbook, OB view modes
+// crypto_order_actions.cpp — submit_order, cancel_order, live data fetchers
+// crypto_credentials.cpp — load/save/has credentials, render_credentials_popup
diff --git a/fincept-cpp/src/screens/crypto_trading/crypto_watchlist.cpp b/fincept-cpp/src/screens/crypto_trading/crypto_watchlist.cpp
new file mode 100644
index 000000000..22e63ebce
--- /dev/null
+++ b/fincept-cpp/src/screens/crypto_trading/crypto_watchlist.cpp
@@ -0,0 +1,242 @@
+#include "crypto_trading_screen.h"
+#include "crypto_internal.h"
+#include "ui/theme.h"
+#include "trading/exchange_service.h"
+#include "core/logger.h"
+#include <imgui.h>
+#include <algorithm>
+
+namespace fincept::crypto {
+
+using namespace theme::colors;
+
+void CryptoTradingScreen::render_watchlist(float w, float h) {
+ ImGui::PushStyleColor(ImGuiCol_ChildBg, BG_PANEL);
+ ImGui::BeginChild("##crypto_watchlist", ImVec2(w, h), true);
+
+ // Header
+ ImGui::TextColored(ACCENT, "WATCHLIST");
+ ImGui::SameLine();
+
+ int loaded = 0;
+ {
+ std::lock_guard<std::mutex> lock(data_mutex_);
+ for (auto& w : watchlist_) if (w.has_data) loaded++;
+ }
+ ImGui::TextColored(TEXT_DIM, "(%d/%d)", loaded, (int)watchlist_.size());
+
+ if (wl_fetching_) {
+ ImGui::SameLine();
+ ImGui::TextColored(WARNING, "[*]");
+ }
+
+ // Search / Filter field
+ ImGui::PushItemWidth(-1);
+ ImGui::PushStyleColor(ImGuiCol_FrameBg, BG_INPUT);
+ bool search_changed = ImGui::InputTextWithHint("##wl_filter", "Search symbol...",
+ watchlist_filter_, sizeof(watchlist_filter_));
+ ImGui::PopStyleColor();
+ ImGui::PopItemWidth();
+
+ std::string filter_str(watchlist_filter_);
+ for (auto& c : filter_str) c = (char)std::toupper((unsigned char)c);
+
+ // Fetch exchange markets for search (lazy, cached per exchange)
+ if (search_changed && filter_str.length() >= 2 && !search_fetching_) {
+ // Load markets if not cached for this exchange
+ if (search_cache_exchange_ != exchange_id_ || !search_markets_loaded_) {
+ search_fetching_ = true;
+ std::string ex_id = exchange_id_;
+ launch_async(std::thread([this, ex_id]() {
+ try {
+ auto markets = trading::ExchangeService::instance().fetch_markets("spot");
+ LOG_INFO(TAG, "Loaded %d markets for search from %s",
+ (int)markets.size(), ex_id.c_str());
+ std::lock_guard<std::mutex> lock(data_mutex_);
+ all_markets_ = std::move(markets);
+ search_cache_exchange_ = ex_id;
+ search_markets_loaded_ = true;
+ } catch (const std::exception& e) {
+ LOG_ERROR(TAG, "Failed to load markets for search: %s", e.what());
+ }
+ search_fetching_ = false;
+ }));
+ }
+ }
+
+ // Build search results from cached markets
+ bool has_search = filter_str.length() >= 2 && search_markets_loaded_;
+ std::vector<trading::MarketInfo> filtered_markets;
+ if (has_search) {
+ std::lock_guard<std::mutex> lock(data_mutex_);
+ int count = 0;
+ for (const auto& m : all_markets_) {
+ if (!m.active) continue;
+ std::string sym_upper = m.symbol;
+ for (auto& c : sym_upper) c = (char)std::toupper((unsigned char)c);
+ if (sym_upper.find(filter_str) != std::string::npos) {
+ // Skip if already in watchlist
+ bool in_wl = false;
+ for (const auto& w : watchlist_) {
+ if (w.symbol == m.symbol) { in_wl = true; break; }
+ }
+ if (!in_wl) {
+ filtered_markets.push_back(m);
+ if (++count >= 20) break; // limit results
+ }
+ }
+ }
+ }
+
+ ImGui::Separator();
+
+ // Scrollable list
+ ImGui::BeginChild("##wl_scroll", ImVec2(0, 0), false);
+
+ char buf[64];
+ std::lock_guard<std::mutex> lock(data_mutex_);
+
+ // --- Watchlist entries ---
+ for (int i = 0; i < (int)watchlist_.size(); i++) {
+ auto& entry = watchlist_[i];
+
+ // Filter check
+ if (!filter_str.empty()) {
+ std::string sym_upper = entry.symbol;
+ for (auto& c : sym_upper) c = (char)std::toupper((unsigned char)c);
+ if (sym_upper.find(filter_str) == std::string::npos) continue;
+ }
+
+ bool is_selected = (entry.symbol == selected_symbol_);
+ ImGui::PushID(i);
+
+ ImGui::PushStyleColor(ImGuiCol_Header, BG_WIDGET);
+ ImGui::PushStyleColor(ImGuiCol_HeaderHovered, BG_HOVER);
+
+ if (ImGui::Selectable("##wl_sel", is_selected, ImGuiSelectableFlags_SpanAllColumns, ImVec2(0, 22))) {
+ watchlist_selected_ = i;
+ switch_symbol(entry.symbol);
+ }
+
+ ImGui::PopStyleColor(2);
+
+ // Draw content over the selectable
+ ImGui::SameLine(4);
+
+ // Symbol name (truncate base only)
+ std::string base = entry.symbol;
+ auto slash = base.find('/');
+ if (slash != std::string::npos) base = base.substr(0, slash);
+ ImGui::TextColored(TEXT_PRIMARY, "%s", base.c_str());
+
+ if (entry.has_data) {
+ // Price on right
+ if (entry.price > 1.0)
+ std::snprintf(buf, sizeof(buf), "%.2f", entry.price);
+ else if (entry.price > 0.01)
+ std::snprintf(buf, sizeof(buf), "%.4f", entry.price);
+ else
+ std::snprintf(buf, sizeof(buf), "%.6f", entry.price);
+
+ ImVec4 col = entry.change_pct >= 0 ? MARKET_GREEN : MARKET_RED;
+
+ // Change % next to symbol
+ ImGui::SameLine(0, 4);
+ char pct_buf[16];
+ std::snprintf(pct_buf, sizeof(pct_buf), "%.1f%%", entry.change_pct);
+ ImGui::TextColored(col, "%s", pct_buf);
+
+ // Price on far right
+ float price_w = ImGui::CalcTextSize(buf).x;
+ float avail = ImGui::GetContentRegionAvail().x;
+ if (avail > price_w + 4) {
+ ImGui::SameLine(w - price_w - 16);
+ ImGui::TextColored(col, "%s", buf);
+ }
+ } else {
+ float avail = ImGui::GetContentRegionAvail().x;
+ if (avail > 20) {
+ ImGui::SameLine(w - 30);
+ ImGui::TextColored(TEXT_DIM, "...");
+ }
+ }
+
+ ImGui::PopID();
+ }
+
+ // --- Exchange search results (symbols not in watchlist) ---
+ if (!filtered_markets.empty()) {
+ ImGui::Separator();
+ ImGui::TextColored(TEXT_DIM, "Exchange results:");
+ ImGui::Spacing();
+
+ for (int i = 0; i < (int)filtered_markets.size(); i++) {
+ const auto& m = filtered_markets[i];
+ ImGui::PushID(10000 + i);
+
+ ImGui::PushStyleColor(ImGuiCol_Header, ImVec4(0.1f, 0.15f, 0.2f, 1.0f));
+ ImGui::PushStyleColor(ImGuiCol_HeaderHovered, BG_HOVER);
+
+ if (ImGui::Selectable("##search_sel", false, ImGuiSelectableFlags_SpanAllColumns, ImVec2(0, 22))) {
+ // Add to watchlist
+ WatchlistEntry new_entry;
+ new_entry.symbol = m.symbol;
+ watchlist_.push_back(new_entry);
+ watchlist_selected_ = (int)watchlist_.size() - 1;
+ LOG_INFO(TAG, "Added %s to watchlist from search", m.symbol.c_str());
+
+ // Clear search field
+ watchlist_filter_[0] = '\0';
+
+ // Defer symbol switch — we hold data_mutex_ here,
+ // switch_symbol() will run in the render loop next frame
+ pending_symbol_switch_ = m.symbol;
+ }
+
+ ImGui::PopStyleColor(2);
+
+ ImGui::SameLine(4);
+
+ // Show base/quote
+ std::string base = m.base;
+ ImGui::TextColored(ACCENT, "%s", base.c_str());
+ ImGui::SameLine(0, 2);
+ ImGui::TextColored(TEXT_DIM, "/%s", m.quote.c_str());
+
+ // Type on right
+ float type_w = ImGui::CalcTextSize(m.type.c_str()).x;
+ float avail = ImGui::GetContentRegionAvail().x;
+ if (avail > type_w + 4) {
+ ImGui::SameLine(w - type_w - 16);
+ ImGui::TextColored(TEXT_DIM, "%s", m.type.c_str());
+ }
+
+ ImGui::PopID();
+ }
+ } else if (filter_str.length() >= 2 && search_fetching_) {
+ ImGui::Separator();
+ ImGui::TextColored(TEXT_DIM, "Searching...");
+ } else if (filter_str.length() >= 2 && search_markets_loaded_ && filtered_markets.empty()) {
+ // Check if all matches are in watchlist already
+ bool any_watchlist_match = false;
+ for (const auto& w : watchlist_) {
+ std::string sym_upper = w.symbol;
+ for (auto& c : sym_upper) c = (char)std::toupper((unsigned char)c);
+ if (sym_upper.find(filter_str) != std::string::npos) {
+ any_watchlist_match = true;
+ break;
+ }
+ }
+ if (!any_watchlist_match) {
+ ImGui::Separator();
+ ImGui::TextColored(TEXT_DIM, "No results");
+ }
+ }
+
+ ImGui::EndChild();
+ ImGui::EndChild();
+ ImGui::PopStyleColor();
+}
+
+
+} // namespace fincept::crypto