FinceptTerminal is a modern finance application offering advanced market analytics, investment research, and economic data tools, designed for interactive exploration and data-driven decision-making in a user-friendly environment.
C++ ai-agentsalgorithmic-tradingbloomberg-terminalcppfinancefinancial-marketsfintechgood-first-issueinvestmentinvestment-researchmachine-learningopensourcepythonqtquantitative-financestock-markettrading
agent updates
tilakpatel224e236b90b392
diff --git a/README.md b/README.mdindex 73cb2c846..c2273668a 100644--- a/README.md+++ b/README.md@@ -18,6 +18,15 @@ State-of-the-art financial intelligence platform with CFA-level analytics, AI au+<table>+ <tr>+ <td align="center" width="25%"><a href="https://raw.githubusercontent.com/Fincept-Corporation/FinceptTerminal/main/images/EquityResearch.png"><img src="https://raw.githubusercontent.com/Fincept-Corporation/FinceptTerminal/main/images/EquityResearch.png" width="100%"/></a><br/><sub><b>Equity Research</b></sub></td>+ <td align="center" width="25%"><a href="https://raw.githubusercontent.com/Fincept-Corporation/FinceptTerminal/main/images/Portfolio.png"><img src="https://raw.githubusercontent.com/Fincept-Corporation/FinceptTerminal/main/images/Portfolio.png" width="100%"/></a><br/><sub><b>Portfolio</b></sub></td>+ <td align="center" width="25%"><a href="https://raw.githubusercontent.com/Fincept-Corporation/FinceptTerminal/main/images/News.png"><img src="https://raw.githubusercontent.com/Fincept-Corporation/FinceptTerminal/main/images/News.png" width="100%"/></a><br/><sub><b>News</b></sub></td>+ <td align="center" width="25%"><a href="https://raw.githubusercontent.com/Fincept-Corporation/FinceptTerminal/main/images/NodeEditor.png"><img src="https://raw.githubusercontent.com/Fincept-Corporation/FinceptTerminal/main/images/NodeEditor.png" width="100%"/></a><br/><sub><b>Node Editor</b></sub></td>+ </tr>+</table>+</div>---diff --git a/fincept-qt/.claude/scheduled_tasks.lock b/fincept-qt/.claude/scheduled_tasks.locknew file mode 100644index 000000000..19a455c6a--- /dev/null+++ b/fincept-qt/.claude/scheduled_tasks.lock@@ -0,0 +1 @@+{"sessionId":"54076053-ea32-4933-b1f9-939dc29ceb71","pid":7040,"acquiredAt":1776441988628}\ No newline at end of filediff --git a/fincept-qt/CMakeLists.txt b/fincept-qt/CMakeLists.txtindex 0cc87a6c3..c13a2a615 100644--- a/fincept-qt/CMakeLists.txt+++ b/fincept-qt/CMakeLists.txt@@ -61,9 +61,13 @@ set(CMAKE_UNITY_BUILD ON)# 32 was too large: one TU change forced a 32-file recompile; 14 limits blast radius.set(CMAKE_UNITY_BUILD_BATCH_SIZE 14)-# FetchContent: after first successful download, never hit the network again.-# Cuts configure time by 5-15s on incremental configures (no git fetch for 5 deps).-set(FETCHCONTENT_UPDATES_DISCONNECTED ON CACHE BOOL "" FORCE)+# FetchContent: default to skipping the update step after first download to cut+# configure time by 5-15s on incremental configures. Not FORCEd so developers+# can toggle it off (-DFETCHCONTENT_UPDATES_DISCONNECTED=OFF) when a GIT_TAG is+# bumped to a commit not yet present in the local clone — otherwise the build+# wedges with "Requested git ref ... is not present locally". CMake docs:+# https://cmake.org/cmake/help/latest/module/FetchContent.html#variable:FETCHCONTENT_UPDATES_DISCONNECTED+set(FETCHCONTENT_UPDATES_DISCONNECTED ON CACHE BOOL "Skip FetchContent update step after initial download")# MSVC compiler flags for maximum build throughput:# /MP — multi-processor compilation (uses all logical cores within one project)@@ -112,11 +116,11 @@ endif()add_compile_definitions(NOMINMAX WIN32_LEAN_AND_MEAN)# ── Qt packages ──────────────────────────────────────────────────────────────-# Qt is pinned to 6.7.2 (LTS track) across all platforms. Releases must build+# Qt is pinned to 6.8.3 across all platforms. Releases must build# on exactly this version to guarantee binary/ABI stability of the shipped# installer. Developers may override for local experimentation with# -DFINCEPT_ALLOW_QT_DRIFT=ON (not for CI or release builds).-set(FINCEPT_QT_VERSION 6.7.2)+set(FINCEPT_QT_VERSION 6.8.3)if(FINCEPT_ALLOW_QT_DRIFT)find_package(Qt6 REQUIRED COMPONENTSWidgets Charts PrintSupport Network Sql Concurrent Multimedia)@@ -299,7 +303,7 @@ if(MSVC)target_compile_options(SingleApplication PRIVATE /W0)endif()-# ── Qt Advanced Docking System (Bloomberg-style detachable panels) ────────────+# ── Qt Advanced Docking System (detachable panels) ───────────────────────────# Panels become CDockWidgets — drag to float, dock, move to any monitor.# LGPL — compatible with AGPL. Used in Qt Creator itself.set(BUILD_EXAMPLES OFF CACHE BOOL "" FORCE)@@ -490,6 +494,9 @@ set(TRADING_SOURCESsrc/trading/websocket/AngelOneWebSocket.cpp# Indian brokerssrc/trading/brokers/zerodha/ZerodhaBroker.cpp+ src/trading/brokers/zerodha/Totp.cpp+ src/trading/brokers/zerodha/ZerodhaAutoLogin.cpp+ src/trading/auth/RedirectServer.cppsrc/trading/brokers/angelone/AngelOneBroker.cppsrc/trading/brokers/fyers/FyersBroker.cppsrc/trading/brokers/upstox/UpstoxBroker.cpp@@ -510,6 +517,7 @@ set(TRADING_SOURCES# Instrument system (Phase 1)src/trading/instruments/InstrumentRepository.cppsrc/trading/instruments/ZerodhaInstrumentParser.cpp+ src/trading/instruments/GrowwInstrumentParser.cppsrc/trading/instruments/InstrumentService.cpp)@@ -729,7 +737,6 @@ set(SCREEN_SOURCESsrc/screens/equity_trading/EquityOrderEntry.cppsrc/screens/equity_trading/EquityOrderBook.cppsrc/screens/equity_trading/EquityBottomPanel.cpp- src/screens/equity_trading/EquityCredentials.cppsrc/screens/equity_trading/AccountManagementDialog.cppsrc/screens/equity_trading/BroadcastOrderDialog.cppsrc/screens/data_sources/DataSourcesScreen.cpp@@ -996,7 +1003,6 @@ set_source_files_properties(src/screens/equity_trading/EquityOrderEntry.cppsrc/screens/equity_trading/EquityOrderBook.cppsrc/screens/equity_trading/EquityBottomPanel.cpp- src/screens/equity_trading/EquityCredentials.cppsrc/screens/equity_trading/AccountManagementDialog.cppsrc/screens/equity_trading/BroadcastOrderDialog.cppsrc/screens/data_sources/DataSourcesScreen.cpp@@ -1217,6 +1223,9 @@ set_source_files_properties(src/trading/websocket/AngelOneWebSocket.cpp# Trading broker files — each defines static now_ts() in same namespacesrc/trading/brokers/zerodha/ZerodhaBroker.cpp+ src/trading/brokers/zerodha/Totp.cpp+ src/trading/brokers/zerodha/ZerodhaAutoLogin.cpp+ src/trading/auth/RedirectServer.cppsrc/trading/brokers/angelone/AngelOneBroker.cppsrc/trading/brokers/fyers/FyersBroker.cppsrc/trading/brokers/upstox/UpstoxBroker.cpp@@ -1277,6 +1286,9 @@ set_source_files_properties(# ODR collision if batched, must stay excluded from unityset_source_files_properties(src/trading/brokers/zerodha/ZerodhaBroker.cpp+ src/trading/brokers/zerodha/Totp.cpp+ src/trading/brokers/zerodha/ZerodhaAutoLogin.cpp+ src/trading/auth/RedirectServer.cppsrc/trading/brokers/angelone/AngelOneBroker.cppsrc/trading/brokers/fyers/FyersBroker.cppsrc/trading/brokers/upstox/UpstoxBroker.cppdiff --git a/fincept-qt/scripts/fdic_fetcher.py b/fincept-qt/scripts/fdic_fetcher.pyindex 5859cc904..504eddbcd 100644--- a/fincept-qt/scripts/fdic_fetcher.py+++ b/fincept-qt/scripts/fdic_fetcher.py@@ -129,8 +129,6 @@ class FDICWrapper:"""Get summary demographic information."""return self._fetch_all("demographics", filters, max_records=max_records)-# ===== TAURI CLI HANDLER =====-def main():"""CLI Entry point for C++. Outputs minified JSON to stdout."""if len(sys.argv) < 2:diff --git a/fincept-qt/src/app/MainWindow.cpp b/fincept-qt/src/app/MainWindow.cppindex 7c744117c..63cba57e1 100644--- a/fincept-qt/src/app/MainWindow.cpp+++ b/fincept-qt/src/app/MainWindow.cpp@@ -942,6 +942,7 @@ void MainWindow::on_auth_state_changed() {// Runs concurrently while the user reads the dashboard (3-5s head start).fincept::trading::InstrumentService::instance().load_from_db_async("zerodha");fincept::trading::InstrumentService::instance().load_from_db_async("angelone");+ fincept::trading::InstrumentService::instance().load_from_db_async("groww");} else {// Free/no plan → show pricing gateset_shell_visible(false);diff --git a/fincept-qt/src/core/session/SessionManager.h b/fincept-qt/src/core/session/SessionManager.hindex d1d460cce..6a5857d2d 100644--- a/fincept-qt/src/core/session/SessionManager.h+++ b/fincept-qt/src/core/session/SessionManager.h@@ -37,7 +37,7 @@ class SessionManager : public QObject {void set_dock_layout_version(int window_id, int version);int dock_layout_version(int window_id) const;- // Named perspectives (Bloomberg-style saved layouts)+ // Named perspectives (saved layouts)void save_perspectives(QSettings& source);void load_perspectives(QSettings& target) const;diff --git a/fincept-qt/src/screens/code_editor/CodeEditorScreen.cpp b/fincept-qt/src/screens/code_editor/CodeEditorScreen.cppindex 0e741a70c..89f83ce5e 100644--- a/fincept-qt/src/screens/code_editor/CodeEditorScreen.cpp+++ b/fincept-qt/src/screens/code_editor/CodeEditorScreen.cpp@@ -1,5 +1,5 @@// src/screens/code_editor/CodeEditorScreen.cpp-// Bloomberg-style Python Colab — Obsidian design system implementation.+// Python Colab — Obsidian design system implementation.// Responsive cells, markdown rendering, keyboard shortcuts, collapsible output.#include "screens/code_editor/CodeEditorScreen.h"diff --git a/fincept-qt/src/screens/code_editor/CodeEditorScreen.h b/fincept-qt/src/screens/code_editor/CodeEditorScreen.hindex 06dda7812..d58945060 100644--- a/fincept-qt/src/screens/code_editor/CodeEditorScreen.h+++ b/fincept-qt/src/screens/code_editor/CodeEditorScreen.h@@ -1,5 +1,5 @@// src/screens/code_editor/CodeEditorScreen.h-// Bloomberg-style Python Colab — Jupyter notebook with Obsidian design system.+// Python Colab — Jupyter notebook with Obsidian design system.// Responsive cells, markdown rendering, keyboard shortcuts, collapsible output.#pragma oncediff --git a/fincept-qt/src/screens/crypto_trading/CryptoBottomPanel.cpp b/fincept-qt/src/screens/crypto_trading/CryptoBottomPanel.cppindex 3ec5c3d00..c2c7c111f 100644--- a/fincept-qt/src/screens/crypto_trading/CryptoBottomPanel.cpp+++ b/fincept-qt/src/screens/crypto_trading/CryptoBottomPanel.cpp@@ -1,4 +1,4 @@-// CryptoBottomPanel.cpp — Bloomberg-style tabbed panel with Time&Sales and Depth Chart+// CryptoBottomPanel.cpp — tabbed panel with Time&Sales and Depth Chart#include "screens/crypto_trading/CryptoBottomPanel.h"#include "screens/crypto_trading/CryptoDepthChart.h"@@ -206,14 +206,21 @@ void CryptoBottomPanel::set_positions(const QVector<trading::PtPosition>& positiconst auto& pos = positions[i];const QColor bg = (i % 2 == 0) ? kRowEven() : kRowOdd();+ // Diff every attribute — this table updates at 10 Hz on the paper+ // bookkeeping flush, and only P&L + current_price actually change per+ // tick. Skipping untouched cells cuts the repaint footprint sharply.auto set = [&](int col, const QString& text, const QColor& fg = QColor(),int align = Qt::AlignLeft | Qt::AlignVCenter) {auto* it = ensure_item(positions_table_, i, col);- it->setText(text);- if (fg.isValid())+ if (it->text() != text)+ it->setText(text);+ const QColor cur_fg = it->foreground().color();+ if (fg.isValid() && (it->foreground().style() == Qt::NoBrush || cur_fg != fg))it->setForeground(fg);- it->setBackground(bg);- it->setTextAlignment(align);+ if (it->background().color() != bg)+ it->setBackground(bg);+ if (it->textAlignment() != align)+ it->setTextAlignment(align);};set(0, pos.symbol);diff --git a/fincept-qt/src/screens/crypto_trading/CryptoChart.cpp b/fincept-qt/src/screens/crypto_trading/CryptoChart.cppindex 568a712a6..61388e864 100644--- a/fincept-qt/src/screens/crypto_trading/CryptoChart.cpp+++ b/fincept-qt/src/screens/crypto_trading/CryptoChart.cpp@@ -142,6 +142,7 @@ void CryptoChart::append_candle(const trading::Candle& candle) {const bool is_update = !candles_.isEmpty() && candles_.last().timestamp == candle.timestamp;if (is_update) {+ const trading::Candle prev = candles_.last();candles_.last() = candle;if (!sets.isEmpty()) {auto* last_set = sets.last();@@ -150,6 +151,16 @@ void CryptoChart::append_candle(const trading::Candle& candle) {last_set->setLow(candle.low);last_set->setClose(candle.close);}+ // Intrabar update: if the replaced candle defined the current extreme,+ // bounds may shrink — mark dirty. Otherwise cheap widen-only.+ if (!bounds_dirty_) {+ if (prev.high >= cached_max_price_ || prev.low <= cached_min_price_) {+ bounds_dirty_ = true;+ } else {+ cached_max_price_ = std::max(cached_max_price_, candle.high);+ cached_min_price_ = std::min(cached_min_price_, candle.low);+ }+ }} else {candles_.append(candle);if (candles_.size() > MAX_VISIBLE * 2) {@@ -157,32 +168,62 @@ void CryptoChart::append_candle(const trading::Candle& candle) {rebuild_chart();return;}- if (sets.size() >= MAX_VISIBLE)+ if (sets.size() >= MAX_VISIBLE) {+ // Evicting the oldest set may drop the current extreme — mark dirty+ // so we rescan exactly once on the next axis update.+ const auto* oldest = sets.first();+ if (!bounds_dirty_ &&+ (oldest->low() <= cached_min_price_ || oldest->high() >= cached_max_price_)) {+ bounds_dirty_ = true;+ }series_->remove(sets.first());+ }series_->append(new QCandlestickSet(candle.open, candle.high, candle.low, candle.close, candle.timestamp));++ // Widen-only for new candle if bounds are clean.+ if (!bounds_dirty_) {+ cached_max_price_ = std::max(cached_max_price_, candle.high);+ cached_min_price_ = std::min(cached_min_price_, candle.low);+ }}const auto& visible_sets = series_->sets();if (visible_sets.isEmpty())return;- double min_price = 1e18, max_price = 0;- qint64 min_time = INT64_MAX, max_time = 0;- for (const auto* s : visible_sets) {- min_price = std::min(min_price, s->low());- max_price = std::max(max_price, s->high());- const qint64 ts = static_cast<qint64>(s->timestamp());- if (ts < min_time)- min_time = ts;- if (ts > max_time)- max_time = ts;+ if (bounds_dirty_)+ recompute_bounds();++ // Time axis — min is O(1) from sets.first, max from last. Sets stay ordered+ // by insertion which matches timestamp order for this use case.+ const qint64 min_time = static_cast<qint64>(visible_sets.first()->timestamp());+ const qint64 max_time = static_cast<qint64>(visible_sets.last()->timestamp());+ update_axes(cached_min_price_, cached_max_price_, min_time, max_time);+}++void CryptoChart::recompute_bounds() {+ const auto& sets = series_->sets();+ if (sets.isEmpty()) {+ cached_min_price_ = -1;+ cached_max_price_ = -1;+ bounds_dirty_ = false;+ return;}- update_axes(min_price, max_price, min_time, max_time);+ double mn = 1e18, mx = 0;+ for (const auto* s : sets) {+ mn = std::min(mn, s->low());+ mx = std::max(mx, s->high());+ }+ cached_min_price_ = mn;+ cached_max_price_ = mx;+ bounds_dirty_ = false;}void CryptoChart::clear() {candles_.clear();series_->clear();+ cached_min_price_ = cached_max_price_ = -1;+ bounds_dirty_ = true;}void CryptoChart::update_axes(double min_price, double max_price, qint64 min_time, qint64 max_time) {@@ -232,6 +273,8 @@ void CryptoChart::rebuild_chart() {series_->clear();last_min_price_ = last_max_price_ = -1;last_min_time_ = last_max_time_ = -1;+ cached_min_price_ = cached_max_price_ = -1;+ bounds_dirty_ = true;if (candles_.isEmpty())return;@@ -256,6 +299,13 @@ void CryptoChart::rebuild_chart() {max_time = c.timestamp;}+ // Seed the incremental-bounds cache from this full scan.+ if (min_price < max_price) {+ cached_min_price_ = min_price;+ cached_max_price_ = max_price;+ bounds_dirty_ = false;+ }+update_axes(min_price, max_price, min_time, max_time);}diff --git a/fincept-qt/src/screens/crypto_trading/CryptoChart.h b/fincept-qt/src/screens/crypto_trading/CryptoChart.hindex 69218c52a..f826bc97f 100644--- a/fincept-qt/src/screens/crypto_trading/CryptoChart.h+++ b/fincept-qt/src/screens/crypto_trading/CryptoChart.h@@ -48,12 +48,19 @@ class CryptoChart : public QWidget {QVector<trading::Candle> candles_;static constexpr int MAX_VISIBLE = 120;- // Axis range cache+ // Axis range cache (padded values actually applied to the axis)double last_min_price_ = -1;double last_max_price_ = -1;qint64 last_min_time_ = -1;qint64 last_max_time_ = -1;+ // Incremental price bounds over visible candle set — avoids O(N) rescans+ // on every intrabar tick. -1 means "stale, recompute on next append".+ double cached_min_price_ = -1;+ double cached_max_price_ = -1;+ bool bounds_dirty_ = true;+ void recompute_bounds();+// Pending timeframe request while a fetch is already in-flight// set_candles() will emit timeframe_changed again if this is setQString pending_tf_;diff --git a/fincept-qt/src/screens/crypto_trading/CryptoCredentials.cpp b/fincept-qt/src/screens/crypto_trading/CryptoCredentials.cppindex 7bb1070ee..dc4e9e547 100644--- a/fincept-qt/src/screens/crypto_trading/CryptoCredentials.cpp+++ b/fincept-qt/src/screens/crypto_trading/CryptoCredentials.cpp@@ -8,18 +8,54 @@#include <QJsonDocument>#include <QJsonObject>#include <QPushButton>+#include <QStyle>#include <QTimer>#include <QVBoxLayout>using namespace fincept::ui;-// Obsidian Design System input style+// Single dialog-level stylesheet using objectName selectors — 18+ inline+// setStyleSheet calls collapsed into one CSS parse. Applied in the ctor.namespace {-static QString kInputStyle() {- return QString("QLineEdit { background: %1; border: 1px solid %2; color: %3; padding: 6px; "- "font-size: 13px; font-family: 'Consolas', 'Courier New', monospace; }"- "QLineEdit:focus { border-color: %4; }")- .arg(colors::BG_SURFACE(), colors::BORDER_DIM(), colors::TEXT_PRIMARY(), colors::BORDER_BRIGHT());+static QString kDialogStyle() {+ const QString mono = "'Consolas', 'Courier New', monospace";+ return QString(+ // Dialog background+ "QDialog { background: %1; color: %2; font-family: %13; }"+ // Inputs (API key/secret/password/TOTP)+ "QLineEdit { background: %3; border: 1px solid %4; color: %2; padding: 6px; "+ " font-size: 13px; font-family: %13; }"+ "QLineEdit:focus { border-color: %5; }"+ // Labels by role+ "QLabel#credTitle { color: %6; font-size: 14px; font-weight: 700; letter-spacing: 0.5px; font-family: %13; }"+ "QLabel#credInfo { color: %7; font-size: 12px; font-family: %13; }"+ "QLabel#credFieldLabel { color: %7; font-size: 12px; font-weight: 700; letter-spacing: 0.5px; font-family: %13; }"+ "QLabel#credTotpCode { color: %6; font-size: 18px; font-weight: 700; letter-spacing: 2px; font-family: %13; }"+ "QLabel#credTotpCountdown { color: %8; font-size: 11px; font-family: %13; }"+ "QLabel#credStatusErr { color: %9; font-size: 12px; font-family: %13; }"+ "QLabel#credStatusOk { color: %10; font-size: 12px; font-family: %13; }"+ "QLabel#credStatusWarn { color: %11; font-size: 12px; font-family: %13; }"+ // Buttons+ "QPushButton#credClearBtn { background: rgba(220,38,38,0.1); color: %9; border: 1px solid %12; "+ " padding: 6px 16px; font-weight: 700; font-size: 12px; font-family: %13; }"+ "QPushButton#credClearBtn:hover { background: %9; color: %2; }"+ "QPushButton#credSaveBtn { background: rgba(217,119,6,0.1); color: %6; border: 1px solid %14; "+ " padding: 6px 16px; font-weight: 700; font-size: 12px; font-family: %13; }"+ "QPushButton#credSaveBtn:hover { background: %6; color: %1; }")+ .arg(colors::BG_BASE(), // %1+ colors::TEXT_PRIMARY(), // %2+ colors::BG_SURFACE(), // %3+ colors::BORDER_DIM(), // %4+ colors::BORDER_BRIGHT(), // %5+ colors::AMBER(), // %6+ colors::TEXT_SECONDARY(), // %7+ colors::TEXT_TERTIARY(), // %8+ colors::NEGATIVE(), // %9+ colors::POSITIVE(), // %10+ colors::WARNING(), // %11+ colors::NEGATIVE_DIM(), // %12+ mono) // %13+ .arg(colors::AMBER_DIM()); // %14}} // namespace@@ -29,9 +65,8 @@ CryptoCredentials::CryptoCredentials(const QString& exchange_id, QWidget* parent: QDialog(parent), exchange_id_(exchange_id) {setWindowTitle(QString("API Credentials — %1").arg(exchange_id.toUpper()));setMinimumWidth(400);- setStyleSheet(QString("QDialog { background: %1; color: %2; "- "font-family: 'Consolas', 'Courier New', monospace; }")- .arg(colors::BG_BASE(), colors::TEXT_PRIMARY()));+ // ONE dialog-level stylesheet drives all widgets via objectName selectors.+ setStyleSheet(kDialogStyle());auto* layout = new QVBoxLayout(this);layout->setSpacing(8);@@ -39,16 +74,12 @@ CryptoCredentials::CryptoCredentials(const QString& exchange_id, QWidget* parent// Headerauto* title = new QLabel(QString("API CREDENTIALS %1").arg(exchange_id.toUpper()));- title->setStyleSheet(QString("color: %1; font-size: 14px; font-weight: 700; letter-spacing: 0.5px; "- "font-family: 'Consolas', 'Courier New', monospace;")- .arg(colors::AMBER()));+ title->setObjectName("credTitle");layout->addWidget(title);auto* info = new QLabel("Enter your exchange API credentials for live trading.\n""Keys are stored locally in encrypted secure storage.");- info->setStyleSheet(QString("color: %1; font-size: 12px; "- "font-family: 'Consolas', 'Courier New', monospace;")- .arg(colors::TEXT_SECONDARY()));+ info->setObjectName("credInfo");info->setWordWrap(true);layout->addWidget(info);@@ -56,54 +87,42 @@ CryptoCredentials::CryptoCredentials(const QString& exchange_id, QWidget* parent// API Keyauto* key_lbl = new QLabel("API KEY");- key_lbl->setStyleSheet(QString("color: %1; font-size: 12px; font-weight: 700; letter-spacing: 0.5px; "- "font-family: 'Consolas', 'Courier New', monospace;")- .arg(colors::TEXT_SECONDARY()));+ key_lbl->setObjectName("credFieldLabel");layout->addWidget(key_lbl);key_edit_ = new QLineEdit;key_edit_->setPlaceholderText("Enter API key");- key_edit_->setStyleSheet(kInputStyle());key_edit_->setFixedHeight(28);layout->addWidget(key_edit_);// API Secretauto* secret_lbl = new QLabel("API SECRET");- secret_lbl->setStyleSheet(QString("color: %1; font-size: 12px; font-weight: 700; letter-spacing: 0.5px; "- "font-family: 'Consolas', 'Courier New', monospace;")- .arg(colors::TEXT_SECONDARY()));+ secret_lbl->setObjectName("credFieldLabel");layout->addWidget(secret_lbl);secret_edit_ = new QLineEdit;secret_edit_->setPlaceholderText("Enter API secret");secret_edit_->setEchoMode(QLineEdit::Password);- secret_edit_->setStyleSheet(kInputStyle());secret_edit_->setFixedHeight(28);layout->addWidget(secret_edit_);// Passwordauto* pw_lbl = new QLabel("PASSWORD (OKX/KUCOIN)");- pw_lbl->setStyleSheet(QString("color: %1; font-size: 12px; font-weight: 700; letter-spacing: 0.5px; "- "font-family: 'Consolas', 'Courier New', monospace;")- .arg(colors::TEXT_SECONDARY()));+ pw_lbl->setObjectName("credFieldLabel");layout->addWidget(pw_lbl);password_edit_ = new QLineEdit;password_edit_->setPlaceholderText("Optional");password_edit_->setEchoMode(QLineEdit::Password);- password_edit_->setStyleSheet(kInputStyle());password_edit_->setFixedHeight(28);layout->addWidget(password_edit_);// TOTP sectionlayout->addSpacing(4);auto* totp_lbl = new QLabel("TOTP SECRET (2FA)");- totp_lbl->setStyleSheet(QString("color: %1; font-size: 12px; font-weight: 700; letter-spacing: 0.5px; "- "font-family: 'Consolas', 'Courier New', monospace;")- .arg(colors::TEXT_SECONDARY()));+ totp_lbl->setObjectName("credFieldLabel");layout->addWidget(totp_lbl);totp_secret_edit_ = new QLineEdit;totp_secret_edit_->setPlaceholderText("Base32 secret (optional)");totp_secret_edit_->setEchoMode(QLineEdit::Password);- totp_secret_edit_->setStyleSheet(kInputStyle());totp_secret_edit_->setFixedHeight(28);layout->addWidget(totp_secret_edit_);@@ -111,15 +130,11 @@ CryptoCredentials::CryptoCredentials(const QString& exchange_id, QWidget* parenttotp_row->setSpacing(8);totp_code_label_ = new QLabel("CODE: --");- totp_code_label_->setStyleSheet(QString("color: %1; font-size: 18px; font-weight: 700; letter-spacing: 2px; "- "font-family: 'Consolas', 'Courier New', monospace;")- .arg(colors::AMBER()));+ totp_code_label_->setObjectName("credTotpCode");totp_row->addWidget(totp_code_label_);totp_countdown_label_ = new QLabel("");- totp_countdown_label_->setStyleSheet(- QString("color: %1; font-size: 11px; font-family: 'Consolas', 'Courier New', monospace;")- .arg(colors::TEXT_TERTIARY()));+ totp_countdown_label_->setObjectName("credTotpCountdown");totp_row->addWidget(totp_countdown_label_);totp_row->addStretch();layout->addLayout(totp_row);@@ -138,31 +153,23 @@ CryptoCredentials::CryptoCredentials(const QString& exchange_id, QWidget* parent}});- // Status+ // Status — objectName flipped by on_save/on_clear to pick status colorstatus_label_ = new QLabel("");- status_label_->setStyleSheet("font-size: 12px; font-family: 'Consolas', 'Courier New', monospace;");+ status_label_->setObjectName("credStatusOk");layout->addWidget(status_label_);// Buttons — Obsidian danger + accentauto* btn_row = new QHBoxLayout;auto* clear_btn = new QPushButton("CLEAR");- clear_btn->setStyleSheet(QString("QPushButton { background: rgba(220,38,38,0.1); color: %1; border: 1px solid %2; "- "padding: 6px 16px; font-weight: 700; font-size: 12px; "- "font-family: 'Consolas', 'Courier New', monospace; }"- "QPushButton:hover { background: %1; color: %3; }")- .arg(colors::NEGATIVE(), colors::NEGATIVE_DIM(), colors::TEXT_PRIMARY()));+ clear_btn->setObjectName("credClearBtn");connect(clear_btn, &QPushButton::clicked, this, &CryptoCredentials::on_clear);btn_row->addWidget(clear_btn);btn_row->addStretch();auto* save_btn = new QPushButton("SAVE & CONNECT");- save_btn->setStyleSheet(QString("QPushButton { background: rgba(217,119,6,0.1); color: %1; border: 1px solid %2; "- "padding: 6px 16px; font-weight: 700; font-size: 12px; "- "font-family: 'Consolas', 'Courier New', monospace; }"- "QPushButton:hover { background: %1; color: %3; }")- .arg(colors::AMBER(), colors::AMBER_DIM(), colors::BG_BASE()));+ save_btn->setObjectName("credSaveBtn");connect(save_btn, &QPushButton::clicked, this, &CryptoCredentials::on_save);btn_row->addWidget(save_btn);@@ -187,17 +194,11 @@ void CryptoCredentials::set_values(const QString& key, const QString& secret, covoid CryptoCredentials::on_save() {if (api_key().isEmpty() || api_secret().isEmpty()) {- status_label_->setText("API key and secret are required");- status_label_->setStyleSheet(QString("color: %1; font-size: 12px; "- "font-family: 'Consolas', 'Courier New', monospace;")- .arg(colors::NEGATIVE()));+ set_status("API key and secret are required", "credStatusErr");return;}emit credentials_saved(api_key(), api_secret(), password());- status_label_->setText("Credentials saved");- status_label_->setStyleSheet(QString("color: %1; font-size: 12px; "- "font-family: 'Consolas', 'Courier New', monospace;")- .arg(colors::POSITIVE()));+ set_status("Credentials saved", "credStatusOk");accept();}@@ -205,10 +206,17 @@ void CryptoCredentials::on_clear() {key_edit_->clear();secret_edit_->clear();password_edit_->clear();- status_label_->setText("Credentials cleared");- status_label_->setStyleSheet(QString("color: %1; font-size: 12px; "- "font-family: 'Consolas', 'Courier New', monospace;")- .arg(colors::WARNING()));+ set_status("Credentials cleared", "credStatusWarn");+}++void CryptoCredentials::set_status(const QString& text, const QString& object_name) {+ status_label_->setText(text);+ if (status_label_->objectName() != object_name) {+ status_label_->setObjectName(object_name);+ // Force re-evaluation of object-name-based selectors in the dialog stylesheet.+ status_label_->style()->unpolish(status_label_);+ status_label_->style()->polish(status_label_);+ }}void CryptoCredentials::on_totp_tick() {diff --git a/fincept-qt/src/screens/crypto_trading/CryptoCredentials.h b/fincept-qt/src/screens/crypto_trading/CryptoCredentials.hindex c4a375be6..1f681c5da 100644--- a/fincept-qt/src/screens/crypto_trading/CryptoCredentials.h+++ b/fincept-qt/src/screens/crypto_trading/CryptoCredentials.h@@ -29,6 +29,7 @@ class CryptoCredentials : public QDialog {private:void refresh_totp();+ void set_status(const QString& text, const QString& object_name);QLineEdit* key_edit_ = nullptr;QLineEdit* secret_edit_ = nullptr;diff --git a/fincept-qt/src/screens/crypto_trading/CryptoOrderEntry.cpp b/fincept-qt/src/screens/crypto_trading/CryptoOrderEntry.cppindex d86f812b5..40414efbc 100644--- a/fincept-qt/src/screens/crypto_trading/CryptoOrderEntry.cpp+++ b/fincept-qt/src/screens/crypto_trading/CryptoOrderEntry.cpp@@ -248,6 +248,8 @@ CryptoOrderEntry::CryptoOrderEntry(QWidget* parent) : QWidget(parent) {}void CryptoOrderEntry::set_buy_side(bool is_buy) {+ if (is_buy == is_buy_side_)+ return; // no-op — avoids repoling children on redundant clicksis_buy_side_ = is_buy;buy_tab_->setProperty("active", is_buy);sell_tab_->setProperty("active", !is_buy);@@ -257,19 +259,38 @@ void CryptoOrderEntry::set_buy_side(bool is_buy) {submit_btn_->setText(label);submit_btn_->setObjectName(is_buy ? "cryptoBuySubmit" : "cryptoSellSubmit");- // Single style refresh on the parent instead of 6 individual unpolish/polish calls- style()->unpolish(this);- style()->polish(this);+ // Narrow style refresh — only the widgets whose dynamic property or+ // objectName actually changed, not the entire order-entry subtree.+ const auto repolish = [](QWidget* w) {+ w->style()->unpolish(w);+ w->style()->polish(w);+ };+ repolish(buy_tab_);+ repolish(sell_tab_);+ repolish(submit_btn_);}void CryptoOrderEntry::set_order_type(int idx) {+ if (idx == active_type_) {+ // Still update enabled state + cost preview for defensive callers+ price_edit_->setEnabled(idx == 1 || idx == 3);+ stop_price_edit_->setEnabled(idx == 2 || idx == 3);+ update_cost_preview();+ return;+ }+ const int prev = active_type_;active_type_ = idx;for (int i = 0; i < 4; ++i)type_btns_[i]->setProperty("active", i == idx);- // Single parent-level style refresh instead of 8 individual unpolish/polish calls- style()->unpolish(this);- style()->polish(this);+ // Only repoll the two buttons whose "active" property changed.+ const auto repolish = [](QWidget* w) {+ w->style()->unpolish(w);+ w->style()->polish(w);+ };+ if (prev >= 0 && prev < 4)+ repolish(type_btns_[prev]);+ repolish(type_btns_[idx]);price_edit_->setEnabled(idx == 1 || idx == 3);stop_price_edit_->setEnabled(idx == 2 || idx == 3);diff --git a/fincept-qt/src/screens/crypto_trading/CryptoOrderEntry.h b/fincept-qt/src/screens/crypto_trading/CryptoOrderEntry.hindex d443973ba..58df901dc 100644--- a/fincept-qt/src/screens/crypto_trading/CryptoOrderEntry.h+++ b/fincept-qt/src/screens/crypto_trading/CryptoOrderEntry.h@@ -1,5 +1,5 @@#pragma once-// Crypto Order Entry — Bloomberg-style BUY/SELL tabs with toggle type buttons+// Crypto Order Entry — BUY/SELL tabs with toggle type buttons#include <QComboBox>#include <QLabel>diff --git a/fincept-qt/src/screens/crypto_trading/CryptoTickerBar.cpp b/fincept-qt/src/screens/crypto_trading/CryptoTickerBar.cppindex a4487ed99..118b09ddc 100644--- a/fincept-qt/src/screens/crypto_trading/CryptoTickerBar.cpp+++ b/fincept-qt/src/screens/crypto_trading/CryptoTickerBar.cpp@@ -5,6 +5,8 @@#include <QHBoxLayout>+#include <cmath>+using namespace fincept::ui;namespace fincept::screens::crypto {@@ -71,15 +73,32 @@ void CryptoTickerBar::set_symbol(const QString& symbol) {symbol_label_->setText(symbol);}+// Round a value to the display precision (here 2 decimals). Two inputs that+// round identically mean identical rendered text — no setText needed.+static inline double round_pp(double v, int places = 2) {+ double mul = 1.0;+ for (int i = 0; i < places; ++i)+ mul *= 10.0;+ return std::round(v * mul) / mul;+}+void CryptoTickerBar::update_data(double price, double change_pct, double high, double low, double volume,bool ws_connected) {if (price <= 0)return;- price_label_->setText(QString("$%1").arg(price, 0, 'f', 2));+ const double price_disp = round_pp(price);+ if (price_disp != last_price_display_) {+ price_label_->setText(QString("$%1").arg(price_disp, 0, 'f', 2));+ last_price_display_ = price_disp;+ }const bool positive = change_pct >= 0;- change_label_->setText(QString("%1%2%").arg(positive ? "+" : "").arg(change_pct, 0, 'f', 2));+ const double change_disp = round_pp(change_pct);+ if (change_disp != last_change_display_) {+ change_label_->setText(QString("%1%2%").arg(positive ? "+" : "").arg(change_disp, 0, 'f', 2));+ last_change_display_ = change_disp;+ }// Only update style on state flip — P7if (positive != last_positive_) {@@ -89,23 +108,58 @@ void CryptoTickerBar::update_data(double price, double change_pct, double high,last_positive_ = positive;}- high_label_->setText(QString("H:%1").arg(high, 0, 'f', 2));- low_label_->setText(QString("L:%1").arg(low, 0, 'f', 2));+ const double high_disp = round_pp(high);+ if (high_disp != last_high_display_) {+ high_label_->setText(QString("H:%1").arg(high_disp, 0, 'f', 2));+ last_high_display_ = high_disp;+ }+ const double low_disp = round_pp(low);+ if (low_disp != last_low_display_) {+ low_label_->setText(QString("L:%1").arg(low_disp, 0, 'f', 2));+ last_low_display_ = low_disp;+ }- if (volume >= 1e9)- volume_label_->setText(QString("Vol:%1B").arg(volume / 1e9, 0, 'f', 2));- else if (volume >= 1e6)- volume_label_->setText(QString("Vol:%1M").arg(volume / 1e6, 0, 'f', 2));- else- volume_label_->setText(QString("Vol:%1").arg(volume, 0, 'f', 0));+ int vol_unit;+ double vol_disp;+ QString vol_text;+ if (volume >= 1e9) {+ vol_unit = 2;+ vol_disp = round_pp(volume / 1e9);+ vol_text = QString("Vol:%1B").arg(vol_disp, 0, 'f', 2);+ } else if (volume >= 1e6) {+ vol_unit = 1;+ vol_disp = round_pp(volume / 1e6);+ vol_text = QString("Vol:%1M").arg(vol_disp, 0, 'f', 2);+ } else {+ vol_unit = 0;+ vol_disp = std::round(volume);+ vol_text = QString("Vol:%1").arg(vol_disp, 0, 'f', 0);+ }+ if (vol_unit != last_volume_unit_ || vol_disp != last_volume_display_) {+ volume_label_->setText(vol_text);+ last_volume_unit_ = vol_unit;+ last_volume_display_ = vol_disp;+ }Q_UNUSED(ws_connected);}void CryptoTickerBar::update_bid_ask(double bid, double ask, double spread) {- bid_label_->setText(QString("B:%1").arg(bid, 0, 'f', 2));- ask_label_->setText(QString("A:%1").arg(ask, 0, 'f', 2));- spread_label_->setText(QString("S:%1").arg(spread, 0, 'f', 2));+ const double b = round_pp(bid);+ const double a = round_pp(ask);+ const double s = round_pp(spread);+ if (b != last_bid_display_) {+ bid_label_->setText(QString("B:%1").arg(b, 0, 'f', 2));+ last_bid_display_ = b;+ }+ if (a != last_ask_display_) {+ ask_label_->setText(QString("A:%1").arg(a, 0, 'f', 2));+ last_ask_display_ = a;+ }+ if (s != last_spread_display_) {+ spread_label_->setText(QString("S:%1").arg(s, 0, 'f', 2));+ last_spread_display_ = s;+ }}void CryptoTickerBar::update_mark_price(double mark_price, double index_price) {diff --git a/fincept-qt/src/screens/crypto_trading/CryptoTickerBar.h b/fincept-qt/src/screens/crypto_trading/CryptoTickerBar.hindex f3e64db18..adfa530d0 100644--- a/fincept-qt/src/screens/crypto_trading/CryptoTickerBar.h+++ b/fincept-qt/src/screens/crypto_trading/CryptoTickerBar.h@@ -29,8 +29,19 @@ class CryptoTickerBar : public QWidget {QLabel* mark_price_label_ = nullptr;QLabel* index_price_label_ = nullptr;- // State cache — avoid redundant style updates+ // State cache — avoid redundant setText calls at ticker rate. Values are+ // rounded to the display precision before comparing so we only repaint on+ // a pixel-visible change.bool last_positive_ = true;+ double last_price_display_ = -1;+ double last_change_display_ = 1e300;+ double last_high_display_ = -1;+ double last_low_display_ = -1;+ double last_volume_display_ = -1;+ int last_volume_unit_ = -1; // 0=raw, 1=M, 2=B+ double last_bid_display_ = -1;+ double last_ask_display_ = -1;+ double last_spread_display_ = -1;};} // namespace fincept::screens::cryptodiff --git a/fincept-qt/src/screens/crypto_trading/CryptoTradingScreen.cpp b/fincept-qt/src/screens/crypto_trading/CryptoTradingScreen.cppindex 664b5523a..dda6ab977 100644--- a/fincept-qt/src/screens/crypto_trading/CryptoTradingScreen.cpp+++ b/fincept-qt/src/screens/crypto_trading/CryptoTradingScreen.cpp@@ -1,4 +1,4 @@-// Crypto Trading Screen — Bloomberg-style coordinator+// Crypto Trading Screen — coordinator#include "screens/crypto_trading/CryptoTradingScreen.h"#include "core/logging/Logger.h"@@ -19,7 +19,6 @@#include <QCompleter>#include <QDateTime>#include <QHBoxLayout>-#include <QMutexLocker>#include <QPointer>#include <QSplitter>#include <QStringListModel>@@ -95,11 +94,36 @@ void CryptoTradingScreen::hideEvent(QHideEvent* event) {clock_timer_->stop();if (ws_flush_timer_)ws_flush_timer_->stop();- LOG_INFO(TAG, "Screen hidden — timers stopped");++ // Reset WS/state trackers so apply_feed_mode and update_clock re-emit+ // their state when the tab becomes visible again.+ last_ws_state_ = -1;+ last_ws_status_label_state_ = -1;++ // Drop any buffered WS updates — they'll be stale by next show and would+ // cause a spurious full-burst flush right after the screen reappears.+ pending_tickers_.clear();+ pending_primary_ticker_ = {};+ has_pending_primary_ = false;+ pending_orderbook_ = {};+ has_pending_orderbook_ = false;+ pending_candles_.clear();+ pending_trades_.clear();++ // Reset async-fetch guards — if a fetch was in-flight when we hid, its+ // reply will still fire (widget isn't destroyed, just hidden) and will+ // decrement live_inflight_; we just zero the counter so a spurious extra+ // decrement from a stuck task doesn't underflow into negative values.+ candles_fetching_.store(false);+ live_inflight_.store(0);+ // paper_bookkeeping_in_flight_ is NOT cleared — a worker thread may still+ // be running and will reset it via the invokeMethod callback when done.++ LOG_INFO(TAG, "Screen hidden — timers stopped, buffers cleared");}// ============================================================================-// UI Setup — Bloomberg 4-zone layout+// UI Setup — 4-zone layout// ============================================================================void CryptoTradingScreen::setup_ui() {@@ -289,24 +313,61 @@ void CryptoTradingScreen::setup_timers() {connect(ws_flush_timer_, &QTimer::timeout, this, &CryptoTradingScreen::flush_ws_updates);ws_flush_timer_->setInterval(100); // 10fps- // Defer to next event loop tick (0ms) — just enough to let the widget be shown- // before we start spinning up processes. Daemon is already pre-warming in the- // background via ExchangeService constructor so it should be ready by the time- // the user actually clicks this tab.+ // Defer to next event loop tick — start the WS stream and portfolio (both+ // cheap / local) immediately, then gate the *daemon-bound* fetches on the+ // daemon-ready signal so they don't race the cold boot and fall back to+ // raw-QProcess script calls (which each block a threadpool worker for up+ // to 30s). If the daemon never comes up, a single-shot timer still kicks+ // the fetches after 8s so the user sees degraded-but-not-empty data.QTimer::singleShot(0, this, [this]() {init_exchange();load_portfolio();- refresh_ticker();- refresh_orderbook();- refresh_watchlist();- async_fetch_candles(selected_symbol_, chart_->current_timeframe());+ refresh_ticker(); // cheap — reads ExchangeService's in-memory cache++ auto* es = &trading::ExchangeService::instance();+ auto run_initial_fetches = [this]() {+ if (startup_fetches_done_)+ return;+ startup_fetches_done_ = true;+ refresh_orderbook();+ refresh_watchlist();+ async_fetch_candles(selected_symbol_, chart_->current_timeframe());+ };++ if (es->wait_for_daemon_ready(0)) {+ // Daemon already warm (pre-warmed by ExchangeService ctor or a+ // previous session). Fire immediately.+ run_initial_fetches();+ } else {+ // Connect once; disconnect after first fire.+ auto conn = std::make_shared<QMetaObject::Connection>();+ *conn = connect(es, &trading::ExchangeService::daemon_ready, this, [this, conn, run_initial_fetches]() {+ QObject::disconnect(*conn);+ run_initial_fetches();+ });+ // Safety net: if daemon never comes up within 8s, proceed anyway+ // so the user eventually sees data.+ QTimer::singleShot(8000, this, [this, conn, run_initial_fetches]() {+ if (startup_fetches_done_)+ return;+ QObject::disconnect(*conn);+ LOG_WARN(TAG, "Daemon not ready after 8s — firing startup fetches via script fallback");+ run_initial_fetches();+ });+ }});}void CryptoTradingScreen::update_clock() {clock_label_->setText(QDateTime::currentDateTime().toString("HH:mm:ss"));- // Update WS status- const bool connected = ExchangeService::instance().is_ws_connected();++ // WS status label — only reapply text + stylesheet on state change. A+ // setStyleSheet call triggers a CSS reparse and repaint; doing that every+ // second on an unchanging state was pure waste.+ const int connected = ExchangeService::instance().is_ws_connected() ? 1 : 0;+ if (connected == last_ws_status_label_state_)+ return;+ last_ws_status_label_state_ = connected;ws_status_->setText(connected ? "LIVE" : "REST");ws_status_->setStyleSheet(QString("color: %1;").arg(connected ? ui::colors::POSITIVE() : ui::colors::WARNING()));}@@ -325,53 +386,67 @@ void CryptoTradingScreen::init_exchange() {es.start_ws_stream(selected_symbol_, watchlist_symbols_);// WS price callback → accumulate into pending buffers (flushed at 10fps by ws_flush_timer_)- // This coalesces ~50 msgs/sec into ~10 UI updates/sec- ws_price_cb_id_ = es.on_price_update([this](const QString& symbol, const TickerData& ticker) {+ // This coalesces ~50 msgs/sec into ~10 UI updates/sec.+ // QPointer guard: callbacks are invoked from the WS reader thread, so the+ // widget could be torn down between dispatch and our lambda body running.+ QPointer<CryptoTradingScreen> self = this;+ ws_price_cb_id_ = es.on_price_update([self](const QString& symbol, const TickerData& ticker) {+ if (!self) return;QMetaObject::invokeMethod(- this,- [this, symbol, ticker]() {- pending_tickers_[symbol] = ticker; // latest wins per symbol- if (symbol == selected_symbol_) {- pending_primary_ticker_ = ticker;- has_pending_primary_ = true;+ self.data(),+ [self, symbol, ticker]() {+ if (!self) return;+ self->pending_tickers_[symbol] = ticker; // latest wins per symbol+ if (symbol == self->selected_symbol_) {+ self->pending_primary_ticker_ = ticker;+ self->has_pending_primary_ = true;}},Qt::QueuedConnection);});- // WS orderbook callback- ws_ob_cb_id_ = es.on_orderbook_update([this](const QString& symbol, const OrderBookData& ob) {- if (symbol == selected_symbol_) {- QMetaObject::invokeMethod(- this,- [this, ob]() {- orderbook_->set_data(ob.bids, ob.asks, ob.spread, ob.spread_pct);- bottom_panel_->set_depth_data(ob.bids, ob.asks, ob.spread, ob.spread_pct);- if (ob_timer_)- ob_timer_->stop();- },- Qt::QueuedConnection);- }+ // WS orderbook callback → buffer latest; flushed at 10fps by ws_flush_timer_+ ws_ob_cb_id_ = es.on_orderbook_update([self](const QString& symbol, const OrderBookData& ob) {+ if (!self || symbol != self->selected_symbol_)+ return;+ QMetaObject::invokeMethod(+ self.data(),+ [self, ob]() {+ if (!self) return;+ self->pending_orderbook_ = ob;+ self->has_pending_orderbook_ = true;+ },+ Qt::QueuedConnection);});- // WS candle callback- ws_candle_cb_id_ = es.on_candle_update([this](const QString& symbol, const Candle& candle) {- if (symbol == selected_symbol_) {- QMetaObject::invokeMethod(this, [this, candle]() { chart_->append_candle(candle); }, Qt::QueuedConnection);- }+ // WS candle callback → buffer pending candles; flushed at 10fps by ws_flush_timer_+ ws_candle_cb_id_ = es.on_candle_update([self](const QString& symbol, const Candle& candle) {+ if (!self || symbol != self->selected_symbol_)+ return;+ QMetaObject::invokeMethod(+ self.data(),+ [self, candle]() {+ if (!self) return;+ self->pending_candles_.append(candle);+ },+ Qt::QueuedConnection);});- // WS trade callback → Time & Sales- ws_trade_cb_id_ = es.on_trade_update([this](const QString& symbol, const TradeData& trade) {- if (symbol == selected_symbol_) {- TradeEntry entry;- entry.side = trade.side;- entry.price = trade.price;- entry.amount = trade.amount;- entry.timestamp = trade.timestamp;- QMetaObject::invokeMethod(- this, [this, entry]() { bottom_panel_->add_trade_entry(entry); }, Qt::QueuedConnection);- }+ // WS trade callback → buffer trade entries; flushed at 10fps by ws_flush_timer_+ ws_trade_cb_id_ = es.on_trade_update([self](const QString& symbol, const TradeData& trade) {+ if (!self || symbol != self->selected_symbol_)+ return;+ TradeEntry entry;+ entry.side = trade.side;+ entry.price = trade.price;+ entry.amount = trade.amount;+ QMetaObject::invokeMethod(+ self.data(),+ [self, entry]() {+ if (!self) return;+ self->pending_trades_.append(entry);+ },+ Qt::QueuedConnection);});initialized_ = true;@@ -418,8 +493,10 @@ void CryptoTradingScreen::async_fetch_candles(const QString& symbol, const QStrivoid CryptoTradingScreen::async_fetch_live_positions() {QPointer<CryptoTradingScreen> self = this;QtConcurrent::run([self]() {- if (!self)+ if (!self) {+ // Widget destroyed before dispatch — no counter to decrement.return;+ }auto result = ExchangeService::instance().fetch_positions_live(self->selected_symbol_);QMetaObject::invokeMethod(self,@@ -428,6 +505,7 @@ void CryptoTradingScreen::async_fetch_live_positions() {return;if (result.contains("positions"))self->bottom_panel_->set_live_positions(result.value("positions").toArray());+ self->live_inflight_.fetch_sub(1);},Qt::QueuedConnection);});@@ -446,6 +524,7 @@ void CryptoTradingScreen::async_fetch_live_orders() {return;if (result.contains("orders"))self->bottom_panel_->set_live_orders(result.value("orders").toArray());+ self->live_inflight_.fetch_sub(1);},Qt::QueuedConnection);});@@ -467,6 +546,7 @@ void CryptoTradingScreen::async_fetch_live_balance() {double used = result.value("used").toObject().value("USDT").toDouble();self->bottom_panel_->set_live_balance(free, total, used);self->order_entry_->set_balance(free);+ self->live_inflight_.fetch_sub(1);},Qt::QueuedConnection);});@@ -477,11 +557,37 @@ void CryptoTradingScreen::async_fetch_live_balance() {// ============================================================================void CryptoTradingScreen::on_exchange_changed(const QString& exchange) {+ if (exchange == exchange_id_)+ return;exchange_id_ = exchange;exchange_btn_->setText(exchange.toUpper());+auto& es = ExchangeService::instance();++ // Tear down current WS stream + drop stale callbacks so ticks from the+ // previous exchange can't race into buffers post-switch.+ es.stop_ws_stream();+ if (ws_price_cb_id_ >= 0) { es.remove_price_callback(ws_price_cb_id_); ws_price_cb_id_ = -1; }+ if (ws_ob_cb_id_ >= 0) { es.remove_orderbook_callback(ws_ob_cb_id_); ws_ob_cb_id_ = -1; }+ if (ws_candle_cb_id_ >= 0) { es.remove_candle_callback(ws_candle_cb_id_); ws_candle_cb_id_ = -1; }+ if (ws_trade_cb_id_ >= 0) { es.remove_trade_callback(ws_trade_cb_id_); ws_trade_cb_id_ = -1; }++ // Clear accumulated buffers — stale data from the old exchange is useless.+ pending_tickers_.clear();+ pending_orderbook_ = {};+ has_pending_orderbook_ = false;+ pending_primary_ticker_ = {};+ has_pending_primary_ = false;+ pending_candles_.clear();+ pending_trades_.clear();+ last_ws_state_ = -1; // re-evaluate feed mode after new stream connects+es.set_exchange(exchange_id_);- es.start_ws_stream(selected_symbol_, watchlist_symbols_);++ // Re-initialize — this re-registers all four WS callbacks + starts the stream.+ initialized_ = false;+ init_exchange();+load_portfolio();async_fetch_candles(selected_symbol_, chart_->current_timeframe());ScreenStateManager::instance().notify_changed(this);@@ -495,14 +601,25 @@ void CryptoTradingScreen::on_symbol_selected(const QString& symbol) {}void CryptoTradingScreen::switch_symbol(const QString& symbol) {- ExchangeService::instance().unwatch_symbol(selected_symbol_, portfolio_id_);+ auto& es = ExchangeService::instance();+ es.unwatch_symbol(selected_symbol_, portfolio_id_);selected_symbol_ = symbol;symbol_input_->setText(symbol);ticker_bar_->set_symbol(symbol);order_entry_->set_symbol(symbol);watchlist_->set_active_symbol(symbol);- ExchangeService::instance().watch_symbol(selected_symbol_, portfolio_id_);- ExchangeService::instance().set_ws_primary_symbol(symbol);++ // Drop per-symbol buffers tied to the old symbol to prevent cross-symbol leakage.+ has_pending_primary_ = false;+ pending_primary_ticker_ = {};+ has_pending_orderbook_ = false;+ pending_orderbook_ = {};+ pending_candles_.clear();+ pending_trades_.clear();+ market_info_cache_ = {};++ es.watch_symbol(selected_symbol_, portfolio_id_);+ es.set_ws_primary_symbol(symbol);refresh_ticker();refresh_orderbook();async_fetch_candles(selected_symbol_, chart_->current_timeframe());@@ -644,7 +761,34 @@ void CryptoTradingScreen::on_search_requested(const QString& filter) {// WS Update Coalescing — flush accumulated data to UI at 10fps// ============================================================================+void CryptoTradingScreen::apply_feed_mode(bool ws_connected) {+ // Called on WS-state edge transitions. When WS is live we can stop REST+ // polling; when it drops we must restart so the screen keeps updating.+ const int desired = ws_connected ? 1 : 0;+ if (desired == last_ws_state_)+ return;+ last_ws_state_ = desired;++ if (ws_connected) {+ if (ticker_timer_ && ticker_timer_->isActive()) ticker_timer_->stop();+ if (ob_timer_ && ob_timer_->isActive()) ob_timer_->stop();+ if (watchlist_timer_ && watchlist_timer_->isActive()) watchlist_timer_->stop();+ if (portfolio_timer_ && portfolio_timer_->isActive()) portfolio_timer_->stop();+ LOG_INFO(TAG, "WS connected — REST polling paused");+ } else {+ if (isVisible()) {+ if (ticker_timer_ && !ticker_timer_->isActive()) ticker_timer_->start();+ if (ob_timer_ && !ob_timer_->isActive()) ob_timer_->start();+ if (watchlist_timer_ && !watchlist_timer_->isActive()) watchlist_timer_->start();+ if (portfolio_timer_ && !portfolio_timer_->isActive()) portfolio_timer_->start();+ LOG_WARN(TAG, "WS disconnected — REST polling resumed");+ }+ }+}+void CryptoTradingScreen::flush_ws_updates() {+ apply_feed_mode(ExchangeService::instance().is_ws_connected());+// Flush primary symbol ticker → header bar + order entryif (has_pending_primary_) {const auto& t = pending_primary_ticker_;@@ -656,6 +800,28 @@ void CryptoTradingScreen::flush_ws_updates() {has_pending_primary_ = false;}+ // Flush latest orderbook snapshot (one repaint per flush tick, not per WS msg)+ if (has_pending_orderbook_) {+ const auto& ob = pending_orderbook_;+ orderbook_->set_data(ob.bids, ob.asks, ob.spread, ob.spread_pct);+ bottom_panel_->set_depth_data(ob.bids, ob.asks, ob.spread, ob.spread_pct);+ has_pending_orderbook_ = false;+ }++ // Flush buffered candles in order (chart handles intrabar updates via timestamp match)+ if (!pending_candles_.isEmpty()) {+ for (const auto& c : pending_candles_)+ chart_->append_candle(c);+ pending_candles_.clear();+ }++ // Flush buffered trade entries — one loop instead of one invokeMethod per trade+ if (!pending_trades_.isEmpty()) {+ for (const auto& entry : pending_trades_)+ bottom_panel_->add_trade_entry(entry);+ pending_trades_.clear();+ }+// Flush all accumulated tickers → watchlist + paper trading engineif (!pending_tickers_.isEmpty()) {QVector<TickerData> batch;@@ -665,54 +831,74 @@ void CryptoTradingScreen::flush_ws_updates() {pending_tickers_.clear();watchlist_->update_prices(batch);- // Feed WS prices into paper trading engine (position prices + order triggers)+ // Feed WS prices into paper trading engine on a worker thread — every tick+ // would otherwise do 3N+ SQLite ops on the UI thread (price update, order+ // match, SL/TP check) plus 1-5 queries for UI refresh at 10Hz.if (trading_mode_ == TradingMode::Paper && !portfolio_id_.isEmpty()) {- // Snapshot open order count before checks — a drop means a fill occurred- const int orders_before = pt_get_orders(portfolio_id_, "open").size();-- for (const auto& ticker : batch) {- if (ticker.last <= 0)- continue;- // Update position current_price and unrealized P&L- pt_update_position_price(portfolio_id_, ticker.symbol, ticker.last);- // Check limit/stop order fills- PriceData pd;- pd.last = ticker.last;- pd.bid = ticker.bid;- pd.ask = ticker.ask;- pd.timestamp = ticker.timestamp;- OrderMatcher::instance().check_orders(ticker.symbol, pd, portfolio_id_);- OrderMatcher::instance().check_sl_tp_triggers(portfolio_id_, ticker.symbol, ticker.last);- }+ // Drop this tick if the previous batch is still running — keeps us+ // from queueing work faster than the DB can drain it.+ bool expected = false;+ if (paper_bookkeeping_in_flight_.compare_exchange_strong(expected, true)) {+ QPointer<CryptoTradingScreen> self = this;+ const QString pid = portfolio_id_;+ QtConcurrent::run([self, pid, batch]() {+ struct Result {+ QVector<PtPosition> positions;+ bool fill_occurred = false;+ PtPortfolio portfolio;+ QVector<PtOrder> orders;+ QVector<PtTrade> trades;+ PtStats stats;+ };+ Result r;+ try {+ const int orders_before = pt_get_orders(pid, "open").size();+ for (const auto& ticker : batch) {+ if (ticker.last <= 0)+ continue;+ pt_update_position_price(pid, ticker.symbol, ticker.last);+ PriceData pd;+ pd.last = ticker.last;+ pd.bid = ticker.bid;+ pd.ask = ticker.ask;+ pd.timestamp = ticker.timestamp;+ OrderMatcher::instance().check_orders(ticker.symbol, pd, pid);+ OrderMatcher::instance().check_sl_tp_triggers(pid, ticker.symbol, ticker.last);+ }+ r.positions = pt_get_positions(pid);+ const int orders_after = pt_get_orders(pid, "open").size();+ r.fill_occurred = orders_after < orders_before;+ if (r.fill_occurred) {+ r.portfolio = pt_get_portfolio(pid);+ r.orders = pt_get_orders(pid);+ r.trades = pt_get_trades(pid, 50);+ r.stats = pt_get_stats(pid);+ }+ } catch (...) {+ if (self)+ LOG_WARN("CryptoTradingScreen", "Paper bookkeeping worker threw");+ }- // Push updated positions directly to UI at WS rate (10fps via ws_flush_timer_).- // Don't wait for portfolio_timer_ (1500ms) — users need to see P&L move with price.- try {- bottom_panel_->set_positions(pt_get_positions(portfolio_id_));-- // On a fill (order count dropped), refresh full portfolio state- const int orders_after = pt_get_orders(portfolio_id_, "open").size();- if (orders_after < orders_before) {- portfolio_ = pt_get_portfolio(portfolio_id_);- order_entry_->set_balance(portfolio_.balance);- bottom_panel_->set_orders(pt_get_orders(portfolio_id_));- bottom_panel_->set_trades(pt_get_trades(portfolio_id_, 50));- bottom_panel_->set_stats(pt_get_stats(portfolio_id_));- }- } catch (...) {- LOG_WARN("CryptoTradingScreen", "Exception updating portfolio UI from WebSocket price update");+ if (!self)+ return; // widget destroyed — nothing to reset+ QMetaObject::invokeMethod(self, [self, r]() {+ if (!self)+ return;+ self->paper_bookkeeping_in_flight_.store(false);+ self->bottom_panel_->set_positions(r.positions);+ if (r.fill_occurred) {+ self->portfolio_ = r.portfolio;+ self->order_entry_->set_balance(r.portfolio.balance);+ self->bottom_panel_->set_orders(r.orders);+ self->bottom_panel_->set_trades(r.trades);+ self->bottom_panel_->set_stats(r.stats);+ }+ }, Qt::QueuedConnection);+ });}-- // Stop the redundant portfolio poll while WS is delivering price updates.- if (portfolio_timer_ && portfolio_timer_->isActive())- portfolio_timer_->stop();}-- // Stop redundant polling timers while WS is delivering data- if (ticker_timer_ && ticker_timer_->isActive())- ticker_timer_->stop();- if (watchlist_timer_ && watchlist_timer_->isActive())- watchlist_timer_->stop();+ // Polling timers are managed centrally by apply_feed_mode() at the top+ // of this function — no per-flush stop/start here.}}@@ -759,21 +945,44 @@ void CryptoTradingScreen::refresh_portfolio() {if (trading_mode_ == TradingMode::Live)return;- try {- portfolio_ = pt_get_portfolio(portfolio_id_);- auto positions = pt_get_positions(portfolio_id_);- auto orders = pt_get_orders(portfolio_id_);- auto trades = pt_get_trades(portfolio_id_, 50);- auto stats = pt_get_stats(portfolio_id_);-- order_entry_->set_balance(portfolio_.balance);- bottom_panel_->set_positions(positions);- bottom_panel_->set_orders(orders);- bottom_panel_->set_trades(trades);- bottom_panel_->set_stats(stats);- } catch (...) {- LOG_WARN("CryptoTradingScreen", "Exception refreshing portfolio panel");- }+ // Perform 5 SQLite reads on a worker thread — with 1.5s timer + order+ // placement/cancel flushes, this was one of the loudest UI-thread stalls.+ QPointer<CryptoTradingScreen> self = this;+ const QString pid = portfolio_id_;+ QtConcurrent::run([self, pid]() {+ struct Snapshot {+ PtPortfolio portfolio;+ QVector<PtPosition> positions;+ QVector<PtOrder> orders;+ QVector<PtTrade> trades;+ PtStats stats;+ bool ok = false;+ };+ Snapshot s;+ try {+ s.portfolio = pt_get_portfolio(pid);+ s.positions = pt_get_positions(pid);+ s.orders = pt_get_orders(pid);+ s.trades = pt_get_trades(pid, 50);+ s.stats = pt_get_stats(pid);+ s.ok = true;+ } catch (...) {+ if (self)+ LOG_WARN("CryptoTradingScreen", "Exception refreshing portfolio panel");+ }+ if (!self || !s.ok)+ return;+ QMetaObject::invokeMethod(self, [self, s]() {+ if (!self)+ return;+ self->portfolio_ = s.portfolio;+ self->order_entry_->set_balance(s.portfolio.balance);+ self->bottom_panel_->set_positions(s.positions);+ self->bottom_panel_->set_orders(s.orders);+ self->bottom_panel_->set_trades(s.trades);+ self->bottom_panel_->set_stats(s.stats);+ }, Qt::QueuedConnection);+ });}void CryptoTradingScreen::refresh_watchlist() {@@ -798,27 +1007,52 @@ void CryptoTradingScreen::refresh_watchlist() {void CryptoTradingScreen::refresh_market_info() {if (!initialized_)return;+ // Fire the two daemon calls on separate worker threads so their UI-thread+ // return paths run independently. The daemon serializes via its own mutex,+ // but the funding-rate branch updates the ticker mark price as soon as it+ // lands instead of waiting for open-interest too. Each worker writes its+ // portion into market_info_cache_ on the UI thread, then pushes the union+ // to the bottom panel — cache access is UI-thread-only, no lock needed.QPointer<CryptoTradingScreen> self = this;- QtConcurrent::run([self]() {+ const QString symbol = selected_symbol_;++ QtConcurrent::run([self, symbol]() {if (!self)return;- auto fr = ExchangeService::instance().fetch_funding_rate(self->selected_symbol_);- auto oi = ExchangeService::instance().fetch_open_interest(self->selected_symbol_);- MarketInfoData info;- info.funding_rate = fr.funding_rate;- info.mark_price = fr.mark_price;- info.index_price = fr.index_price;- info.next_funding_time = fr.next_funding_timestamp;- info.open_interest = oi.open_interest;- info.open_interest_value = oi.open_interest_value;- info.has_data = true;+ auto fr = ExchangeService::instance().fetch_funding_rate(symbol);QMetaObject::invokeMethod(self,- [self, info]() {+ [self, symbol, fr]() {if (!self)return;- self->bottom_panel_->set_market_info(info);- self->ticker_bar_->update_mark_price(info.mark_price, info.index_price);+ if (self->selected_symbol_ != symbol)+ return; // user switched symbols — discard stale result+ self->market_info_cache_.funding_rate = fr.funding_rate;+ self->market_info_cache_.mark_price = fr.mark_price;+ self->market_info_cache_.index_price = fr.index_price;+ self->market_info_cache_.next_funding_time = fr.next_funding_timestamp;+ self->market_info_cache_.has_data = true;+ self->ticker_bar_->update_mark_price(fr.mark_price, fr.index_price);+ self->bottom_panel_->set_market_info(self->market_info_cache_);+ },+ Qt::QueuedConnection);+ });++ QtConcurrent::run([self, symbol]() {+ if (!self)+ return;+ auto oi = ExchangeService::instance().fetch_open_interest(symbol);+ QMetaObject::invokeMethod(+ self,+ [self, symbol, oi]() {+ if (!self)+ return;+ if (self->selected_symbol_ != symbol)+ return; // user switched symbols — discard stale result+ self->market_info_cache_.open_interest = oi.open_interest;+ self->market_info_cache_.open_interest_value = oi.open_interest_value;+ self->market_info_cache_.has_data = true;+ self->bottom_panel_->set_market_info(self->market_info_cache_);},Qt::QueuedConnection);});@@ -831,15 +1065,17 @@ void CryptoTradingScreen::refresh_candles() {void CryptoTradingScreen::refresh_live_data() {if (trading_mode_ != TradingMode::Live)return;- if (live_fetching_.exchange(true))+ // Skip this tick entirely if any of the 4 live fetches from the previous+ // tick are still in-flight — prevents burst-stacking against the exchange+ // API and against the daemon's request pipeline.+ if (live_inflight_.load() > 0)return;+ live_inflight_.store(4);async_fetch_live_positions();async_fetch_live_orders();async_fetch_live_balance();async_fetch_my_trades();-- live_fetching_ = false;}void CryptoTradingScreen::async_fetch_my_trades() {@@ -854,6 +1090,7 @@ void CryptoTradingScreen::async_fetch_my_trades() {if (!self)return;self->bottom_panel_->update_my_trades(result);+ self->live_inflight_.fetch_sub(1);},Qt::QueuedConnection);});@@ -917,9 +1154,28 @@ void CryptoTradingScreen::restore_state(const QVariantMap& state) {const QString exch = state.value("exchange_id", "kraken").toString();const QString sym = state.value("selected_symbol", "BTC/USDT").toString();- if (exch != exchange_id_)+ const bool exch_changed = (exch != exchange_id_);+ const bool sym_changed = (sym != selected_symbol_);++ if (!exch_changed && !sym_changed)+ return;++ // When both change, avoid two teardown/re-subscribe cycles: set the+ // symbol first so the exchange-change path re-initializes on the NEW+ // symbol directly, and skip the follow-up switch_symbol call.+ if (exch_changed) {+ if (sym_changed) {+ selected_symbol_ = sym;+ symbol_input_->setText(sym);+ ticker_bar_->set_symbol(sym);+ order_entry_->set_symbol(sym);+ watchlist_->set_active_symbol(sym);+ }on_exchange_changed(exch);- if (sym != selected_symbol_)+ return;+ }++ if (sym_changed)on_symbol_selected(sym);}diff --git a/fincept-qt/src/screens/crypto_trading/CryptoTradingScreen.h b/fincept-qt/src/screens/crypto_trading/CryptoTradingScreen.hindex 3a827ac17..d81d064cc 100644--- a/fincept-qt/src/screens/crypto_trading/CryptoTradingScreen.h+++ b/fincept-qt/src/screens/crypto_trading/CryptoTradingScreen.h@@ -1,5 +1,5 @@#pragma once-// Crypto Trading Screen — Bloomberg-style coordinator+// Crypto Trading Screen — coordinator#include "screens/IStatefulScreen.h"#include "screens/crypto_trading/CryptoTypes.h"@@ -10,7 +10,6 @@#include <QLabel>#include <QLineEdit>#include <QMenu>-#include <QMutex>#include <QPushButton>#include <QShowEvent>#include <QStringList>@@ -125,7 +124,18 @@ class CryptoTradingScreen : public QWidget, public IStatefulScreen {// Async fetch guardsstd::atomic<bool> candles_fetching_{false};- std::atomic<bool> live_fetching_{false};+ std::atomic<int> live_inflight_{0}; // counts async_fetch_live_* tasks still running+ std::atomic<bool> paper_bookkeeping_in_flight_{false};++ // Startup gate — ensures daemon-dependent fetches fire exactly once,+ // either via daemon_ready signal or via the 8s safety fallback timeout.+ bool startup_fetches_done_ = false;++ // WS/REST mode edge detection — when WS transitions online we stop REST+ // polling; when it drops we restart it. tri-state: -1 = unknown.+ int last_ws_state_ = -1;+ int last_ws_status_label_state_ = -1; // separate from last_ws_state_ since update_clock is 1Hz+ void apply_feed_mode(bool ws_connected);QStringList watchlist_symbols_ = {"BTC/USDT", "ETH/USDT", "SOL/USDT", "BNB/USDT", "XRP/USDT", "DOGE/USDT", "ADA/USDT",@@ -134,14 +144,33 @@ class CryptoTradingScreen : public QWidget, public IStatefulScreen {"INJ/USDT", "NEAR/USDT", "WIF/USDT", "PEPE/USDT",};- QMutex data_mutex_;bool initialized_ = false;+ // Cached market info — funding rate and open interest arrive on separate+ // workers so we merge into this cache and emit the union to the bottom+ // panel from each worker's return path (UI-thread — no lock needed).+ crypto::MarketInfoData market_info_cache_;+// ── WS update coalescing (10fps UI flush) ──QTimer* ws_flush_timer_ = nullptr;QHash<QString, trading::TickerData> pending_tickers_; // accumulated since last flushtrading::TickerData pending_primary_ticker_; // latest for selected symbolbool has_pending_primary_ = false;++ // Orderbook coalescing — latest-wins. Raw bursts (~20 msgs/sec on busy+ // symbols) collapse to one UI refresh per flush tick (10/sec).+ trading::OrderBookData pending_orderbook_;+ bool has_pending_orderbook_ = false;++ // Candle coalescing — append closed candles in order, keep the latest+ // in-progress candle separately so we render partial bars without+ // flooding the chart on every tick.+ QVector<trading::Candle> pending_candles_;++ // Trade coalescing — batch recent trades so bottom_panel_ does one list+ // append per flush tick instead of one per WS message.+ QVector<crypto::TradeEntry> pending_trades_;+void flush_ws_updates();};diff --git a/fincept-qt/src/screens/data_sources/DataSourcesScreen.h b/fincept-qt/src/screens/data_sources/DataSourcesScreen.hindex 608f54bf3..41d01b323 100644--- a/fincept-qt/src/screens/data_sources/DataSourcesScreen.h+++ b/fincept-qt/src/screens/data_sources/DataSourcesScreen.h@@ -1,5 +1,5 @@#pragma once-// Data Sources Screen — Bloomberg-style data connector command center.+// Data Sources Screen — data connector command center.#include "screens/IStatefulScreen.h"#include "screens/data_sources/DataSourceTypes.h"diff --git a/fincept-qt/src/screens/docs/DocsScreen.cpp b/fincept-qt/src/screens/docs/DocsScreen.cppindex c9d71f251..e7c2b0af7 100644--- a/fincept-qt/src/screens/docs/DocsScreen.cpp+++ b/fincept-qt/src/screens/docs/DocsScreen.cpp@@ -233,7 +233,7 @@ QWidget* DocsScreen::page_welcome() {"Fincept Terminal is a professional-grade desktop financial intelligence platform ""built in native C++ with Qt6. It provides institutional-quality market data, ""trading capabilities, quantitative research tools, and AI-powered analytics — "- "all in a single Bloomberg Terminal-inspired interface.\n\n"+ "all in a single unified terminal interface.\n\n""With 45+ integrated screens, real-time WebSocket feeds, embedded Python analytics, ""and support for 15+ broker integrations, Fincept Terminal bridges the gap between ""retail and institutional tooling.",@@ -556,7 +556,7 @@ QWidget* DocsScreen::page_crypto_trading() {vl->setSpacing(12);vl->addWidget(make_heading("CRYPTO TRADING"));- vl->addWidget(make_muted_label("Bloomberg-style multi-exchange crypto trading terminal"));+ vl->addWidget(make_muted_label("Multi-exchange crypto trading terminal"));auto* sep = new QFrame;sep->setFrameShape(QFrame::HLine);diff --git a/fincept-qt/src/screens/equity_trading/AccountManagementDialog.cpp b/fincept-qt/src/screens/equity_trading/AccountManagementDialog.cppindex 86d96501a..583abdc40 100644--- a/fincept-qt/src/screens/equity_trading/AccountManagementDialog.cpp+++ b/fincept-qt/src/screens/equity_trading/AccountManagementDialog.cpp@@ -1,15 +1,29 @@// AccountManagementDialog.cpp — multi-account credential management#include "screens/equity_trading/AccountManagementDialog.h"+#include "core/logging/Logger.h"+#include "trading/AccountManager.h"#include "trading/BrokerRegistry.h"+#include "trading/auth/RedirectServer.h"+#include "trading/brokers/zerodha/ZerodhaBroker.h"#include "ui/theme/Theme.h"+#include <QCoreApplication>+#include <QDesktopServices>+#include <QFrame>#include <QHBoxLayout>#include <QJsonDocument>#include <QJsonObject>#include <QMessageBox>+#include <QMetaObject>+#include <QPointer>+#include <QRadioButton>+#include <QScrollArea>+#include <QUrl>+#include <QUrlQuery>#include <QVBoxLayout>+#include <QtConcurrent/QtConcurrentRun>namespace fincept::screens::equity {@@ -163,6 +177,11 @@ void AccountManagementDialog::setup_ui() {form_layout->addLayout(action_row);right_stack_->addWidget(form_page_);++ // Zerodha-specific page (populated on-demand by build_zerodha_form())+ zerodha_page_ = new QWidget(this);+ right_stack_->addWidget(zerodha_page_);+right_stack_->setCurrentWidget(empty_page_);root->addWidget(right_stack_, 2);@@ -211,6 +230,27 @@ void AccountManagementDialog::on_account_selected(int row) {}const auto prof = broker->profile();++ // Zerodha gets its own dedicated form; all others use the generic builder.+ if (account.broker_id == QStringLiteral("zerodha")) {+ build_zerodha_form();+ const QString state_str = connection_state_str(account.state);+ if (z_title_)+ z_title_->setText(QString("%1 — %2 | %3").arg(account.display_name, prof.region, prof.currency));+ if (z_status_) {+ z_status_->setText(QString("Status: %1").arg(state_str));+ if (account.state == ConnectionState::Connected)+ z_status_->setStyleSheet(QString("color: %1;").arg(colors::POSITIVE()));+ else if (account.state == ConnectionState::Error || account.state == ConnectionState::TokenExpired)+ z_status_->setStyleSheet(QString("color: %1;").arg(colors::NEGATIVE()));+ else+ z_status_->setStyleSheet(QString("color: %1;").arg(colors::TEXT_SECONDARY()));+ }+ load_saved_credentials(selected_account_id_);+ right_stack_->setCurrentWidget(zerodha_page_);+ return;+ }+form_title_->setText(QString("%1 — %2 | %3").arg(account.display_name, prof.region, prof.currency));// Update status@@ -259,6 +299,18 @@ void AccountManagementDialog::build_credential_form(const trading::BrokerProfilevoid AccountManagementDialog::load_saved_credentials(const QString& account_id) {auto creds = AccountManager::instance().load_credentials(account_id);++ // Zerodha branch — populate the dedicated form.+ if (creds.broker_id == QStringLiteral("zerodha") && z_api_key_) {+ z_api_key_->setText(creds.api_key);+ z_api_secret_->setText(creds.api_secret);+ z_user_id_->setText(creds.user_id);+ const auto extra = QJsonDocument::fromJson(creds.additional_data.toUtf8()).object();+ z_password_->setText(extra.value("password").toString());+ z_totp_secret_->setText(extra.value("totp_secret").toString());+ return;+ }+int idx = 0;for (const auto& def : cred_field_defs_) {if (def.field == CredentialField::Environment)@@ -304,6 +356,15 @@ void AccountManagementDialog::on_add_account() {}auto account = AccountManager::instance().add_account(broker_id, name);+ if (account.account_id.isEmpty()) {+ // AccountManager returns an empty account on persistence failure (e.g. FK+ // violation, paper-portfolio creation failed). Surface this instead of+ // silently pretending the account was added.+ QMessageBox::critical(this, "Add Account",+ "Could not save the account to the database. "+ "Check the application log for details.");+ return;+ }display_name_input_->clear();refresh_account_list();@@ -381,41 +442,75 @@ void AccountManagementDialog::on_connect_account() {++idx;}- // Attempt token exchange+ // Attempt token exchange asynchronously — exchange_token() makes a blocking+ // HTTP call (BrokerHttp::execute uses QEventLoop), so running it on the UI+ // thread freezes the entire terminal until the request completes. Offload+ // to a worker thread and post results back via QMetaObject::invokeMethod.form_status_->setText("Connecting...");form_status_->setStyleSheet(QString("color: %1;").arg(colors::AMBER()));-- auto result = broker->exchange_token(creds.api_key, creds.api_secret, auth_code);- if (!result.success) {- form_status_->setText(QString("Error: %1").arg(result.error));- form_status_->setStyleSheet(QString("color: %1;").arg(colors::NEGATIVE()));- AccountManager::instance().set_connection_state(selected_account_id_, ConnectionState::Error, result.error);- refresh_account_list();- return;- }-- // Merge token exchange results into credentials- creds.access_token = result.access_token;- if (!result.user_id.isEmpty())- creds.user_id = result.user_id;- if (!result.additional_data.isEmpty()) {- // Merge additional_data (keep existing fields like client_code)- auto existing = QJsonDocument::fromJson(creds.additional_data.toUtf8()).object();- auto extra = QJsonDocument::fromJson(result.additional_data.toUtf8()).object();- for (auto it = extra.begin(); it != extra.end(); ++it)- existing[it.key()] = it.value();- creds.additional_data = QJsonDocument(existing).toJson(QJsonDocument::Compact);- }-- // Save credentials and update state- AccountManager::instance().save_credentials(selected_account_id_, creds);- AccountManager::instance().set_connection_state(selected_account_id_, ConnectionState::Connected);-- form_status_->setText(QString("Connected as %1").arg(creds.user_id.isEmpty() ? creds.api_key.left(8) + "..." : creds.user_id));- form_status_->setStyleSheet(QString("color: %1;").arg(colors::POSITIVE()));- refresh_account_list();-- emit credentials_saved(selected_account_id_);+ connect_btn_->setEnabled(false);++ const QString account_id = selected_account_id_;+ QPointer<AccountManagementDialog> self = this;+ const QString api_key_val = creds.api_key;+ const QString api_secret_val = creds.api_secret;+ const QString auth_code_val = auth_code;+ const QString existing_additional = creds.additional_data;++ QtConcurrent::run([self, broker, account_id, api_key_val, api_secret_val, auth_code_val, existing_additional]() {+ auto result = broker->exchange_token(api_key_val, api_secret_val, auth_code_val);++ QMetaObject::invokeMethod(+ qApp,+ [self, account_id, api_key_val, api_secret_val, auth_code_val, existing_additional, result]() {+ // Always update AccountManager — it's thread-safe and survives dialog close+ if (!result.success) {+ AccountManager::instance().set_connection_state(account_id, ConnectionState::Error, result.error);+ if (self) {+ self->form_status_->setText(QString("Error: %1").arg(result.error));+ self->form_status_->setStyleSheet(QString("color: %1;").arg(colors::NEGATIVE()));+ self->connect_btn_->setEnabled(true);+ if (self->selected_account_id_ == account_id)+ self->refresh_account_list();+ }+ return;+ }++ // Build merged credentials+ BrokerCredentials creds;+ creds.broker_id = AccountManager::instance().get_account(account_id).broker_id;+ creds.api_key = api_key_val;+ creds.api_secret = api_secret_val;+ creds.access_token = result.access_token;+ if (!result.user_id.isEmpty())+ creds.user_id = result.user_id;++ // Merge additional_data (keep existing like client_code, add new from token response)+ auto existing = QJsonDocument::fromJson(existing_additional.toUtf8()).object();+ auto extra = QJsonDocument::fromJson(result.additional_data.toUtf8()).object();+ for (auto it = extra.begin(); it != extra.end(); ++it)+ existing[it.key()] = it.value();+ if (!existing.isEmpty())+ creds.additional_data = QJsonDocument(existing).toJson(QJsonDocument::Compact);++ AccountManager::instance().save_credentials(account_id, creds);+ AccountManager::instance().set_connection_state(account_id, ConnectionState::Connected);++ // Emit signal so EquityTradingScreen starts the data stream, even if the+ // dialog has been closed in the meantime.+ if (self) {+ emit self->credentials_saved(account_id);+ self->form_status_->setText(QString("Connected as %1")+ .arg(creds.user_id.isEmpty() ? creds.api_key.left(8) + "..."+ : creds.user_id));+ self->form_status_->setStyleSheet(QString("color: %1;").arg(colors::POSITIVE()));+ self->connect_btn_->setEnabled(true);+ if (self->selected_account_id_ == account_id)+ self->refresh_account_list();+ }+ },+ Qt::QueuedConnection);+ });}void AccountManagementDialog::on_rename_account() {@@ -436,4 +531,399 @@ void AccountManagementDialog::on_rename_account() {}}+// ── Zerodha-specific form ───────────────────────────────────────────────────++void AccountManagementDialog::build_zerodha_form() {+ // Idempotent — rebuild only if not yet built.+ if (z_api_key_ != nullptr)+ return;++ auto* outer = new QVBoxLayout(zerodha_page_);+ outer->setContentsMargins(0, 0, 0, 0);++ auto* scroll = new QScrollArea(zerodha_page_);+ scroll->setWidgetResizable(true);+ scroll->setFrameShape(QFrame::NoFrame);+ outer->addWidget(scroll);++ auto* container = new QWidget;+ scroll->setWidget(container);+ auto* v = new QVBoxLayout(container);+ v->setContentsMargins(8, 8, 8, 8);+ v->setSpacing(10);++ // Title + status+ z_title_ = new QLabel("Zerodha");+ z_title_->setObjectName("titleLabel");+ v->addWidget(z_title_);+ z_status_ = new QLabel(" ");+ z_status_->setObjectName("statusLabel");+ v->addWidget(z_status_);++ // Collapsible "First-time setup" panel+ z_setup_toggle_ = new QPushButton(QString::fromUtf8("\xe2\x96\xb8") + QStringLiteral(" First-time setup (4 steps)"));+ z_setup_toggle_->setStyleSheet(QString("text-align:left;background:transparent;color:%1;"+ "border:none;padding:4px 0;font-weight:700;")+ .arg(colors::AMBER()));+ v->addWidget(z_setup_toggle_);++ z_setup_panel_ = new QWidget;+ auto* setup = new QVBoxLayout(z_setup_panel_);+ setup->setContentsMargins(12, 4, 12, 12);+ setup->setSpacing(4);+ auto add_step = [&](const QString& text) {+ auto* l = new QLabel(text);+ l->setWordWrap(true);+ l->setTextFormat(Qt::RichText);+ l->setOpenExternalLinks(true);+ l->setStyleSheet(QString("color:%1;font-size:11px;").arg(colors::TEXT_SECONDARY()));+ setup->addWidget(l);+ };+ add_step("1. Create a Kite Connect app at <a href='https://developers.kite.trade/apps'>developers.kite.trade/apps</a>.");+ add_step("2. Register redirect URL <b>http://127.0.0.1:5010/</b> on that app.");+ add_step("3. Enable TOTP 2FA on your Zerodha account (<a href='https://support.zerodha.com/category/your-zerodha-account/login-credentials/articles/time-based-otp'>support.zerodha.com</a>).");+ add_step("4. For auto-login, copy the Base32 TOTP secret during 2FA setup (\"Can't scan?\" link).");+ z_setup_panel_->setVisible(false);+ v->addWidget(z_setup_panel_);++ QPointer<AccountManagementDialog> self = this;+ connect(z_setup_toggle_, &QPushButton::clicked, this, [self]() {+ if (!self) return;+ const bool vis = !self->z_setup_panel_->isVisible();+ self->z_setup_panel_->setVisible(vis);+ self->z_setup_toggle_->setText((vis ? QString::fromUtf8("\xe2\x96\xbe") : QString::fromUtf8("\xe2\x96\xb8"))+ + QStringLiteral(" First-time setup (4 steps)"));+ });++ // Mode radio+ auto* mode_row = new QHBoxLayout;+ mode_row->setSpacing(16);+ z_mode_totp_ = new QRadioButton("Auto-login (TOTP)");+ z_mode_browser_ = new QRadioButton("Browser login");+ z_mode_totp_->setChecked(true);+ mode_row->addWidget(z_mode_totp_);+ mode_row->addWidget(z_mode_browser_);+ mode_row->addStretch();+ v->addLayout(mode_row);++ auto add_labeled_field = [&](QBoxLayout* lay, const QString& label, QLineEdit*& out,+ const QString& placeholder, const QString& hint, bool password) {+ auto* hdr = make_field_label(label);+ lay->addWidget(hdr);+ out = make_field(placeholder, password);+ lay->addWidget(out);+ if (!hint.isEmpty()) {+ auto* h = new QLabel(hint);+ h->setStyleSheet(QString("color:%1;font-size:10px;margin-bottom:4px;")+ .arg(colors::TEXT_SECONDARY()));+ lay->addWidget(h);+ }+ };++ // Always-visible+ add_labeled_field(v, "API KEY", z_api_key_, "Enter API Key...",+ "from developers.kite.trade -> My Apps", false);+ add_labeled_field(v, "API SECRET", z_api_secret_, "Enter API Secret...",+ "same console, shown once - regenerate if lost", true);++ // TOTP group+ z_totp_group_ = new QWidget;+ auto* tv = new QVBoxLayout(z_totp_group_);+ tv->setContentsMargins(0, 0, 0, 0);+ tv->setSpacing(6);+ add_labeled_field(tv, "KITE USER ID", z_user_id_, "e.g. AB1234", "", false);+ add_labeled_field(tv, "PASSWORD", z_password_, "Zerodha login password", "", true);+ add_labeled_field(tv, "TOTP SECRET", z_totp_secret_, "Base32 string",+ "Base32 secret from Zerodha 2FA setup", true);+ v->addWidget(z_totp_group_);++ // Browser group+ z_browser_group_ = new QWidget;+ auto* bv = new QVBoxLayout(z_browser_group_);+ bv->setContentsMargins(0, 0, 0, 0);+ bv->setSpacing(6);+ z_browser_btn_ = new QPushButton("Open Kite login in browser");+ z_browser_btn_->setStyleSheet(QString("QPushButton { background: %1; color: %2; padding: 10px; font-weight: 700; }")+ .arg(colors::AMBER(), colors::BG_BASE()));+ bv->addWidget(z_browser_btn_);+ z_manual_toggle_ = new QPushButton("Redirect didn't work? Paste request_token manually");+ z_manual_toggle_->setStyleSheet(QString("text-align:left;background:transparent;color:%1;"+ "border:none;padding:4px 0;font-size:11px;")+ .arg(colors::TEXT_SECONDARY()));+ bv->addWidget(z_manual_toggle_);+ z_manual_panel_ = new QWidget;+ auto* mv = new QVBoxLayout(z_manual_panel_);+ mv->setContentsMargins(0, 0, 0, 0);+ mv->setSpacing(4);+ z_manual_token_ = make_field("Paste request_token here", false);+ mv->addWidget(z_manual_token_);+ z_manual_connect_btn_ = new QPushButton("Connect with pasted token");+ z_manual_connect_btn_->setStyleSheet(QString("QPushButton { background: %1; color: %2; }")+ .arg(colors::BG_RAISED(), colors::TEXT_PRIMARY()));+ mv->addWidget(z_manual_connect_btn_);+ z_manual_panel_->setVisible(false);+ bv->addWidget(z_manual_panel_);+ z_browser_group_->setVisible(false);+ v->addWidget(z_browser_group_);++ connect(z_manual_toggle_, &QPushButton::clicked, this, [self]() {+ if (!self) return;+ self->z_manual_panel_->setVisible(!self->z_manual_panel_->isVisible());+ });++ v->addStretch();++ // Bottom action row+ auto* btn_row = new QHBoxLayout;+ z_rename_btn_ = new QPushButton("RENAME");+ z_rename_btn_->setStyleSheet(QString("QPushButton { background: %1; color: %2; }")+ .arg(colors::BG_RAISED(), colors::TEXT_PRIMARY()));+ btn_row->addWidget(z_rename_btn_);+ z_connect_btn_ = new QPushButton("CONNECT");+ z_connect_btn_->setStyleSheet(QString("QPushButton { background: %1; color: %2; padding: 8px 24px; }")+ .arg(colors::AMBER(), colors::BG_BASE()));+ btn_row->addWidget(z_connect_btn_);+ v->addLayout(btn_row);++ // Wire signals+ connect(z_mode_totp_, &QRadioButton::toggled, this, &AccountManagementDialog::on_zerodha_mode_changed);+ connect(z_connect_btn_, &QPushButton::clicked, this, &AccountManagementDialog::on_connect_zerodha_totp);+ connect(z_browser_btn_, &QPushButton::clicked, this, &AccountManagementDialog::on_connect_zerodha_browser);+ connect(z_manual_connect_btn_, &QPushButton::clicked, this,+ &AccountManagementDialog::on_connect_zerodha_manual_paste);+ connect(z_rename_btn_, &QPushButton::clicked, this, &AccountManagementDialog::on_rename_account);++ on_zerodha_mode_changed();+}++void AccountManagementDialog::on_zerodha_mode_changed() {+ if (!z_mode_totp_)+ return;+ const bool totp = z_mode_totp_->isChecked();+ z_totp_group_->setVisible(totp);+ z_browser_group_->setVisible(!totp);+ z_connect_btn_->setVisible(totp);+}++void AccountManagementDialog::persist_zerodha_creds_before_auth() {+ BrokerCredentials creds;+ creds.broker_id = "zerodha";+ creds.api_key = z_api_key_->text().trimmed();+ creds.api_secret = z_api_secret_->text();+ creds.user_id = z_user_id_->text().trimmed();++ QJsonObject extra;+ extra.insert("password", z_password_->text());+ extra.insert("totp_secret", z_totp_secret_->text().trimmed());+ creds.additional_data = QString::fromUtf8(QJsonDocument(extra).toJson(QJsonDocument::Compact));++ AccountManager::instance().save_credentials(selected_account_id_, creds);+}++void AccountManagementDialog::on_connect_zerodha_totp() {+ if (selected_account_id_.isEmpty())+ return;++ const QString api_key = z_api_key_->text().trimmed();+ const QString api_secret = z_api_secret_->text();+ const QString user_id = z_user_id_->text().trimmed();+ const QString password = z_password_->text();+ const QString totp_secret = z_totp_secret_->text().trimmed();++ auto show_err = [this](const QString& msg) {+ z_status_->setText(msg);+ z_status_->setStyleSheet(QString("color:%1;").arg(colors::NEGATIVE()));+ };+ if (api_key.isEmpty()) { show_err("Missing field: API Key"); return; }+ if (api_secret.isEmpty()) { show_err("Missing field: API Secret"); return; }+ if (user_id.isEmpty()) { show_err("Missing field: Kite User ID"); return; }+ if (password.isEmpty()) { show_err("Missing field: Password"); return; }+ if (totp_secret.isEmpty()){ show_err("Missing field: TOTP Secret"); return; }++ // BUG 1 FIX: persist immediately so failure doesn't wipe the form.+ persist_zerodha_creds_before_auth();++ z_status_->setText("Logging in...");+ z_status_->setStyleSheet(QString("color:%1;").arg(colors::AMBER()));+ z_connect_btn_->setEnabled(false);++ const QString acct = selected_account_id_;+ QPointer<AccountManagementDialog> self = this;++ QtConcurrent::run([self, acct, user_id, password, api_key, api_secret, totp_secret]() {+ trading::ZerodhaBroker broker;+ auto stage_cb = [self](const QString& stage) {+ QMetaObject::invokeMethod(qApp, [self, stage]() {+ if (!self || !self->z_status_) return;+ self->z_status_->setText(stage);+ }, Qt::QueuedConnection);+ };+ auto result = broker.login_with_totp(user_id, password, api_key, api_secret,+ totp_secret, stage_cb);++ QMetaObject::invokeMethod(qApp, [self, acct, result]() {+ if (!self) return;+ auto& am = AccountManager::instance();++ if (result.success) {+ auto creds = am.load_credentials(acct);+ creds.access_token = result.access_token;+ if (!result.user_id.isEmpty())+ creds.user_id = result.user_id;+ // Merge broker-returned extras into saved additional_data JSON.+ auto saved_obj = QJsonDocument::fromJson(creds.additional_data.toUtf8()).object();+ const auto returned_obj =+ QJsonDocument::fromJson(result.additional_data.toUtf8()).object();+ for (auto it = returned_obj.begin(); it != returned_obj.end(); ++it)+ saved_obj.insert(it.key(), it.value());+ creds.additional_data =+ QString::fromUtf8(QJsonDocument(saved_obj).toJson(QJsonDocument::Compact));+ am.save_credentials(acct, creds);+ am.set_connection_state(acct, ConnectionState::Connected, {});+ self->z_status_->setText(QString("Connected as %1").arg(result.user_id));+ self->z_status_->setStyleSheet(QString("color:%1;").arg(colors::POSITIVE()));+ emit self->credentials_saved(acct);+ } else {+ am.set_connection_state(acct, ConnectionState::Error, result.error);+ self->z_status_->setText(result.error);+ self->z_status_->setStyleSheet(QString("color:%1;").arg(colors::NEGATIVE()));+ }+ self->z_connect_btn_->setEnabled(true);+ self->refresh_account_list();+ }, Qt::QueuedConnection);+ });+}++void AccountManagementDialog::on_connect_zerodha_browser() {+ if (selected_account_id_.isEmpty())+ return;++ const QString api_key = z_api_key_->text().trimmed();+ const QString api_secret = z_api_secret_->text();+ if (api_key.isEmpty() || api_secret.isEmpty()) {+ z_status_->setText("Enter API Key and API Secret first");+ z_status_->setStyleSheet(QString("color:%1;").arg(colors::NEGATIVE()));+ return;+ }++ // BUG 1 FIX: persist key+secret now.+ persist_zerodha_creds_before_auth();++ // Tear down any prior server+ if (z_redirect_server_) {+ z_redirect_server_->deleteLater();+ z_redirect_server_ = nullptr;+ }+ z_redirect_server_ = new trading::auth::RedirectServer(this);++ if (!z_redirect_server_->start(5010, 120)) {+ z_status_->setText("Port 5010 busy - use manual paste fallback");+ z_status_->setStyleSheet(QString("color:%1;").arg(colors::NEGATIVE()));+ z_redirect_server_->deleteLater();+ z_redirect_server_ = nullptr;+ z_manual_panel_->setVisible(true);+ return;+ }++ QPointer<AccountManagementDialog> self = this;+ connect(z_redirect_server_, &trading::auth::RedirectServer::request_token_received, this,+ [self, api_key, api_secret](const QString& token) {+ if (!self) return;+ self->z_status_->setText("Exchanging token...");+ self->exchange_and_store_token_async(api_key, api_secret, token);+ if (self->z_redirect_server_) {+ self->z_redirect_server_->deleteLater();+ self->z_redirect_server_ = nullptr;+ }+ });+ connect(z_redirect_server_, &trading::auth::RedirectServer::timeout, this, [self]() {+ if (!self) return;+ self->z_status_->setText("Browser login timed out - try again or paste manually");+ self->z_status_->setStyleSheet(QString("color:%1;").arg(colors::NEGATIVE()));+ if (self->z_redirect_server_) {+ self->z_redirect_server_->deleteLater();+ self->z_redirect_server_ = nullptr;+ }+ });++ z_status_->setText(QString("Waiting for browser login on port %1 (120s)...")+ .arg(z_redirect_server_->port()));+ z_status_->setStyleSheet(QString("color:%1;").arg(colors::AMBER()));+ QDesktopServices::openUrl(QUrl(trading::ZerodhaBroker::kite_login_url(api_key)));+}++void AccountManagementDialog::on_connect_zerodha_manual_paste() {+ if (selected_account_id_.isEmpty())+ return;+ const QString api_key = z_api_key_->text().trimmed();+ const QString api_secret = z_api_secret_->text();+ QString token = z_manual_token_->text().trimmed();+ if (api_key.isEmpty() || api_secret.isEmpty() || token.isEmpty()) {+ z_status_->setText("Enter API Key, API Secret, and paste request_token");+ z_status_->setStyleSheet(QString("color:%1;").arg(colors::NEGATIVE()));+ return;+ }+ // Accept either a raw token or the full redirect URL (e.g. "https://127.0.0.1/?request_token=...&status=success").+ LOG_INFO("Zerodha", QString("manual paste input (%1 chars): %2").arg(token.length()).arg(token));+ if (token.contains(QStringLiteral("request_token"), Qt::CaseInsensitive)) {+ const QUrl url = token.startsWith(QStringLiteral("http"), Qt::CaseInsensitive)+ ? QUrl(token)+ : QUrl(QStringLiteral("http://x/?") + token);+ const QString extracted = QUrlQuery(url).queryItemValue(QStringLiteral("request_token"));+ if (!extracted.isEmpty())+ token = extracted;+ }+ LOG_INFO("Zerodha", QString("manual paste extracted token: %1").arg(token));+ if (token.contains(QLatin1Char('/')) || token.contains(QLatin1Char('?')) || token.contains(QLatin1Char('='))) {+ z_status_->setText("Could not find request_token in pasted text");+ z_status_->setStyleSheet(QString("color:%1;").arg(colors::NEGATIVE()));+ return;+ }+ persist_zerodha_creds_before_auth();+ z_status_->setText("Exchanging token...");+ z_status_->setStyleSheet(QString("color:%1;").arg(colors::AMBER()));+ exchange_and_store_token_async(api_key, api_secret, token);+}++void AccountManagementDialog::exchange_and_store_token_async(const QString& api_key,+ const QString& api_secret,+ const QString& request_token) {+ z_connect_btn_->setEnabled(false);+ z_browser_btn_->setEnabled(false);+ z_manual_connect_btn_->setEnabled(false);++ const QString acct = selected_account_id_;+ QPointer<AccountManagementDialog> self = this;++ QtConcurrent::run([self, acct, api_key, api_secret, request_token]() {+ trading::ZerodhaBroker broker;+ auto result = broker.exchange_token(api_key, api_secret, request_token);++ QMetaObject::invokeMethod(qApp, [self, acct, result]() {+ if (!self) return;+ auto& am = AccountManager::instance();++ if (result.success) {+ auto creds = am.load_credentials(acct);+ creds.access_token = result.access_token;+ if (!result.user_id.isEmpty())+ creds.user_id = result.user_id;+ am.save_credentials(acct, creds);+ am.set_connection_state(acct, ConnectionState::Connected, {});+ self->z_status_->setText(QString("Connected as %1").arg(result.user_id));+ self->z_status_->setStyleSheet(QString("color:%1;").arg(colors::POSITIVE()));+ emit self->credentials_saved(acct);+ } else {+ am.set_connection_state(acct, ConnectionState::Error, result.error);+ self->z_status_->setText(result.error);+ self->z_status_->setStyleSheet(QString("color:%1;").arg(colors::NEGATIVE()));+ }+ self->z_connect_btn_->setEnabled(true);+ self->z_browser_btn_->setEnabled(true);+ self->z_manual_connect_btn_->setEnabled(true);+ self->refresh_account_list();+ }, Qt::QueuedConnection);+ });+}+} // namespace fincept::screens::equitydiff --git a/fincept-qt/src/screens/equity_trading/AccountManagementDialog.h b/fincept-qt/src/screens/equity_trading/AccountManagementDialog.hindex 036c6cadd..0b1107b9d 100644--- a/fincept-qt/src/screens/equity_trading/AccountManagementDialog.h+++ b/fincept-qt/src/screens/equity_trading/AccountManagementDialog.h@@ -6,13 +6,20 @@#include "trading/BrokerAccount.h"#include "trading/BrokerInterface.h"+#include <QCheckBox>#include <QComboBox>#include <QDialog>#include <QLabel>#include <QLineEdit>#include <QListWidget>#include <QPushButton>+#include <QRadioButton>#include <QStackedWidget>+#include <QVBoxLayout>++namespace fincept::trading::auth {+class RedirectServer;+}namespace fincept::screens::equity {@@ -37,6 +44,16 @@ class AccountManagementDialog : public QDialog {void build_credential_form(const trading::BrokerProfile& profile);void load_saved_credentials(const QString& account_id);+ // Zerodha-specific form + handlers+ void build_zerodha_form();+ void on_zerodha_mode_changed();+ void on_connect_zerodha_totp();+ void on_connect_zerodha_browser();+ void on_connect_zerodha_manual_paste();+ void persist_zerodha_creds_before_auth();+ void exchange_and_store_token_async(const QString& api_key, const QString& api_secret,+ const QString& request_token);+// Left panel — account listQListWidget* account_list_ = nullptr;QPushButton* add_btn_ = nullptr;@@ -48,6 +65,7 @@ class AccountManagementDialog : public QDialog {QStackedWidget* right_stack_ = nullptr;QWidget* empty_page_ = nullptr;QWidget* form_page_ = nullptr;+ QWidget* zerodha_page_ = nullptr;QLabel* form_title_ = nullptr;QLabel* form_status_ = nullptr;QVBoxLayout* fields_layout_ = nullptr;@@ -58,6 +76,30 @@ class AccountManagementDialog : public QDialog {QVector<QLineEdit*> cred_fields_;QVector<trading::CredentialFieldDef> cred_field_defs_;+ // Zerodha-specific widgets+ QLabel* z_title_ = nullptr;+ QLabel* z_status_ = nullptr;+ QPushButton* z_setup_toggle_ = nullptr;+ QWidget* z_setup_panel_ = nullptr;+ QRadioButton* z_mode_totp_ = nullptr;+ QRadioButton* z_mode_browser_ = nullptr;+ QLineEdit* z_api_key_ = nullptr;+ QLineEdit* z_api_secret_ = nullptr;+ QWidget* z_totp_group_ = nullptr;+ QLineEdit* z_user_id_ = nullptr;+ QLineEdit* z_password_ = nullptr;+ QLineEdit* z_totp_secret_ = nullptr;+ QWidget* z_browser_group_ = nullptr;+ QPushButton* z_browser_btn_ = nullptr;+ QPushButton* z_manual_toggle_ = nullptr;+ QWidget* z_manual_panel_ = nullptr;+ QLineEdit* z_manual_token_ = nullptr;+ QPushButton* z_manual_connect_btn_ = nullptr;+ QPushButton* z_connect_btn_ = nullptr;+ QPushButton* z_rename_btn_ = nullptr;++ trading::auth::RedirectServer* z_redirect_server_ = nullptr;+// Currently selected accountQString selected_account_id_;};diff --git a/fincept-qt/src/screens/equity_trading/EquityBottomPanel.cpp b/fincept-qt/src/screens/equity_trading/EquityBottomPanel.cppindex 778f2ac55..1c0a6a596 100644--- a/fincept-qt/src/screens/equity_trading/EquityBottomPanel.cpp+++ b/fincept-qt/src/screens/equity_trading/EquityBottomPanel.cpp@@ -10,6 +10,7 @@#include <QHeaderView>#include <QLineEdit>#include <QPushButton>+#include <QScrollBar>#include <QVBoxLayout>namespace fincept::screens::equity {@@ -67,17 +68,83 @@ void EquityBottomPanel::setup_positions_tab() {// ── Holdings Tab ───────────────────────────────────────────────────────────void EquityBottomPanel::setup_holdings_tab() {+ auto* tab = new QWidget;+ auto* v = new QVBoxLayout(tab);+ v->setContentsMargins(0, 0, 0, 0);+ v->setSpacing(0);++ // Summary strip across the top of the Holdings tab.+ auto* strip = new QWidget;+ strip->setObjectName("eqHoldingsStrip");+ strip->setStyleSheet(QString("#eqHoldingsStrip{background:%1;border-bottom:1px solid %2;}")+ .arg(fincept::ui::colors::PANEL(), fincept::ui::colors::BORDER()));+ auto* strip_layout = new QHBoxLayout(strip);+ strip_layout->setContentsMargins(12, 6, 12, 6);+ strip_layout->setSpacing(24);++ auto make_stat = [&](const QString& caption) -> QLabel* {+ auto* cell = new QWidget;+ auto* cv = new QVBoxLayout(cell);+ cv->setContentsMargins(0, 0, 0, 0);+ cv->setSpacing(1);+ auto* cap = new QLabel(caption);+ cap->setStyleSheet(QString("color:%1;font-size:10px;letter-spacing:0.5px;")+ .arg(fincept::ui::colors::TEXT_SECONDARY()));+ auto* val = new QLabel("--");+ val->setStyleSheet(QString("color:%1;font-size:13px;font-weight:700;")+ .arg(fincept::ui::colors::TEXT_PRIMARY()));+ cv->addWidget(cap);+ cv->addWidget(val);+ strip_layout->addWidget(cell);+ return val;+ };+ holdings_count_label_ = make_stat("HOLDINGS");+ holdings_invested_label_ = make_stat("INVESTED");+ holdings_current_label_ = make_stat("CURRENT");+ holdings_pnl_label_ = make_stat("TOTAL P&L");+ holdings_pnl_pct_label_ = make_stat("RETURN %");+ strip_layout->addStretch(1);++ holdings_import_btn_ = new QPushButton("IMPORT TO PORTFOLIO");+ holdings_import_btn_->setCursor(Qt::PointingHandCursor);+ holdings_import_btn_->setEnabled(false);+ holdings_import_btn_->setStyleSheet(+ QString("QPushButton{background:%1;color:%2;border:1px solid %3;padding:4px 12px;"+ "font-size:11px;font-weight:700;letter-spacing:0.5px;}"+ "QPushButton:hover{background:%4;color:#000;}"+ "QPushButton:disabled{color:%5;border-color:%3;}")+ .arg(fincept::ui::colors::PANEL(), fincept::ui::colors::ORANGE(),+ fincept::ui::colors::BORDER(), fincept::ui::colors::ORANGE(),+ fincept::ui::colors::TEXT_SECONDARY()));+ connect(holdings_import_btn_, &QPushButton::clicked, this, [this]() {+ if (!last_holdings_.isEmpty())+ emit import_holdings_requested(last_holdings_);+ });+ strip_layout->addWidget(holdings_import_btn_);++ v->addWidget(strip);+holdings_table_ = new QTableWidget;holdings_table_->setObjectName("eqTable");- holdings_table_->setColumnCount(7);- holdings_table_->setHorizontalHeaderLabels({"Symbol", "Qty", "Avg Price", "LTP", "Invested", "Current", "P&L %"});+ holdings_table_->setColumnCount(8);+ holdings_table_->setHorizontalHeaderLabels(+ {"Symbol", "Qty", "Avg Price", "LTP", "Invested", "Current", "P&L", "P&L %"});holdings_table_->verticalHeader()->setVisible(false);holdings_table_->setSelectionBehavior(QAbstractItemView::SelectRows);holdings_table_->setEditTriggers(QAbstractItemView::NoEditTriggers);holdings_table_->setShowGrid(false);holdings_table_->horizontalHeader()->setStretchLastSection(true);holdings_table_->verticalHeader()->setDefaultSectionSize(22);- tabs_->addTab(holdings_table_, "HOLDINGS");+ holdings_table_->setAlternatingRowColors(true);+ holdings_table_->setSortingEnabled(true);+ // Smooth pixel-based scrolling (default is per-item, which feels janky).+ holdings_table_->setVerticalScrollMode(QAbstractItemView::ScrollPerPixel);+ holdings_table_->setHorizontalScrollMode(QAbstractItemView::ScrollPerPixel);+ holdings_table_->verticalScrollBar()->setSingleStep(8);+ holdings_table_->horizontalScrollBar()->setSingleStep(16);++ v->addWidget(holdings_table_, 1);+ tabs_->addTab(tab, "HOLDINGS");}// ── Orders Tab ─────────────────────────────────────────────────────────────@@ -265,21 +332,75 @@ void EquityBottomPanel::set_positions(const QVector<trading::BrokerPosition>& po}void EquityBottomPanel::set_holdings(const QVector<trading::BrokerHolding>& holdings) {+ last_holdings_ = holdings;+ if (holdings_import_btn_)+ holdings_import_btn_->setEnabled(!holdings.isEmpty());++ // Disable sorting during population so setItem assignments stay at intended rows.+ const bool was_sorting = holdings_table_->isSortingEnabled();+ holdings_table_->setSortingEnabled(false);holdings_table_->setRowCount(holdings.size());++ double total_invested = 0.0;+ double total_current = 0.0;+ double total_pnl = 0.0;++ const QColor pos_color(fincept::ui::colors::POSITIVE());+ const QColor neg_color(fincept::ui::colors::NEGATIVE());++ auto set_num = [](QTableWidgetItem* it, double v, int precision) {+ it->setData(Qt::DisplayRole, QString::number(v, 'f', precision));+ it->setData(Qt::UserRole, v); // for potential custom sort; Display still orders alphabetically+ };+for (int i = 0; i < holdings.size(); ++i) {const auto& h = holdings[i];ensure_item(holdings_table_, i, 0)->setText(h.symbol);- ensure_item(holdings_table_, i, 1)->setText(QString::number(h.quantity, 'f', 0));- ensure_item(holdings_table_, i, 2)->setText(QString::number(h.avg_price, 'f', 2));- ensure_item(holdings_table_, i, 3)->setText(QString::number(h.ltp, 'f', 2));- ensure_item(holdings_table_, i, 4)->setText(QString::number(h.invested_value, 'f', 2));- ensure_item(holdings_table_, i, 5)->setText(QString::number(h.current_value, 'f', 2));+ set_num(ensure_item(holdings_table_, i, 1), h.quantity, 0);+ set_num(ensure_item(holdings_table_, i, 2), h.avg_price, 2);+ set_num(ensure_item(holdings_table_, i, 3), h.ltp, 2);+ set_num(ensure_item(holdings_table_, i, 4), h.invested_value, 2);+ set_num(ensure_item(holdings_table_, i, 5), h.current_value, 2);auto* pnl_item = ensure_item(holdings_table_, i, 6);- pnl_item->setText(QString("%1%").arg(h.pnl_pct, 0, 'f', 2));- pnl_item->setForeground(h.pnl_pct >= 0 ? QColor(fincept::ui::colors::POSITIVE())- : QColor(fincept::ui::colors::NEGATIVE()));+ pnl_item->setText(QString::number(h.pnl, 'f', 2));+ pnl_item->setForeground(h.pnl >= 0 ? pos_color : neg_color);++ auto* pct_item = ensure_item(holdings_table_, i, 7);+ pct_item->setText(QString("%1%").arg(h.pnl_pct, 0, 'f', 2));+ pct_item->setForeground(h.pnl_pct >= 0 ? pos_color : neg_color);++ total_invested += h.invested_value;+ total_current += h.current_value;+ total_pnl += h.pnl;}++ const double total_pct = total_invested > 0 ? (total_pnl / total_invested) * 100.0 : 0.0;++ if (holdings_count_label_)+ holdings_count_label_->setText(QString::number(holdings.size()));+ if (holdings_invested_label_)+ holdings_invested_label_->setText(QString::number(total_invested, 'f', 2));+ if (holdings_current_label_)+ holdings_current_label_->setText(QString::number(total_current, 'f', 2));+ if (holdings_pnl_label_) {+ holdings_pnl_label_->setText(QString("%1%2")+ .arg(total_pnl >= 0 ? "+" : "")+ .arg(QString::number(total_pnl, 'f', 2)));+ holdings_pnl_label_->setStyleSheet(+ QString("color:%1;font-size:13px;font-weight:700;")+ .arg(total_pnl >= 0 ? fincept::ui::colors::POSITIVE() : fincept::ui::colors::NEGATIVE()));+ }+ if (holdings_pnl_pct_label_) {+ holdings_pnl_pct_label_->setText(QString("%1%2%")+ .arg(total_pct >= 0 ? "+" : "")+ .arg(QString::number(total_pct, 'f', 2)));+ holdings_pnl_pct_label_->setStyleSheet(+ QString("color:%1;font-size:13px;font-weight:700;")+ .arg(total_pct >= 0 ? fincept::ui::colors::POSITIVE() : fincept::ui::colors::NEGATIVE()));+ }++ holdings_table_->setSortingEnabled(was_sorting);}void EquityBottomPanel::set_orders(const QVector<trading::BrokerOrderInfo>& orders) {diff --git a/fincept-qt/src/screens/equity_trading/EquityBottomPanel.h b/fincept-qt/src/screens/equity_trading/EquityBottomPanel.hindex 4deccb5f8..889a731ee 100644--- a/fincept-qt/src/screens/equity_trading/EquityBottomPanel.h+++ b/fincept-qt/src/screens/equity_trading/EquityBottomPanel.h@@ -42,6 +42,7 @@ class EquityBottomPanel : public QWidget {signals:void cancel_order_requested(const QString& order_id);void modify_order_requested(const QString& order_id, double new_qty, double new_price);+ void import_holdings_requested(const QVector<trading::BrokerHolding>& holdings);private:void setup_positions_tab();@@ -59,6 +60,13 @@ class EquityBottomPanel : public QWidget {QTableWidget* positions_table_ = nullptr;QTableWidget* holdings_table_ = nullptr;+ QLabel* holdings_invested_label_ = nullptr;+ QLabel* holdings_current_label_ = nullptr;+ QLabel* holdings_pnl_label_ = nullptr;+ QLabel* holdings_pnl_pct_label_ = nullptr;+ QLabel* holdings_count_label_ = nullptr;+ class QPushButton* holdings_import_btn_ = nullptr;+ QVector<trading::BrokerHolding> last_holdings_;QTableWidget* orders_table_ = nullptr;QTableWidget* calendar_table_ = nullptr;QTableWidget* time_sales_table_ = nullptr;diff --git a/fincept-qt/src/screens/equity_trading/EquityCredentials.cpp b/fincept-qt/src/screens/equity_trading/EquityCredentials.cppdeleted file mode 100644index de5d6febb..000000000--- a/fincept-qt/src/screens/equity_trading/EquityCredentials.cpp+++ /dev/null@@ -1,360 +0,0 @@-// EquityCredentials.cpp — broker credential dialog driven by BrokerProfile-#include "screens/equity_trading/EquityCredentials.h"--#include "trading/BrokerRegistry.h"-#include "ui/theme/Theme.h"--#include <QHBoxLayout>-#include <QJsonDocument>-#include <QJsonObject>-#include <QPushButton>-#include <QVBoxLayout>--namespace fincept::screens::equity {--using namespace fincept::ui;--// ── helpers ──────────────────────────────────────────────────────────────────--static QGroupBox* make_section(const QString& title, const QString& color) {- auto* box = new QGroupBox(title);- box->setStyleSheet(QString("QGroupBox { border: 1px solid %1; border-radius: 3px; margin-top: 8px;"- " color: %1; font-size: 11px; font-weight: 700; padding: 8px 6px 6px 6px; }"- "QGroupBox::title { subcontrol-origin: margin; left: 8px; padding: 0 4px; }")- .arg(color));- return box;-}--static QLineEdit* make_field(const QString& placeholder, bool password = false) {- auto* f = new QLineEdit;- f->setPlaceholderText(placeholder);- if (password)- f->setEchoMode(QLineEdit::Password);- return f;-}--static QLabel* make_field_label(const QString& text) {- auto* l = new QLabel(text);- l->setObjectName("fieldLabel");- return l;-}--// ── constructor ──────────────────────────────────────────────────────────────--EquityCredentials::EquityCredentials(const QString& broker_id, const trading::BrokerProfile& profile, QWidget* parent)- : QDialog(parent), broker_id_(broker_id), profile_(profile) {-- setWindowTitle(QString("Connect — %1").arg(profile.display_name));- setMinimumWidth(420);- setStyleSheet(QString("QDialog { background: %1; color: %2; }"- "QLabel#fieldLabel { color: %3; font-size: 11px; font-weight: 700; }"- "QLabel#titleLabel { color: %4; font-size: 14px; font-weight: 700; }"- "QLabel#infoLabel { color: %5; font-size: 10px; }"- "QLabel#savedLabel { color: %6; font-size: 10px; font-weight: 700; }"- "QLineEdit { background: %7; border: 1px solid %8; color: %2;"- " padding: 6px; font-size: 12px; border-radius: 2px; }"- "QLineEdit:focus { border-color: %4; }"- "QComboBox { background: %7; border: 1px solid %8; color: %2;"- " padding: 4px 6px; font-size: 12px; }"- "QComboBox::drop-down { border: none; }"- "QComboBox QAbstractItemView { background: %9; color: %2;"- " selection-background-color: rgba(217,119,6,0.3); }"- "QPushButton { padding: 8px 16px; font-weight: 700; font-size: 12px; border-radius: 2px; }")- .arg(colors::BG_SURFACE())- .arg(colors::TEXT_PRIMARY())- .arg(colors::TEXT_SECONDARY())- .arg(colors::AMBER())- .arg(colors::TEXT_TERTIARY())- .arg(colors::POSITIVE())- .arg(colors::BG_BASE())- .arg(colors::BORDER_MED())- .arg(colors::BG_RAISED()));-- auto* root = new QVBoxLayout(this);- root->setSpacing(8);- root->setContentsMargins(16, 16, 16, 16);-- // Title row- auto* title = new QLabel(QString("%1 | %2 | %3").arg(profile.display_name, profile.region, profile.currency));- title->setObjectName("titleLabel");- root->addWidget(title);-- if (!profile.brokerage_info.isEmpty()) {- auto* info = new QLabel(QString("Brokerage: %1").arg(profile.brokerage_info));- info->setObjectName("infoLabel");- root->addWidget(info);- }- root->addSpacing(4);-- // Load existing saved credentials- auto* broker = trading::BrokerRegistry::instance().get(broker_id_);-- if (profile.has_native_paper) {- // ── Dual section: LIVE + PAPER side by side ───────────────────────- setMinimumWidth(560);- auto* cols = new QHBoxLayout;- cols->setSpacing(12);-- // --- LIVE section ---- auto* live_box = make_section("LIVE ACCOUNT", colors::AMBER.get());- auto* live_lay = new QVBoxLayout(live_box);- live_lay->setSpacing(4);-- live_lay->addWidget(make_field_label("API KEY ID"));- field_live_key_ = make_field("Enter live API Key ID...");- live_lay->addWidget(field_live_key_);-- live_lay->addWidget(make_field_label("API SECRET KEY"));- field_live_secret_ = make_field("Enter live Secret Key...", true);- live_lay->addWidget(field_live_secret_);-- live_status_ = new QLabel;- live_status_->setObjectName("savedLabel");- live_lay->addWidget(live_status_);-- auto* live_btn = new QPushButton("CONNECT LIVE");- live_btn->setStyleSheet(QString("background: rgba(217,119,6,0.15); color: %1; border: 1px solid %2;")- .arg(colors::AMBER())- .arg(colors::AMBER_DIM()));- live_btn->setCursor(Qt::PointingHandCursor);- connect(live_btn, &QPushButton::clicked, this, [this]() { on_connect("live"); });- live_lay->addWidget(live_btn);-- auto* live_clear = new QPushButton("CLEAR");- live_clear->setStyleSheet(QString("background: rgba(220,38,38,0.1); color: %1; border: 1px solid %2;")- .arg(colors::NEGATIVE())- .arg(colors::NEGATIVE_DIM()));- live_clear->setCursor(Qt::PointingHandCursor);- connect(live_clear, &QPushButton::clicked, this, [this]() { on_clear("live"); });- live_lay->addWidget(live_clear);-- // --- PAPER section ---- auto* paper_box = make_section("PAPER ACCOUNT", "#3b82f6");- auto* paper_lay = new QVBoxLayout(paper_box);- paper_lay->setSpacing(4);-- paper_lay->addWidget(make_field_label("API KEY ID"));- field_paper_key_ = make_field("Enter paper API Key ID (PK...)...");- paper_lay->addWidget(field_paper_key_);-- paper_lay->addWidget(make_field_label("API SECRET KEY"));- field_paper_secret_ = make_field("Enter paper Secret Key...", true);- paper_lay->addWidget(field_paper_secret_);-- paper_status_ = new QLabel;- paper_status_->setObjectName("savedLabel");- paper_lay->addWidget(paper_status_);-- auto* paper_btn = new QPushButton("CONNECT PAPER");- paper_btn->setStyleSheet("background: rgba(59,130,246,0.15); color: #3b82f6; border: 1px solid #1d4ed8;");- paper_btn->setCursor(Qt::PointingHandCursor);- connect(paper_btn, &QPushButton::clicked, this, [this]() { on_connect("paper"); });- paper_lay->addWidget(paper_btn);-- auto* paper_clear = new QPushButton("CLEAR");- paper_clear->setStyleSheet(QString("background: rgba(220,38,38,0.1); color: %1; border: 1px solid %2;")- .arg(colors::NEGATIVE())- .arg(colors::NEGATIVE_DIM()));- paper_clear->setCursor(Qt::PointingHandCursor);- connect(paper_clear, &QPushButton::clicked, this, [this]() { on_clear("paper"); });- paper_lay->addWidget(paper_clear);-- cols->addWidget(live_box);- cols->addWidget(paper_box);- root->addLayout(cols);-- // Pre-fill from saved credentials- if (broker) {- auto live_creds = broker->load_credentials_for_env("live");- auto paper_creds = broker->load_credentials_for_env("paper");- if (!live_creds.api_key.isEmpty()) {- field_live_key_->setText(live_creds.api_key);- field_live_secret_->setText(live_creds.api_secret);- live_status_->setText(- QString("● Saved: %1")- .arg(live_creds.user_id.isEmpty() ? live_creds.api_key.left(8) + "..." : live_creds.user_id));- }- if (!paper_creds.api_key.isEmpty()) {- field_paper_key_->setText(paper_creds.api_key);- field_paper_secret_->setText(paper_creds.api_secret);- paper_status_->setText(QString("● Saved: %1")- .arg(paper_creds.user_id.isEmpty() ? paper_creds.api_key.left(8) + "..."- : paper_creds.user_id));- }- }-- } else {- // ── Single section for regular brokers ───────────────────────────- for (const auto& field_def : profile.credential_fields) {- root->addWidget(make_field_label(field_def.label));- switch (field_def.field) {- case trading::CredentialField::ClientCode:- field_client_code_ = make_field(field_def.placeholder);- root->addWidget(field_client_code_);- break;- case trading::CredentialField::ApiKey:- field_key_ = make_field(field_def.placeholder);- root->addWidget(field_key_);- break;- case trading::CredentialField::ApiSecret:- field_secret_ = make_field(field_def.placeholder, field_def.secret);- root->addWidget(field_secret_);- break;- case trading::CredentialField::AuthCode:- field_auth_ = make_field(field_def.placeholder);- root->addWidget(field_auth_);- break;- case trading::CredentialField::Environment:- field_env_ = new QComboBox;- field_env_->addItem("Paper Trading", "paper");- field_env_->addItem("Live Trading", "live");- root->addWidget(field_env_);- break;- }- }-- // Pre-fill saved creds- if (broker) {- auto creds = broker->load_credentials();- if (!creds.api_key.isEmpty() && field_key_)- field_key_->setText(creds.api_key);- if (!creds.api_secret.isEmpty() && field_secret_)- field_secret_->setText(creds.api_secret);- if (!creds.additional_data.isEmpty() && field_env_) {- int idx = field_env_->findData(creds.additional_data);- if (idx >= 0)- field_env_->setCurrentIndex(idx);- }- // Pre-fill client_code and totp_secret from additional_data JSON- if (field_client_code_ && !creds.additional_data.isEmpty()) {- auto doc = QJsonDocument::fromJson(creds.additional_data.toUtf8());- if (doc.isObject()) {- auto obj = doc.object();- if (!obj.value("client_code").toString().isEmpty())- field_client_code_->setText(obj.value("client_code").toString());- if (field_auth_ && !obj.value("totp_secret").toString().isEmpty())- field_auth_->setText(obj.value("totp_secret").toString());- }- }- }-- root->addSpacing(4);- auto* btn_row = new QHBoxLayout;- auto* save_btn = new QPushButton("CONNECT");- save_btn->setStyleSheet(QString("background: rgba(217,119,6,0.15); color: %1; border: 1px solid %2;")- .arg(colors::AMBER())- .arg(colors::AMBER_DIM()));- save_btn->setCursor(Qt::PointingHandCursor);- connect(save_btn, &QPushButton::clicked, this, [this]() { on_connect(""); });-- auto* clear_btn = new QPushButton("CLEAR");- clear_btn->setStyleSheet(QString("background: rgba(220,38,38,0.1); color: %1; border: 1px solid %2;")- .arg(colors::NEGATIVE())- .arg(colors::NEGATIVE_DIM()));- clear_btn->setCursor(Qt::PointingHandCursor);- connect(clear_btn, &QPushButton::clicked, this, [this]() { on_clear(""); });-- btn_row->addWidget(save_btn);- btn_row->addWidget(clear_btn);- root->addLayout(btn_row);- }-- status_label_ = new QLabel("");- status_label_->setWordWrap(true);- root->addWidget(status_label_);- root->addStretch();- adjustSize();-}--// ── slots ─────────────────────────────────────────────────────────────────────--void EquityCredentials::on_connect(const QString& env) {- QString key, secret, auth;-- if (env == "live") {- key = field_live_key_ ? field_live_key_->text().trimmed() : QString();- secret = field_live_secret_ ? field_live_secret_->text().trimmed() : QString();- auth = "live";- } else if (env == "paper") {- key = field_paper_key_ ? field_paper_key_->text().trimmed() : QString();- secret = field_paper_secret_ ? field_paper_secret_->text().trimmed() : QString();- auth = "paper";- } else {- // Regular broker- key = field_key_ ? field_key_->text().trimmed() : QString();- secret = field_secret_ ? field_secret_->text().trimmed() : QString();- if (field_env_)- auth = field_env_->currentData().toString();- else if (field_auth_)- auth = field_auth_->text().trimmed();-- // If broker has a separate client code field, pack it into auth as JSON- if (field_client_code_ && !field_client_code_->text().trimmed().isEmpty()) {- QJsonObject extra;- extra["client_code"] = field_client_code_->text().trimmed();- extra["totp_secret"] = auth;- auth = QString::fromUtf8(QJsonDocument(extra).toJson(QJsonDocument::Compact));- }- }-- if (key.isEmpty()) {- status_label_->setText("API Key is required");- status_label_->setStyleSheet(QString("color: %1;").arg(colors::NEGATIVE()));- return;- }- if (secret.isEmpty() && (field_secret_ || field_live_secret_ || field_paper_secret_)) {- status_label_->setText("API Secret is required");- status_label_->setStyleSheet(QString("color: %1;").arg(colors::NEGATIVE()));- return;- }-- emit credentials_saved(broker_id_, key, secret, auth);- status_label_->setText("Connecting...");- status_label_->setStyleSheet(QString("color: %1;").arg(colors::WARNING()));- // Don't close — let the screen update the status label and close when done-}--void EquityCredentials::on_clear(const QString& env) {- if (env == "live") {- if (field_live_key_)- field_live_key_->clear();- if (field_live_secret_)- field_live_secret_->clear();- if (live_status_)- live_status_->clear();- } else if (env == "paper") {- if (field_paper_key_)- field_paper_key_->clear();- if (field_paper_secret_)- field_paper_secret_->clear();- if (paper_status_)- paper_status_->clear();- } else {- if (field_key_)- field_key_->clear();- if (field_secret_)- field_secret_->clear();- if (field_auth_)- field_auth_->clear();- }- status_label_->setText("Cleared");- status_label_->setStyleSheet(QString("color: %1;").arg(colors::WARNING()));-}--void EquityCredentials::mark_connected(const QString& env, const QString& account_id) {- const QString label = QString("● Connected: %1").arg(account_id);- if (env == "live" && live_status_) {- live_status_->setText(label);- } else if (env == "paper" && paper_status_) {- paper_status_->setText(label);- }- status_label_->setText("Connected successfully");- status_label_->setStyleSheet(QString("color: %1;").arg(colors::POSITIVE()));-}--void EquityCredentials::mark_error(const QString& error) {- status_label_->setText(QString("Error: %1").arg(error));- status_label_->setStyleSheet(QString("color: %1;").arg(colors::NEGATIVE()));-}--} // namespace fincept::screens::equitydiff --git a/fincept-qt/src/screens/equity_trading/EquityCredentials.h b/fincept-qt/src/screens/equity_trading/EquityCredentials.hdeleted file mode 100644index cb7338537..000000000--- a/fincept-qt/src/screens/equity_trading/EquityCredentials.h+++ /dev/null@@ -1,57 +0,0 @@-#pragma once-// EquityCredentials — broker credential dialog driven by BrokerProfile-// For brokers with has_native_paper=true, shows separate LIVE and PAPER sections.--#include "trading/BrokerInterface.h"--#include <QComboBox>-#include <QDialog>-#include <QGroupBox>-#include <QLabel>-#include <QLineEdit>--namespace fincept::screens::equity {--class EquityCredentials : public QDialog {- Q_OBJECT- public:- explicit EquityCredentials(const QString& broker_id, const trading::BrokerProfile& profile,- QWidget* parent = nullptr);-- // Called by EquityTradingScreen after successful auth to update status labels- void mark_connected(const QString& env, const QString& account_id);- void mark_error(const QString& error);-- signals:- // auth_code == "live" / "paper" (for has_native_paper brokers) or auth code string- void credentials_saved(const QString& broker_id, const QString& api_key, const QString& api_secret,- const QString& auth_code);-- private:- void on_connect(const QString& env); // env="live"/"paper"/"" (regular)- void on_clear(const QString& env);-- QString broker_id_;- trading::BrokerProfile profile_;-- // Native-paper broker fields (e.g. Alpaca) — live side- QLineEdit* field_live_key_ = nullptr;- QLineEdit* field_live_secret_ = nullptr;- QLabel* live_status_ = nullptr;-- // Native-paper broker fields — paper side- QLineEdit* field_paper_key_ = nullptr;- QLineEdit* field_paper_secret_ = nullptr;- QLabel* paper_status_ = nullptr;-- // Regular broker fields- QLineEdit* field_client_code_ = nullptr; // AngelOne: separate client/login ID- QLineEdit* field_key_ = nullptr;- QLineEdit* field_secret_ = nullptr;- QLineEdit* field_auth_ = nullptr;- QComboBox* field_env_ = nullptr;-- QLabel* status_label_ = nullptr;-};--} // namespace fincept::screens::equitydiff --git a/fincept-qt/src/screens/equity_trading/EquityTradingScreen.cpp b/fincept-qt/src/screens/equity_trading/EquityTradingScreen.cppindex 25b0127e3..8ce1b60f9 100644--- a/fincept-qt/src/screens/equity_trading/EquityTradingScreen.cpp+++ b/fincept-qt/src/screens/equity_trading/EquityTradingScreen.cpp@@ -1,4 +1,4 @@-// Equity Trading Screen — Bloomberg-style multi-account coordinator+// Equity Trading Screen — multi-account coordinator#include "screens/equity_trading/EquityTradingScreen.h"#include "core/logging/Logger.h"@@ -11,6 +11,7 @@#include "screens/equity_trading/EquityOrderEntry.h"#include "screens/equity_trading/EquityTickerBar.h"#include "screens/equity_trading/EquityWatchlist.h"+#include "services/portfolio/PortfolioService.h"#include "services/workspace/WorkspaceManager.h"#include "storage/repositories/SettingsRepository.h"#include "trading/AccountManager.h"@@ -22,18 +23,33 @@#include "ui/theme/StyleSheets.h"#include "ui/theme/Theme.h"+#include <QCheckBox>+#include <QComboBox>#include <QCompleter>#include <QDate>#include <QDateTime>+#include <QDialog>+#include <QDialogButtonBox>+#include <QFormLayout>#include <QHBoxLayout>+#include <QHash>+#include <QHeaderView>#include <QJsonArray>#include <QJsonDocument>#include <QJsonObject>+#include <QLineEdit>#include <QMessageBox>#include <QPointer>+#include <QPushButton>+#include <QRadioButton>+#include <QScrollBar>#include <QSplitter>#include <QStringListModel>+#include <QTableWidget>#include <QVBoxLayout>++#include <memory>+#include <QtConcurrent/QtConcurrent>namespace fincept::screens {@@ -149,7 +165,7 @@ void EquityTradingScreen::hideEvent(QHideEvent* event) {}// ============================================================================-// UI Setup — Bloomberg 4-zone layout+// UI Setup — 4-zone layout// ============================================================================void EquityTradingScreen::setup_ui() {@@ -314,6 +330,7 @@ void EquityTradingScreen::setup_ui() {connect(orderbook_, &EquityOrderBook::price_clicked, this, &EquityTradingScreen::on_ob_price_clicked);connect(bottom_panel_, &EquityBottomPanel::cancel_order_requested, this, &EquityTradingScreen::on_cancel_order);connect(bottom_panel_, &EquityBottomPanel::modify_order_requested, this, &EquityTradingScreen::async_modify_order);+ connect(bottom_panel_, &EquityBottomPanel::import_holdings_requested, this, &EquityTradingScreen::on_import_holdings_requested);connect(chart_, &EquityChart::timeframe_changed, this, [this](const QString& tf) {auto* stream = DataStreamManager::instance().stream_for(focused_account_id_);if (stream)@@ -1025,4 +1042,277 @@ void EquityTradingScreen::async_modify_order(const QString& order_id, double qty});}+// ============================================================================+// Import holdings -> Portfolio+// ============================================================================++// Broker-exchange → yfinance suffix. Mirrors PortfolioDialogs.cpp so imported+// symbols match the format the portfolio screen's price engine (yfinance) expects.+static QString yfinance_symbol_for(const QString& symbol, const QString& exchange) {+ static const QHash<QString, QString> suffix_map = {+ {"NSE", ".NS"}, {"BSE", ".BO"}, {"HKEX", ".HK"}, {"TSE", ".T"},+ {"KRX", ".KS"}, {"SGX", ".SI"}, {"ASX", ".AX"}, {"IDX", ".JK"},+ {"MYX", ".KL"}, {"SET", ".BK"}, {"PSE", ".PS"}, {"XETR", ".DE"},+ {"FWB", ".F"}, {"LSE", ".L"}, {"BME", ".MC"}, {"MIL", ".MI"},+ {"SIX", ".SW"}, {"TSX", ".TO"}, {"TSXV", ".V"}, {"BMFBOVESPA", ".SA"},+ {"BIST", ".IS"}, {"EGX", ".CA"},+ };+ const QString sym = symbol.trimmed().toUpper();+ const auto it = suffix_map.find(exchange.trimmed().toUpper());+ if (it == suffix_map.end() || sym.isEmpty() || sym.contains('.'))+ return sym;+ return sym + it.value();+}++void EquityTradingScreen::on_import_holdings_requested(const QVector<trading::BrokerHolding>& holdings) {+ if (holdings.isEmpty())+ return;+ if (focused_account_id_.isEmpty()) {+ QMessageBox::warning(this, "Import Holdings", "No account selected.");+ return;+ }+ const auto account = trading::AccountManager::instance().get_account(focused_account_id_);+ const QString broker_id = account.broker_id;+ auto* broker = trading::BrokerRegistry::instance().get(broker_id);+ const QString default_currency = (broker ? broker->profile().currency : QStringLiteral("USD"));+ const QString suggested_name = account.display_name.isEmpty()+ ? QString("%1 Holdings").arg(broker_id.toUpper())+ : QString("%1 - Holdings").arg(account.display_name);++ QDialog dlg(this);+ dlg.setWindowTitle("Import holdings into portfolio");+ dlg.setMinimumSize(780, 560);++ auto* v = new QVBoxLayout(&dlg);+ v->setContentsMargins(16, 16, 16, 16);+ v->setSpacing(10);++ auto* info = new QLabel(QString("Importing <b>%1</b> holdings from <b>%2</b>. "+ "Tickers are auto-mapped to Yahoo Finance format "+ "(NSE→.NS, BSE→.BO). Edit the <i>Yahoo Ticker</i> column "+ "if any symbol needs a manual override.")+ .arg(holdings.size())+ .arg(account.display_name.isEmpty() ? broker_id.toUpper()+ : account.display_name));+ info->setTextFormat(Qt::RichText);+ info->setWordWrap(true);+ v->addWidget(info);++ // ── Portfolio target selection ────────────────────────────────────────+ auto* mode_new = new QRadioButton("Create a new portfolio");+ auto* mode_existing = new QRadioButton("Add to existing portfolio");+ mode_new->setChecked(true);++ auto* mode_row = new QHBoxLayout;+ mode_row->addWidget(mode_new);+ mode_row->addWidget(mode_existing);+ mode_row->addStretch();+ v->addLayout(mode_row);++ auto* new_row = new QWidget;+ auto* new_form = new QFormLayout(new_row);+ new_form->setContentsMargins(18, 0, 0, 0);+ auto* name_input = new QLineEdit(suggested_name);+ auto* currency_input = new QLineEdit(default_currency);+ new_form->addRow("Name:", name_input);+ new_form->addRow("Currency:", currency_input);+ v->addWidget(new_row);++ auto* existing_combo = new QComboBox;+ existing_combo->setEnabled(false);+ existing_combo->addItem("Loading portfolios...");+ auto* existing_row = new QWidget;+ auto* existing_form = new QFormLayout(existing_row);+ existing_form->setContentsMargins(18, 0, 0, 0);+ existing_form->addRow("Portfolio:", existing_combo);+ existing_row->setVisible(false);+ v->addWidget(existing_row);++ // ── Per-row holdings table with editable yfinance ticker ─────────────+ auto* table = new QTableWidget;+ table->setColumnCount(6);+ table->setHorizontalHeaderLabels(+ {"Import", "Broker Symbol", "Exchange", "Yahoo Ticker (edit)", "Quantity", "Avg Price"});+ table->setRowCount(holdings.size());+ table->verticalHeader()->setVisible(false);+ table->setSelectionMode(QAbstractItemView::NoSelection);+ table->setEditTriggers(QAbstractItemView::AllEditTriggers);+ table->setAlternatingRowColors(true);+ table->setVerticalScrollMode(QAbstractItemView::ScrollPerPixel);+ table->verticalScrollBar()->setSingleStep(8);+ {+ auto* hh = table->horizontalHeader();+ hh->setSectionResizeMode(0, QHeaderView::ResizeToContents);+ hh->setSectionResizeMode(1, QHeaderView::ResizeToContents);+ hh->setSectionResizeMode(2, QHeaderView::ResizeToContents);+ hh->setSectionResizeMode(3, QHeaderView::Stretch);+ hh->setSectionResizeMode(4, QHeaderView::ResizeToContents);+ hh->setSectionResizeMode(5, QHeaderView::ResizeToContents);+ }++ auto make_readonly = [](const QString& text, bool right_align = false) {+ auto* it = new QTableWidgetItem(text);+ it->setFlags(it->flags() & ~Qt::ItemIsEditable);+ if (right_align)+ it->setTextAlignment(Qt::AlignRight | Qt::AlignVCenter);+ return it;+ };++ for (int r = 0; r < holdings.size(); ++r) {+ const auto& h = holdings[r];++ // Col 0: import checkbox (centered via a container widget)+ auto* cb_cell = new QWidget;+ auto* cb_lay = new QHBoxLayout(cb_cell);+ cb_lay->setContentsMargins(0, 0, 0, 0);+ auto* cb = new QCheckBox;+ cb->setChecked(h.quantity > 0 && !h.symbol.isEmpty());+ cb->setProperty("row_index", r);+ cb_lay->addWidget(cb, 0, Qt::AlignCenter);+ table->setCellWidget(r, 0, cb_cell);++ table->setItem(r, 1, make_readonly(h.symbol));+ table->setItem(r, 2, make_readonly(h.exchange));++ auto* yf_item = new QTableWidgetItem(yfinance_symbol_for(h.symbol, h.exchange));+ yf_item->setFlags(yf_item->flags() | Qt::ItemIsEditable);+ table->setItem(r, 3, yf_item);++ table->setItem(r, 4, make_readonly(QString::number(h.quantity, 'f', 2), true));+ table->setItem(r, 5, make_readonly(QString::number(h.avg_price, 'f', 2), true));+ }+ v->addWidget(table, 1);++ // Select/Deselect all helpers+ auto* select_row = new QHBoxLayout;+ auto* select_all_btn = new QPushButton("Select all");+ auto* deselect_all_btn = new QPushButton("Deselect all");+ select_row->addWidget(select_all_btn);+ select_row->addWidget(deselect_all_btn);+ select_row->addStretch();+ v->addLayout(select_row);++ auto set_all_checked = [table](bool on) {+ for (int r = 0; r < table->rowCount(); ++r) {+ if (auto* w = table->cellWidget(r, 0)) {+ if (auto* cb = w->findChild<QCheckBox*>())+ cb->setChecked(on);+ }+ }+ };+ QObject::connect(select_all_btn, &QPushButton::clicked, &dlg, [set_all_checked]() { set_all_checked(true); });+ QObject::connect(deselect_all_btn, &QPushButton::clicked, &dlg, [set_all_checked]() { set_all_checked(false); });++ auto* buttons = new QDialogButtonBox(QDialogButtonBox::Ok | QDialogButtonBox::Cancel);+ buttons->button(QDialogButtonBox::Ok)->setText("IMPORT");+ v->addWidget(buttons);++ auto sync_mode = [&]() {+ const bool is_new = mode_new->isChecked();+ new_row->setVisible(is_new);+ existing_row->setVisible(!is_new);+ };+ QObject::connect(mode_new, &QRadioButton::toggled, &dlg, sync_mode);+ QObject::connect(mode_existing, &QRadioButton::toggled, &dlg, sync_mode);+ sync_mode();++ // Load existing portfolios asynchronously.+ auto& ps = fincept::services::PortfolioService::instance();+ QPointer<QComboBox> combo_guard = existing_combo;+ QPointer<QRadioButton> existing_guard = mode_existing;+ auto conn = QObject::connect(+ &ps, &fincept::services::PortfolioService::portfolios_loaded, &dlg,+ [combo_guard, existing_guard](const QVector<fincept::portfolio::Portfolio>& list) {+ if (!combo_guard) return;+ combo_guard->clear();+ if (list.isEmpty()) {+ combo_guard->addItem("(no portfolios yet)");+ combo_guard->setEnabled(false);+ if (existing_guard) existing_guard->setEnabled(false);+ } else {+ for (const auto& p : list)+ combo_guard->addItem(QString("%1 (%2)").arg(p.name, p.currency), p.id);+ combo_guard->setEnabled(true);+ }+ });+ ps.load_portfolios();++ QObject::connect(buttons, &QDialogButtonBox::accepted, &dlg, &QDialog::accept);+ QObject::connect(buttons, &QDialogButtonBox::rejected, &dlg, &QDialog::reject);++ if (dlg.exec() != QDialog::Accepted) {+ QObject::disconnect(conn);+ return;+ }+ QObject::disconnect(conn);++ // Collect selected rows with their (possibly edited) yfinance tickers.+ struct ImportRow {+ QString symbol;+ double quantity = 0;+ double avg_price = 0;+ };+ QVector<ImportRow> rows;+ rows.reserve(holdings.size());+ for (int r = 0; r < holdings.size(); ++r) {+ auto* w = table->cellWidget(r, 0);+ auto* cb = w ? w->findChild<QCheckBox*>() : nullptr;+ if (!cb || !cb->isChecked())+ continue;+ const QString yf = table->item(r, 3)->text().trimmed().toUpper();+ if (yf.isEmpty())+ continue;+ rows.push_back({yf, holdings[r].quantity, holdings[r].avg_price});+ }+ if (rows.isEmpty()) {+ QMessageBox::information(this, "Import Holdings", "Nothing selected to import.");+ return;+ }++ auto do_add_assets = [rows](const QString& portfolio_id) {+ auto& svc = fincept::services::PortfolioService::instance();+ const QString today = QDate::currentDate().toString(Qt::ISODate);+ for (const auto& row : rows) {+ if (row.quantity <= 0 || row.symbol.isEmpty())+ continue;+ svc.add_asset(portfolio_id, row.symbol, row.quantity, row.avg_price, today);+ }+ };++ if (mode_new->isChecked()) {+ const QString name = name_input->text().trimmed();+ if (name.isEmpty()) {+ QMessageBox::warning(this, "Import Holdings", "Portfolio name is required.");+ return;+ }+ const QString currency = currency_input->text().trimmed().isEmpty()+ ? default_currency+ : currency_input->text().trimmed().toUpper();+ QPointer<EquityTradingScreen> self = this;+ auto once = std::make_shared<QMetaObject::Connection>();+ const int count = rows.size();+ *once = connect(&ps, &fincept::services::PortfolioService::portfolio_created, this,+ [self, once, do_add_assets, name, count](const fincept::portfolio::Portfolio& p) {+ if (!self || p.name != name)+ return;+ QObject::disconnect(*once);+ do_add_assets(p.id);+ QMessageBox::information(self, "Import Holdings",+ QString("Imported %1 holdings into portfolio \"%2\".")+ .arg(count)+ .arg(p.name));+ });+ ps.create_portfolio(name, account.display_name, currency, "Imported from " + broker_id.toUpper());+ } else {+ const QString pid = existing_combo->currentData().toString();+ if (pid.isEmpty()) {+ QMessageBox::warning(this, "Import Holdings", "Select a portfolio first.");+ return;+ }+ do_add_assets(pid);+ QMessageBox::information(this, "Import Holdings",+ QString("Imported %1 holdings.").arg(rows.size()));+ }+}+} // namespace fincept::screensdiff --git a/fincept-qt/src/screens/equity_trading/EquityTradingScreen.h b/fincept-qt/src/screens/equity_trading/EquityTradingScreen.hindex de4797c4f..0ebb41d5c 100644--- a/fincept-qt/src/screens/equity_trading/EquityTradingScreen.h+++ b/fincept-qt/src/screens/equity_trading/EquityTradingScreen.h@@ -1,5 +1,5 @@#pragma once-// Equity Trading Screen — Bloomberg-style multi-account coordinator.+// Equity Trading Screen — multi-account coordinator.// Supports multiple broker accounts simultaneously via DataStreamManager.// Each account has its own data stream (WS/polling), portfolio, and credentials.@@ -54,6 +54,7 @@ class EquityTradingScreen : public QWidget, public IWorkspaceParticipant {void on_order_submitted(const trading::UnifiedOrder& order);void on_cancel_order(const QString& order_id);void on_ob_price_clicked(double price);+ void on_import_holdings_requested(const QVector<trading::BrokerHolding>& holdings);void refresh_candles();void update_clock();diff --git a/fincept-qt/src/screens/equity_trading/EquityWatchlist.h b/fincept-qt/src/screens/equity_trading/EquityWatchlist.hindex 963f7bd93..02d55f4c7 100644--- a/fincept-qt/src/screens/equity_trading/EquityWatchlist.h+++ b/fincept-qt/src/screens/equity_trading/EquityWatchlist.h@@ -1,5 +1,5 @@#pragma once-// Equity Watchlist — compact Bloomberg-style with change% coloring+// Equity Watchlist — compact with change% coloring#include "trading/TradingTypes.h"diff --git a/fincept-qt/src/screens/ma_analytics/MAAnalyticsScreen.h b/fincept-qt/src/screens/ma_analytics/MAAnalyticsScreen.hindex 62cdabba5..e31eb1cc2 100644--- a/fincept-qt/src/screens/ma_analytics/MAAnalyticsScreen.h+++ b/fincept-qt/src/screens/ma_analytics/MAAnalyticsScreen.h@@ -15,7 +15,7 @@ namespace fincept::screens {class MAModulePanel;-/// M&A Analytics main screen — 3-panel Bloomberg-style layout.+/// M&A Analytics main screen — 3-panel layout./// Left: module navigation by category (CORE / SPECIALIZED / ANALYTICS)/// Center: active module content (stacked widget)/// Right: module info & capabilities sidebardiff --git a/fincept-qt/src/screens/markets/MarketPanel.h b/fincept-qt/src/screens/markets/MarketPanel.hindex a5fab3fcf..f1cee3f65 100644--- a/fincept-qt/src/screens/markets/MarketPanel.h+++ b/fincept-qt/src/screens/markets/MarketPanel.h@@ -9,7 +9,7 @@namespace fincept::screens {-/// Single market category panel — resizable Bloomberg-style workstation tile.+/// Single market category panel — resizable workstation tile./// Fills all height given by parent QSplitter./// Dynamic row count: recalculated on resizeEvent()./// Per-panel column configuration via [COLS] inline dropdown.diff --git a/fincept-qt/src/screens/markets/MarketsScreen.h b/fincept-qt/src/screens/markets/MarketsScreen.hindex 695372f76..4a7fa43df 100644--- a/fincept-qt/src/screens/markets/MarketsScreen.h+++ b/fincept-qt/src/screens/markets/MarketsScreen.h@@ -13,7 +13,7 @@namespace fincept::screens {-/// Markets terminal — Bloomberg-style workstation with QSplitter panel layout.+/// Markets terminal — workstation with QSplitter panel layout./// Panels fill screen height; horizontal and vertical handles are user-resizable./// Splitter state is persisted to SettingsRepository.class MarketsScreen : public QWidget {diff --git a/fincept-qt/src/screens/portfolio/PortfolioBlotter.h b/fincept-qt/src/screens/portfolio/PortfolioBlotter.hindex e82121967..eb86647a2 100644--- a/fincept-qt/src/screens/portfolio/PortfolioBlotter.h+++ b/fincept-qt/src/screens/portfolio/PortfolioBlotter.h@@ -11,7 +11,7 @@ namespace fincept::screens {class PortfolioSparkline;-/// 11-column sortable positions table matching Bloomberg blotter style.+/// 11-column sortable positions table — blotter style.class PortfolioBlotter : public QWidget {Q_OBJECTpublic:diff --git a/fincept-qt/src/screens/relationship_map/RelationshipGraphScene.h b/fincept-qt/src/screens/relationship_map/RelationshipGraphScene.hindex af85f5fe9..b384db47b 100644--- a/fincept-qt/src/screens/relationship_map/RelationshipGraphScene.h+++ b/fincept-qt/src/screens/relationship_map/RelationshipGraphScene.h@@ -13,7 +13,7 @@ class GraphNodeItem;class RelNode;/// Interactive graph scene for relationship map visualization.-/// Force-directed layout with elastic nodes (Bloomberg-style).+/// Force-directed layout with elastic nodes.class RelationshipGraphScene : public QGraphicsScene {Q_OBJECTpublic:diff --git a/fincept-qt/src/screens/surface_analytics/Surface3DWidget.h b/fincept-qt/src/screens/surface_analytics/Surface3DWidget.hindex 748c978a7..9d4a5068e 100644--- a/fincept-qt/src/screens/surface_analytics/Surface3DWidget.h+++ b/fincept-qt/src/screens/surface_analytics/Surface3DWidget.h@@ -1,5 +1,5 @@#pragma once-// Surface3DWidget — Bloomberg-style 3D surface renderer using QPainter+// Surface3DWidget — 3D surface renderer using QPainter// Supports drag-to-rotate, scroll-to-zoom, color mapping (sequential + diverging)#include <QWidget>diff --git a/fincept-qt/src/screens/trade_viz/TradeVizScreen.cpp b/fincept-qt/src/screens/trade_viz/TradeVizScreen.cppindex 8dd998fb9..66335ba7c 100644--- a/fincept-qt/src/screens/trade_viz/TradeVizScreen.cpp+++ b/fincept-qt/src/screens/trade_viz/TradeVizScreen.cpp@@ -1,4 +1,4 @@-// Trade Visualization — Bloomberg ECTR Trade Flow style+// Trade Visualization — Trade Flow style#include "screens/trade_viz/TradeVizScreen.h"#include "core/session/ScreenStateManager.h"@@ -139,7 +139,7 @@ class TradeFlowChordWidget : public QWidget {double strength = g_partners[i].imports / max_val;- // Draw multiple sub-arcs for thick "bundle" effect like Bloomberg+ // Draw multiple sub-arcs for thick "bundle" effectint num_strands = 2 + static_cast<int>(4 * strength);for (int s = 0; s < num_strands; ++s) {double offset = (s - num_strands / 2.0) * 3.0;@@ -271,7 +271,7 @@ class TradeFlowChordWidget : public QWidget {};// ============================================================================-// Tab bar — Bloomberg "21) Table 22) Settings 23) Export 24) Notes"+// Tab bar — "21) Table 22) Settings 23) Export 24) Notes"// ============================================================================QWidget* TradeVizScreen::build_tab_bar() {@@ -535,7 +535,7 @@ void TradeVizScreen::setup_ui() {root->setContentsMargins(0, 0, 0, 0);root->setSpacing(0);- // ── Tab bar (Bloomberg style) ────────────────────────────────────────────+ // ── Tab bar ──────────────────────────────────────────────────────────────root->addWidget(build_tab_bar());// ── Filter bar ───────────────────────────────────────────────────────────diff --git a/fincept-qt/src/screens/trade_viz/TradeVizScreen.h b/fincept-qt/src/screens/trade_viz/TradeVizScreen.hindex 9a3ecfc49..08597312f 100644--- a/fincept-qt/src/screens/trade_viz/TradeVizScreen.h+++ b/fincept-qt/src/screens/trade_viz/TradeVizScreen.h@@ -11,7 +11,7 @@namespace fincept::screens {-/// Bloomberg ECTR-style Trade Flow visualization.+/// Trade Flow visualization./// Chord diagram showing bilateral trade flows + partner ranking table.class TradeVizScreen : public QWidget, public IStatefulScreen {Q_OBJECTdiff --git a/fincept-qt/src/services/geopolitics/GeopoliticsService.cpp b/fincept-qt/src/services/geopolitics/GeopoliticsService.cppindex f8dce4fd9..cb20b524e 100644--- a/fincept-qt/src/services/geopolitics/GeopoliticsService.cpp+++ b/fincept-qt/src/services/geopolitics/GeopoliticsService.cpp@@ -114,8 +114,19 @@ void GeopoliticsService::fetch_events(const QString& country, const QString& cit}void GeopoliticsService::fetch_unique_countries() {- if (fincept::CacheManager::instance().has("geo:countries"))+ // Cache hit — deserialize and emit, otherwise go to network.+ const QVariant cached = fincept::CacheManager::instance().get("geo:countries");+ if (!cached.isNull()) {+ const QJsonArray arr = QJsonDocument::fromJson(cached.toString().toUtf8()).array();+ QVector<UniqueCountry> countries;+ countries.reserve(arr.size());+ for (const auto& v : arr) {+ const auto o = v.toObject();+ countries.append({o["country"].toString(), o["event_count"].toInt()});+ }+ emit countries_loaded(countries);return;+ }QPointer<GeopoliticsService> self = this;HttpClient::instance().get(@@ -131,18 +142,38 @@ void GeopoliticsService::fetch_unique_countries() {auto arr = data["unique_countries"].toArray();QVector<UniqueCountry> countries;countries.reserve(arr.size());+ QJsonArray to_cache;for (const auto& v : arr) {auto o = v.toObject();- countries.append({o["country"].toString(), o["event_count"].toInt()});+ const QString name = o["country"].toString();+ const int count = o["event_count"].toInt();+ countries.append({name, count});+ QJsonObject entry;+ entry["country"] = name;+ entry["event_count"] = count;+ to_cache.append(entry);}- fincept::CacheManager::instance().put("geo:countries", QVariant(true), kRefDataTtlSec, "geopolitics");+ fincept::CacheManager::instance().put(+ "geo:countries",+ QVariant(QString::fromUtf8(QJsonDocument(to_cache).toJson(QJsonDocument::Compact))), kRefDataTtlSec,+ "geopolitics");emit self->countries_loaded(countries);});}void GeopoliticsService::fetch_unique_categories() {- if (fincept::CacheManager::instance().has("geo:categories"))+ const QVariant cached = fincept::CacheManager::instance().get("geo:categories");+ if (!cached.isNull()) {+ const QJsonArray arr = QJsonDocument::fromJson(cached.toString().toUtf8()).array();+ QVector<UniqueCategory> cats;+ cats.reserve(arr.size());+ for (const auto& v : arr) {+ const auto o = v.toObject();+ cats.append({o["event_category"].toString(), o["event_count"].toInt()});+ }+ emit categories_loaded(cats);return;+ }QPointer<GeopoliticsService> self = this;HttpClient::instance().get(QString(kApiBase) + "?get_unique_categories=true", [self](Result<QJsonDocument> result) {@@ -157,11 +188,21 @@ void GeopoliticsService::fetch_unique_categories() {auto arr = data["unique_categories"].toArray();QVector<UniqueCategory> cats;cats.reserve(arr.size());+ QJsonArray to_cache;for (const auto& v : arr) {auto o = v.toObject();- cats.append({o["event_category"].toString(), o["event_count"].toInt()});+ const QString name = o["event_category"].toString();+ const int count = o["event_count"].toInt();+ cats.append({name, count});+ QJsonObject entry;+ entry["event_category"] = name;+ entry["event_count"] = count;+ to_cache.append(entry);}- fincept::CacheManager::instance().put("geo:categories", QVariant(true), kRefDataTtlSec, "geopolitics");+ fincept::CacheManager::instance().put(+ "geo:categories",+ QVariant(QString::fromUtf8(QJsonDocument(to_cache).toJson(QJsonDocument::Compact))), kRefDataTtlSec,+ "geopolitics");emit self->categories_loaded(cats);});}diff --git a/fincept-qt/src/services/portfolio/PortfolioService.h b/fincept-qt/src/services/portfolio/PortfolioService.hindex 176faea8c..3c63f9201 100644--- a/fincept-qt/src/services/portfolio/PortfolioService.h+++ b/fincept-qt/src/services/portfolio/PortfolioService.h@@ -111,6 +111,10 @@ class PortfolioService : public QObject {const portfolio::Portfolio& portfolio);// ── Summary cache (P11) ──────────────────────────────────────────────────+ // In-memory (not CacheManager) intentionally: PortfolioSummary holds nested+ // Portfolio + QVector<HoldingWithQuote>, which would require a large JSON+ // (de)serializer to persist. The summary is cheap to recompute from quotes+ // on restart, so durability gains nothing. Kept tight with a 5-min TTL.struct CachedSummary {portfolio::PortfolioSummary summary;qint64 timestamp = 0;diff --git a/fincept-qt/src/services/workflow/WorkflowCache.cpp b/fincept-qt/src/services/workflow/WorkflowCache.cppindex 50ec31533..1027ff183 100644--- a/fincept-qt/src/services/workflow/WorkflowCache.cpp+++ b/fincept-qt/src/services/workflow/WorkflowCache.cpp@@ -33,16 +33,25 @@ QJsonValue WorkflowCache::get(const QString& key) const {misses_++;return {};}- hits_++;// Values are stored as compact JSON stringsconst QByteArray raw = cv.toString().toUtf8();QJsonDocument doc = QJsonDocument::fromJson(raw);+ if (doc.isNull()) {+ // Corrupt or unparseable payload — treat as miss, don't inflate hit stats+ misses_++;+ return {};+ }+ hits_++;if (doc.isArray())return doc.array();- if (doc.isObject())- return doc.object();- // Scalar: stored as {"v": <value>}- return doc.object()["v"];+ if (doc.isObject()) {+ const QJsonObject obj = doc.object();+ // Scalar was wrapped as {"v": <value>} — unwrap+ if (obj.size() == 1 && obj.contains("v"))+ return obj.value("v");+ return obj;+ }+ return {};}bool WorkflowCache::has(const QString& key) const {diff --git a/fincept-qt/src/storage/cache/CacheManager.cpp b/fincept-qt/src/storage/cache/CacheManager.cppindex b173448f4..0135b3d61 100644--- a/fincept-qt/src/storage/cache/CacheManager.cpp+++ b/fincept-qt/src/storage/cache/CacheManager.cpp@@ -6,6 +6,20 @@namespace fincept {+namespace {+// Escape LIKE wildcards (% and _) in user-supplied prefixes. Paired with "ESCAPE '\\'" in SQL.+QString escape_like(const QString& s) {+ QString out;+ out.reserve(s.size());+ for (QChar ch : s) {+ if (ch == '\\' || ch == '%' || ch == '_')+ out.append('\\');+ out.append(ch);+ }+ return out;+}+} // namespace+CacheManager& CacheManager::instance() {static CacheManager s;return s;@@ -14,18 +28,31 @@ CacheManager& CacheManager::instance() {CacheManager::CacheManager(QObject* parent) : QObject(parent) {}void CacheManager::put(const QString& key, const QVariant& value, int ttl_seconds, const QString& category) {+ if (key.isEmpty())+ return;auto& cdb = CacheDatabase::instance();if (!cdb.is_open())return;const QString data = value.toString();- cdb.execute("INSERT OR REPLACE INTO unified_cache "- "(key, value, category, ttl_seconds, expires_at, hit_count, size_bytes) "- "VALUES (?, ?, ?, ?, datetime('now', '+' || ? || ' seconds'), 0, ?)",- {key, data, category, ttl_seconds, ttl_seconds, data.size()});+ const int size_bytes = data.toUtf8().size();+ // ON CONFLICT DO UPDATE preserves created_at and hit_count across re-puts of the same key.+ // (INSERT OR REPLACE would delete+insert, resetting those fields.)+ cdb.execute("INSERT INTO unified_cache "+ "(key, value, category, ttl_seconds, expires_at, size_bytes) "+ "VALUES (?, ?, ?, ?, datetime('now', '+' || ? || ' seconds'), ?) "+ "ON CONFLICT(key) DO UPDATE SET "+ " value=excluded.value, "+ " category=excluded.category, "+ " ttl_seconds=excluded.ttl_seconds, "+ " expires_at=excluded.expires_at, "+ " size_bytes=excluded.size_bytes",+ {key, data, category, ttl_seconds, ttl_seconds, size_bytes});}QVariant CacheManager::get(const QString& key) const {+ if (key.isEmpty())+ return {};auto& cdb = CacheDatabase::instance();if (!cdb.is_open())return {};@@ -38,13 +65,19 @@ QVariant CacheManager::get(const QString& key) const {if (!q.next())return {};- // Increment hit counter (fire-and-forget)- cdb.execute("UPDATE unified_cache SET hit_count = hit_count + 1 WHERE key = ?", {key});-return q.value(0).toString();}+std::optional<QString> CacheManager::try_get(const QString& key) const {+ const QVariant v = get(key);+ if (v.isNull())+ return std::nullopt;+ return v.toString();+}+bool CacheManager::has(const QString& key) const {+ if (key.isEmpty())+ return false;auto& cdb = CacheDatabase::instance();if (!cdb.is_open())return false;@@ -58,15 +91,20 @@ bool CacheManager::has(const QString& key) const {}void CacheManager::remove(const QString& key) {+ if (key.isEmpty())+ return;auto& cdb = CacheDatabase::instance();if (cdb.is_open())cdb.execute("DELETE FROM unified_cache WHERE key = ?", {key});}void CacheManager::remove_prefix(const QString& prefix) {+ // Empty prefix would match everything — refuse to accidentally DELETE FROM unified_cache.+ if (prefix.isEmpty())+ return;auto& cdb = CacheDatabase::instance();if (cdb.is_open())- cdb.execute("DELETE FROM unified_cache WHERE key LIKE ?", {prefix + "%"});+ cdb.execute("DELETE FROM unified_cache WHERE key LIKE ? ESCAPE '\\'", {escape_like(prefix) + "%"});}void CacheManager::clear() {@@ -76,6 +114,8 @@ void CacheManager::clear() {}void CacheManager::clear_category(const QString& category) {+ if (category.isEmpty())+ return;auto& cdb = CacheDatabase::instance();if (cdb.is_open())cdb.execute("DELETE FROM unified_cache WHERE category = ?", {category});diff --git a/fincept-qt/src/storage/cache/CacheManager.h b/fincept-qt/src/storage/cache/CacheManager.hindex c599fe59f..bd55a5df8 100644--- a/fincept-qt/src/storage/cache/CacheManager.h+++ b/fincept-qt/src/storage/cache/CacheManager.h@@ -3,6 +3,8 @@#include <QString>#include <QVariant>+#include <optional>+namespace fincept {/// SQLite-backed cache. All reads and writes go directly to CacheDatabase (cache.db).@@ -13,7 +15,11 @@ class CacheManager : public QObject {static CacheManager& instance();void put(const QString& key, const QVariant& value, int ttl_seconds = 300, const QString& category = "general");+ /// Returns the cached value (as QString-convertible QVariant) or a null QVariant on miss/expiry.QVariant get(const QString& key) const;+ /// Single-query variant of get(): std::nullopt on miss, value on hit. Prefer this over has()+get()+ /// — those two-round-trips duplicate work since get() already checks expiry.+ std::optional<QString> try_get(const QString& key) const;bool has(const QString& key) const;void remove(const QString& key);void remove_prefix(const QString& prefix);diff --git a/fincept-qt/src/storage/repositories/AccountRepository.cpp b/fincept-qt/src/storage/repositories/AccountRepository.cppindex 9c7959c15..b4c307b40 100644--- a/fincept-qt/src/storage/repositories/AccountRepository.cpp+++ b/fincept-qt/src/storage/repositories/AccountRepository.cpp@@ -20,19 +20,27 @@ trading::BrokerAccount AccountRepository::map_row(QSqlQuery& q) {}Result<void> AccountRepository::insert(const trading::BrokerAccount& account) {+ // Bind NULL (not empty string) when no paper portfolio is linked — an empty+ // TEXT value is not NULL and would violate the FK constraint against pt_portfolios(id).+ const QVariant portfolio_bind = account.paper_portfolio_id.isEmpty()+ ? QVariant(QMetaType(QMetaType::QString))+ : QVariant(account.paper_portfolio_id);return exec_write("INSERT INTO broker_accounts (id, broker_id, display_name, paper_portfolio_id, trading_mode, is_active, created_at) ""VALUES (?, ?, ?, ?, ?, ?, ?)",{account.account_id, account.broker_id, account.display_name,- account.paper_portfolio_id, account.trading_mode,+ portfolio_bind, account.trading_mode,account.is_active ? 1 : 0, account.created_at});}Result<void> AccountRepository::update(const trading::BrokerAccount& account) {+ const QVariant portfolio_bind = account.paper_portfolio_id.isEmpty()+ ? QVariant(QMetaType(QMetaType::QString))+ : QVariant(account.paper_portfolio_id);return exec_write("UPDATE broker_accounts SET broker_id = ?, display_name = ?, paper_portfolio_id = ?, ""trading_mode = ?, is_active = ? WHERE id = ?",- {account.broker_id, account.display_name, account.paper_portfolio_id,+ {account.broker_id, account.display_name, portfolio_bind,account.trading_mode, account.is_active ? 1 : 0, account.account_id});}diff --git a/fincept-qt/src/storage/sqlite/CacheDatabase.cpp b/fincept-qt/src/storage/sqlite/CacheDatabase.cppindex 3b7a463d6..54ba61a6c 100644--- a/fincept-qt/src/storage/sqlite/CacheDatabase.cpp+++ b/fincept-qt/src/storage/sqlite/CacheDatabase.cpp@@ -2,6 +2,8 @@#include "core/logging/Logger.h"+#include <QMutexLocker>+namespace fincept {CacheDatabase& CacheDatabase::instance() {@@ -21,7 +23,20 @@ Result<void> CacheDatabase::open(const QString& path) {if (pr.is_err())return pr;- return create_tables();+ auto tr = create_tables();+ if (tr.is_err())+ return tr;++ // One-shot startup sweep of expired rows — prevents unbounded growth of unified_cache+ // across sessions. Cheap: idx_cache_expires makes this a range scan.+ auto sweep = execute("DELETE FROM unified_cache WHERE expires_at < datetime('now')");+ if (sweep.is_ok()) {+ const int removed = sweep.value().numRowsAffected();+ if (removed > 0)+ LOG_INFO("CacheDB", QString("Startup sweep removed %1 expired cache rows").arg(removed));+ }++ return Result<void>::ok();}void CacheDatabase::close() {@@ -34,6 +49,7 @@ bool CacheDatabase::is_open() const {}Result<QSqlQuery> CacheDatabase::execute(const QString& sql, const QVariantList& params) {+ QMutexLocker lock(&mutex_);QSqlQuery query(db_);query.prepare(sql);for (int i = 0; i < params.size(); ++i) {@@ -46,6 +62,7 @@ Result<QSqlQuery> CacheDatabase::execute(const QString& sql, const QVariantList&}Result<void> CacheDatabase::exec(const QString& sql) {+ QMutexLocker lock(&mutex_);QSqlQuery query(db_);if (!query.exec(sql)) {return Result<void>::err(query.lastError().text().toStdString());@@ -54,8 +71,11 @@ Result<void> CacheDatabase::exec(const QString& sql) {}Result<void> CacheDatabase::apply_pragmas() {+ // synchronous=NORMAL under WAL is the standard safe/fast combo. OFF risked full DB+ // corruption on power loss — now that cache.db also holds tab_sessions and+ // screen_state, durability matters more than the marginal write gain of OFF.const char* pragmas[] = {- "PRAGMA journal_mode = WAL", "PRAGMA synchronous = OFF", "PRAGMA cache_size = -10000",+ "PRAGMA journal_mode = WAL", "PRAGMA synchronous = NORMAL", "PRAGMA cache_size = -10000","PRAGMA temp_store = MEMORY", "PRAGMA mmap_size = 134217728", "PRAGMA busy_timeout = 3000",};for (auto* p : pragmas) {diff --git a/fincept-qt/src/storage/sqlite/CacheDatabase.h b/fincept-qt/src/storage/sqlite/CacheDatabase.hindex b818585f6..79e34f5ef 100644--- a/fincept-qt/src/storage/sqlite/CacheDatabase.h+++ b/fincept-qt/src/storage/sqlite/CacheDatabase.h@@ -1,6 +1,7 @@#pragma once#include "core/result/Result.h"+#include <QMutex>#include <QSqlDatabase>#include <QSqlError>#include <QSqlQuery>@@ -10,7 +11,10 @@namespace fincept {/// Separate SQLite database for ephemeral cache data.-/// Uses synchronous=OFF for maximum write speed.+/// Uses synchronous=NORMAL under WAL for safe, fast writes.+/// A QMutex serializes access: Qt's QSqlDatabase connection is not thread-safe,+/// and this cache is read/written from services whose callbacks may run on+/// worker threads (HttpClient, PythonRunner finished signals).class CacheDatabase {public:static CacheDatabase& instance();@@ -30,6 +34,7 @@ class CacheDatabase {Result<void> create_tables();QSqlDatabase db_;+ mutable QMutex mutex_;};} // namespace finceptdiff --git a/fincept-qt/src/trading/AccountDataStream.cpp b/fincept-qt/src/trading/AccountDataStream.cppindex 6122292eb..3cb37ae38 100644--- a/fincept-qt/src/trading/AccountDataStream.cpp+++ b/fincept-qt/src/trading/AccountDataStream.cpp@@ -213,6 +213,7 @@ void AccountDataStream::async_fetch_positions() {auto* broker = BrokerRegistry::instance().get(bid);if (!broker) return;auto creds = AccountManager::instance().load_credentials(acct_id);+ if (creds.api_key.isEmpty()) return;auto result = broker->get_positions(creds);if (!result.success || !result.data) {if (result.error.startsWith("[TOKEN_EXPIRED]") && self)@@ -238,6 +239,7 @@ void AccountDataStream::async_fetch_holdings() {auto* broker = BrokerRegistry::instance().get(bid);if (!broker) return;auto creds = AccountManager::instance().load_credentials(acct_id);+ if (creds.api_key.isEmpty()) return;auto result = broker->get_holdings(creds);if (!result.success || !result.data) {if (result.error.startsWith("[TOKEN_EXPIRED]") && self)@@ -263,6 +265,7 @@ void AccountDataStream::async_fetch_orders() {auto* broker = BrokerRegistry::instance().get(bid);if (!broker) return;auto creds = AccountManager::instance().load_credentials(acct_id);+ if (creds.api_key.isEmpty()) return;auto result = broker->get_orders(creds);if (!result.success || !result.data) {if (result.error.startsWith("[TOKEN_EXPIRED]") && self)@@ -288,6 +291,7 @@ void AccountDataStream::async_fetch_funds() {auto* broker = BrokerRegistry::instance().get(bid);if (!broker) return;auto creds = AccountManager::instance().load_credentials(acct_id);+ if (creds.api_key.isEmpty()) return;auto result = broker->get_funds(creds);if (!result.success || !result.data) {if (result.error.startsWith("[TOKEN_EXPIRED]") && self)diff --git a/fincept-qt/src/trading/AccountManager.cpp b/fincept-qt/src/trading/AccountManager.cppindex 3a18f0138..8377ac77a 100644--- a/fincept-qt/src/trading/AccountManager.cpp+++ b/fincept-qt/src/trading/AccountManager.cpp@@ -11,6 +11,9 @@#include <QMutexLocker>#include <QUuid>+#include <cmath>+#include <exception>+namespace fincept::trading {// ── Credential key helpers ──────────────────────────────────────────────────@@ -141,17 +144,48 @@ BrokerAccount AccountManager::add_account(const QString& broker_id, const QStrinQString currency = "INR";if (broker) {const auto prof = broker->profile();- paper_balance = prof.default_paper_balance;- currency = prof.currency;+ if (std::isfinite(prof.default_paper_balance) && prof.default_paper_balance > 0.0)+ paper_balance = prof.default_paper_balance;+ if (!prof.currency.isEmpty())+ currency = prof.currency;}- auto portfolio = pt_create_portfolio(- display_name + " Paper", paper_balance, currency,- 1.0, "cross", 0.001, account.account_id);- account.paper_portfolio_id = portfolio.id;+ // pt_create_portfolio throws on invalid args or DB failure. Catch here so a+ // throw does not propagate across the Qt signal/slot boundary and terminate+ // the app. Account creation proceeds without a paper portfolio on failure.+ try {+ auto portfolio = pt_create_portfolio(+ display_name + " Paper", paper_balance, currency,+ 1.0, "cross", 0.001, account.account_id);+ account.paper_portfolio_id = portfolio.id;+ } catch (const std::exception& e) {+ LOG_ERROR("AccountManager",+ QString("Failed to create paper portfolio for %1 (%2): %3")+ .arg(broker_id, display_name, e.what()));+ account.paper_portfolio_id.clear();+ }- // Persist to DB- AccountRepository::instance().insert(account);+ // Persist to DB. If the insert fails (e.g. FK violation, disk full), do NOT+ // add the account to the in-memory cache — otherwise the UI would show a+ // "connected" account that silently vanishes on the next app launch.+ auto insert_result = AccountRepository::instance().insert(account);+ if (insert_result.is_err()) {+ LOG_ERROR("AccountManager",+ QString("Failed to persist account %1 (%2) for broker %3: %4")+ .arg(account.account_id, display_name, broker_id,+ QString::fromStdString(insert_result.error())));+ // Clean up the orphaned paper portfolio we created above.+ if (!account.paper_portfolio_id.isEmpty()) {+ try {+ pt_delete_portfolio(account.paper_portfolio_id);+ } catch (const std::exception& e) {+ LOG_WARN("AccountManager",+ QString("Could not clean up orphaned paper portfolio %1: %2")+ .arg(account.paper_portfolio_id, e.what()));+ }+ }+ return {}; // empty BrokerAccount signals failure to caller+ }// Add to in-memory cache{@@ -286,6 +320,9 @@ bool AccountManager::has_account(const QString& account_id) const {// ── Credentials ─────────────────────────────────────────────────────────────+// NOTE: creds.additional_data is an opaque JSON blob owned by the individual+// broker dialog. E.g., Zerodha stores {"password":"...","totp_secret":"..."}.+// AccountManager does not interpret it.void AccountManager::save_credentials(const QString& account_id, const BrokerCredentials& creds) {auto& secure = SecureStorage::instance();secure.store(acct_key(account_id, "api_key"), creds.api_key);diff --git a/fincept-qt/src/trading/BrokerInterface.h b/fincept-qt/src/trading/BrokerInterface.hindex 061b64b2b..71fd850fa 100644--- a/fincept-qt/src/trading/BrokerInterface.h+++ b/fincept-qt/src/trading/BrokerInterface.h@@ -20,6 +20,9 @@ enum class CredentialField {AuthCode, // "Auth Code" / "TOTP secret" (base32)Environment, // "Live / Paper" toggle — Alpaca onlyClientCode, // Secondary login ID (AngelOne: client code separate from API key)+ Password, // Zerodha login password (auto-login flow)+ TotpSecret, // Zerodha Base32 TOTP secret (auto-login flow)+ UserId, // Zerodha Kite user id (e.g., AB1234)};struct CredentialFieldDef {diff --git a/fincept-qt/src/trading/ExchangeService.cpp b/fincept-qt/src/trading/ExchangeService.cppindex d65ced85c..163d3f566 100644--- a/fincept-qt/src/trading/ExchangeService.cpp+++ b/fincept-qt/src/trading/ExchangeService.cpp@@ -365,6 +365,33 @@ bool ExchangeService::is_daemon_running() const {return daemon_process_ && daemon_process_->state() == QProcess::Running && daemon_ready_.load();}+bool ExchangeService::wait_for_daemon_ready(int timeout_ms) {+ // Fast path — already up.+ if (daemon_ready_.load())+ return true;++ // Kick the daemon start if the process hasn't been spawned yet. start_daemon+ // must run on the main thread because it owns daemon_process_.+ if (!daemon_process_) {+ if (QThread::currentThread() == thread()) {+ start_daemon();+ } else {+ QMetaObject::invokeMethod(this, [this]() { start_daemon(); }, Qt::QueuedConnection);+ }+ }++ // Wait on the ready condition (signalled from drain_daemon_buffer when the+ // __init__ line arrives). Safe to call from worker threads only.+ QMutexLocker lock(&daemon_mutex_);+ QElapsedTimer elapsed;+ elapsed.start();+ while (!daemon_ready_.load() && elapsed.elapsed() < timeout_ms) {+ const int remaining = timeout_ms - static_cast<int>(elapsed.elapsed());+ daemon_response_ready_.wait(&daemon_mutex_, std::max(remaining, 50));+ }+ return daemon_ready_.load();+}+void ExchangeService::drain_daemon_buffer() {if (!daemon_process_)return;@@ -403,8 +430,9 @@ void ExchangeService::drain_daemon_buffer() {daemon_process_->write(data);credentials_sent_to_daemon_ = true;}- // Wake any thread waiting for daemon readiness+ // Wake any thread waiting for daemon readiness and notify subscribersdaemon_response_ready_.wakeAll();+ emit daemon_ready();continue;}@@ -419,25 +447,17 @@ void ExchangeService::drain_daemon_buffer() {QJsonObject ExchangeService::daemon_call(const QString& method, const QJsonObject& args, int timeout_ms) {// daemon_call() is called from background threads (QtConcurrent::run).- // The daemon process lives on the main thread, so all writes must go- // through invokeMethod. Responses arrive via drain_daemon_buffer() on- // the main thread and are stored in daemon_responses_ under mutex.- // We use QWaitCondition to sleep until our response arrives.-- // Auto-start daemon if not running (must happen on main thread)- if (!is_daemon_running()) {- QMetaObject::invokeMethod(this, [this]() { start_daemon(); }, Qt::BlockingQueuedConnection);- // Wait for daemon_ready_ via wait condition- {- QMutexLocker lock(&daemon_mutex_);- QElapsedTimer wait;- wait.start();- while (!daemon_ready_.load() && wait.elapsed() < 5000) {- daemon_response_ready_.wait(&daemon_mutex_, 100);- }- }- if (!daemon_ready_.load()) {- LOG_WARN(TAG, "Daemon not ready after 5s, falling back to script");+ // The daemon process lives on the main thread, so all writes are marshalled+ // there via a non-blocking queued invocation. Responses arrive via+ // drain_daemon_buffer() on the main thread and are stored in+ // daemon_responses_ under mutex. We sleep on a wait condition until our+ // response arrives or `timeout_ms` elapses.++ // Auto-start + wait for ready. Uses QueuedConnection internally — never+ // blocks a worker on the main event loop.+ if (!daemon_ready_.load()) {+ if (!wait_for_daemon_ready(std::min(timeout_ms, 8000))) {+ LOG_WARN(TAG, "Daemon not ready, falling back to script for: " + method);return {{"error", "Daemon not ready"}};}}@@ -453,7 +473,10 @@ QJsonObject ExchangeService::daemon_call(const QString& method, const QJsonObjecreq["args"] = args;QByteArray data = QJsonDocument(req).toJson(QJsonDocument::Compact) + "\n";- // Send credentials if needed, then send the request — both on main thread+ // Send credentials + request via QueuedConnection — returns immediately to+ // the worker, which then sleeps on the wait condition below. Previously+ // this used BlockingQueuedConnection, which stalled the worker waiting for+ // the UI event loop to drain (H4).QMetaObject::invokeMethod(this,[this, data]() {@@ -477,7 +500,7 @@ QJsonObject ExchangeService::daemon_call(const QString& method, const QJsonObjec}daemon_process_->write(data);},- Qt::BlockingQueuedConnection);+ Qt::QueuedConnection);// Wait for response using QWaitCondition (proper cross-thread signaling)QMutexLocker lock(&daemon_mutex_);@@ -866,7 +889,13 @@ QJsonObject ExchangeService::call_script(const QString& script, const QStringLisQProcess proc;proc.start(python_path, full_args);- proc.waitForFinished(30000);+ const bool finished = proc.waitForFinished(30000);+ if (!finished) {+ LOG_WARN(TAG, QString("call_script timed out after 30s: %1").arg(script));+ proc.kill();+ proc.waitForFinished(500);+ return {{"error", "Script timed out: " + script}};+ }QString output = proc.readAllStandardOutput().trimmed();if (output.isEmpty()) {@@ -1039,7 +1068,7 @@ MarketInfo ExchangeService::parse_market(const QJsonObject& j) {TickerData ExchangeService::fetch_ticker(const QString& symbol) {// Daemon path: ~100ms (reuses warm ccxt instance)// Legacy path: ~900ms (spawns Python, imports ccxt, creates exchange)- if (is_daemon_running()) {+ if (wait_for_daemon_ready()) {auto j = daemon_call("fetch_ticker", {{"symbol", symbol}});if (!j.contains("error"))return parse_ticker(j);@@ -1052,7 +1081,7 @@ TickerData ExchangeService::fetch_ticker(const QString& symbol) {}QVector<TickerData> ExchangeService::fetch_tickers(const QStringList& symbols) {- if (is_daemon_running()) {+ if (wait_for_daemon_ready()) {QJsonArray sym_arr;for (const auto& s : symbols)sym_arr.append(s);@@ -1078,7 +1107,7 @@ QVector<TickerData> ExchangeService::fetch_tickers(const QStringList& symbols) {}OrderBookData ExchangeService::fetch_orderbook(const QString& symbol, int limit) {- if (is_daemon_running()) {+ if (wait_for_daemon_ready()) {auto j = daemon_call("fetch_orderbook", {{"symbol", symbol}, {"limit", limit}});if (!j.contains("error"))return parse_orderbook(j);@@ -1091,7 +1120,7 @@ OrderBookData ExchangeService::fetch_orderbook(const QString& symbol, int limit)}QVector<Candle> ExchangeService::fetch_ohlcv(const QString& symbol, const QString& timeframe, int limit) {- if (is_daemon_running()) {+ if (wait_for_daemon_ready()) {auto j = daemon_call("fetch_ohlcv", {{"symbol", symbol}, {"timeframe", timeframe}, {"limit", limit}});if (!j.contains("error") && j.contains("candles")) {QVector<Candle> result;@@ -1113,7 +1142,7 @@ QVector<Candle> ExchangeService::fetch_ohlcv(const QString& symbol, const QStrin}QVector<MarketInfo> ExchangeService::fetch_markets(const QString& type, const QString& query) {- if (is_daemon_running()) {+ if (wait_for_daemon_ready()) {QJsonObject args;if (!type.isEmpty())args["type"] = type;@@ -1145,7 +1174,7 @@ QVector<MarketInfo> ExchangeService::fetch_markets(const QString& type, const QS}QStringList ExchangeService::list_exchange_ids() {- if (is_daemon_running()) {+ if (wait_for_daemon_ready()) {auto j = daemon_call("list_exchange_ids", {});if (!j.contains("error") && j.contains("exchanges")) {QStringList result;@@ -1166,7 +1195,7 @@ QStringList ExchangeService::list_exchange_ids() {}QVector<TradeData> ExchangeService::fetch_trades(const QString& symbol, int limit) {- if (is_daemon_running()) {+ if (wait_for_daemon_ready()) {auto j = daemon_call("fetch_trades", {{"symbol", symbol}, {"limit", limit}});if (!j.contains("error") && j.contains("trades")) {QVector<TradeData> result;@@ -1207,7 +1236,7 @@ QVector<TradeData> ExchangeService::fetch_trades(const QString& symbol, int limi}FundingRateData ExchangeService::fetch_funding_rate(const QString& symbol) {- if (is_daemon_running()) {+ if (wait_for_daemon_ready()) {auto j = daemon_call("fetch_funding_rate", {{"symbol", symbol}});if (!j.contains("error")) {FundingRateData fr;@@ -1234,7 +1263,7 @@ FundingRateData ExchangeService::fetch_funding_rate(const QString& symbol) {}OpenInterestData ExchangeService::fetch_open_interest(const QString& symbol) {- if (is_daemon_running()) {+ if (wait_for_daemon_ready()) {auto j = daemon_call("fetch_open_interest", {{"symbol", symbol}});if (!j.contains("error")) {OpenInterestData oi;@@ -1257,7 +1286,7 @@ OpenInterestData ExchangeService::fetch_open_interest(const QString& symbol) {}QJsonObject ExchangeService::fetch_balance() {- if (is_daemon_running()) {+ if (wait_for_daemon_ready()) {auto j = daemon_call("fetch_balance", {});if (!j.contains("error"))return j;@@ -1267,7 +1296,7 @@ QJsonObject ExchangeService::fetch_balance() {QJsonObject ExchangeService::place_exchange_order(const QString& symbol, const QString& side, const QString& type,double amount, double price) {- if (is_daemon_running()) {+ if (wait_for_daemon_ready()) {QJsonObject args;args["symbol"] = symbol;args["side"] = side;@@ -1287,7 +1316,7 @@ QJsonObject ExchangeService::place_exchange_order(const QString& symbol, const Q}QJsonObject ExchangeService::cancel_exchange_order(const QString& order_id, const QString& symbol) {- if (is_daemon_running()) {+ if (wait_for_daemon_ready()) {auto j = daemon_call("cancel_order", {{"order_id", order_id}, {"symbol", symbol}});if (!j.contains("error"))return j;@@ -1296,7 +1325,7 @@ QJsonObject ExchangeService::cancel_exchange_order(const QString& order_id, cons}QJsonObject ExchangeService::fetch_positions_live(const QString& symbol) {- if (is_daemon_running()) {+ if (wait_for_daemon_ready()) {QJsonObject args;if (!symbol.isEmpty())args["symbol"] = symbol;@@ -1311,7 +1340,7 @@ QJsonObject ExchangeService::fetch_positions_live(const QString& symbol) {}QJsonObject ExchangeService::fetch_open_orders_live(const QString& symbol) {- if (is_daemon_running()) {+ if (wait_for_daemon_ready()) {QJsonObject args;if (!symbol.isEmpty())args["symbol"] = symbol;@@ -1329,7 +1358,7 @@ MarkPriceData ExchangeService::fetch_mark_price(const QString& symbol) {MarkPriceData mp;mp.symbol = symbol;QJsonObject j;- if (is_daemon_running()) {+ if (wait_for_daemon_ready()) {j = daemon_call("fetch_mark_price", {{"symbol", symbol}});if (j.contains("error"))j = {};@@ -1345,7 +1374,7 @@ MarkPriceData ExchangeService::fetch_mark_price(const QString& symbol) {}QJsonObject ExchangeService::fetch_my_trades(const QString& symbol, int limit) {- if (is_daemon_running()) {+ if (wait_for_daemon_ready()) {auto j = daemon_call("fetch_my_trades", {{"symbol", symbol}, {"limit", limit}});if (!j.contains("error"))return j;@@ -1355,7 +1384,7 @@ QJsonObject ExchangeService::fetch_my_trades(const QString& symbol, int limit) {}QJsonObject ExchangeService::fetch_trading_fees(const QString& symbol) {- if (is_daemon_running()) {+ if (wait_for_daemon_ready()) {QJsonObject args;if (!symbol.isEmpty())args["symbol"] = symbol;@@ -1371,7 +1400,7 @@ QJsonObject ExchangeService::fetch_trading_fees(const QString& symbol) {}QJsonObject ExchangeService::set_leverage(const QString& symbol, int leverage) {- if (is_daemon_running()) {+ if (wait_for_daemon_ready()) {auto j = daemon_call("set_leverage", {{"symbol", symbol}, {"leverage", leverage}});if (!j.contains("error"))return j;@@ -1381,7 +1410,7 @@ QJsonObject ExchangeService::set_leverage(const QString& symbol, int leverage) {}QJsonObject ExchangeService::set_margin_mode(const QString& symbol, const QString& mode) {- if (is_daemon_running()) {+ if (wait_for_daemon_ready()) {auto j = daemon_call("set_margin_mode", {{"symbol", symbol}, {"mode", mode}});if (!j.contains("error"))return j;diff --git a/fincept-qt/src/trading/ExchangeService.h b/fincept-qt/src/trading/ExchangeService.hindex 79cab3ee0..7619dcdfc 100644--- a/fincept-qt/src/trading/ExchangeService.h+++ b/fincept-qt/src/trading/ExchangeService.h@@ -33,6 +33,19 @@ class ExchangeService : public QObject {QString get_exchange() const;void set_credentials(const ExchangeCredentials& creds);+ // Daemon readiness — block (in background thread only!) up to `timeout_ms`+ // for the persistent ccxt daemon to finish booting. Returns true if ready.+ // Avoids per-call raw QProcess fallback when daemon is still starting.+ bool wait_for_daemon_ready(int timeout_ms = 8000);++ signals:+ // Emitted (from main thread) when the ccxt daemon has finished booting and+ // is ready to serve fetch requests. Subscribers can defer first data+ // fetches until this fires to avoid racing the cold-boot path.+ void daemon_ready();++ public:+// Price feedvoid watch_symbol(const QString& symbol, const QString& portfolio_id);void unwatch_symbol(const QString& symbol, const QString& portfolio_id);diff --git a/fincept-qt/src/trading/auth/RedirectServer.cpp b/fincept-qt/src/trading/auth/RedirectServer.cppnew file mode 100644index 000000000..c4b0f6915--- /dev/null+++ b/fincept-qt/src/trading/auth/RedirectServer.cpp@@ -0,0 +1,113 @@+#include "trading/auth/RedirectServer.h"++#include "core/logging/Logger.h"++#include <QHostAddress>+#include <QTcpSocket>+#include <QUrl>+#include <QUrlQuery>++namespace fincept::trading::auth {++namespace {+constexpr const char* kResponseHtml =+ "<!doctype html><html><head><meta charset='utf-8'>"+ "<title>Fincept - Zerodha login</title>"+ "<style>body{font-family:system-ui;background:#0f172a;color:#e2e8f0;"+ "display:flex;align-items:center;justify-content:center;height:100vh;margin:0}"+ "div{text-align:center}h1{color:#d97706;font-size:20px}p{color:#94a3b8}</style>"+ "</head><body><div><h1>Login captured</h1>"+ "<p>You can close this tab and return to Fincept Terminal.</p></div></body></html>";+}++RedirectServer::RedirectServer(QObject* parent)+ : QObject(parent),+ server_(new QTcpServer(this)),+ timeout_timer_(new QTimer(this)) {+ timeout_timer_->setSingleShot(true);+ connect(server_, &QTcpServer::newConnection, this, &RedirectServer::handle_new_connection);+ connect(timeout_timer_, &QTimer::timeout, this, &RedirectServer::handle_timeout);+}++RedirectServer::~RedirectServer() { stop(); }++bool RedirectServer::start(quint16 preferred_port, int timeout_seconds) {+ if (server_->isListening())+ server_->close();++ if (!server_->listen(QHostAddress::LocalHost, preferred_port)) {+ LOG_WARN("RedirectServer",+ QString("Port %1 busy - falling back to ephemeral").arg(preferred_port));+ if (!server_->listen(QHostAddress::LocalHost, 0)) {+ LOG_ERROR("RedirectServer",+ QString("Failed to bind loopback: %1").arg(server_->errorString()));+ return false;+ }+ }+ port_ = server_->serverPort();+ timeout_timer_->start(timeout_seconds * 1000);+ LOG_INFO("RedirectServer", QString("Listening on 127.0.0.1:%1").arg(port_));+ return true;+}++void RedirectServer::stop() {+ timeout_timer_->stop();+ if (server_->isListening())+ server_->close();+}++void RedirectServer::handle_new_connection() {+ QTcpSocket* sock = server_->nextPendingConnection();+ if (!sock)+ return;++ connect(sock, &QTcpSocket::readyRead, this, [this, sock]() {+ const QByteArray request = sock->readAll();+ const int line_end = request.indexOf("\r\n");+ const QByteArray first_line = (line_end >= 0) ? request.left(line_end) : request;+ const QList<QByteArray> parts = first_line.split(' ');++ QString token;+ QString error_msg;+ if (parts.size() >= 2) {+ const QUrl url(QStringLiteral("http://localhost") + QString::fromLatin1(parts.at(1)));+ const QUrlQuery q(url);+ token = q.queryItemValue("request_token");+ if (token.isEmpty()) {+ const QString err = q.queryItemValue("error");+ error_msg = err.isEmpty() ? QStringLiteral("request_token missing in redirect") : err;+ }+ } else {+ error_msg = QStringLiteral("Malformed request");+ }++ const QByteArray body(kResponseHtml);+ QByteArray response = "HTTP/1.1 200 OK\r\n";+ response += "Content-Type: text/html; charset=utf-8\r\n";+ response += "Content-Length: " + QByteArray::number(body.size()) + "\r\n";+ response += "Connection: close\r\n\r\n";+ response += body;+ sock->write(response);+ sock->flush();+ sock->disconnectFromHost();+ connect(sock, &QTcpSocket::disconnected, sock, &QTcpSocket::deleteLater);++ timeout_timer_->stop();+ if (!token.isEmpty()) {+ LOG_INFO("RedirectServer", "Captured request_token");+ server_->close();+ emit request_token_received(token);+ } else {+ LOG_WARN("RedirectServer", "No token in redirect: " + error_msg);+ emit error(error_msg);+ }+ });+}++void RedirectServer::handle_timeout() {+ LOG_WARN("RedirectServer", "Browser login timed out");+ server_->close();+ emit timeout();+}++} // namespace fincept::trading::authdiff --git a/fincept-qt/src/trading/auth/RedirectServer.h b/fincept-qt/src/trading/auth/RedirectServer.hnew file mode 100644index 000000000..2a461f56f--- /dev/null+++ b/fincept-qt/src/trading/auth/RedirectServer.h@@ -0,0 +1,44 @@+#pragma once+// Loopback HTTP server that catches a single OAuth-style redirect carrying+// ?request_token=...&status=success in the query string.+//+// Binds 127.0.0.1:preferred_port. If that port is busy, binds to an ephemeral+// port and exposes it via port().+//+// Owned by the dialog for the duration of one browser-login attempt.++#include <QObject>+#include <QTcpServer>+#include <QTimer>++namespace fincept::trading::auth {++class RedirectServer : public QObject {+ Q_OBJECT+ public:+ explicit RedirectServer(QObject* parent = nullptr);+ ~RedirectServer() override;++ // Starts listening. Returns true on success. Updates port() on ephemeral fallback.+ // timeout_seconds triggers timeout() if no request arrives in that window.+ bool start(quint16 preferred_port = 5010, int timeout_seconds = 120);+ void stop();++ quint16 port() const { return port_; }++ signals:+ void request_token_received(const QString& token);+ void error(const QString& message);+ void timeout();++ private slots:+ void handle_new_connection();+ void handle_timeout();++ private:+ QTcpServer* server_ = nullptr;+ QTimer* timeout_timer_ = nullptr;+ quint16 port_ = 0;+};++} // namespace fincept::trading::authdiff --git a/fincept-qt/src/trading/brokers/BrokerHttp.cpp b/fincept-qt/src/trading/brokers/BrokerHttp.cppindex 4ef824374..1f82f4a74 100644--- a/fincept-qt/src/trading/brokers/BrokerHttp.cpp+++ b/fincept-qt/src/trading/brokers/BrokerHttp.cpp@@ -5,10 +5,11 @@#include "core/logging/Logger.h"#include <QEventLoop>-#include <QMutexLocker>#include <QNetworkAccessManager>#include <QNetworkReply>#include <QNetworkRequest>+#include <QThread>+#include <QThreadStorage>#include <QTimer>#include <QUrl>#include <QUrlQuery>@@ -99,10 +100,23 @@ BrokerHttpResponse BrokerHttp::put_raw(const QString& url, const QByteArray& bodBrokerHttpResponse BrokerHttp::execute(const QString& method, const QString& url, const QByteArray& body,const QString& content_type, const QMap<QString, QString>& headers) {- QMutexLocker locker(&mutex_);- QNetworkAccessManager nam;+ // One QNetworkAccessManager per worker thread so TLS/TCP connections are+ // reused across calls (keep-alive), instead of being created and torn down+ // for each request. Removed the global mutex — QNAM handles its own queueing+ // and the previous serialization was causing broker calls to block one+ // another, which made token exchange feel like it took "minutes".+ static QThreadStorage<QNetworkAccessManager*> tls_nam;+ if (!tls_nam.hasLocalData())+ tls_nam.setLocalData(new QNetworkAccessManager);+ QNetworkAccessManager& nam = *tls_nam.localData();+QUrl req_url(url);QNetworkRequest req(req_url);+ req.setAttribute(QNetworkRequest::Http2AllowedAttribute, true);+ req.setAttribute(QNetworkRequest::HttpPipeliningAllowedAttribute, true);+ // Explicit per-request transfer timeout so a dead socket aborts fast instead+ // of quietly draining the 8s budget. Qt >= 6.2.+ req.setTransferTimeout(timeout_ms_);// Set headersfor (auto it = headers.constBegin(); it != headers.constEnd(); ++it) {diff --git a/fincept-qt/src/trading/brokers/BrokerHttp.h b/fincept-qt/src/trading/brokers/BrokerHttp.hindex 227ecbcba..eb171ab2f 100644--- a/fincept-qt/src/trading/brokers/BrokerHttp.h+++ b/fincept-qt/src/trading/brokers/BrokerHttp.h@@ -7,7 +7,6 @@#include <QJsonDocument>#include <QJsonObject>#include <QMap>-#include <QMutex>#include <QString>namespace fincept::trading {@@ -55,15 +54,15 @@ class BrokerHttp {// Raw body PUT — caller provides pre-encoded body + headers (Tradier modify_order)BrokerHttpResponse put_raw(const QString& url, const QByteArray& body, const QMap<QString, QString>& headers = {});- // Timeout in ms (default 15s)+ // Timeout in ms (default 8s — tight enough to surface network issues fast,+ // long enough to tolerate a cold TLS handshake).void set_timeout(int ms) { timeout_ms_ = ms; }private:BrokerHttp() = default;BrokerHttpResponse execute(const QString& method, const QString& url, const QByteArray& body,const QString& content_type, const QMap<QString, QString>& headers);- int timeout_ms_ = 15000;- QMutex mutex_; // guards concurrent calls from QtConcurrent worker threads+ int timeout_ms_ = 8000;};} // namespace fincept::tradingdiff --git a/fincept-qt/src/trading/brokers/GrowwBroker.h b/fincept-qt/src/trading/brokers/GrowwBroker.hdeleted file mode 100644index abdb769e4..000000000--- a/fincept-qt/src/trading/brokers/GrowwBroker.h+++ /dev/null@@ -1,63 +0,0 @@-#pragma once-#include "trading/BrokerInterface.h"--namespace fincept::trading {--class GrowwBroker : public IBroker {- public:- BrokerId id() const override { return BrokerId::Groww; }- const char* name() const override { return "Groww"; }- const char* base_url() const override { return "https://groww.in/v1/api"; }-- BrokerProfile profile() const override {- return BrokerProfile{- .id = "groww",- .display_name = "Groww",- .region = "IN",- .currency = "INR",- .credential_fields =- {- {CredentialField::ApiKey, "API KEY", "Enter API Key...", false},- {CredentialField::ApiSecret, "API SECRET", "Enter API Secret...", true},- },- .exchanges = {"NSE", "BSE"},- .product_types =- {- {"Intraday (MIS)", ProductType::Intraday},- {"Delivery (CNC)", ProductType::Delivery},- },- .supports_intraday = true,- .supports_bracket_order = false,- .supports_cover_order = false,- .has_native_paper = false,- .default_paper_balance = 1000000.0,- .default_watchlist = {"HDFCBANK", "ICICIBANK", "SBIN", "TCS", "INFY", "RELIANCE", "TATAMOTORS",- "BAJFINANCE", "HINDUNILVR", "ITC"},- .default_symbol = "RELIANCE",- .default_exchange = "NSE",- .brokerage_info = "\u20B920/order intraday, 0% delivery",- };- }-- TokenExchangeResponse exchange_token(const QString& api_key, const QString& api_secret,- const QString& auth_code) override;- OrderPlaceResponse place_order(const BrokerCredentials& creds, const UnifiedOrder& order) override;- ApiResponse<QJsonObject> modify_order(const BrokerCredentials& creds, const QString& order_id,- const QJsonObject& mods) override;- ApiResponse<QJsonObject> cancel_order(const BrokerCredentials& creds, const QString& order_id) override;- ApiResponse<QVector<BrokerOrderInfo>> get_orders(const BrokerCredentials& creds) override;- ApiResponse<QJsonObject> get_trade_book(const BrokerCredentials& creds) override;- ApiResponse<QVector<BrokerPosition>> get_positions(const BrokerCredentials& creds) override;- ApiResponse<QVector<BrokerHolding>> get_holdings(const BrokerCredentials& creds) override;- ApiResponse<BrokerFunds> get_funds(const BrokerCredentials& creds) override;- ApiResponse<QVector<BrokerQuote>> get_quotes(const BrokerCredentials& creds,- const QVector<QString>& symbols) override;- ApiResponse<QVector<BrokerCandle>> get_history(const BrokerCredentials& creds, const QString& symbol,- const QString& resolution, const QString& from_date,- const QString& to_date) override;-- protected:- QMap<QString, QString> auth_headers(const BrokerCredentials& creds) const override;-};--} // namespace fincept::tradingdiff --git a/fincept-qt/src/trading/brokers/IndianBrokers.cpp b/fincept-qt/src/trading/brokers/IndianBrokers.cppindex ac48a0ea4..3402783e3 100644--- a/fincept-qt/src/trading/brokers/IndianBrokers.cpp+++ b/fincept-qt/src/trading/brokers/IndianBrokers.cpp@@ -1,13 +1,12 @@-// Indian Brokers — implementation for Zerodha, AngelOne, Upstox, Dhan, Kotak, Groww,-// AliceBlue, 5Paisa, IIFL, Motilal, Shoonya-// Each broker implements auth_headers + exchange_token + 10 trading API methods.+// Indian Brokers — stub implementations for brokers not yet fully built out.+// Groww and Zerodha have full implementations in their own broker-specific directories;+// everyone else here gets auth_headers + placeholder trading-API stubs.#include "core/logging/Logger.h"#include "trading/brokers/AliceBlueBroker.h"#include "trading/brokers/BrokerHttp.h"#include "trading/brokers/DhanBroker.h"#include "trading/brokers/FivePaisaBroker.h"-#include "trading/brokers/GrowwBroker.h"#include "trading/brokers/IIFLBroker.h"#include "trading/brokers/KotakBroker.h"#include "trading/brokers/MotilalBroker.h"@@ -504,15 +503,7 @@ QMap<QString, QString> KotakBroker::auth_headers(const BrokerCredentials& creds)}IMPL_STUB_METHODS(KotakBroker)-// ── Groww ──-QMap<QString, QString> GrowwBroker::auth_headers(const BrokerCredentials& creds) const {- QMap<QString, QString> h;- h["Authorization"] = "Bearer " + creds.access_token;- h["Content-Type"] = "application/json";- h["Accept"] = "application/json";- return h;-}-IMPL_STUB_METHODS(GrowwBroker)+// Groww is implemented in src/trading/brokers/groww/GrowwBroker.cpp (full, non-stub).// ── AliceBlue ──QMap<QString, QString> AliceBlueBroker::auth_headers(const BrokerCredentials& creds) const {diff --git a/fincept-qt/src/trading/brokers/groww/GrowwBroker.cpp b/fincept-qt/src/trading/brokers/groww/GrowwBroker.cppindex c9e487999..4120d2108 100644--- a/fincept-qt/src/trading/brokers/groww/GrowwBroker.cpp+++ b/fincept-qt/src/trading/brokers/groww/GrowwBroker.cpp@@ -7,7 +7,9 @@#include <QJsonArray>#include <QJsonDocument>#include <QJsonObject>+#include <QUrl>#include <QUrlQuery>+#include <QUuid>namespace fincept::trading {@@ -22,22 +24,32 @@ static int64_t now_ts() {bool GrowwBroker::is_token_expired(const BrokerHttpResponse& resp) {if (resp.status_code == 401 || resp.status_code == 403)return true;- if (!resp.json.isEmpty()) {- QString status = resp.json["status"].toString();- if (!status.isEmpty() && status != "SUCCESS")- return false; // error but not necessarily token expiry — checked per-call- }+ // GA005 = insufficient authorization (token expired / invalid).+ // See Groww error taxonomy — GA001 invalid input, GA006 business reject (funds), etc.+ if (error_code(resp) == QLatin1String("GA005"))+ return true;return false;}QString GrowwBroker::checked_error(const BrokerHttpResponse& resp, const QString& fallback) {if (!resp.json.isEmpty()) {+ // Preferred Groww shape: { status: "FAILURE", error: { code: "GA00x", message: "..." } }+ QJsonValue err_v = resp.json["error"];+ if (err_v.isObject()) {+ QJsonObject e = err_v.toObject();+ QString msg = e["message"].toString();+ QString code = e["code"].toString();+ if (!msg.isEmpty() && !code.isEmpty())+ return QString("[%1] %2").arg(code, msg);+ if (!msg.isEmpty())+ return msg;+ }+QString msg = resp.json["message"].toString();if (!msg.isEmpty())return msg;- msg = resp.json["error"].toString();- if (!msg.isEmpty())- return msg;+ if (err_v.isString())+ return err_v.toString();QString status = resp.json["status"].toString();if (!status.isEmpty() && status != "SUCCESS")return QString("Groww error: status=%1").arg(status);@@ -49,6 +61,20 @@ QString GrowwBroker::checked_error(const BrokerHttpResponse& resp, const QStringreturn fallback;}+QString GrowwBroker::error_code(const BrokerHttpResponse& resp) {+ if (resp.json.isEmpty())+ return {};+ QJsonValue err_v = resp.json["error"];+ if (err_v.isObject())+ return err_v.toObject()["code"].toString();+ return {};+}++bool GrowwBroker::is_rate_limited(const BrokerHttpResponse& resp) {+ // Groww surfaces rate-limit breaches via HTTP 429 without a GA code in the body.+ return resp.status_code == 429;+}+// exchange as sent to Groww order endpoints (NSE/BSE for CASH; NSE/BSE for FNO)QString GrowwBroker::groww_exchange(const QString& exchange) {if (exchange == "NFO")@@ -95,21 +121,28 @@ QString GrowwBroker::groww_order_type(OrderType t) {// resolution string → interval_in_minutes for Groww historical APIint GrowwBroker::resolution_to_minutes(const QString& resolution) {- if (resolution == "1" || resolution == "1m")+ return history_interval_minutes(resolution);+}++// Groww /v1/historical/candles accepts 1, 5, 10, 15, 30, 60 minute bars plus 1440 (1D)+// and 10080 (1W). Windows are capped per interval: ≤5m → 30d, 10–30m → 90d, ≥1h → 180d.+int GrowwBroker::history_interval_minutes(const QString& resolution) {+ const QString r = resolution.toLower();+ if (r == "1" || r == "1m")return 1;- if (resolution == "5" || resolution == "5m")+ if (r == "5" || r == "5m")return 5;- if (resolution == "10" || resolution == "10m")+ if (r == "10" || r == "10m")return 10;- if (resolution == "15" || resolution == "15m")+ if (r == "15" || r == "15m")return 15;- if (resolution == "30" || resolution == "30m")+ if (r == "30" || r == "30m")return 30;- if (resolution == "60" || resolution == "1h")+ if (r == "60" || r == "1h")return 60;- if (resolution == "D" || resolution == "1D")+ if (r == "d" || r == "1d" || r == "day")return 1440;- if (resolution == "W" || resolution == "1W")+ if (r == "w" || r == "1w" || r == "week")return 10080;return 1;}@@ -123,6 +156,7 @@ QMap<QString, QString> GrowwBroker::auth_headers(const BrokerCredentials& creds){"Authorization", "Bearer " + creds.access_token},{"Content-Type", "application/json"},{"Accept", "application/json"},+ {"X-API-VERSION", "1.0"},};}@@ -209,16 +243,24 @@ ApiResponse<QJsonObject> GrowwBroker::modify_order(const BrokerCredentials& credint64_t ts = now_ts();auto hdrs = auth_headers(creds);+ // Groww requires groww_order_id + order_type + segment in the body.+ // Caller may pass segment/exchange in the mods JSON; default to CASH when absent.+ QString segment = mods.value("segment").toString();+ if (segment.isEmpty()) {+ QString exchange = mods.value("exchange").toString();+ segment = groww_segment(exchange.isEmpty() ? QStringLiteral("NSE") : exchange);+ }+QJsonObject body;- body["order_id"] = order_id;+ body["groww_order_id"] = order_id;+ body["segment"] = segment;+ body["order_type"] = mods.contains("order_type") ? mods["order_type"].toString() : QStringLiteral("LIMIT");if (mods.contains("quantity"))body["quantity"] = mods["quantity"];if (mods.contains("price"))body["price"] = mods["price"];if (mods.contains("trigger_price"))body["trigger_price"] = mods["trigger_price"];- if (mods.contains("order_type"))- body["order_type"] = mods["order_type"];auto resp = BrokerHttp::instance().post_json("https://api.groww.in/v1/order/modify", body, hdrs);@@ -238,10 +280,18 @@ ApiResponse<QJsonObject> GrowwBroker::cancel_order(const BrokerCredentials& credint64_t ts = now_ts();auto hdrs = auth_headers(creds);- QJsonObject body;- body["order_id"] = order_id;+ // Groww requires groww_order_id + segment. IBroker::cancel_order has no segment,+ // so try CASH first; if the order isn't found there, retry on FNO.+ auto do_cancel = [&](const QString& segment) {+ QJsonObject body;+ body["groww_order_id"] = order_id;+ body["segment"] = segment;+ return BrokerHttp::instance().post_json("https://api.groww.in/v1/order/cancel", body, hdrs);+ };- auto resp = BrokerHttp::instance().post_json("https://api.groww.in/v1/order/cancel", body, hdrs);+ auto resp = do_cancel(QStringLiteral("CASH"));+ if (resp.success && resp.json["status"].toString() != "SUCCESS")+ resp = do_cancel(QStringLiteral("FNO"));if (!resp.success)return {false, std::nullopt, checked_error(resp, "Network error"), ts};@@ -328,14 +378,61 @@ ApiResponse<QJsonObject> GrowwBroker::get_trade_book(const BrokerCredentials& crint64_t ts = now_ts();auto hdrs = auth_headers(creds);- auto resp = BrokerHttp::instance().get("https://api.groww.in/v1/order/trade/list", hdrs);+ // Groww has no global trade book — trades are fetched per order via+ // GET /v1/order/trades/{groww_order_id}?segment=...&page=0&page_size=50.+ // Aggregate trades across filled orders in both segments into a single payload.+ QJsonArray all_trades;- if (!resp.success)- return {false, std::nullopt, checked_error(resp, "Network error"), ts};- if (is_token_expired(resp))- return {false, std::nullopt, "[TOKEN_EXPIRED]", ts};+ auto fetch_segment_trades = [&](const QString& segment) {+ constexpr int PAGE_SIZE = 25;+ int page = 0;+ while (true) {+ QString list_url = QString("https://api.groww.in/v1/order/list?segment=%1&page=%2&page_size=%3")+ .arg(segment)+ .arg(page)+ .arg(PAGE_SIZE);+ auto list_resp = BrokerHttp::instance().get(list_url, hdrs);+ if (!list_resp.success || is_token_expired(list_resp))+ return;++ QJsonArray orders = list_resp.json["payload"].toObject()["order_list"].toArray();+ for (const auto& it : orders) {+ QJsonObject o = it.toObject();+ QString status = o["status"].toString();+ if (o["filled_quantity"].toInt() == 0 && status != "COMPLETED" && status != "EXECUTED")+ continue;++ QString oid = o["groww_order_id"].toString();+ if (oid.isEmpty())+ oid = o["order_id"].toString();+ if (oid.isEmpty())+ continue;++ QString trades_url = QString("https://api.groww.in/v1/order/trades/%1?segment=%2&page=0&page_size=50")+ .arg(oid, segment);+ auto tr = BrokerHttp::instance().get(trades_url, hdrs);+ if (!tr.success || is_token_expired(tr))+ continue;++ QJsonArray tlist = tr.json["payload"].toObject()["trade_list"].toArray();+ for (const auto& t : tlist)+ all_trades.append(t);+ }+ if (orders.size() < PAGE_SIZE)+ break;+ ++page;+ }+ };- return {true, resp.json, "", ts};+ fetch_segment_trades(QStringLiteral("CASH"));+ fetch_segment_trades(QStringLiteral("FNO"));++ QJsonObject result;+ QJsonObject payload;+ payload["trade_list"] = all_trades;+ result["status"] = "SUCCESS";+ result["payload"] = payload;+ return {true, result, "", ts};}ApiResponse<QVector<BrokerPosition>> GrowwBroker::get_positions(const BrokerCredentials& creds) {@@ -351,20 +448,37 @@ ApiResponse<QVector<BrokerPosition>> GrowwBroker::get_positions(const BrokerCredif (is_token_expired(resp))return false;- QJsonArray list = resp.json["payload"].toArray();+ // Positions live under payload.positions per Groww docs.+ QJsonValue payload_v = resp.json["payload"];+ QJsonArray list = payload_v.isObject() ? payload_v.toObject()["positions"].toArray() : payload_v.toArray();for (const auto& item : list) {QJsonObject p = item.toObject();- int qty = p["quantity"].toInt();++ // Net open quantity = credit (buy) - debit (sell). Prefer the API's+ // explicit `quantity` if present; otherwise derive from credit/debit.+ int qty = 0;+ if (p.contains("quantity") && !p["quantity"].isNull()) {+ qty = p["quantity"].toInt();+ } else {+ int credit = p["credit_quantity"].toInt();+ int debit = p["debit_quantity"].toInt();+ qty = credit - debit;+ }if (qty == 0)continue;+ // avg_price preference: net_price → credit_price (for long) → debit_price (for short)+ double avg = p["net_price"].toDouble();+ if (avg == 0.0)+ avg = (qty > 0) ? p["credit_price"].toDouble() : p["debit_price"].toDouble();+BrokerPosition pos;pos.symbol = p["trading_symbol"].toString();pos.exchange = p["exchange"].toString();pos.quantity = qty;- pos.avg_price = p["buy_price"].toDouble();- pos.ltp = p["ltp"].toDouble();- pos.pnl = p["pnl"].toDouble();+ pos.avg_price = avg;+ pos.ltp = 0.0; // Not returned by positions endpoint; query live-data/ltp separately if needed.+ pos.pnl = p["realised_pnl"].toDouble();pos.product_type = p["product"].toString();positions.append(pos);}@@ -381,7 +495,7 @@ ApiResponse<QVector<BrokerHolding>> GrowwBroker::get_holdings(const BrokerCredenint64_t ts = now_ts();auto hdrs = auth_headers(creds);- auto resp = BrokerHttp::instance().get("https://api.groww.in/v1/portfolio/holdings", hdrs);+ auto resp = BrokerHttp::instance().get("https://api.groww.in/v1/holdings/user", hdrs);if (!resp.success)return {false, std::nullopt, checked_error(resp, "Network error"), ts};@@ -396,11 +510,12 @@ ApiResponse<QVector<BrokerHolding>> GrowwBroker::get_holdings(const BrokerCredenQJsonObject h = item.toObject();BrokerHolding holding;holding.symbol = h["trading_symbol"].toString();- holding.exchange = h["exchange"].toString();+ // exchange is not in the Groww holdings response; NSE is the DP default for equity holdings.+ holding.exchange = h.contains("exchange") ? h["exchange"].toString() : QStringLiteral("NSE");holding.quantity = h["quantity"].toInt();holding.avg_price = h["average_price"].toDouble();- holding.ltp = h["last_price"].toDouble();- holding.pnl = h["pnl"].toDouble();+ holding.ltp = 0.0; // Not returned by holdings endpoint; query live-data/ltp separately if needed.+ holding.pnl = 0.0; // Derived value — compute in the service layer once LTP is fetched.holdings.append(holding);}@@ -432,40 +547,170 @@ ApiResponse<BrokerFunds> GrowwBroker::get_funds(const BrokerCredentials& creds)return {true, funds, "", ts};}-ApiResponse<QVector<BrokerQuote>> GrowwBroker::get_quotes(const BrokerCredentials& creds,- const QVector<QString>& symbols) {- int64_t ts = now_ts();+GrowwBroker::SymbolRef GrowwBroker::split_symbol(const QString& sym) {+ SymbolRef r;+ r.orig = sym;+ r.exchange = QStringLiteral("NSE");+ r.trading_symbol = sym;+ const int colon = sym.indexOf(':');+ if (colon != -1) {+ r.exchange = sym.left(colon);+ r.trading_symbol = sym.mid(colon + 1);+ }+ r.segment = groww_segment(r.exchange);+ r.exchange_symbol = groww_exchange(r.exchange) + "_" + r.trading_symbol;+ return r;+}++bool GrowwBroker::fetch_ltp_batch(const BrokerCredentials& creds, const QString& segment,+ const QVector<SymbolRef>& refs, QVector<BrokerQuote>& out) {+ if (refs.isEmpty())+ return true;auto hdrs = auth_headers(creds);- QVector<BrokerQuote> quotes;- for (const QString& sym : symbols) {- // symbols may be "NSE:RELIANCE" or just "RELIANCE" — split if colon present- QString exchange = "NSE";- QString trading_symbol = sym;- int colon = sym.indexOf(':');- if (colon != -1) {- exchange = sym.left(colon);- trading_symbol = sym.mid(colon + 1);+ // Groww accepts up to 50 symbols per call — chunk accordingly.+ constexpr int BATCH = 50;+ for (int start = 0; start < refs.size(); start += BATCH) {+ const int end = std::min<int>(start + BATCH, refs.size());++ QStringList syms;+ syms.reserve(end - start);+ for (int i = start; i < end; ++i)+ syms << refs[i].exchange_symbol;++ // exchange_symbols is a repeatable query param: ?exchange_symbols=NSE_A&exchange_symbols=NSE_B+ QUrl url(QStringLiteral("https://api.groww.in/v1/live-data/ltp"));+ QUrlQuery q;+ q.addQueryItem(QStringLiteral("segment"), segment);+ for (const auto& s : syms)+ q.addQueryItem(QStringLiteral("exchange_symbols"), s);+ url.setQuery(q);++ auto resp = BrokerHttp::instance().get(url.toString(), hdrs);+ if (!resp.success)+ return false;+ if (is_token_expired(resp))+ return false;++ // Response shape: payload.ltp is a map { "NSE_RELIANCE": 2850.5, ... }+ QJsonObject payload = resp.json["payload"].toObject();+ QJsonObject ltp_map = payload["ltp"].toObject();+ if (ltp_map.isEmpty())+ ltp_map = payload; // some variants return the map directly++ for (int i = start; i < end; ++i) {+ const auto& ref = refs[i];+ if (!ltp_map.contains(ref.exchange_symbol))+ continue;+ double ltp = ltp_map.value(ref.exchange_symbol).toDouble();++ // upsert by orig symbol+ int idx = -1;+ for (int k = 0; k < out.size(); ++k) {+ if (out[k].symbol == ref.orig) {+ idx = k;+ break;+ }+ }+ if (idx == -1) {+ BrokerQuote bq;+ bq.symbol = ref.orig;+ bq.ltp = ltp;+ out.append(bq);+ } else {+ out[idx].ltp = ltp;+ }}+ }+ return true;+}++bool GrowwBroker::fetch_ohlc_batch(const BrokerCredentials& creds, const QString& segment,+ const QVector<SymbolRef>& refs, QVector<BrokerQuote>& out) {+ if (refs.isEmpty())+ return true;+ auto hdrs = auth_headers(creds);++ constexpr int BATCH = 50;+ for (int start = 0; start < refs.size(); start += BATCH) {+ const int end = std::min<int>(start + BATCH, refs.size());- QString segment = groww_segment(exchange);- QString ex = groww_exchange(exchange);+ QUrl url(QStringLiteral("https://api.groww.in/v1/live-data/ohlc"));+ QUrlQuery q;+ q.addQueryItem(QStringLiteral("segment"), segment);+ for (int i = start; i < end; ++i)+ q.addQueryItem(QStringLiteral("exchange_symbols"), refs[i].exchange_symbol);+ url.setQuery(q);+ auto resp = BrokerHttp::instance().get(url.toString(), hdrs);+ if (!resp.success)+ return false;+ if (is_token_expired(resp))+ return false;++ // Response shape: payload.ohlc is a map { "NSE_RELIANCE": {open,high,low,close,...}, ... }+ QJsonObject payload = resp.json["payload"].toObject();+ QJsonObject ohlc_map = payload["ohlc"].toObject();+ if (ohlc_map.isEmpty())+ ohlc_map = payload;++ for (int i = start; i < end; ++i) {+ const auto& ref = refs[i];+ if (!ohlc_map.contains(ref.exchange_symbol))+ continue;+ QJsonObject ohlc = ohlc_map.value(ref.exchange_symbol).toObject();++ int idx = -1;+ for (int k = 0; k < out.size(); ++k) {+ if (out[k].symbol == ref.orig) {+ idx = k;+ break;+ }+ }+ BrokerQuote* q_ptr = nullptr;+ if (idx == -1) {+ BrokerQuote bq;+ bq.symbol = ref.orig;+ out.append(bq);+ q_ptr = &out.last();+ } else {+ q_ptr = &out[idx];+ }+ q_ptr->open = ohlc["open"].toDouble();+ q_ptr->high = ohlc["high"].toDouble();+ q_ptr->low = ohlc["low"].toDouble();+ q_ptr->close = ohlc["close"].toDouble();+ if (ohlc.contains("volume"))+ q_ptr->volume = ohlc["volume"].toDouble();+ }+ }+ return true;+}++ApiResponse<QVector<BrokerQuote>> GrowwBroker::get_quotes(const BrokerCredentials& creds,+ const QVector<QString>& symbols) {+ int64_t ts = now_ts();+ QVector<BrokerQuote> quotes;++ // Single-symbol path: the /live-data/quote endpoint returns the full snapshot+ // (ltp + ohlc + volume + bid/ask). Prefer it when only one symbol is requested.+ if (symbols.size() == 1) {+ auto hdrs = auth_headers(creds);+ const auto ref = split_symbol(symbols.first());QString url = QString("https://api.groww.in/v1/live-data/quote""?exchange=%1&segment=%2&trading_symbol=%3")- .arg(ex, segment, trading_symbol);-+ .arg(groww_exchange(ref.exchange), ref.segment, ref.trading_symbol);auto resp = BrokerHttp::instance().get(url, hdrs);if (!resp.success)- continue;+ return {false, std::nullopt, checked_error(resp, "Network error"), ts};if (is_token_expired(resp))- break;+ return {false, std::nullopt, "[TOKEN_EXPIRED]", ts};QJsonObject payload = resp.json["payload"].toObject();QJsonObject ohlc = payload["ohlc"].toObject();BrokerQuote q;- q.symbol = sym;+ q.symbol = ref.orig;q.ltp = payload["last_price"].toDouble();q.open = ohlc["open"].toDouble();q.high = ohlc["high"].toDouble();@@ -473,6 +718,22 @@ ApiResponse<QVector<BrokerQuote>> GrowwBroker::get_quotes(const BrokerCredentialq.close = ohlc["close"].toDouble();q.volume = payload["volume"].toDouble();quotes.append(q);+ return {true, quotes, "", ts};+ }++ // Batch path: group symbols by segment (CASH/FNO are separate buckets on Groww's+ // /live-data/ltp and /live-data/ohlc), then issue at most 2 RPCs per segment+ // (ltp + ohlc) per 50-symbol chunk. Drops N per-symbol calls to O(1) per 50.+ QMap<QString, QVector<SymbolRef>> by_segment;+ for (const QString& sym : symbols) {+ auto ref = split_symbol(sym);+ by_segment[ref.segment].append(ref);+ }++ for (auto it = by_segment.constBegin(); it != by_segment.constEnd(); ++it) {+ if (!fetch_ltp_batch(creds, it.key(), it.value(), quotes))+ continue; // best-effort — partial batch still returns what succeeded+ fetch_ohlc_batch(creds, it.key(), it.value(), quotes);}return {true, quotes, "", ts};@@ -494,17 +755,24 @@ ApiResponse<QVector<BrokerCandle>> GrowwBroker::get_history(const BrokerCredentiQString segment = groww_segment(exchange);QString ex = groww_exchange(exchange);- int interval = resolution_to_minutes(resolution);+ int interval = history_interval_minutes(resolution);- // Groww expects datetime format "YYYY-MM-DD HH:MM:SS"- // from_date/to_date arrive as "YYYY-MM-DD" — append times+ // Groww /v1/historical/candles is the current endpoint (replaces /candle/range).+ // Expects datetime format "YYYY-MM-DD HH:MM:SS"; callers pass bare dates, so pin+ // to the NSE session window. groww_symbol = trading_symbol for cash/F&O.QString start_time = from_date + " 09:15:00";QString end_time = to_date + " 15:30:00";- QString url = QString("https://api.groww.in/v1/historical/candle/range"- "?exchange=%1&segment=%2&trading_symbol=%3"- "&start_time=%4&end_time=%5&interval_in_minutes=%6")- .arg(ex, segment, trading_symbol, start_time, end_time, QString::number(interval));+ QUrl qurl(QStringLiteral("https://api.groww.in/v1/historical/candles"));+ QUrlQuery qq;+ qq.addQueryItem(QStringLiteral("exchange"), ex);+ qq.addQueryItem(QStringLiteral("segment"), segment);+ qq.addQueryItem(QStringLiteral("groww_symbol"), trading_symbol);+ qq.addQueryItem(QStringLiteral("start_time"), start_time);+ qq.addQueryItem(QStringLiteral("end_time"), end_time);+ qq.addQueryItem(QStringLiteral("candle_interval"), QString::number(interval));+ qurl.setQuery(qq);+ const QString url = qurl.toString();auto resp = BrokerHttp::instance().get(url, hdrs);@@ -535,4 +803,334 @@ ApiResponse<QVector<BrokerCandle>> GrowwBroker::get_history(const BrokerCredentireturn {true, result, "", ts};}+// ============================================================================+// Pre-trade margin calculator — POST /v1/margins/detail/orders?segment=...+// ============================================================================++QJsonObject GrowwBroker::order_to_margin_row(const UnifiedOrder& order) {+ QJsonObject row;+ row["trading_symbol"] = order.symbol;+ row["quantity"] = order.quantity;+ row["exchange"] = groww_exchange(order.exchange);+ row["product"] = groww_product(order.product_type);+ row["order_type"] = groww_order_type(order.order_type);+ row["transaction_type"] = (order.side == OrderSide::Buy) ? "BUY" : "SELL";+ // Margin API wants the price for LIMIT/SL-L orders; MARKET can be omitted.+ if (order.order_type != OrderType::Market)+ row["price"] = order.price;+ if (order.order_type == OrderType::StopLoss || order.order_type == OrderType::StopLossLimit)+ row["trigger_price"] = order.stop_price;+ return row;+}++ApiResponse<OrderMargin> GrowwBroker::get_order_margins(const BrokerCredentials& creds,+ const UnifiedOrder& order) {+ int64_t ts = now_ts();+ auto hdrs = auth_headers(creds);++ const QString segment = groww_segment(order.exchange);+ QJsonArray arr;+ arr.append(order_to_margin_row(order));++ QString url = QString("https://api.groww.in/v1/margins/detail/orders?segment=%1").arg(segment);+ auto resp = BrokerHttp::instance().post_json_array(url, arr, hdrs);++ if (!resp.success)+ return {false, std::nullopt, checked_error(resp, "Network error"), ts};+ if (is_token_expired(resp))+ return {false, std::nullopt, "[TOKEN_EXPIRED]", ts};+ if (resp.json["status"].toString() != "SUCCESS")+ return {false, std::nullopt, checked_error(resp, "Margin calc failed"), ts};++ // Response payload shape varies by segment; common fields:+ // total_requirement, exposure_required, span_required, option_buy_premium,+ // brokerage_and_charges, cash_cnc_margin_required, cash_mis_margin_required+ QJsonObject payload = resp.json["payload"].toObject();+ OrderMargin m;+ m.symbol = order.symbol;+ m.exchange = order.exchange;+ m.side = (order.side == OrderSide::Buy) ? "BUY" : "SELL";+ m.quantity = order.quantity;+ m.price = order.price;+ m.total = payload["total_requirement"].toDouble();+ m.var_margin = payload["span_required"].toDouble(); // closest analogue for F&O; 0 for cash+ m.elm = payload["exposure_required"].toDouble();+ m.additional = payload["option_buy_premium"].toDouble();+ m.cash = payload.contains("cash_cnc_margin_required")+ ? payload["cash_cnc_margin_required"].toDouble()+ : payload["cash_mis_margin_required"].toDouble();+ m.bo_margin = 0.0; // Groww has no bracket orders+ m.pnl = 0.0;+ if (m.total > 0 && order.price > 0 && order.quantity > 0)+ m.leverage = (order.price * order.quantity) / m.total;+ return {true, m, "", ts};+}++ApiResponse<BasketMargin> GrowwBroker::get_basket_margins(const BrokerCredentials& creds,+ const QVector<UnifiedOrder>& orders) {+ int64_t ts = now_ts();+ if (orders.isEmpty())+ return {true, BasketMargin{}, "", ts};++ auto hdrs = auth_headers(creds);+ // Groww scopes margin calls by segment (query param). Group legs by segment and+ // issue one RPC per bucket; aggregate totals client-side.+ QMap<QString, QVector<UnifiedOrder>> by_segment;+ for (const auto& o : orders)+ by_segment[groww_segment(o.exchange)].append(o);++ BasketMargin result;+ for (auto it = by_segment.constBegin(); it != by_segment.constEnd(); ++it) {+ QJsonArray arr;+ for (const auto& o : it.value())+ arr.append(order_to_margin_row(o));++ QString url = QString("https://api.groww.in/v1/margins/detail/orders?segment=%1").arg(it.key());+ QJsonDocument doc(arr);+ auto resp = BrokerHttp::instance().post_raw(url, doc.toJson(QJsonDocument::Compact), hdrs);++ if (!resp.success)+ return {false, std::nullopt, checked_error(resp, "Network error"), ts};+ if (is_token_expired(resp))+ return {false, std::nullopt, "[TOKEN_EXPIRED]", ts};+ if (resp.json["status"].toString() != "SUCCESS")+ return {false, std::nullopt, checked_error(resp, "Basket margin failed"), ts};++ QJsonObject payload = resp.json["payload"].toObject();+ const double total = payload["total_requirement"].toDouble();+ // Groww returns the netted total for the whole segment basket in one shot.+ result.initial_margin += total;+ result.final_margin += total; // no pre/post netting split in Groww response++ // Per-order rows aren't broken out by Groww; emit a best-effort synthetic row.+ for (const auto& o : it.value()) {+ OrderMargin m;+ m.symbol = o.symbol;+ m.exchange = o.exchange;+ m.side = (o.side == OrderSide::Buy) ? "BUY" : "SELL";+ m.quantity = o.quantity;+ m.price = o.price;+ m.total = 0.0; // unknown per-leg — only the segment total is returned+ result.orders.append(m);+ }+ }+ return {true, result, "", ts};+}++// ============================================================================+// User profile — GET /v1/user/detail+// Groww exposes only: vendor_user_id, ucc, nse_enabled, bse_enabled,+// ddpi_enabled, active_segments. No name / email over the trade API.+// ============================================================================++ApiResponse<QJsonObject> GrowwBroker::get_profile(const BrokerCredentials& creds) {+ int64_t ts = now_ts();+ auto hdrs = auth_headers(creds);++ auto resp = BrokerHttp::instance().get("https://api.groww.in/v1/user/detail", hdrs);+ if (!resp.success)+ return {false, std::nullopt, checked_error(resp, "Network error"), ts};+ if (is_token_expired(resp))+ return {false, std::nullopt, "[TOKEN_EXPIRED]", ts};+ if (resp.json["status"].toString() != "SUCCESS")+ return {false, std::nullopt, checked_error(resp, "Profile fetch failed"), ts};++ return {true, resp.json["payload"].toObject(), "", ts};+}++// ============================================================================+// Smart Orders (GTT / OCO) — /v1/order-advance/*+// Groww has no iceberg/slice — slicing must be done client-side. These hooks+// expose GTT + OCO through the standard IBroker::gtt_* interface.+// ============================================================================++QJsonObject GrowwBroker::gtt_to_advance_body(const GttOrder& g, bool is_create) {+ QJsonObject body;+ if (is_create)+ body["reference_id"] = g.gtt_id.isEmpty() ? QUuid::createUuid().toString(QUuid::WithoutBraces) : g.gtt_id;+ body["smart_order_type"] = (g.type == GttOrderType::OCO) ? "OCO" : "GTT";+ body["segment"] = groww_segment(g.exchange);+ body["trading_symbol"] = g.symbol;++ if (!g.triggers.isEmpty()) {+ const GttTrigger& t0 = g.triggers.first();+ body["quantity"] = t0.quantity;+ body["trigger_price"] = t0.trigger_price;++ QJsonObject leg;+ leg["transaction_type"] = (t0.side == OrderSide::Buy) ? "BUY" : "SELL";+ leg["order_type"] = groww_order_type(t0.order_type);+ leg["product"] = groww_product(t0.product);+ leg["exchange"] = groww_exchange(g.exchange);+ if (t0.limit_price > 0)+ leg["price"] = t0.limit_price;+ body["order"] = leg;++ if (g.type == GttOrderType::OCO && g.triggers.size() > 1) {+ const GttTrigger& t1 = g.triggers.at(1);+ QJsonObject leg2;+ leg2["transaction_type"] = (t1.side == OrderSide::Buy) ? "BUY" : "SELL";+ leg2["order_type"] = groww_order_type(t1.order_type);+ leg2["product"] = groww_product(t1.product);+ leg2["exchange"] = groww_exchange(g.exchange);+ if (t1.limit_price > 0)+ leg2["price"] = t1.limit_price;+ QJsonObject oco;+ oco["trigger_price"] = t1.trigger_price;+ oco["order"] = leg2;+ body["secondary_order"] = oco;+ }+ }+ return body;+}++GttOrder GrowwBroker::parse_advance_to_gtt(const QJsonObject& payload) {+ GttOrder g;+ g.gtt_id = payload["smart_order_id"].toString();+ if (g.gtt_id.isEmpty())+ g.gtt_id = payload["reference_id"].toString();+ g.symbol = payload["trading_symbol"].toString();+ // Groww stores exchange inside the leg payload; fall back to NSE if segment-only.+ QJsonObject leg = payload["order"].toObject();+ g.exchange = leg.contains("exchange") ? leg["exchange"].toString() : QStringLiteral("NSE");+ g.type = (payload["smart_order_type"].toString() == "OCO") ? GttOrderType::OCO : GttOrderType::Single;+ g.status = payload["status"].toString().toLower();+ g.created_at = payload["created_at"].toString();+ g.updated_at = payload["updated_at"].toString();++ GttTrigger t0;+ t0.trigger_price = payload["trigger_price"].toDouble();+ t0.quantity = payload["quantity"].toDouble();+ t0.side = (leg["transaction_type"].toString() == "BUY") ? OrderSide::Buy : OrderSide::Sell;+ t0.limit_price = leg["price"].toDouble();+ g.triggers.append(t0);++ if (g.type == GttOrderType::OCO) {+ QJsonObject sec = payload["secondary_order"].toObject();+ QJsonObject leg2 = sec["order"].toObject();+ GttTrigger t1;+ t1.trigger_price = sec["trigger_price"].toDouble();+ t1.quantity = t0.quantity;+ t1.side = (leg2["transaction_type"].toString() == "BUY") ? OrderSide::Buy : OrderSide::Sell;+ t1.limit_price = leg2["price"].toDouble();+ g.triggers.append(t1);+ }+ return g;+}++GttPlaceResponse GrowwBroker::gtt_place(const BrokerCredentials& creds, const GttOrder& order) {+ auto hdrs = auth_headers(creds);+ QJsonObject body = gtt_to_advance_body(order, /*is_create=*/true);++ auto resp = BrokerHttp::instance().post_json("https://api.groww.in/v1/order-advance/create", body, hdrs);+ if (!resp.success)+ return {false, "", checked_error(resp, "Network error")};+ if (is_token_expired(resp))+ return {false, "", "[TOKEN_EXPIRED]"};+ if (resp.json["status"].toString() != "SUCCESS")+ return {false, "", checked_error(resp, "GTT create failed")};++ QJsonObject payload = resp.json["payload"].toObject();+ QString id = payload["smart_order_id"].toString();+ if (id.isEmpty())+ id = payload["reference_id"].toString();+ return {true, id, ""};+}++ApiResponse<GttOrder> GrowwBroker::gtt_get(const BrokerCredentials& creds, const QString& gtt_id) {+ int64_t ts = now_ts();+ auto hdrs = auth_headers(creds);++ // Groww needs segment + smart_order_type in the path. Caller only passed the id,+ // so try both (CASH/GTT, CASH/OCO, FNO/GTT, FNO/OCO). Stop at the first match.+ const QStringList segs = {"CASH", "FNO"};+ const QStringList types = {"GTT", "OCO"};+ for (const auto& seg : segs) {+ for (const auto& type : types) {+ QString url = QString("https://api.groww.in/v1/order-advance/status/%1/%2/internal/%3")+ .arg(seg, type, gtt_id);+ auto resp = BrokerHttp::instance().get(url, hdrs);+ if (!resp.success || is_token_expired(resp))+ continue;+ if (resp.json["status"].toString() != "SUCCESS")+ continue;+ QJsonObject payload = resp.json["payload"].toObject();+ if (payload.isEmpty())+ continue;+ return {true, parse_advance_to_gtt(payload), "", ts};+ }+ }+ return {false, std::nullopt, "GTT not found", ts};+}++ApiResponse<QVector<GttOrder>> GrowwBroker::gtt_list(const BrokerCredentials& creds) {+ int64_t ts = now_ts();+ auto hdrs = auth_headers(creds);++ QVector<GttOrder> out;+ const QStringList segs = {"CASH", "FNO"};+ const QStringList types = {"GTT", "OCO"};+ for (const auto& seg : segs) {+ for (const auto& type : types) {+ QString url = QString("https://api.groww.in/v1/order-advance/list?segment=%1"+ "&smart_order_type=%2&page=0&page_size=100")+ .arg(seg, type);+ auto resp = BrokerHttp::instance().get(url, hdrs);+ if (!resp.success || is_token_expired(resp))+ continue;+ if (resp.json["status"].toString() != "SUCCESS")+ continue;+ QJsonArray list = resp.json["payload"].toObject()["smart_order_list"].toArray();+ for (const auto& v : list) {+ QJsonObject o = v.toObject();+ if (!o.isEmpty())+ out.append(parse_advance_to_gtt(o));+ }+ }+ }+ return {true, out, "", ts};+}++ApiResponse<GttOrder> GrowwBroker::gtt_modify(const BrokerCredentials& creds, const QString& gtt_id,+ const GttOrder& updated) {+ int64_t ts = now_ts();+ auto hdrs = auth_headers(creds);+ QJsonObject body = gtt_to_advance_body(updated, /*is_create=*/false);++ QString url = QString("https://api.groww.in/v1/order-advance/modify/%1").arg(gtt_id);+ auto resp = BrokerHttp::instance().put_json(url, body, hdrs);+ if (!resp.success)+ return {false, std::nullopt, checked_error(resp, "Network error"), ts};+ if (is_token_expired(resp))+ return {false, std::nullopt, "[TOKEN_EXPIRED]", ts};+ if (resp.json["status"].toString() != "SUCCESS")+ return {false, std::nullopt, checked_error(resp, "GTT modify failed"), ts};++ // Server echoes the updated smart order; re-parse so callers see the canonical state.+ return {true, parse_advance_to_gtt(resp.json["payload"].toObject()), "", ts};+}++ApiResponse<QJsonObject> GrowwBroker::gtt_cancel(const BrokerCredentials& creds, const QString& gtt_id) {+ int64_t ts = now_ts();+ auto hdrs = auth_headers(creds);++ // Cancel endpoint needs segment + type in the path. Walk the 4-way grid as in gtt_get.+ const QStringList segs = {"CASH", "FNO"};+ const QStringList types = {"GTT", "OCO"};+ BrokerHttpResponse last;+ for (const auto& seg : segs) {+ for (const auto& type : types) {+ QString url = QString("https://api.groww.in/v1/order-advance/cancel/%1/%2/%3").arg(seg, type, gtt_id);+ last = BrokerHttp::instance().post_json(url, QJsonObject{}, hdrs);+ if (!last.success)+ continue;+ if (is_token_expired(last))+ return {false, std::nullopt, "[TOKEN_EXPIRED]", ts};+ if (last.json["status"].toString() == "SUCCESS")+ return {true, last.json, "", ts};+ }+ }+ return {false, std::nullopt, checked_error(last, "GTT cancel failed"), ts};+}+} // namespace fincept::tradingdiff --git a/fincept-qt/src/trading/brokers/groww/GrowwBroker.h b/fincept-qt/src/trading/brokers/groww/GrowwBroker.hindex 14b7aad81..0f8cdc54d 100644--- a/fincept-qt/src/trading/brokers/groww/GrowwBroker.h+++ b/fincept-qt/src/trading/brokers/groww/GrowwBroker.h@@ -9,6 +9,11 @@ class GrowwBroker : public IBroker {BrokerId id() const override { return BrokerId::Groww; }const char* name() const override { return "Groww"; }const char* base_url() const override { return "https://api.groww.in"; }+ // Streams route through the Python ws_bridge → openalgo groww_adapter.+ // Groww's native protocol is NATS.io over WSS with NKEY/Ed25519 auth ++ // protobuf payloads; a native Qt QWebSocket implementation is non-trivial+ // (would need NATS framing, libsodium, and 4 compiled .proto schemas).+ const char* ws_adapter_name() const override { return "groww"; }BrokerProfile profile() const override {return BrokerProfile{@@ -58,8 +63,30 @@ class GrowwBroker : public IBroker {const QString& resolution, const QString& from_date,const QString& to_date) override;+ // Pre-trade margin calculator — POST /v1/margins/detail/orders?segment=...+ ApiResponse<OrderMargin> get_order_margins(const BrokerCredentials& creds, const UnifiedOrder& order) override;+ ApiResponse<BasketMargin> get_basket_margins(const BrokerCredentials& creds,+ const QVector<UnifiedOrder>& orders) override;++ // User profile — GET /v1/user/detail. Groww exposes ucc + segments only.+ ApiResponse<QJsonObject> get_profile(const BrokerCredentials& creds);++ // Smart Orders (GTT / OCO) — /v1/order-advance/*. Groww has no iceberg/slice; exposed+ // via the GTT hooks so callers have a unified surface.+ GttPlaceResponse gtt_place(const BrokerCredentials& creds, const GttOrder& order) override;+ ApiResponse<GttOrder> gtt_get(const BrokerCredentials& creds, const QString& gtt_id) override;+ ApiResponse<QVector<GttOrder>> gtt_list(const BrokerCredentials& creds) override;+ ApiResponse<GttOrder> gtt_modify(const BrokerCredentials& creds, const QString& gtt_id,+ const GttOrder& updated) override;+ ApiResponse<QJsonObject> gtt_cancel(const BrokerCredentials& creds, const QString& gtt_id) override;+static bool is_token_expired(const BrokerHttpResponse& resp);static QString checked_error(const BrokerHttpResponse& resp, const QString& fallback);+ // Classify a Groww response by its error.code field (GA000..GA007 + HTTP 429).+ // Returns an empty string when the response is successful or carries no GA code.+ // Callers can branch on the code (e.g. "GA005" → token expiry) for retry logic.+ static QString error_code(const BrokerHttpResponse& resp);+ static bool is_rate_limited(const BrokerHttpResponse& resp);protected:QMap<QString, QString> auth_headers(const BrokerCredentials& creds) const override;@@ -70,6 +97,33 @@ class GrowwBroker : public IBroker {static QString groww_product(ProductType p);static QString groww_order_type(OrderType t);static int resolution_to_minutes(const QString& resolution);++ // Batch helpers for /v1/live-data/ltp and /v1/live-data/ohlc.+ // Groww accepts up to 50 exchange_symbols per call (format: "NSE_RELIANCE").+ // Both endpoints share a 10 req/sec, 300/min, 5000/day bucket with /quote.+ struct SymbolRef {+ QString orig; // caller-supplied, e.g. "NSE:RELIANCE" or "RELIANCE"+ QString exchange; // NSE, BSE, NFO, BFO+ QString segment; // CASH, FNO+ QString trading_symbol;+ QString exchange_symbol; // groww_exchange + "_" + trading_symbol+ };+ static SymbolRef split_symbol(const QString& sym);+ // Fills ltp/open/high/low/close on the matching BrokerQuote entries.+ // Returns true on successful RPC (partial symbol matches still return true).+ bool fetch_ltp_batch(const BrokerCredentials& creds, const QString& segment,+ const QVector<SymbolRef>& refs, QVector<BrokerQuote>& out);+ bool fetch_ohlc_batch(const BrokerCredentials& creds, const QString& segment,+ const QVector<SymbolRef>& refs, QVector<BrokerQuote>& out);++ // /v1/historical/candles candle_interval mapping. Groww accepts integer minutes+ // for 1,5,10,15,30,60; "1D" and "1W" map to 1440 / 10080.+ static int history_interval_minutes(const QString& resolution);+ // Build the order JSON used by /v1/margins/detail/orders (per-order object inside the array).+ static QJsonObject order_to_margin_row(const UnifiedOrder& order);+ // Smart-order helpers+ static QJsonObject gtt_to_advance_body(const GttOrder& g, bool is_create);+ static GttOrder parse_advance_to_gtt(const QJsonObject& payload);};} // namespace fincept::tradingdiff --git a/fincept-qt/src/trading/brokers/zerodha/Totp.cpp b/fincept-qt/src/trading/brokers/zerodha/Totp.cppnew file mode 100644index 000000000..66d580f3f--- /dev/null+++ b/fincept-qt/src/trading/brokers/zerodha/Totp.cpp@@ -0,0 +1,69 @@+#include "trading/brokers/zerodha/Totp.h"++#include <QCryptographicHash>+#include <QMessageAuthenticationCode>++namespace fincept::trading::zerodha {++QByteArray base32_decode(const QString& input) {+ QByteArray result;+ int buffer = 0;+ int bits_left = 0;+ for (QChar c : input) {+ if (c.isSpace() || c == QLatin1Char('='))+ continue;+ int val = 0;+ const char ch = c.toUpper().toLatin1();+ if (ch >= 'A' && ch <= 'Z')+ val = ch - 'A';+ else if (ch >= '2' && ch <= '7')+ val = 26 + (ch - '2');+ else+ return {}; // invalid character+ buffer = (buffer << 5) | val;+ bits_left += 5;+ if (bits_left >= 8) {+ bits_left -= 8;+ result.append(static_cast<char>((buffer >> bits_left) & 0xFF));+ }+ }+ return result;+}++namespace {+quint64 int_pow10(int digits) {+ quint64 v = 1;+ for (int i = 0; i < digits; ++i) v *= 10ULL;+ return v;+}+} // namespace++QString generate_totp(const QString& base32_secret, qint64 unix_time_seconds,+ int digits, int step_seconds) {+ const QByteArray key = base32_decode(base32_secret);+ if (key.isEmpty())+ return {};++ const qint64 counter = unix_time_seconds / step_seconds;+ QByteArray counter_bytes;+ counter_bytes.resize(8);+ for (int i = 7; i >= 0; --i) {+ counter_bytes[i] = static_cast<char>((counter >> (8 * (7 - i))) & 0xFF);+ }++ QMessageAuthenticationCode mac(QCryptographicHash::Sha1, key);+ mac.addData(counter_bytes);+ const QByteArray hmac = mac.result();++ const int offset = hmac.at(hmac.size() - 1) & 0x0F;+ const quint32 bin_code = (static_cast<quint32>(hmac.at(offset) & 0x7F) << 24)+ | (static_cast<quint32>(hmac.at(offset + 1) & 0xFF) << 16)+ | (static_cast<quint32>(hmac.at(offset + 2) & 0xFF) << 8)+ | (static_cast<quint32>(hmac.at(offset + 3) & 0xFF));++ const quint32 modulus = static_cast<quint32>(int_pow10(digits));+ const QString code = QString::number(bin_code % modulus);+ return code.rightJustified(digits, QLatin1Char('0'));+}++} // namespace fincept::trading::zerodhadiff --git a/fincept-qt/src/trading/brokers/zerodha/Totp.h b/fincept-qt/src/trading/brokers/zerodha/Totp.hnew file mode 100644index 000000000..52027c2fa--- /dev/null+++ b/fincept-qt/src/trading/brokers/zerodha/Totp.h@@ -0,0 +1,20 @@+#pragma once+// RFC-6238 TOTP generator (HMAC-SHA1, 30s step, 6 digits by default).+// Pure function — no Qt event loop, safe to call from worker threads.++#include <QString>+#include <QByteArray>++namespace fincept::trading::zerodha {++// Returns an empty QString on invalid Base32 input.+QString generate_totp(const QString& base32_secret,+ qint64 unix_time_seconds,+ int digits = 6,+ int step_seconds = 30);++// Exposed for testing — decodes an RFC-4648 Base32 string (A-Z, 2-7, ignores+// whitespace and '=' padding). Returns empty QByteArray on invalid input.+QByteArray base32_decode(const QString& input);++} // namespace fincept::trading::zerodhadiff --git a/fincept-qt/src/trading/brokers/zerodha/ZerodhaAutoLogin.cpp b/fincept-qt/src/trading/brokers/zerodha/ZerodhaAutoLogin.cppnew file mode 100644index 000000000..487d9b6ee--- /dev/null+++ b/fincept-qt/src/trading/brokers/zerodha/ZerodhaAutoLogin.cpp@@ -0,0 +1,222 @@+#include "trading/brokers/zerodha/ZerodhaAutoLogin.h"++#include "core/logging/Logger.h"+#include "trading/brokers/zerodha/Totp.h"++#include <QCryptographicHash>+#include <QDateTime>+#include <QEventLoop>+#include <QJsonDocument>+#include <QJsonObject>+#include <QNetworkAccessManager>+#include <QNetworkCookieJar>+#include <QNetworkReply>+#include <QNetworkRequest>+#include <QUrl>+#include <QUrlQuery>++namespace fincept::trading::zerodha {++namespace {++struct HttpResult {+ int status = 0;+ QByteArray body;+ QUrl final_url;+ QString network_error;+};++HttpResult do_request(QNetworkAccessManager& nam, QNetworkRequest req, const QByteArray& body,+ bool is_post, bool follow_redirects) {+ req.setAttribute(QNetworkRequest::RedirectPolicyAttribute,+ follow_redirects ? QNetworkRequest::NoLessSafeRedirectPolicy+ : QNetworkRequest::ManualRedirectPolicy);+ QNetworkReply* reply = is_post ? nam.post(req, body) : nam.get(req);++ QEventLoop loop;+ QObject::connect(reply, &QNetworkReply::finished, &loop, &QEventLoop::quit);+ loop.exec();++ HttpResult r;+ r.status = reply->attribute(QNetworkRequest::HttpStatusCodeAttribute).toInt();+ r.body = reply->readAll();+ r.final_url = reply->url();+ if (reply->error() != QNetworkReply::NoError && r.status == 0)+ r.network_error = reply->errorString();+ reply->deleteLater();+ return r;+}++QString extract_error(const QByteArray& body, const QString& fallback) {+ const auto doc = QJsonDocument::fromJson(body);+ if (!doc.isObject())+ return fallback;+ const QString message = doc.object().value("message").toString();+ return message.isEmpty() ? fallback : message;+}++} // namespace++AutoLoginResult run_auto_login(const QString& user_id, const QString& password,+ const QString& api_key, const QString& api_secret,+ const QString& totp_secret,+ const ProgressCallback& progress) {+ AutoLoginResult out;+ out.token.success = false;++ const auto report = [&](const QString& stage) {+ if (progress) progress(stage);+ LOG_INFO("ZerodhaAutoLogin", stage);+ };++ if (user_id.isEmpty() || password.isEmpty() || api_key.isEmpty() ||+ api_secret.isEmpty() || totp_secret.isEmpty()) {+ out.token.error = "Missing one or more required fields";+ return out;+ }++ QNetworkAccessManager nam;+ nam.setCookieJar(new QNetworkCookieJar(&nam));++ QString request_id;++ // Step 1: /api/login+ report("Logging in...");+ {+ QNetworkRequest req(QUrl("https://kite.zerodha.com/api/login"));+ req.setHeader(QNetworkRequest::ContentTypeHeader, "application/x-www-form-urlencoded");++ QUrlQuery form;+ form.addQueryItem("user_id", user_id);+ form.addQueryItem("password", password);+ const auto body = form.toString(QUrl::FullyEncoded).toUtf8();++ HttpResult r = do_request(nam, req, body, /*is_post=*/true, /*follow=*/false);+ if (r.status != 200) {+ out.token.error = extract_error(r.body, r.network_error.isEmpty()+ ? QStringLiteral("Invalid Kite user ID or password")+ : r.network_error);+ return out;+ }+ const auto doc = QJsonDocument::fromJson(r.body);+ request_id = doc.object().value("data").toObject().value("request_id").toString();+ if (request_id.isEmpty()) {+ out.token.error = "Login response missing request_id";+ return out;+ }+ }++ // Step 2: /api/twofa+ report("Submitting 2FA...");+ {+ const QString totp = generate_totp(totp_secret, QDateTime::currentSecsSinceEpoch());+ if (totp.isEmpty()) {+ out.token.error = "TOTP secret is not valid Base32";+ return out;+ }++ QNetworkRequest req(QUrl("https://kite.zerodha.com/api/twofa"));+ req.setHeader(QNetworkRequest::ContentTypeHeader, "application/x-www-form-urlencoded");+ QUrlQuery form;+ form.addQueryItem("user_id", user_id);+ form.addQueryItem("request_id", request_id);+ form.addQueryItem("twofa_value", totp);+ form.addQueryItem("twofa_type", "totp");+ form.addQueryItem("skip_session", "");+ const auto body = form.toString(QUrl::FullyEncoded).toUtf8();++ HttpResult r = do_request(nam, req, body, /*is_post=*/true, /*follow=*/false);+ if (r.status != 200) {+ QString msg = extract_error(r.body, "Invalid TOTP");+ if (msg.contains("TwoFAException", Qt::CaseInsensitive) ||+ msg.contains("TOTP", Qt::CaseInsensitive))+ msg = "Invalid TOTP - check your device clock";+ out.token.error = msg;+ LOG_WARN("ZerodhaAutoLogin",+ QString("2FA failed (system_time=%1, generated_code_len=%2)")+ .arg(QDateTime::currentSecsSinceEpoch())+ .arg(totp.size()));+ return out;+ }+ }++ // Step 3: /connect/finish (capture redirect)+ report("Capturing request_token...");+ QString request_token;+ {+ QUrl url("https://kite.zerodha.com/connect/finish");+ QUrlQuery q;+ q.addQueryItem("api_key", api_key);+ q.addQueryItem("v", "3");+ url.setQuery(q);+ QNetworkRequest req(url);++ HttpResult r = do_request(nam, req, {}, /*is_post=*/false, /*follow=*/true);++ // Parse request_token from final URL query (set during redirect).+ const QUrlQuery final_q(r.final_url);+ request_token = final_q.queryItemValue("request_token");+ if (request_token.isEmpty()) {+ // Fallback: scan response body text.+ const QString body_str = QString::fromUtf8(r.body);+ const int idx = body_str.indexOf("request_token=");+ if (idx >= 0) {+ const int end = body_str.indexOf('&', idx);+ const int start = idx + static_cast<int>(qstrlen("request_token="));+ request_token = body_str.mid(start, (end >= 0 ? end : body_str.size()) - start);+ }+ }+ if (request_token.isEmpty()) {+ out.token.error = "Could not capture request_token from redirect chain";+ return out;+ }+ }++ // Step 4: Exchange for access_token+ report("Exchanging token...");+ {+ const QByteArray checksum =+ QCryptographicHash::hash((api_key + request_token + api_secret).toUtf8(),+ QCryptographicHash::Sha256)+ .toHex();++ QNetworkRequest req(QUrl("https://api.kite.trade/session/token"));+ req.setHeader(QNetworkRequest::ContentTypeHeader, "application/x-www-form-urlencoded");+ req.setRawHeader("X-Kite-Version", "3");++ QUrlQuery form;+ form.addQueryItem("api_key", api_key);+ form.addQueryItem("request_token", request_token);+ form.addQueryItem("checksum", QString::fromLatin1(checksum));+ const auto body = form.toString(QUrl::FullyEncoded).toUtf8();++ HttpResult r = do_request(nam, req, body, /*is_post=*/true, /*follow=*/false);+ if (r.status != 200) {+ QString msg = extract_error(r.body, "Token exchange failed");+ if (msg.contains("TokenException", Qt::CaseInsensitive))+ msg = "Invalid api_secret for this api_key";+ out.token.error = msg;+ return out;+ }++ const auto doc = QJsonDocument::fromJson(r.body);+ const auto data = doc.object().value("data").toObject();+ out.token.success = true;+ out.token.access_token = data.value("access_token").toString();+ out.token.user_id = data.value("user_id").toString();+ QJsonObject extra;+ for (auto it = data.begin(); it != data.end(); ++it) {+ const QString k = it.key();+ if (k == "access_token" || k == "user_id")+ continue;+ extra.insert(k, it.value());+ }+ out.token.additional_data =+ QString::fromUtf8(QJsonDocument(extra).toJson(QJsonDocument::Compact));+ }++ report(QString("Connected as %1").arg(out.token.user_id));+ return out;+}++} // namespace fincept::trading::zerodhadiff --git a/fincept-qt/src/trading/brokers/zerodha/ZerodhaAutoLogin.h b/fincept-qt/src/trading/brokers/zerodha/ZerodhaAutoLogin.hnew file mode 100644index 000000000..d025bc037--- /dev/null+++ b/fincept-qt/src/trading/brokers/zerodha/ZerodhaAutoLogin.h@@ -0,0 +1,32 @@+#pragma once+// 5-step Zerodha TOTP auto-login chain:+// 1. POST /api/login (user_id, password) -> request_id+// 2. POST /api/twofa (user_id, request_id, twofa_value) -> enctoken cookie+// 3. GET /connect/finish?api_key=... -> redirect URL carrying request_token+// 4. Exchange request_token via SHA-256 checksum -> access_token+//+// Owns its own QNetworkAccessManager + QNetworkCookieJar so the enctoken+// cookie persists between steps. Uses QEventLoop internally - MUST be called+// from a worker thread, never the UI thread.++#include "trading/TradingTypes.h"+#include <QString>+#include <functional>++namespace fincept::trading::zerodha {++struct AutoLoginResult {+ TokenExchangeResponse token; // success + access_token + user_id, or error+ QString detailed_error; // e.g., "TwoFAException: Invalid TOTP"+};++using ProgressCallback = std::function<void(const QString& stage)>;++AutoLoginResult run_auto_login(const QString& user_id,+ const QString& password,+ const QString& api_key,+ const QString& api_secret,+ const QString& totp_secret,+ const ProgressCallback& progress = {});++} // namespace fincept::trading::zerodhadiff --git a/fincept-qt/src/trading/brokers/zerodha/ZerodhaBroker.cpp b/fincept-qt/src/trading/brokers/zerodha/ZerodhaBroker.cppindex 2c2d4ee91..b2c1ec1d3 100644--- a/fincept-qt/src/trading/brokers/zerodha/ZerodhaBroker.cpp+++ b/fincept-qt/src/trading/brokers/zerodha/ZerodhaBroker.cpp@@ -2,6 +2,7 @@#include "core/logging/Logger.h"#include "trading/brokers/BrokerHttp.h"+#include "trading/brokers/zerodha/ZerodhaAutoLogin.h"#include "trading/instruments/InstrumentService.h"#include <QCryptographicHash>@@ -11,6 +12,19 @@namespace fincept::trading {+QString ZerodhaBroker::kite_login_url(const QString& api_key) {+ return QStringLiteral("https://kite.zerodha.com/connect/login?v=3&api_key=%1").arg(api_key);+}++TokenExchangeResponse ZerodhaBroker::login_with_totp(const QString& user_id, const QString& password,+ const QString& api_key, const QString& api_secret,+ const QString& totp_secret,+ std::function<void(const QString&)> progress) {+ auto result = zerodha::run_auto_login(user_id, password, api_key, api_secret, totp_secret,+ std::move(progress));+ return result.token;+}+static int64_t now_ts() {return QDateTime::currentSecsSinceEpoch();}@@ -94,13 +108,26 @@ TokenExchangeResponse ZerodhaBroker::exchange_token(const QString& api_key, consQByteArray input = (api_key + request_token + api_secret).toUtf8();QString checksum = QCryptographicHash::hash(input, QCryptographicHash::Sha256).toHex();+ LOG_INFO("Zerodha", QString("exchange_token: api_key=%1 req_token_len=%2 secret_len=%3")+ .arg(api_key).arg(request_token.length()).arg(api_secret.length()));+QMap<QString, QString> params = {{"api_key", api_key}, {"request_token", request_token}, {"checksum", checksum}};QMap<QString, QString> headers = {{"X-Kite-Version", kite_api_version}};auto resp = BrokerHttp::instance().post_form(QString(base_url()) + "/session/token", params, headers);+ LOG_INFO("Zerodha", QString("exchange_token HTTP %1 success=%2 body=%3")+ .arg(resp.status_code).arg(resp.success).arg(resp.raw_body.left(500)));+TokenExchangeResponse result;if (!resp.success) {- result.error = resp.error;+ // Surface Kite's error_type + message when available.+ const QString kite_msg = resp.json.value("message").toString();+ const QString kite_type = resp.json.value("error_type").toString();+ if (!kite_msg.isEmpty())+ result.error = kite_type.isEmpty() ? kite_msg : QString("%1: %2").arg(kite_type, kite_msg);+ else+ result.error = resp.error.isEmpty() ? QString("HTTP %1").arg(resp.status_code) : resp.error;+ LOG_ERROR("Zerodha", QString("exchange_token failed: %1").arg(result.error));return result;}if (resp.json.value("status").toString() == "success") {@@ -109,8 +136,10 @@ TokenExchangeResponse ZerodhaBroker::exchange_token(const QString& api_key, consresult.access_token = data.value("access_token").toString();result.refresh_token = data.value("refresh_token").toString();result.user_id = data.value("user_id").toString();+ LOG_INFO("Zerodha", QString("exchange_token ok: user_id=%1").arg(result.user_id));} else {result.error = resp.json.value("message").toString("Token exchange failed");+ LOG_ERROR("Zerodha", QString("exchange_token status!=success: %1").arg(result.error));}return result;}diff --git a/fincept-qt/src/trading/brokers/zerodha/ZerodhaBroker.h b/fincept-qt/src/trading/brokers/zerodha/ZerodhaBroker.hindex 44c929bbc..1f0293a98 100644--- a/fincept-qt/src/trading/brokers/zerodha/ZerodhaBroker.h+++ b/fincept-qt/src/trading/brokers/zerodha/ZerodhaBroker.h@@ -2,6 +2,8 @@#include "trading/BrokerInterface.h"#include "trading/brokers/BrokerHttp.h"+#include <functional>+namespace fincept::trading {class ZerodhaBroker : public IBroker {@@ -47,6 +49,17 @@ class ZerodhaBroker : public IBroker {TokenExchangeResponse exchange_token(const QString& api_key, const QString& api_secret,const QString& auth_code) override;++ /// Returns the URL users visit to authenticate via Zerodha's web UI.+ /// Pure string - safe from any thread.+ static QString kite_login_url(const QString& api_key);++ /// Runs the full headless TOTP auto-login chain. MUST be called from a+ /// worker thread. Internally uses QEventLoop across 4 HTTP round-trips.+ TokenExchangeResponse login_with_totp(const QString& user_id, const QString& password,+ const QString& api_key, const QString& api_secret,+ const QString& totp_secret,+ std::function<void(const QString&)> progress = {});OrderPlaceResponse place_order(const BrokerCredentials& creds, const UnifiedOrder& order) override;ApiResponse<QJsonObject> modify_order(const BrokerCredentials& creds, const QString& order_id,const QJsonObject& mods) override;diff --git a/fincept-qt/src/trading/instruments/GrowwInstrumentParser.cpp b/fincept-qt/src/trading/instruments/GrowwInstrumentParser.cppnew file mode 100644index 000000000..e14b41384--- /dev/null+++ b/fincept-qt/src/trading/instruments/GrowwInstrumentParser.cpp@@ -0,0 +1,231 @@+#include "trading/instruments/GrowwInstrumentParser.h"++#include "core/logging/Logger.h"++#include <QDate>+#include <QHash>+#include <QMap>+#include <QStringList>+#include <QTextStream>++namespace fincept::trading {+namespace {++// Groww uses short trading_symbols for indices (NIFTY, BANKNIFTY, INDIAVIX, MIDCAP50 …).+// Most already match the fincept normalised form — map the handful that differ.+// Anonymous namespace isolates this from ZerodhaInstrumentParser's index_map()+// under Ninja's unity-build (same symbol name otherwise collides).+const QMap<QString, QString>& groww_index_map() {+ static const QMap<QString, QString> m = {+ // Groww short form → fincept normalised+ {"NIFTY", "NIFTY"},+ {"BANKNIFTY", "BANKNIFTY"},+ {"NIFTYJR", "NIFTYNXT50"},+ {"MIDCAP50", "NIFTYMIDCAP50"},+ {"NIFTYMIDCAP", "NIFTYMIDCAP100"},+ {"NIFTYMIDCAP150", "NIFTYMIDCAP150"},+ {"NIFTYSMALLCAP250", "NIFTYSMALLCAP250"},+ {"NIFTYMIDSELECT", "MIDCPNIFTY"},+ {"NIFTYPVTBANK", "NIFTYPVTBANK"},+ {"NIFTYPHARMA", "NIFTYPHARMA"},+ {"NIFTYIT", "NIFTYIT"},+ {"NIFTYMETAL", "NIFTYMETAL"},+ {"NIFTYMEDIA", "NIFTYMEDIA"},+ {"NIFTYAUTO", "NIFTYAUTO"},+ {"NIFTYENERGY", "NIFTYENERGY"},+ {"NIFTYFMCG", "NIFTYFMCG"},+ {"NIFTYREALTY", "NIFTYREALTY"},+ {"NIFTYPSUBANK", "NIFTYPSUBANK"},+ {"NIFTYINFRA", "NIFTYINFRA"},+ {"NIFTY100", "NIFTY100"},+ {"NIFTY200", "NIFTY200"},+ {"NIFTY500", "NIFTY500"},+ {"NIFTYTOTALMCAP", "NIFTYTOTALMCAP"},+ {"INDIAVIX", "INDIAVIX"},+ // BSE+ {"SENSEX", "SENSEX"},+ {"BANKEX", "BANKEX"},+ {"SENSEX50", "SENSEX50"},+ };+ return m;+}++} // namespace++// "2026-04-28" → "28APR26"+QString GrowwInstrumentParser::expiry_nodashes(const QString& expiry_iso) {+ if (expiry_iso.isEmpty())+ return {};+ QDate d = QDate::fromString(expiry_iso, "yyyy-MM-dd");+ if (!d.isValid())+ return {};+ return d.toString("ddMMMyy").toUpper();+}++QString GrowwInstrumentParser::map_index_name(const QString& trading_symbol) {+ return groww_index_map().value(trading_symbol.toUpper(), trading_symbol.toUpper());+}++// Groww exchange column is NSE/BSE/MCX even for derivatives; segment distinguishes+// CASH vs FNO vs COMMODITY. Fincept uses NFO/BFO for Indian derivatives.+QString GrowwInstrumentParser::normalise_exchange(const QString& raw_exchange, const QString& segment,+ const QString& itype) {+ QString ex = raw_exchange.toUpper();+ QString seg = segment.toUpper();++ if (itype == "IDX") {+ // Index: append _INDEX suffix+ return ex + "_INDEX";+ }+ if (seg == "FNO") {+ if (ex == "NSE")+ return QStringLiteral("NFO");+ if (ex == "BSE")+ return QStringLiteral("BFO");+ return ex; // unexpected, leave as-is+ }+ if (seg == "COMMODITY") {+ return QStringLiteral("MCX");+ }+ // CASH → NSE/BSE unchanged+ return ex;+}++QString GrowwInstrumentParser::normalise_symbol(const QString& trading_symbol, const QString& underlying,+ const QString& itype, const QString& expiry_nd, double strike) {+ if (itype == "FUT") {+ // underlying + DDMMMYY + FUT, e.g. "NIFTY28APR26FUT"+ if (!underlying.isEmpty() && !expiry_nd.isEmpty())+ return underlying.toUpper() + expiry_nd + "FUT";+ return trading_symbol; // fallback+ }+ if (itype == "CE" || itype == "PE") {+ if (!underlying.isEmpty() && !expiry_nd.isEmpty()) {+ // Drop decimals for whole-number strikes; keep decimals otherwise (e.g. silver)+ QString strike_str;+ if (strike == static_cast<qint64>(strike))+ strike_str = QString::number(static_cast<qint64>(strike));+ else+ strike_str = QString::number(strike, 'f', 2);+ return underlying.toUpper() + expiry_nd + strike_str + itype;+ }+ return trading_symbol;+ }+ if (itype == "IDX") {+ return map_index_name(trading_symbol);+ }+ // EQ and everything else: use trading_symbol as-is (already exchange-canonical).+ return trading_symbol;+}++static InstrumentType map_groww_type(const QString& itype) {+ if (itype == "EQ")+ return InstrumentType::EQ;+ if (itype == "FUT")+ return InstrumentType::FUT;+ if (itype == "CE")+ return InstrumentType::CE;+ if (itype == "PE")+ return InstrumentType::PE;+ if (itype == "IDX")+ return InstrumentType::INDEX;+ return InstrumentType::UNKNOWN;+}++Instrument GrowwInstrumentParser::parse_row(const QStringList& cols) {+ if (cols.size() < 21)+ return {};++ Instrument inst;+ inst.broker_id = QStringLiteral("groww");++ QString raw_exchange = cols[0].trimmed();+ QString exchange_token_raw = cols[1].trimmed();+ QString trading_symbol = cols[2].trimmed();+ // cols[3] groww_symbol (human-readable, unused)+ QString name_field = cols[4].trimmed();+ QString itype = cols[5].trimmed().toUpper();+ QString segment = cols[6].trimmed().toUpper();+ // cols[7] series (unused)+ // cols[8] isin (unused)+ QString underlying = cols[9].trimmed().toUpper();+ // cols[10] underlying_exchange_token (unused for now)+ QString expiry_iso = cols[11].trimmed();+ double strike = cols[12].toDouble();+ int lot_size = cols[13].toInt();+ double tick_size = cols[14].toDouble();++ // Groww indices carry a string exchange_token (e.g. "NIFTY"); other types are numeric.+ // Parse as long; non-numeric tokens get 0 and we fall back to symbol lookup.+ bool token_ok = false;+ qint64 etoken = exchange_token_raw.toLongLong(&token_ok);+ inst.exchange_token = token_ok ? etoken : 0;+ inst.instrument_token = inst.exchange_token; // Groww has only one token per row++ inst.brsymbol = trading_symbol;+ // For F&O the "name" column is empty, so prefer underlying_symbol; for EQ use the+ // descriptive security name when present.+ inst.name = underlying.isEmpty() ? name_field.toUpper() : underlying;+ inst.brexchange = raw_exchange.toUpper();+ inst.tick_size = tick_size > 0 ? tick_size : 0.05;+ inst.lot_size = lot_size > 0 ? lot_size : 1;++ // Strike of -0.01 is a sentinel Groww uses for FUT rows (no strike).+ inst.strike = (itype == "CE" || itype == "PE") ? strike : 0.0;++ if (!expiry_iso.isEmpty()) {+ QString nd = expiry_nodashes(expiry_iso);+ if (!nd.isEmpty())+ inst.expiry = nd.left(2) + "-" + nd.mid(2, 3) + "-" + nd.right(2); // "28-APR-26"+ }++ inst.exchange = normalise_exchange(raw_exchange, segment, itype);+ inst.instrument_type = map_groww_type(itype);+ inst.symbol = normalise_symbol(trading_symbol, underlying, itype, expiry_nodashes(expiry_iso), strike);++ return inst;+}++QVector<Instrument> GrowwInstrumentParser::parse(const QByteArray& csv_data) {+ QVector<Instrument> results;+ if (csv_data.isEmpty()) {+ LOG_WARN("GrowwParser", "Empty CSV data received");+ return results;+ }++ QTextStream stream(csv_data);+ QString header = stream.readLine();+ Q_UNUSED(header)++ int row = 1;+ int skipped = 0;+ results.reserve(250000); // Groww has ~200k rows (equity + full F&O chain)+ while (!stream.atEnd()) {+ QString line = stream.readLine();+ if (line.isEmpty())+ continue;+ ++row;++ // Groww CSV has no quoted fields with commas — simple split is safe.+ QStringList cols = line.split(',');+ if (cols.size() < 21) {+ ++skipped;+ continue;+ }++ Instrument inst = parse_row(cols);+ // Require at least trading_symbol + brexchange.+ if (inst.brsymbol.isEmpty() || inst.brexchange.isEmpty()) {+ ++skipped;+ continue;+ }++ results.append(inst);+ }++ LOG_INFO("GrowwParser",+ QString("Parsed %1 instruments (skipped %2 malformed rows)").arg(results.size()).arg(skipped));+ return results;+}++} // namespace fincept::tradingdiff --git a/fincept-qt/src/trading/instruments/GrowwInstrumentParser.h b/fincept-qt/src/trading/instruments/GrowwInstrumentParser.hnew file mode 100644index 000000000..8c6ea1179--- /dev/null+++ b/fincept-qt/src/trading/instruments/GrowwInstrumentParser.h@@ -0,0 +1,47 @@+#pragma once+#include "trading/instruments/InstrumentTypes.h"++#include <QByteArray>+#include <QVector>++namespace fincept::trading {++/// Parses Groww's instruments CSV (from+/// https://growwapi-assets.groww.in/instruments/instrument.csv) and normalises+/// each row into an Instrument struct.+///+/// Groww CSV columns (21 fields, in order):+/// 0: exchange 1: exchange_token 2: trading_symbol+/// 3: groww_symbol 4: name 5: instrument_type+/// 6: segment 7: series 8: isin+/// 9: underlying_symbol 10: underlying_exchange_token+/// 11: expiry_date 12: strike_price 13: lot_size+/// 14: tick_size 15: freeze_quantity 16: is_reserved+/// 17: buy_allowed 18: sell_allowed 19: internal_trading_symbol+/// 20: is_intraday+///+/// Normalisation rules (mirrored from ZerodhaInstrumentParser so that cross-broker+/// symbol lookups behave identically):+/// EQ : symbol = trading_symbol+/// FUT : symbol = underlying_symbol + expiry_nodashes + "FUT"+/// CE/PE : symbol = underlying_symbol + expiry_nodashes + strike_int + type+/// IDX : symbol = map_index_name(trading_symbol); exchange = "NSE_INDEX" / "BSE_INDEX"+/// exchange normalisation (fincept convention):+/// CASH + NSE → NSE FNO + NSE → NFO COMMODITY + MCX → MCX+/// CASH + BSE → BSE FNO + BSE → BFO (IDX → <exchange>_INDEX)+class GrowwInstrumentParser {+ public:+ /// Parse raw CSV bytes downloaded from the Groww instruments URL.+ /// Returns empty vector on parse failure (logged internally).+ static QVector<Instrument> parse(const QByteArray& csv_data);++ private:+ static Instrument parse_row(const QStringList& cols);+ static QString normalise_symbol(const QString& trading_symbol, const QString& underlying, const QString& itype,+ const QString& expiry_nd, double strike);+ static QString normalise_exchange(const QString& raw_exchange, const QString& segment, const QString& itype);+ static QString expiry_nodashes(const QString& expiry_iso); // "2026-04-28" → "28APR26"+ static QString map_index_name(const QString& trading_symbol);+};++} // namespace fincept::tradingdiff --git a/fincept-qt/src/trading/instruments/InstrumentService.cpp b/fincept-qt/src/trading/instruments/InstrumentService.cppindex 79e0a997e..3b01dff47 100644--- a/fincept-qt/src/trading/instruments/InstrumentService.cpp+++ b/fincept-qt/src/trading/instruments/InstrumentService.cpp@@ -3,6 +3,7 @@#include "core/logging/Logger.h"#include "storage/sqlite/Database.h"#include "trading/brokers/BrokerHttp.h"+#include "trading/instruments/GrowwInstrumentParser.h"#include "trading/instruments/InstrumentRepository.h"#include "trading/instruments/ZerodhaInstrumentParser.h"@@ -439,6 +440,8 @@ void InstrumentService::do_refresh(const QString& broker_id, const BrokerCredentpayload = download_zerodha_csv(creds);} else if (broker_id == "angelone") {payload = download_angel_master_json();+ } else if (broker_id == "groww") {+ payload = download_groww_csv();} else {QMetaObject::invokeMethod(this,@@ -472,6 +475,8 @@ void InstrumentService::do_refresh(const QString& broker_id, const BrokerCredentinstruments = ZerodhaInstrumentParser::parse(payload);} else if (broker_id == "angelone") {instruments = parse_angel_master_json(payload);+ } else if (broker_id == "groww") {+ instruments = GrowwInstrumentParser::parse(payload);}if (instruments.isEmpty()) {@@ -573,4 +578,45 @@ QByteArray InstrumentService::download_angel_master_json() {return data;}+QByteArray InstrumentService::download_groww_csv() {+ // Public, unauthenticated CSV (~27MB) with the full equity + F&O + commodity master.+ // Own QNAM (not BrokerHttp) because the download dominates the shared client's+ // mutex for 10-30s on slow links and would starve concurrent quote/order calls.+ static const QString kUrl = "https://growwapi-assets.groww.in/instruments/instrument.csv";++ QNetworkAccessManager nam;+ QNetworkRequest req{QUrl(kUrl)};+ req.setRawHeader("Accept", "text/csv");+ req.setAttribute(QNetworkRequest::RedirectPolicyAttribute, QNetworkRequest::NoLessSafeRedirectPolicy);++ QNetworkReply* reply = nam.get(req);++ QEventLoop loop;+ QTimer timer;+ timer.setSingleShot(true);+ QObject::connect(reply, &QNetworkReply::finished, &loop, &QEventLoop::quit);+ QObject::connect(&timer, &QTimer::timeout, &loop, &QEventLoop::quit);+ timer.start(60000); // 60s — ~27MB file on slow connection+ loop.exec();++ if (!timer.isActive()) {+ reply->abort();+ reply->deleteLater();+ LOG_ERROR("InstrumentService", "Groww instrument CSV download timed out");+ return {};+ }+ timer.stop();++ if (reply->error() != QNetworkReply::NoError) {+ LOG_ERROR("InstrumentService", "Failed to download Groww instrument CSV: " + reply->errorString());+ reply->deleteLater();+ return {};+ }++ QByteArray data = reply->readAll();+ reply->deleteLater();+ LOG_INFO("InstrumentService", QString("Downloaded Groww instrument CSV: %1 bytes").arg(data.size()));+ return data;+}+} // namespace fincept::tradingdiff --git a/fincept-qt/src/trading/instruments/InstrumentService.h b/fincept-qt/src/trading/instruments/InstrumentService.hindex 18eb24d09..71a2d38be 100644--- a/fincept-qt/src/trading/instruments/InstrumentService.h+++ b/fincept-qt/src/trading/instruments/InstrumentService.h@@ -110,6 +110,7 @@ class InstrumentService : public QObject {void do_refresh(const QString& broker_id, const BrokerCredentials& creds);static QByteArray download_zerodha_csv(const BrokerCredentials& creds);static QByteArray download_angel_master_json();+ static QByteArray download_groww_csv();};} // namespace fincept::tradingdiff --git a/fincept-qt/src/ui/navigation/CommandBar.h b/fincept-qt/src/ui/navigation/CommandBar.hindex f4d29d90e..1066354ff 100644--- a/fincept-qt/src/ui/navigation/CommandBar.h+++ b/fincept-qt/src/ui/navigation/CommandBar.h@@ -25,7 +25,7 @@ struct AssetType {QString description; // e.g. "Search stocks by symbol or name"};-/// Bloomberg-style command bar with live search and dropdown navigation.+/// Command bar with live search and dropdown navigation./// Type a command alias, screen name, or keyword — press Enter or click to navigate./// Supports /type queries (e.g. "/stock AAPL") to search assets via API.class CommandBar : public QWidget {diff --git a/fincept-qt/src/ui/tables/DataTable.h b/fincept-qt/src/ui/tables/DataTable.hindex 8f08368c8..dc5fcd218 100644--- a/fincept-qt/src/ui/tables/DataTable.h+++ b/fincept-qt/src/ui/tables/DataTable.h@@ -5,7 +5,7 @@namespace fincept::ui {-/// Reusable Bloomberg-style data table with alternating rows.+/// Reusable data table with alternating rows.class DataTable : public QTableWidget {Q_OBJECTpublic:diff --git a/fincept-qt/src/ui/widgets/LoadingOverlay.h b/fincept-qt/src/ui/widgets/LoadingOverlay.hindex 9f7ef22a5..41b5cfe88 100644--- a/fincept-qt/src/ui/widgets/LoadingOverlay.h+++ b/fincept-qt/src/ui/widgets/LoadingOverlay.h@@ -8,7 +8,7 @@namespace fincept::ui {-/// Bloomberg-style loading overlay with pulsing bar animation.+/// Loading overlay with pulsing bar animation./// Colors update automatically when the theme changes./// Usage:/// 1. Create as child of the content widget: new LoadingOverlay(content_widget)diff --git a/fincept-qt/src/ui/widgets/SearchBar.h b/fincept-qt/src/ui/widgets/SearchBar.hindex 70188a9a9..0a4a179f3 100644--- a/fincept-qt/src/ui/widgets/SearchBar.h+++ b/fincept-qt/src/ui/widgets/SearchBar.h@@ -5,7 +5,7 @@namespace fincept::ui {-/// Bloomberg-style search/command input bar.+/// Search/command input bar.class SearchBar : public QWidget {Q_OBJECTpublic:diff --git a/images/AIQuantLab.png b/images/AIQuantLab.pngdeleted file mode 100644index 3fa1b567c..000000000Binary files a/images/AIQuantLab.png and /dev/null differdiff --git a/images/Backtesting.png b/images/Backtesting.pngdeleted file mode 100644index c1b3318a6..000000000Binary files a/images/Backtesting.png and /dev/null differdiff --git a/images/Chat.png b/images/Chat.pngdeleted file mode 100644index 26c59e806..000000000Binary files a/images/Chat.png and /dev/null differdiff --git a/images/Dashboard.png b/images/Dashboard.pngindex 511ffda73..b9937fbce 100644Binary files a/images/Dashboard.png and b/images/Dashboard.png differdiff --git a/images/Economy.png b/images/Economy.pngdeleted file mode 100644index b7efba411..000000000Binary files a/images/Economy.png and /dev/null differdiff --git a/images/Equity.png b/images/Equity.pngdeleted file mode 100644index 93e6f99ac..000000000Binary files a/images/Equity.png and /dev/null differdiff --git a/images/EquityResearch.png b/images/EquityResearch.pngnew file mode 100644index 000000000..b57550757Binary files /dev/null and b/images/EquityResearch.png differdiff --git a/images/Forum.png b/images/Forum.pngdeleted file mode 100644index 66ef83eda..000000000Binary files a/images/Forum.png and /dev/null differdiff --git a/images/Geopolitics.png b/images/Geopolitics.pngdeleted file mode 100644index 42b695084..000000000Binary files a/images/Geopolitics.png and /dev/null differdiff --git a/images/GlobalTrade.png b/images/GlobalTrade.pngdeleted file mode 100644index 4f3e3f266..000000000Binary files a/images/GlobalTrade.png and /dev/null differdiff --git a/images/Markets.png b/images/Markets.pngdeleted file mode 100644index d83cc30b0..000000000Binary files a/images/Markets.png and /dev/null differdiff --git a/images/News.png b/images/News.pngindex 57fba821e..91d9c1885 100644Binary files a/images/News.png and b/images/News.png differdiff --git a/images/NodeEditor.png b/images/NodeEditor.pngnew file mode 100644index 000000000..32461eb82Binary files /dev/null and b/images/NodeEditor.png differdiff --git a/images/Portfolio.png b/images/Portfolio.pngnew file mode 100644index 000000000..fd417a3d9Binary files /dev/null and b/images/Portfolio.png differdiff --git a/images/RelationshipMap.png b/images/RelationshipMap.pngdeleted file mode 100644index d0825d013..000000000Binary files a/images/RelationshipMap.png and /dev/null differdiff --git a/images/TradeAnalysis.png b/images/TradeAnalysis.pngdeleted file mode 100644index 809f63205..000000000Binary files a/images/TradeAnalysis.png and /dev/null differdiff --git a/images/snapshot-product-hunt-button.png b/images/snapshot-product-hunt-button.pngdeleted file mode 100644index ec6a3ff52..000000000Binary files a/images/snapshot-product-hunt-button.png and /dev/null differ