Skip to content

FinceptTerminal is a modern finance application offering advanced market analytics, investment research, and economic data tools, designed for interactive exploration and data-driven decision-making in a user-friendly environment.

broker update

tilakpatel22a63b4a4e3033
diff --git a/fincept-qt/CMakeLists.txt b/fincept-qt/CMakeLists.txt
index b9fe4d23b..b29da86eb 100644
--- a/fincept-qt/CMakeLists.txt
+++ b/fincept-qt/CMakeLists.txt
@@ -684,6 +684,7 @@ set(CORE_SOURCES
src/core/events/EventBus.cpp
src/core/HealthMonitor.cpp
src/core/layout/LayoutTypes.cpp
+ src/core/layout/DockLayoutSelftest.cpp
src/core/layout/LayoutCatalog.cpp
src/core/layout/LayoutTemplates.cpp
src/core/layout/WorkspaceMatcher.cpp
@@ -861,6 +862,8 @@ set(STORAGE_SOURCES
src/storage/sqlite/migrations/v042_scan_watch_events.cpp
src/storage/sqlite/migrations/v043_feed_subscriptions.cpp
src/storage/sqlite/migrations/v044_feed_items.cpp
+ src/storage/sqlite/migrations/v045_scan_watch_universe.cpp
+ src/storage/sqlite/migrations/v046_fno_algo.cpp
# Historical OHLCV data store (Historify, Phase 3 §13)
src/storage/HistoricalDataStore.cpp
@@ -966,6 +969,8 @@ set(MCP_SOURCES
# Trading
set(TRADING_SOURCES
src/trading/PaperTrading.cpp
+ src/trading/PaperTradingSelftest.cpp
+ src/trading/PaperMarkService.cpp
src/trading/OrderMatcher.cpp
src/trading/BrokerRegistry.cpp
src/trading/UnifiedTrading.cpp
@@ -1078,7 +1083,12 @@ set(ALGO_ENGINE_SOURCES
src/algo_engine/AlgoScanner.cpp
src/algo_engine/CandleDataFetcher.cpp
src/algo_engine/ScanMonitor.cpp
+ src/algo_engine/RealtimeScanRunner.cpp
+ src/algo_engine/UniverseScanSelftest.cpp
src/algo_engine/BacktestEngine.cpp
+ src/algo_engine/fno/FnoAlgoTypes.cpp
+ src/algo_engine/fno/FnoAlgoSelftest.cpp
+ src/algo_engine/fno/FnoLegResolver.cpp
)
# Services
@@ -1515,6 +1525,7 @@ set(SCREEN_SOURCES
src/screens/equity_trading/EquityOrderEntry.cpp
src/screens/equity_trading/EquityOrderBook.cpp
src/screens/equity_trading/EquityBottomPanel.cpp
+ src/screens/common/PaperBlotterPanel.cpp
src/screens/equity_trading/AccountManagementDialog.cpp
src/screens/equity_trading/BroadcastOrderDialog.cpp
src/screens/equity_trading/OrderConfirmDialog.cpp
@@ -1671,6 +1682,7 @@ set(SCREEN_SOURCES
src/screens/algo_trading/StrategyBuilderPanel.cpp
src/screens/algo_trading/StrategyListPanel.cpp
src/screens/algo_trading/ScannerPanel.cpp
+ src/screens/algo_trading/UniverseScannerPanel.cpp
src/screens/algo_trading/AlertsPanel.cpp
src/screens/algo_trading/DeploymentDashboard.cpp
src/screens/algo_trading/AlgoDeployDialog.cpp
@@ -1931,6 +1943,7 @@ set_source_files_properties(
src/screens/algo_trading/AlgoTradingScreen.cpp
src/screens/algo_trading/DeploymentDashboard.cpp
src/screens/algo_trading/ScannerPanel.cpp
+ src/screens/algo_trading/UniverseScannerPanel.cpp
src/screens/algo_trading/AlertsPanel.cpp
src/screens/algo_trading/StrategyBuilderPanel.cpp
src/screens/algo_trading/StrategyListPanel.cpp
@@ -1985,6 +1998,7 @@ set_source_files_properties(
src/screens/equity_trading/EquityOrderEntry.cpp
src/screens/equity_trading/EquityOrderBook.cpp
src/screens/equity_trading/EquityBottomPanel.cpp
+ src/screens/common/PaperBlotterPanel.cpp
src/screens/equity_trading/AccountManagementDialog.cpp
src/screens/equity_trading/BroadcastOrderDialog.cpp
src/screens/equity_trading/OrderConfirmDialog.cpp
@@ -2342,6 +2356,8 @@ set_source_files_properties(
src/storage/sqlite/migrations/v042_scan_watch_events.cpp
src/storage/sqlite/migrations/v043_feed_subscriptions.cpp
src/storage/sqlite/migrations/v044_feed_items.cpp
+ src/storage/sqlite/migrations/v045_scan_watch_universe.cpp
+ src/storage/sqlite/migrations/v046_fno_algo.cpp
# Polymarket screen files — each defines static fmt_* helpers in same namespace
src/screens/polymarket/PolymarketScreen.cpp
src/screens/polymarket/PolymarketCommandBar.cpp
@@ -2487,6 +2503,10 @@ set_source_files_properties(
src/mcp/tools/GeopoliticsTools.cpp
src/mcp/tools/ExcelTools.cpp
src/mcp/tools/SurfaceAnalyticsTools.cpp
+ src/algo_engine/fno/FnoAlgoSelftest.cpp
+ src/algo_engine/fno/FnoLegResolver.cpp
+ src/trading/PaperTradingSelftest.cpp
+ src/trading/PaperMarkService.cpp
PROPERTIES SKIP_UNITY_BUILD_INCLUSION TRUE
)
diff --git a/fincept-qt/src/algo_engine/AlgoEngineTypes.h b/fincept-qt/src/algo_engine/AlgoEngineTypes.h
index 50a8b3c15..6b35a681e 100644
--- a/fincept-qt/src/algo_engine/AlgoEngineTypes.h
+++ b/fincept-qt/src/algo_engine/AlgoEngineTypes.h
@@ -162,6 +162,16 @@ struct AlgoMetrics {
// ── Order signal ────────────────────────────────────────────────────────────
+// One leg of a multi-leg F&O order. Empty AlgoOrderSignal.legs means the
+// single-symbol equity path (symbol/quantity/side fields) is used instead.
+struct AlgoOrderLeg {
+ QString symbol; // broker-native option/future symbol
+ qint64 instrument_token = 0;
+ QString side; // BUY | SELL
+ double quantity = 0;
+ double price = 0; // limit price; 0 = market
+};
+
struct AlgoOrderSignal {
QString deployment_id;
QString account_id;
@@ -175,6 +185,7 @@ struct AlgoOrderSignal {
double trigger_price = 0;
QString reason;
QString mode = "paper"; // paper | live — paper simulates the fill, live routes to the broker
+ QVector<AlgoOrderLeg> legs; // multi-leg F&O orders; empty = single-symbol equity path
};
// ── Live dashboard snapshot ───────────────────────────────────────────────────
diff --git a/fincept-qt/src/algo_engine/RealtimeScanRunner.cpp b/fincept-qt/src/algo_engine/RealtimeScanRunner.cpp
new file mode 100644
index 000000000..3e8e67355
--- /dev/null
+++ b/fincept-qt/src/algo_engine/RealtimeScanRunner.cpp
@@ -0,0 +1,186 @@
+// src/algo_engine/RealtimeScanRunner.cpp
+#include "algo_engine/RealtimeScanRunner.h"
+
+#include "algo_engine/ConditionEvaluator.h"
+#include "core/logging/Logger.h"
+#include "trading/DataStreamManager.h"
+#include "trading/TradingTypes.h" // BrokerQuote
+
+#include <QDateTime>
+#include <QJsonObject>
+#include <QStringList>
+#include <QTimer>
+
+#include <functional>
+
+namespace fincept::algo {
+
+RealtimeScanRunner::RealtimeScanRunner(QString watch_id, QStringList universe,
+ QJsonArray conditions, QString logic, QString timeframe,
+ QString broker_id, QString account_id, QString data_source,
+ int sweep_ms, int cooldown_min, QObject* parent)
+ : QObject(parent)
+ , watch_id_(std::move(watch_id))
+ , universe_(std::move(universe))
+ , conditions_(std::move(conditions))
+ , logic_(std::move(logic))
+ , timeframe_(std::move(timeframe))
+ , tf_enum_(timeframe_from_string(timeframe_ == QStringLiteral("live") ? QStringLiteral("1m")
+ : timeframe_))
+ , broker_id_(std::move(broker_id))
+ , account_id_(std::move(account_id))
+ , data_source_(std::move(data_source))
+ , sweep_ms_(sweep_ms)
+ , cooldown_min_(cooldown_min)
+ , required_bars_(required_bars(conditions_)) {}
+
+RealtimeScanRunner::~RealtimeScanRunner() {
+ qDeleteAll(states_);
+ states_.clear();
+}
+
+int RealtimeScanRunner::required_bars(const QJsonArray& conditions) {
+ int max_need = 2;
+ std::function<void(const QJsonArray&)> walk = [&](const QJsonArray& arr) {
+ for (const auto& v : arr) {
+ const QJsonObject o = v.toObject();
+ if (o.contains(QStringLiteral("children"))) {
+ walk(o.value(QStringLiteral("children")).toArray());
+ continue;
+ }
+ const int period = o.value(QStringLiteral("params")).toObject()
+ .value(QStringLiteral("period")).toInt(0);
+ const int cperiod = o.value(QStringLiteral("compare_params")).toObject()
+ .value(QStringLiteral("period")).toInt(0);
+ const int offset = o.value(QStringLiteral("offset")).toInt(0);
+ const int coffset = o.value(QStringLiteral("compare_offset")).toInt(0);
+ const int need = qMax(period, cperiod) + qMax(offset, coffset) + 2;
+ if (need > max_need)
+ max_need = need;
+ }
+ };
+ walk(conditions);
+ return max_need;
+}
+
+QString RealtimeScanRunner::consumer_id(const QString& symbol) const {
+ return QStringLiteral("uscan:") + watch_id_ + QLatin1Char(':') + symbol;
+}
+
+void RealtimeScanRunner::start() {
+ const int buf = qMax(required_bars_ + 50, 60);
+ for (const QString& sym : universe_) {
+ auto* st = new SymbolState();
+ st->agg = std::make_unique<CandleAggregator>(sym, tf_enum_, buf);
+ states_.insert(sym, st);
+ }
+
+ // Live feed. open_quote_feed is thread-safe (mutates streams/DataHub on the main
+ // thread internally) and delivers the callback on this (the scan) thread because
+ // `this` is the owner.
+ auto& dsm = fincept::trading::DataStreamManager::instance();
+ for (const QString& sym : universe_) {
+ dsm.open_quote_feed(this, consumer_id(sym), account_id_, sym,
+ [this, sym](const fincept::trading::BrokerQuote& q) { on_quote(sym, q); });
+ }
+
+ sweep_timer_ = new QTimer(this);
+ sweep_timer_->setInterval(qMax(100, sweep_ms_));
+ connect(sweep_timer_, &QTimer::timeout, this, &RealtimeScanRunner::on_sweep);
+ sweep_timer_->start();
+
+ emit status_changed(watch_id_, QStringLiteral("running"));
+ LOG_INFO("RealtimeScanRunner",
+ QString("watch=%1 started: %2 symbols, sweep=%3ms, req_bars=%4")
+ .arg(watch_id_).arg(universe_.size()).arg(sweep_ms_).arg(required_bars_));
+}
+
+void RealtimeScanRunner::stop() {
+ if (sweep_timer_) {
+ sweep_timer_->stop();
+ sweep_timer_->deleteLater();
+ sweep_timer_ = nullptr;
+ }
+ auto& dsm = fincept::trading::DataStreamManager::instance();
+ for (const QString& sym : universe_)
+ dsm.close_quote_feed(consumer_id(sym), account_id_);
+ LOG_INFO("RealtimeScanRunner", QString("watch=%1 stopped").arg(watch_id_));
+}
+
+void RealtimeScanRunner::warm(const QString& symbol, const QVector<OhlcvCandle>& candles) {
+ auto it = states_.find(symbol);
+ if (it == states_.end() || candles.isEmpty())
+ return;
+ SymbolState* st = it.value();
+ st->agg->warm_from(candles);
+ st->warmed = true;
+ st->dirty = true; // evaluate on the next sweep
+}
+
+void RealtimeScanRunner::on_quote(const QString& symbol, const fincept::trading::BrokerQuote& q) {
+ auto it = states_.find(symbol);
+ if (it == states_.end())
+ return;
+ SymbolState* st = it.value();
+ const int64_t ts = q.timestamp > 0 ? q.timestamp : QDateTime::currentMSecsSinceEpoch();
+ st->agg->on_tick(q.ltp, q.volume, ts);
+ if (st->last_price > 0)
+ st->prev_price = st->last_price;
+ st->last_price = q.ltp;
+ st->dirty = true;
+}
+
+QVector<OhlcvCandle> RealtimeScanRunner::eval_window(const SymbolState& st) const {
+ // Mirror DeploymentRunner::live_eval_window — append the previous and current
+ // ticks as the last two closed bars so tick-to-tick crossovers are detected.
+ QVector<OhlcvCandle> candles = st.agg->closed_candles();
+ const int64_t now = QDateTime::currentMSecsSinceEpoch();
+ if (st.prev_price > 0) {
+ OhlcvCandle prev;
+ prev.open = prev.high = prev.low = prev.close = st.prev_price;
+ prev.open_time = prev.close_time = now - 1;
+ prev.volume = 0;
+ prev.is_closed = true;
+ candles.append(prev);
+ }
+ OhlcvCandle cur;
+ cur.open = cur.high = cur.low = cur.close = st.last_price;
+ cur.open_time = cur.close_time = now;
+ cur.volume = 0;
+ cur.is_closed = true;
+ candles.append(cur);
+ return candles;
+}
+
+void RealtimeScanRunner::on_sweep() {
+ const qint64 now = QDateTime::currentMSecsSinceEpoch();
+ const qint64 cooldown_ms = static_cast<qint64>(qMax(0, cooldown_min_)) * 60000;
+
+ for (auto it = states_.begin(); it != states_.end(); ++it) {
+ SymbolState* st = it.value();
+ if (!st->warmed || !st->dirty || st->last_price <= 0)
+ continue;
+ st->dirty = false;
+
+ const QVector<OhlcvCandle> window = eval_window(*st);
+ if (window.size() < 2)
+ continue;
+
+ const auto eval = ConditionEvaluator::evaluate_group(conditions_, logic_, window);
+ if (eval.triggered) {
+ if (st->armed && now - st->last_fired_ms >= cooldown_ms) {
+ QStringList parts;
+ for (const auto& d : eval.details)
+ parts << QString("%1 %2 %3").arg(d.indicator, d.op,
+ QString::number(d.target_value, 'f', 2));
+ emit match_found(watch_id_, it.key(), st->last_price, parts.join(" & "));
+ st->last_fired_ms = now;
+ st->armed = false;
+ }
+ } else {
+ st->armed = true;
+ }
+ }
+}
+
+} // namespace fincept::algo
diff --git a/fincept-qt/src/algo_engine/RealtimeScanRunner.h b/fincept-qt/src/algo_engine/RealtimeScanRunner.h
new file mode 100644
index 000000000..1cc0972c1
--- /dev/null
+++ b/fincept-qt/src/algo_engine/RealtimeScanRunner.h
@@ -0,0 +1,85 @@
+// src/algo_engine/RealtimeScanRunner.h
+#pragma once
+#include "algo_engine/AlgoEngineTypes.h"
+#include "algo_engine/CandleAggregator.h"
+
+#include <QHash>
+#include <QJsonArray>
+#include <QObject>
+#include <QString>
+#include <QStringList>
+#include <QVector>
+
+#include <memory>
+
+class QTimer;
+
+namespace fincept::trading { struct BrokerQuote; }
+
+namespace fincept::algo {
+
+/// Runs ONE realtime universe scan on ScanMonitor's dedicated scan thread.
+/// Subscribes the whole universe to the live quote feed, keeps a per-symbol candle
+/// window, and on a coalesced sweep (default 500 ms) evaluates the strategy
+/// conditions on every symbol that priced since the last sweep. Emits match_found
+/// on a fresh false→true edge, gated by a per-symbol cooldown. Alert-only — there is
+/// NO position/order machinery here.
+class RealtimeScanRunner : public QObject {
+ Q_OBJECT
+ public:
+ RealtimeScanRunner(QString watch_id, QStringList universe, QJsonArray conditions,
+ QString logic, QString timeframe, QString broker_id,
+ QString account_id, QString data_source, int sweep_ms,
+ int cooldown_min, QObject* parent = nullptr);
+ ~RealtimeScanRunner() override;
+
+ /// Minimum bars of history the conditions need: max(indicator period,
+ /// compare period) + max(offset, compare_offset) + 2 (crossing lookback),
+ /// floored at 2. Recurses into nested condition groups. Pure/static — also
+ /// covered by --selftest-universe-scan.
+ static int required_bars(const QJsonArray& conditions);
+
+ public slots:
+ void start(); // scan thread
+ void stop(); // scan thread
+ void warm(const QString& symbol, const QVector<OhlcvCandle>& candles); // scan thread
+
+ signals:
+ void match_found(const QString& watch_id, const QString& symbol,
+ double price, const QString& detail);
+ void status_changed(const QString& watch_id, const QString& status);
+
+ private:
+ struct SymbolState {
+ std::unique_ptr<CandleAggregator> agg;
+ double last_price = 0;
+ double prev_price = 0;
+ bool armed = true; // edge gate: fire only on false→true
+ bool dirty = false; // priced since last sweep
+ bool warmed = false; // has history → eligible to evaluate
+ qint64 last_fired_ms = 0;
+ };
+
+ void on_quote(const QString& symbol, const fincept::trading::BrokerQuote& q);
+ void on_sweep();
+ QString consumer_id(const QString& symbol) const;
+ QVector<OhlcvCandle> eval_window(const SymbolState& st) const;
+
+ const QString watch_id_;
+ const QStringList universe_;
+ const QJsonArray conditions_;
+ const QString logic_;
+ const QString timeframe_;
+ const Timeframe tf_enum_;
+ const QString broker_id_;
+ const QString account_id_;
+ const QString data_source_;
+ const int sweep_ms_;
+ const int cooldown_min_;
+ const int required_bars_;
+
+ QHash<QString, SymbolState*> states_; // owned; built in start(), freed in dtor (scan thread)
+ QTimer* sweep_timer_ = nullptr;
+};
+
+} // namespace fincept::algo
diff --git a/fincept-qt/src/algo_engine/ScanMonitor.cpp b/fincept-qt/src/algo_engine/ScanMonitor.cpp
index 77997a06e..b8527539a 100644
--- a/fincept-qt/src/algo_engine/ScanMonitor.cpp
+++ b/fincept-qt/src/algo_engine/ScanMonitor.cpp
@@ -3,14 +3,18 @@
#include "algo_engine/CandleDataFetcher.h"
#include "algo_engine/ConditionEvaluator.h"
+#include "algo_engine/RealtimeScanRunner.h"
#include "core/logging/Logger.h"
+#include "services/algo_trading/AlgoTradingTypes.h"
#include "services/notifications/NotificationService.h"
#include "storage/repositories/ScanEventRepository.h"
+#include "trading/instruments/InstrumentRepository.h"
#include "ui/notifications/NotificationService.h"
#include <QDateTime>
#include <QJsonObject>
#include <QStringList>
+#include <QThread>
#include <QTimer>
namespace fincept::algo {
@@ -33,13 +37,20 @@ void ScanMonitor::start() {
.arg(QString::fromStdString(r.error())));
return;
}
- for (const auto& w : r.value())
+ for (const auto& w : r.value()) {
+ if (w.mode == QStringLiteral("realtime"))
+ continue; // realtime universe scans are started on demand from the Universe tab
start_watch(w);
+ }
LOG_INFO("ScanMonitor", QString("started %1 active watch(es)").arg(r.value().size()));
}
void ScanMonitor::start_watch(const ScanWatch& w) {
stop_watch(w.id); // idempotent
+ if (w.mode == QStringLiteral("realtime")) {
+ start_realtime(w);
+ return;
+ }
auto* run = new Runner();
run->watch = w;
run->timer = new QTimer(this);
@@ -58,6 +69,10 @@ void ScanMonitor::stop_watch(const QString& id) {
run->timer->stop();
run->timer->deleteLater();
}
+ if (run->rt) {
+ QMetaObject::invokeMethod(run->rt, "stop", Qt::QueuedConnection);
+ run->rt->deleteLater(); // deleted on the scan thread after stop() runs
+ }
delete run;
}
}
@@ -133,6 +148,117 @@ void ScanMonitor::on_candles(const QString& id,
emit watch_status_changed(id, status);
}
+QStringList ScanMonitor::resolve_universe(const ScanWatch& w) {
+ const QString u = w.universe;
+ if (u == QStringLiteral("NSE_EQ") || u == QStringLiteral("BSE_EQ")) {
+ const QString exch = (u == QStringLiteral("NSE_EQ")) ? QStringLiteral("NSE")
+ : QStringLiteral("BSE");
+ const auto rows = fincept::trading::InstrumentRepository::instance().list(
+ exch, w.broker_id, fincept::trading::InstrumentType::EQ);
+ QStringList out;
+ out.reserve(rows.size());
+ for (const auto& inst : rows)
+ out.append(inst.symbol);
+ return out;
+ }
+ if (u == QStringLiteral("NIFTY50"))
+ return fincept::services::algo::nifty50_symbols();
+ return w.symbols; // '' / CUSTOM
+}
+
+void ScanMonitor::start_realtime(const ScanWatch& w) {
+ if (w.conditions.isEmpty())
+ return;
+
+ const QStringList syms = resolve_universe(w);
+ if (syms.isEmpty()) {
+ ScanWatchRepository::instance().touch_status(w.id, QStringLiteral("error"),
+ QDateTime::currentMSecsSinceEpoch());
+ emit watch_status_changed(w.id, QStringLiteral("error"));
+ LOG_WARN("ScanMonitor",
+ QString("realtime watch %1: empty universe (instrument master loaded for %2?)")
+ .arg(w.id, w.broker_id));
+ return;
+ }
+
+ if (!scan_thread_) {
+ scan_thread_ = new QThread(this);
+ scan_thread_->setObjectName(QStringLiteral("scan-rt"));
+ scan_thread_->start();
+ }
+
+ const int sweep_ms = w.actions.value(QStringLiteral("sweep_ms")).toInt(500);
+ auto* rt = new RealtimeScanRunner(w.id, syms, w.conditions, w.logic, w.timeframe,
+ w.broker_id, w.account_id, w.data_source,
+ sweep_ms, w.cooldown_min);
+ rt->moveToThread(scan_thread_);
+ connect(rt, &RealtimeScanRunner::match_found, this, &ScanMonitor::on_realtime_match);
+ connect(rt, &RealtimeScanRunner::status_changed, this,
+ [this](const QString& id, const QString& s) {
+ ScanWatchRepository::instance().touch_status(
+ id, s, QDateTime::currentMSecsSinceEpoch());
+ emit watch_status_changed(id, s);
+ });
+
+ auto* run = new Runner();
+ run->watch = w;
+ run->rt = rt;
+ runners_.insert(w.id, run);
+
+ QMetaObject::invokeMethod(rt, "start", Qt::QueuedConnection);
+
+ // Warm-up: fetch history on the MAIN thread (CandleDataFetcher owns a QNAM with
+ // main-thread affinity), then forward each symbol's candles to the runner. The
+ // forward is guarded by a runners_ lookup (main-thread-only map) so a stop()
+ // mid-fetch is a no-op, and uses the receiver-context invoke so it is cancelled
+ // if the runner is deleted before delivery.
+ const QString tf = (w.timeframe == QStringLiteral("live")) ? QStringLiteral("1m")
+ : w.timeframe;
+ const int lookback = w.lookback_days > 0
+ ? w.lookback_days
+ : fincept::services::algo::algo_default_lookback_days(tf);
+ const DataSource src = data_source_from_string(w.data_source);
+ const QString id = w.id, broker = w.broker_id, acct = w.account_id;
+ constexpr int kChunk = 50; // throttle: batch the fetch to respect broker rate limits
+ for (int s = 0; s < syms.size(); s += kChunk) {
+ const QStringList batch = syms.mid(s, kChunk);
+ CandleDataFetcher::instance().fetch_multi(
+ batch, tf, lookback, src, broker, acct,
+ [this, id](const QHash<QString, QVector<OhlcvCandle>>& data, const QStringList&) {
+ auto it = runners_.find(id);
+ if (it == runners_.end() || !it.value()->rt)
+ return; // watch stopped while fetching
+ RealtimeScanRunner* rt = it.value()->rt;
+ for (auto d = data.begin(); d != data.end(); ++d) {
+ const QString sym = d.key();
+ const QVector<OhlcvCandle> candles = d.value();
+ QMetaObject::invokeMethod(rt, [rt, sym, candles]() {
+ rt->warm(sym, candles);
+ }, Qt::QueuedConnection);
+ }
+ });
+ }
+
+ ScanWatchRepository::instance().touch_status(w.id, QStringLiteral("warming"),
+ QDateTime::currentMSecsSinceEpoch());
+ emit watch_status_changed(w.id, QStringLiteral("warming"));
+ LOG_INFO("ScanMonitor",
+ QString("realtime watch %1 started: %2 symbols").arg(w.id).arg(syms.size()));
+}
+
+void ScanMonitor::on_realtime_match(const QString& watch_id, const QString& symbol,
+ double price, const QString& detail) {
+ auto it = runners_.find(watch_id);
+ if (it == runners_.end())
+ return;
+ // Continuous: the runner already applied edge + cooldown gating, so just
+ // dispatch (toast / providers / scan_watch_events / watch_fired). Unlike the
+ // poll path, do NOT remove the watch — it keeps scanning.
+ dispatch(it.value()->watch, symbol, detail);
+ // Rich signal for the Universe matches table (carries the live price).
+ emit realtime_match(watch_id, symbol, price, detail);
+}
+
void ScanMonitor::dispatch(const ScanWatch& w, const QString& symbol, const QString& detail) {
const QString msg = QString("%1 — %2").arg(symbol, detail);
const QJsonObject actions = w.actions;
diff --git a/fincept-qt/src/algo_engine/ScanMonitor.h b/fincept-qt/src/algo_engine/ScanMonitor.h
index 768b2be97..bd396ae93 100644
--- a/fincept-qt/src/algo_engine/ScanMonitor.h
+++ b/fincept-qt/src/algo_engine/ScanMonitor.h
@@ -9,9 +9,12 @@
#include <QVector>
class QTimer;
+class QThread;
namespace fincept::algo {
+class RealtimeScanRunner;
+
/// Background service that runs persisted ScanWatches: polls candles on a timer,
/// evaluates each watch's conditions per symbol, edge+cooldown gates, and fires
/// toast/provider alerts. Singleton; lives on the main thread.
@@ -28,6 +31,10 @@ class ScanMonitor : public QObject {
signals:
void watch_fired(const QString& watch_id, const QString& symbol, const QString& detail);
void watch_status_changed(const QString& watch_id, const QString& status);
+ // Realtime-only: carries the live price for the Universe matches table. The
+ // generic watch_fired (above) still drives toasts + alert history for both modes.
+ void realtime_match(const QString& watch_id, const QString& symbol, double price,
+ const QString& detail);
private:
ScanMonitor() = default;
@@ -38,6 +45,7 @@ class ScanMonitor : public QObject {
ScanWatch watch;
QTimer* timer = nullptr;
QHash<QString, SymState> states;
+ RealtimeScanRunner* rt = nullptr; // non-null for mode=='realtime'
};
void start_watch(const ScanWatch& w);
@@ -45,6 +53,13 @@ class ScanMonitor : public QObject {
void on_candles(const QString& id, const QHash<QString, QVector<OhlcvCandle>>& data);
void dispatch(const ScanWatch& w, const QString& symbol, const QString& detail);
+ void start_realtime(const ScanWatch& w);
+ void on_realtime_match(const QString& watch_id, const QString& symbol,
+ double price, const QString& detail);
+ QStringList resolve_universe(const ScanWatch& w);
+
+ QThread* scan_thread_ = nullptr; // lazily created; hosts all RealtimeScanRunners
+
QHash<QString, Runner*> runners_;
};
diff --git a/fincept-qt/src/algo_engine/UniverseScanSelftest.cpp b/fincept-qt/src/algo_engine/UniverseScanSelftest.cpp
new file mode 100644
index 000000000..1dff5f165
--- /dev/null
+++ b/fincept-qt/src/algo_engine/UniverseScanSelftest.cpp
@@ -0,0 +1,91 @@
+// src/algo_engine/UniverseScanSelftest.cpp
+#include "algo_engine/UniverseScanSelftest.h"
+
+#include "algo_engine/ConditionEvaluator.h"
+#include "algo_engine/RealtimeScanRunner.h"
+
+#include <QJsonArray>
+#include <QJsonObject>
+#include <QVector>
+
+#include <cstdio>
+
+namespace fincept::algo {
+
+namespace {
+OhlcvCandle bar(double close) {
+ OhlcvCandle c;
+ c.open = c.high = c.low = c.close = close;
+ c.is_closed = true;
+ return c;
+}
+} // namespace
+
+int run_universe_scan_selftest() {
+ int failures = 0;
+ auto check = [&](bool ok, const char* name) {
+ std::printf(" %s %s\n", ok ? "PASS" : "FAIL", name);
+ if (!ok)
+ ++failures;
+ };
+
+ std::printf("universe-scan selftest:\n");
+
+ // 1. required_bars: a pure price condition needs only the floor (2).
+ {
+ QJsonArray conds;
+ QJsonObject c;
+ c["indicator"] = "CLOSE";
+ c["operator"] = ">";
+ c["value"] = 100.0;
+ conds.append(c);
+ check(RealtimeScanRunner::required_bars(conds) == 2, "required_bars(CLOSE>100) == 2");
+ }
+
+ // 2. required_bars: SMA(200) needs >= 200 bars.
+ {
+ QJsonArray conds;
+ QJsonObject c, p;
+ p["period"] = 200;
+ c["indicator"] = "SMA";
+ c["params"] = p;
+ c["operator"] = ">";
+ c["value"] = 0.0;
+ conds.append(c);
+ check(RealtimeScanRunner::required_bars(conds) >= 200, "required_bars(SMA200) >= 200");
+ }
+
+ // 3. evaluate_group fires on a CLOSE-crosses-above window (99 -> 101).
+ // Three bars are required: IndicatorEngine needs candles.size()>=2 even
+ // after the offset+1 trim, so the crossing window must have at least 3 bars.
+ {
+ QJsonArray conds;
+ QJsonObject c;
+ c["indicator"] = "CLOSE";
+ c["operator"] = "crosses_above";
+ c["value"] = 100.0;
+ conds.append(c);
+ QVector<OhlcvCandle> w{bar(98.0), bar(99.0), bar(101.0)};
+ auto r = ConditionEvaluator::evaluate_group(conds, "AND", w);
+ check(r.triggered, "CLOSE crosses_above 100 (99->101) triggers");
+ }
+
+ // 4. evaluate_group does NOT fire when the level is not met.
+ {
+ QJsonArray conds;
+ QJsonObject c;
+ c["indicator"] = "CLOSE";
+ c["operator"] = ">";
+ c["value"] = 100.0;
+ conds.append(c);
+ QVector<OhlcvCandle> w{bar(98.0), bar(99.0)};
+ auto r = ConditionEvaluator::evaluate_group(conds, "AND", w);
+ check(!r.triggered, "CLOSE>100 (at 99) does NOT trigger");
+ }
+
+ std::printf("universe-scan selftest: %s\n",
+ failures == 0 ? "PASS" : "FAILED");
+ return failures == 0 ? 0 : 1;
+}
+
+} // namespace fincept::algo
diff --git a/fincept-qt/src/algo_engine/UniverseScanSelftest.h b/fincept-qt/src/algo_engine/UniverseScanSelftest.h
new file mode 100644
index 000000000..878fb2fb2
--- /dev/null
+++ b/fincept-qt/src/algo_engine/UniverseScanSelftest.h
@@ -0,0 +1,12 @@
+// src/algo_engine/UniverseScanSelftest.h
+#pragma once
+
+namespace fincept::algo {
+
+/// Headless self-test for the universe-scan core logic. Validates required_bars()
+/// math and that ConditionEvaluator fires/doesn't-fire on the exact synthetic
+/// window the runner builds. No GUI, no threads, no broker, no DB. Returns 0 on
+/// pass, 1 on any failure. Run with: --selftest-universe-scan (QT_QPA_PLATFORM=offscreen).
+int run_universe_scan_selftest();
+
+} // namespace fincept::algo
diff --git a/fincept-qt/src/algo_engine/fno/FnoAlgoSelftest.cpp b/fincept-qt/src/algo_engine/fno/FnoAlgoSelftest.cpp
new file mode 100644
index 000000000..1de17ebc7
--- /dev/null
+++ b/fincept-qt/src/algo_engine/fno/FnoAlgoSelftest.cpp
@@ -0,0 +1,192 @@
+#include "algo_engine/fno/FnoAlgoSelftest.h"
+
+#include "algo_engine/fno/FnoAlgoTypes.h"
+#include "algo_engine/fno/FnoLegResolver.h"
+#include "services/algo_trading/AlgoTradingService.h"
+#include "services/algo_trading/AlgoTradingTypes.h"
+#include "storage/sqlite/Database.h"
+
+#include <QJsonDocument>
+#include <QtGlobal>
+#include <cstdio>
+
+namespace fincept::algo::fno {
+namespace {
+
+int g_failures = 0;
+
+void check(bool cond, const char* label) {
+ std::fprintf(stdout, " %s %s\n", cond ? "[PASS]" : "[FAIL]", label);
+ if (!cond)
+ ++g_failures;
+}
+
+void test_leg_json_roundtrip() {
+ std::fprintf(stdout, "[1] leg JSON round-trip\n");
+ QVector<AlgoFnoLeg> legs;
+ AlgoFnoLeg ce;
+ ce.kind = "CE"; ce.side = "BUY"; ce.lots = 2;
+ ce.strike_mode = "ATM_OFFSET"; ce.strike_value = 2; ce.expiry_mode = "WEEKLY";
+ AlgoFnoLeg pe;
+ pe.kind = "PE"; pe.side = "SELL"; pe.lots = 1;
+ pe.strike_mode = "ABSOLUTE"; pe.strike_value = 23000;
+ pe.expiry_mode = "ABSOLUTE"; pe.expiry_value = "26-JUN-25";
+ legs << ce << pe;
+
+ const QVector<AlgoFnoLeg> back = fno_legs_from_json(fno_legs_to_json(legs));
+ check(back.size() == 2, "round-trip preserves leg count");
+ check(back.size() == 2 && back[0].kind == "CE" && back[0].lots == 2 &&
+ back[0].strike_mode == "ATM_OFFSET" && back[0].side == "BUY" &&
+ back[0].expiry_value.isEmpty(),
+ "leg 0 fields preserved");
+ check(back.size() == 2 && back[1].strike_mode == "ABSOLUTE" &&
+ qFuzzyCompare(back[1].strike_value, 23000.0) &&
+ back[1].expiry_value == "26-JUN-25" && back[1].side == "SELL",
+ "leg 1 fields preserved");
+}
+
+void test_v046_schema() {
+ using fincept::Database;
+ std::fprintf(stdout, "[2] v046 schema columns present\n");
+ auto has_col = [](const QString& table, const QString& col) -> bool {
+ auto q = Database::instance().execute("PRAGMA table_info(" + table + ")", {});
+ if (q.is_err())
+ return false;
+ auto& query = q.value();
+ while (query.next())
+ if (query.value(1).toString() == col) // col 1 = name in PRAGMA table_info
+ return true;
+ return false;
+ };
+ check(has_col("algo_strategies", "instrument_type"), "algo_strategies.instrument_type");
+ check(has_col("algo_strategies", "legs_json"), "algo_strategies.legs_json");
+ check(has_col("algo_deployments", "instrument_type"), "algo_deployments.instrument_type");
+ check(has_col("algo_deployments", "underlying"), "algo_deployments.underlying");
+ check(has_col("algo_deployments", "resolved_expiry"), "algo_deployments.resolved_expiry");
+ check(has_col("algo_deployments", "resolved_legs_json"), "algo_deployments.resolved_legs_json");
+}
+
+void test_persistence_roundtrip() {
+ using fincept::Database;
+ using fincept::services::algo::AlgoStrategy;
+ using fincept::services::algo::AlgoTradingService;
+ std::fprintf(stdout, "[3] strategy persistence round-trip\n");
+
+ AlgoStrategy s;
+ // Fixed id so a crash between save and the DELETE below self-heals on the next
+ // run (the save_strategy UPSERT overwrites the same row).
+ s.id = "selftest-fno-algo-strategy";
+ s.name = "selftest fno algo (delete me)";
+ s.instrument_type = "option";
+ QVector<AlgoFnoLeg> legs;
+ AlgoFnoLeg l;
+ l.kind = "CE"; l.side = "BUY"; l.lots = 1; l.strike_mode = "ATM"; l.expiry_mode = "WEEKLY";
+ legs << l;
+ s.legs = fno_legs_to_json(legs);
+
+ AlgoTradingService::instance().save_strategy(s);
+
+ auto q = Database::instance().execute(
+ "SELECT instrument_type, legs_json FROM algo_strategies WHERE id = ?", {s.id});
+ // is_ok() must gate value() — value() on an error Result is unsafe in this codebase.
+ const bool ok = q.is_ok() && q.value().next();
+ check(ok, "row written and read back");
+ if (ok) {
+ auto& query = q.value();
+ const QString it = query.value(0).toString();
+ const QJsonArray got = QJsonDocument::fromJson(query.value(1).toString().toUtf8()).array();
+ const QVector<AlgoFnoLeg> back = fno_legs_from_json(got);
+ check(it == "option", "instrument_type persisted");
+ check(back.size() == 1 && back[0].kind == "CE" && back[0].strike_mode == "ATM",
+ "legs persisted");
+ }
+
+ // Clean up so the dev DB keeps no selftest residue.
+ Database::instance().execute("DELETE FROM algo_strategies WHERE id = ?", {s.id});
+}
+
+fincept::services::options::OptionChain make_synthetic_chain() {
+ using namespace fincept::services::options;
+ OptionChain c;
+ c.broker_id = "fyers";
+ c.underlying = "NIFTY";
+ c.expiry = "26-JUN-25";
+ c.spot = 23187;
+ c.atm_strike = 23200;
+ // Strikes 22800..23600 step 100; CE delta falls as strike rises.
+ const double strikes[] = {22800, 22900, 23000, 23100, 23200, 23300, 23400, 23500, 23600};
+ const double ce_delta[] = {0.90, 0.82, 0.72, 0.61, 0.50, 0.40, 0.30, 0.22, 0.15};
+ int n = int(sizeof(strikes) / sizeof(strikes[0]));
+ for (int i = 0; i < n; ++i) {
+ OptionChainRow r;
+ r.strike = strikes[i];
+ r.is_atm = (strikes[i] == c.atm_strike);
+ r.ce_token = 1000 + i;
+ r.pe_token = 2000 + i;
+ r.ce_symbol = QString("NIFTY26JUN25C%1").arg(int(strikes[i]));
+ r.pe_symbol = QString("NIFTY26JUN25P%1").arg(int(strikes[i]));
+ r.ce_greeks.delta = ce_delta[i];
+ r.ce_greeks.valid = true;
+ r.pe_greeks.delta = ce_delta[i] - 1.0; // put delta ~ call delta - 1
+ r.pe_greeks.valid = true;
+ c.rows.append(r);
+ }
+ return c;
+}
+
+void test_leg_resolver() {
+ std::fprintf(stdout, "[4] FnoLegResolver\n");
+ const auto chain = make_synthetic_chain();
+
+ auto mk = [](const QString& kind, const QString& mode, double val) {
+ AlgoFnoLeg l;
+ l.kind = kind;
+ l.side = "BUY";
+ l.strike_mode = mode;
+ l.strike_value = val;
+ return l;
+ };
+
+ const auto atm = FnoLegResolver::resolve_one(mk("CE", "ATM", 0), chain);
+ check(atm.valid && qFuzzyCompare(atm.strike, 23200.0) && atm.symbol == "NIFTY26JUN25C23200",
+ "ATM CE -> 23200");
+
+ const auto off = FnoLegResolver::resolve_one(mk("CE", "ATM_OFFSET", 2), chain);
+ check(off.valid && qFuzzyCompare(off.strike, 23400.0), "ATM_OFFSET +2 CE -> 23400");
+
+ const auto abs = FnoLegResolver::resolve_one(mk("PE", "ABSOLUTE", 23000), chain);
+ check(abs.valid && qFuzzyCompare(abs.strike, 23000.0) && abs.symbol == "NIFTY26JUN25P23000",
+ "ABSOLUTE 23000 PE -> 23000");
+
+ const auto dlt = FnoLegResolver::resolve_one(mk("CE", "DELTA", 0.30), chain);
+ check(dlt.valid && qFuzzyCompare(dlt.strike, 23400.0), "DELTA 0.30 CE -> 23400");
+
+ AlgoFnoLeg fut;
+ fut.kind = "FUT";
+ const auto futr = FnoLegResolver::resolve_one(fut, chain);
+ check(!futr.valid, "FUT leg not resolvable from option chain (expected invalid)");
+
+ // A chain row with no tradeable contract (token 0) must resolve as invalid.
+ auto chain0 = make_synthetic_chain();
+ chain0.rows[2].ce_token = 0; // strike 23000 CE: no contract
+ chain0.rows[2].ce_symbol.clear();
+ const auto missing = FnoLegResolver::resolve_one(mk("CE", "ABSOLUTE", 23000), chain0);
+ check(!missing.valid, "missing contract (token 0) -> invalid");
+}
+
+} // namespace
+
+int run_fno_algo_selftest() {
+ std::setvbuf(stdout, nullptr, _IONBF, 0); // unbuffered so output survives a crash mid-test
+ std::fprintf(stdout, "\n=== F&O ALGO SELF-TEST ===\n");
+ g_failures = 0;
+ test_leg_json_roundtrip();
+ test_v046_schema();
+ test_persistence_roundtrip();
+ test_leg_resolver();
+ std::fprintf(stdout, "\n%s (%d failure(s))\n", g_failures == 0 ? "OVERALL PASS" : "OVERALL FAIL",
+ g_failures);
+ return g_failures == 0 ? 0 : 1;
+}
+
+} // namespace fincept::algo::fno
diff --git a/fincept-qt/src/algo_engine/fno/FnoAlgoSelftest.h b/fincept-qt/src/algo_engine/fno/FnoAlgoSelftest.h
new file mode 100644
index 000000000..8d99668dc
--- /dev/null
+++ b/fincept-qt/src/algo_engine/fno/FnoAlgoSelftest.h
@@ -0,0 +1,12 @@
+#pragma once
+
+namespace fincept::algo::fno {
+
+// Headless self-test for the F&O algo foundation. Covers: leg JSON round-trip,
+// v046 schema presence, strategy persistence round-trip, and FnoLegResolver
+// strike resolution.
+// Run with: QT_QPA_PLATFORM=offscreen ./FinceptTerminal --selftest-fno-algo
+// Returns 0 if all checks pass, 1 if any check fails.
+int run_fno_algo_selftest();
+
+} // namespace fincept::algo::fno
diff --git a/fincept-qt/src/algo_engine/fno/FnoAlgoTypes.cpp b/fincept-qt/src/algo_engine/fno/FnoAlgoTypes.cpp
new file mode 100644
index 000000000..3edabee15
--- /dev/null
+++ b/fincept-qt/src/algo_engine/fno/FnoAlgoTypes.cpp
@@ -0,0 +1,40 @@
+#include "algo_engine/fno/FnoAlgoTypes.h"
+
+namespace fincept::algo::fno {
+
+QJsonArray fno_legs_to_json(const QVector<AlgoFnoLeg>& legs) {
+ QJsonArray arr;
+ for (const auto& l : legs) {
+ QJsonObject o;
+ o["kind"] = l.kind;
+ o["side"] = l.side;
+ o["lots"] = l.lots;
+ o["strike_mode"] = l.strike_mode;
+ o["strike_value"] = l.strike_value;
+ o["expiry_mode"] = l.expiry_mode;
+ o["expiry_value"] = l.expiry_value;
+ arr.append(o);
+ }
+ return arr;
+}
+
+QVector<AlgoFnoLeg> fno_legs_from_json(const QJsonArray& arr) {
+ QVector<AlgoFnoLeg> legs;
+ for (const auto& v : arr) {
+ if (!v.isObject())
+ continue; // skip malformed elements rather than injecting an all-default leg
+ const QJsonObject o = v.toObject();
+ AlgoFnoLeg l;
+ l.kind = o.value("kind").toString();
+ l.side = o.value("side").toString(QStringLiteral("BUY"));
+ l.lots = o.value("lots").toInt(1);
+ l.strike_mode = o.value("strike_mode").toString(QStringLiteral("ATM"));
+ l.strike_value = o.value("strike_value").toDouble(0);
+ l.expiry_mode = o.value("expiry_mode").toString(QStringLiteral("WEEKLY"));
+ l.expiry_value = o.value("expiry_value").toString();
+ legs.append(l);
+ }
+ return legs;
+}
+
+} // namespace fincept::algo::fno
diff --git a/fincept-qt/src/algo_engine/fno/FnoAlgoTypes.h b/fincept-qt/src/algo_engine/fno/FnoAlgoTypes.h
new file mode 100644
index 000000000..32f26d07e
--- /dev/null
+++ b/fincept-qt/src/algo_engine/fno/FnoAlgoTypes.h
@@ -0,0 +1,38 @@
+#pragma once
+
+#include <QJsonArray>
+#include <QJsonObject>
+#include <QString>
+#include <QVector>
+
+namespace fincept::algo::fno {
+
+// One leg of an F&O algo strategy, authored as a RULE (not a fixed contract).
+// Concrete strikes/expiries are resolved at entry time by FnoLegResolver.
+struct AlgoFnoLeg {
+ QString kind; // "CE" | "PE" | "FUT"
+ QString side = "BUY"; // "BUY" | "SELL"
+ int lots = 1;
+
+ // Strike rule. strike_value meaning depends on strike_mode:
+ // ATM → ignored
+ // ATM_OFFSET → number of strike steps from ATM (+ = higher strike)
+ // DELTA → target absolute delta (0..1)
+ // ABSOLUTE → exact strike price (pinned)
+ QString strike_mode = "ATM"; // "ATM"|"ATM_OFFSET"|"DELTA"|"ABSOLUTE"
+ double strike_value = 0;
+
+ // Expiry rule. expiry_value meaning depends on expiry_mode:
+ // WEEKLY/MONTHLY → ignored
+ // NEAREST_DTE → minimum days-to-expiry (string integer)
+ // ABSOLUTE → "DD-MMM-YY"
+ QString expiry_mode = "WEEKLY"; // "WEEKLY"|"MONTHLY"|"NEAREST_DTE"|"ABSOLUTE"
+ QString expiry_value;
+};
+
+// JSON (de)serialization — mirrors how AlgoStrategy stores entry/exit conditions
+// as a QJsonArray TEXT column. Pure, no I/O.
+QJsonArray fno_legs_to_json(const QVector<AlgoFnoLeg>& legs);
+QVector<AlgoFnoLeg> fno_legs_from_json(const QJsonArray& arr);
+
+} // namespace fincept::algo::fno
diff --git a/fincept-qt/src/algo_engine/fno/FnoLegResolver.cpp b/fincept-qt/src/algo_engine/fno/FnoLegResolver.cpp
new file mode 100644
index 000000000..a090775c8
--- /dev/null
+++ b/fincept-qt/src/algo_engine/fno/FnoLegResolver.cpp
@@ -0,0 +1,107 @@
+#include "algo_engine/fno/FnoLegResolver.h"
+
+#include <algorithm>
+#include <cmath>
+#include <limits>
+
+namespace fincept::algo::fno {
+
+using fincept::services::options::OptionChain;
+using fincept::services::options::OptionChainRow;
+
+static int FnoLegResolver_atm_index(const OptionChain& chain) {
+ int idx = -1;
+ double best = std::numeric_limits<double>::max();
+ for (int i = 0; i < chain.rows.size(); ++i) {
+ const double d = std::abs(chain.rows[i].strike - chain.atm_strike);
+ if (d < best) {
+ best = d;
+ idx = i;
+ }
+ }
+ return idx;
+}
+
+static int FnoLegResolver_nearest_strike_index(const OptionChain& chain, double strike) {
+ int idx = -1;
+ double best = std::numeric_limits<double>::max();
+ for (int i = 0; i < chain.rows.size(); ++i) {
+ const double d = std::abs(chain.rows[i].strike - strike);
+ if (d < best) {
+ best = d;
+ idx = i;
+ }
+ }
+ return idx;
+}
+
+ResolvedLeg FnoLegResolver::resolve_one(const AlgoFnoLeg& leg, const OptionChain& chain) {
+ ResolvedLeg out;
+ out.kind = leg.kind;
+ out.side = leg.side;
+ out.lots = leg.lots;
+
+ if (chain.rows.isEmpty()) {
+ out.error = QStringLiteral("empty chain");
+ return out;
+ }
+ if (leg.kind != QLatin1String("CE") && leg.kind != QLatin1String("PE")) {
+ out.error = QStringLiteral("non-option leg not resolvable from chain");
+ return out;
+ }
+ const bool is_call = (leg.kind == QLatin1String("CE"));
+
+ int idx = -1;
+ if (leg.strike_mode == QLatin1String("ABSOLUTE")) {
+ idx = FnoLegResolver_nearest_strike_index(chain, leg.strike_value);
+ } else if (leg.strike_mode == QLatin1String("ATM")) {
+ idx = FnoLegResolver_atm_index(chain);
+ } else if (leg.strike_mode == QLatin1String("ATM_OFFSET")) {
+ const int a = FnoLegResolver_atm_index(chain);
+ if (a >= 0)
+ idx = std::clamp(a + static_cast<int>(std::lround(leg.strike_value)), 0,
+ static_cast<int>(chain.rows.size()) - 1);
+ } else if (leg.strike_mode == QLatin1String("DELTA")) {
+ double best = std::numeric_limits<double>::max();
+ for (int i = 0; i < chain.rows.size(); ++i) {
+ const auto& g = is_call ? chain.rows[i].ce_greeks : chain.rows[i].pe_greeks;
+ if (!g.valid)
+ continue;
+ const double d = std::abs(std::abs(g.delta) - std::abs(leg.strike_value));
+ if (d < best) {
+ best = d;
+ idx = i;
+ }
+ }
+ if (idx < 0) {
+ out.error = QStringLiteral("no valid greeks for DELTA resolution");
+ return out;
+ }
+ } else {
+ out.error = QStringLiteral("unknown strike_mode: ") + leg.strike_mode;
+ return out;
+ }
+
+ if (idx < 0 || idx >= chain.rows.size()) {
+ out.error = QStringLiteral("strike not found");
+ return out;
+ }
+ const OptionChainRow& r = chain.rows[idx];
+ out.strike = r.strike;
+ out.token = is_call ? r.ce_token : r.pe_token;
+ out.symbol = is_call ? r.ce_symbol : r.pe_symbol;
+ out.valid = (out.token != 0 && !out.symbol.isEmpty());
+ if (!out.valid)
+ out.error = QStringLiteral("no contract for strike/side in chain");
+ return out;
+}
+
+QVector<ResolvedLeg> FnoLegResolver::resolve(const QVector<AlgoFnoLeg>& legs, const OptionChain& chain) {
+ QVector<ResolvedLeg> out;
+ out.reserve(legs.size());
+ for (const auto& l : legs)
+ out.append(resolve_one(l, chain));
+ return out;
+}
+
+} // namespace fincept::algo::fno
diff --git a/fincept-qt/src/algo_engine/fno/FnoLegResolver.h b/fincept-qt/src/algo_engine/fno/FnoLegResolver.h
new file mode 100644
index 000000000..f20f7c8aa
--- /dev/null
+++ b/fincept-qt/src/algo_engine/fno/FnoLegResolver.h
@@ -0,0 +1,34 @@
+#pragma once
+
+#include "algo_engine/fno/FnoAlgoTypes.h"
+#include "services/options/OptionChainTypes.h"
+
+#include <QString>
+#include <QVector>
+
+namespace fincept::algo::fno {
+
+// A leg rule resolved to a concrete contract against an OptionChain snapshot.
+struct ResolvedLeg {
+ QString kind; // "CE" | "PE"
+ QString side; // "BUY" | "SELL"
+ int lots = 1;
+ double strike = 0;
+ qint64 token = 0;
+ QString symbol; // broker-native symbol taken from the chain row
+ bool valid = false;
+ QString error; // reason resolution failed (when !valid)
+};
+
+// Pure resolver: leg rules + an OptionChain snapshot -> concrete contracts.
+// No I/O, no globals. FUT legs are out of scope here (they resolve from the
+// futures instrument, not the option chain) and return valid=false.
+class FnoLegResolver {
+ public:
+ static ResolvedLeg resolve_one(const AlgoFnoLeg& leg,
+ const fincept::services::options::OptionChain& chain);
+ static QVector<ResolvedLeg> resolve(const QVector<AlgoFnoLeg>& legs,
+ const fincept::services::options::OptionChain& chain);
+};
+
+} // namespace fincept::algo::fno
diff --git a/fincept-qt/src/app/DockScreenRouter.cpp b/fincept-qt/src/app/DockScreenRouter.cpp
index 7993d126b..4286fb21f 100644
--- a/fincept-qt/src/app/DockScreenRouter.cpp
+++ b/fincept-qt/src/app/DockScreenRouter.cpp
@@ -379,6 +379,27 @@ void DockScreenRouter::restore_screen_state(const QString& id) {
}
}
+int DockScreenRouter::flush_all_screen_states() {
+ int flushed = 0;
+ // screens_ holds every MATERIALIZED screen widget (closed-but-not-yet-
+ // dematerialised included). Synchronously persist each stateful one so a
+ // tab that's still on screen at quit doesn't lose its config. Closed tabs
+ // were already saved through the visibilityChanged(false) hide path.
+ for (auto it = screens_.cbegin(); it != screens_.cend(); ++it) {
+ auto* stateful = dynamic_cast<screens::IStatefulScreen*>(it.value());
+ if (!stateful)
+ continue;
+ const PanelInstanceId uuid = panel_uuid_for(it.key());
+ if (!uuid.is_null())
+ ScreenStateManager::instance().save_now_by_uuid_sync(stateful, uuid.to_string());
+ else
+ ScreenStateManager::instance().save_now_sync(stateful);
+ ++flushed;
+ }
+ LOG_INFO("DockRouter", QString("flush_all_screen_states: persisted %1 screen(s)").arg(flushed));
+ return flushed;
+}
+
void DockScreenRouter::apply_ads_theme() {
// ADS's CSS (build_ads_qss on CDockManager) handles all ADS widget styling.
// This function ensures tab widgets and labels don't have stale widget-level
diff --git a/fincept-qt/src/app/DockScreenRouter.h b/fincept-qt/src/app/DockScreenRouter.h
index e7cac3b67..856db0f4b 100644
--- a/fincept-qt/src/app/DockScreenRouter.h
+++ b/fincept-qt/src/app/DockScreenRouter.h
@@ -110,6 +110,30 @@ class DockScreenRouter : public QObject {
/// Panels 5+ tab into the bottom-right area.
void tile_2x2();
+ /// Drop every closed/hidden dock widget out of the dock manager so it is
+ /// not serialised into the saved layout. ADS keeps a toggled-off widget in
+ /// its own area in the tree (Closed="1"); CDockManager::saveState() writes
+ /// all of them and restoreState() faithfully rebuilds them, so closed
+ /// panels accumulate across sessions into dozens of zero-size split areas
+ /// that corrupt the restored grid (a clean left|right comes back as a
+ /// reshuffled top/bottom split). Call this immediately before saveState().
+ ///
+ /// The CDockWidget objects survive — the router owns them in dock_widgets_,
+ /// so navigate()/tab_into()/add_alongside() re-add them on demand via their
+ /// needs_add path (triggered by dockManager()==nullptr). Returns the number
+ /// of panels pruned. No-op (returns 0) when nothing is hidden.
+ int prune_hidden_panels();
+
+ /// Synchronously persist the UI state of EVERY materialized stateful screen
+ /// (IStatefulScreen) right now, on the calling thread. Panels that are
+ /// visible at app-quit never receive visibilityChanged(false), so their
+ /// per-screen save never fires through the normal hide path; and an async
+ /// save dispatched from closeEvent would race process exit. WindowFrame
+ /// calls this at the top of closeEvent so each open tab's latest config
+ /// (FNO underlying/expiry/broker, equity symbol/watchlist, active sub-tab,
+ /// …) is on disk before shutdown. Returns the number of screens flushed.
+ int flush_all_screen_states();
+
/// Phase 5: tear off a panel into a brand-new WindowFrame. Spawns the
/// new frame on the next available monitor (mirrors the
/// new-window-on-next-monitor placement policy). Then performs a
diff --git a/fincept-qt/src/app/DockScreenRouter_Materialize.cpp b/fincept-qt/src/app/DockScreenRouter_Materialize.cpp
index e0593522e..75425f938 100644
--- a/fincept-qt/src/app/DockScreenRouter_Materialize.cpp
+++ b/fincept-qt/src/app/DockScreenRouter_Materialize.cpp
@@ -80,12 +80,25 @@ ads::CDockWidget* DockScreenRouter::create_dock_widget(const QString& id) {
// through duplicate_panel() which calls create_dock_widget with a
// synthetic `<base>#dup<N>` id — each gets its own UUID.
if (!instance_ids_.contains(id)) {
- const PanelInstanceId panel_uuid = PanelInstanceId::generate();
- instance_ids_.insert(id, panel_uuid);
-
WindowId frame_id; // null if the router's parent isn't a WindowFrame
- if (auto* frame = qobject_cast<WindowFrame*>(parent()))
+ int win_id = 0;
+ if (auto* frame = qobject_cast<WindowFrame*>(parent())) {
frame_id = frame->frame_uuid();
+ win_id = frame->window_id();
+ }
+
+ // Derive the instance id DETERMINISTICALLY from window+dock id rather
+ // than a fresh random uuid. The dock id is stable across restarts (the
+ // ADS layout restores the same ids), so the same panel reuses the same
+ // PanelInstanceId every launch — which is what lets ScreenStateManager
+ // find the panel's saved UI state again (restore_by_uuid keys on this).
+ // A random generate() minted a new id each launch, so per-screen state
+ // (FNO underlying/expiry, equity symbol/watchlist, …) was written under
+ // an id that never matched on the next run and was effectively lost.
+ // window id is included so the same dock id in two windows stays unique.
+ const PanelInstanceId panel_uuid =
+ PanelInstanceId::from_name(QStringLiteral("w%1:%2").arg(win_id).arg(id));
+ instance_ids_.insert(id, panel_uuid);
// Strip any "#dup<N>" suffix from the type id so two watchlists
// share a type_id of "watchlist" while having distinct instance_ids.
diff --git a/fincept-qt/src/app/DockScreenRouter_PanelOps.cpp b/fincept-qt/src/app/DockScreenRouter_PanelOps.cpp
index 3f7eb82ec..a260fbf46 100644
--- a/fincept-qt/src/app/DockScreenRouter_PanelOps.cpp
+++ b/fincept-qt/src/app/DockScreenRouter_PanelOps.cpp
@@ -359,6 +359,28 @@ void DockScreenRouter::show_tab_context_menu(const QString& id, const QPoint& gl
menu.exec(global_pos);
}
+int DockScreenRouter::prune_hidden_panels() {
+ if (!manager_)
+ return 0;
+ // dockWidgetsMap() returns a value copy, so removing while iterating the
+ // snapshot is safe; collect first regardless to keep intent obvious.
+ QList<ads::CDockWidget*> closed;
+ for (auto* dw : manager_->dockWidgetsMap()) {
+ if (dw && dw->isClosed())
+ closed.append(dw);
+ }
+ for (auto* dw : closed) {
+ // removeDockWidget() detaches the widget, drops it from the manager's
+ // map and collapses its now-empty area. It does NOT delete the widget,
+ // so the screen and its IStatefulScreen state stay alive in our
+ // dock_widgets_ map for re-add on the next navigate().
+ manager_->removeDockWidget(dw);
+ }
+ if (!closed.isEmpty())
+ LOG_DEBUG("DockRouter", QString("prune_hidden_panels: dropped %1 closed area(s)").arg(closed.size()));
+ return static_cast<int>(closed.size());
+}
+
void DockScreenRouter::tile_2x2() {
// Public `layout.tile_2x2` command: re-grid every open panel in its current
// reading order. Delegates to the shared auto-grid implementation.
diff --git a/fincept-qt/src/app/InstanceLock.cpp b/fincept-qt/src/app/InstanceLock.cpp
index d93876706..459c18c44 100644
--- a/fincept-qt/src/app/InstanceLock.cpp
+++ b/fincept-qt/src/app/InstanceLock.cpp
@@ -169,7 +169,14 @@ void InstanceLock::on_new_connection() {
const auto args = parse_args(payload);
LOG_INFO(kTag, QString("Secondary connected: %1 args").arg(args.size()));
- emit message_received(args);
+ // Defer the emit to the next event-loop turn. Consumers open a modal
+ // monitor picker (QDialog::exec spins a NESTED event loop); doing that
+ // synchronously inside this QLocalSocket::readyRead slot re-enters
+ // socket delivery, and the client's disconnected→deleteLater then frees
+ // the socket mid-emit → doActivate crashes (EXC_BAD_ACCESS). Posting the
+ // emit lets this slot fully unwind before any nested loop runs.
+ QMetaObject::invokeMethod(
+ this, [this, args]() { emit message_received(args); }, Qt::QueuedConnection);
});
connect(client, &QLocalSocket::disconnected, client, &QLocalSocket::deleteLater);
diff --git a/fincept-qt/src/app/WindowFrame.cpp b/fincept-qt/src/app/WindowFrame.cpp
index 5bca97553..5f6facd24 100644
--- a/fincept-qt/src/app/WindowFrame.cpp
+++ b/fincept-qt/src/app/WindowFrame.cpp
@@ -405,6 +405,15 @@ WindowFrame::WindowFrame(int window_id, QWidget* parent, const WindowId& adopted
connect(dock_layout_save_timer_, &QTimer::timeout, this, [this]() {
if (!dock_manager_)
return;
+ // Drop hidden/closed panels before serialising so the saved layout is
+ // exactly the visible grid — otherwise closed areas accumulate into
+ // dozens of phantom splits that corrupt the restored arrangement.
+ // prune emits dockWidgetRemoved/viewToggled (→ schedule_dock_layout_save);
+ // suppress that re-entrant restart while we save the freshly-pruned tree.
+ suppress_layout_save_ = true;
+ if (dock_router_)
+ dock_router_->prune_hidden_panels();
+ suppress_layout_save_ = false;
// SessionManager.save_dock_layout fans out to WorkspaceSnapshotRing
// (60s rate-limited auto snapshot). That covers what the legacy
// 5-min WorkspaceManager autosave used to do, with better cadence.
@@ -749,7 +758,10 @@ WindowFrame::WindowFrame(int window_id, QWidget* parent, const WindowId& adopted
// conflicts with restoreState's layout.
// Layout version: bump this whenever the dock layout format changes to
// automatically discard stale/corrupt saved state from previous versions.
- static constexpr int kDockLayoutVersion = 4;
+ // v5: closed panels are now pruned before save (prune_hidden_panels), so
+ // pre-v5 blobs — bloated with dozens of phantom closed single-widget areas
+ // that reshuffle the restored grid — are discarded rather than restored.
+ static constexpr int kDockLayoutVersion = 5;
bool dock_restored = false;
if (dock_manager_) {
@@ -777,9 +789,13 @@ WindowFrame::WindowFrame(int window_id, QWidget* parent, const WindowId& adopted
dock_restored = dock_manager_->restoreState(saved_dock);
dock_router_->set_suppress_materialize(false);
- // Sanity check: if restoreState produced an unreasonable number
- // of visible dock areas (>6), the layout is likely corrupt.
- if (dock_restored && dock_manager_->openedDockAreas().size() > 6) {
+ // Sanity check: a genuinely corrupt blob restores into dozens of
+ // areas (the pre-prune bug produced 28-33). A legit layout now
+ // tops out around the 4-panel auto-grid plus a few floating /
+ // torn-off panels, so 6 was too tight — it would nuke a valid
+ // grid+float layout. prune_hidden_panels() keeps saved blobs at
+ // visible-panel count, so this is only a backstop for true bloat.
+ if (dock_restored && dock_manager_->openedDockAreas().size() > 16) {
LOG_WARN("WindowFrame", QString("Dock layout corrupt: %1 open areas — resetting")
.arg(dock_manager_->openedDockAreas().size()));
dock_restored = false;
@@ -1071,6 +1087,14 @@ constexpr const char* kActiveForWorkProp = "fincept.active_for_work";
} // namespace
void WindowFrame::closeEvent(QCloseEvent* event) {
+ // Synchronously persist every open tab's UI state BEFORE anything else.
+ // Panels visible at quit never get visibilityChanged(false), so their
+ // per-screen save would otherwise never fire — and an async save here
+ // would race process exit. This guarantees each tab reopens with the
+ // exact config it had (FNO underlying/expiry/broker, equity symbol/
+ // watchlist, active sub-tab, …).
+ if (dock_router_)
+ dock_router_->flush_all_screen_states();
// Force an immediate snapshot bypassing the 60s rate limit so a real
// shutdown always has fresh state to restore from. Per Phase 6 the
// legacy WorkspaceManager autosave is gone — the snapshot ring is the
@@ -1083,6 +1107,13 @@ void WindowFrame::closeEvent(QCloseEvent* event) {
if (QScreen* scr = screen())
SessionManager::instance().save_screen_name(window_id_, scr->name());
if (dock_manager_) {
+ // Persist only the visible grid — drop closed panels so the saved
+ // layout doesn't carry phantom areas that corrupt the restored
+ // arrangement (see DockScreenRouter::prune_hidden_panels).
+ suppress_layout_save_ = true;
+ if (dock_router_)
+ dock_router_->prune_hidden_panels();
+ suppress_layout_save_ = false;
SessionManager::instance().save_dock_layout(window_id_, dock_manager_->saveState());
QSettings tmp;
dock_manager_->savePerspectives(tmp);
diff --git a/fincept-qt/src/app/WindowFrame_Layout.cpp b/fincept-qt/src/app/WindowFrame_Layout.cpp
index 01353ea63..d883b12d9 100644
--- a/fincept-qt/src/app/WindowFrame_Layout.cpp
+++ b/fincept-qt/src/app/WindowFrame_Layout.cpp
@@ -40,7 +40,13 @@ layout::FrameLayout WindowFrame::capture_layout() const {
if (!dock_manager_ || !dock_router_)
return fl;
- // ADS dock state — opaque blob covering splits, tab order, sizes.
+ // ADS dock state — opaque blob covering splits, tab order, sizes. Prune
+ // closed panels first so workspace snapshots capture only the visible grid
+ // and don't carry phantom areas that reshuffle the layout on restore. The
+ // session-layout timer keeps the live tree pruned continuously, so this is
+ // normally a no-op; it just guarantees a clean blob if a snapshot lands in
+ // the sub-500ms window after a layout change.
+ dock_router_->prune_hidden_panels();
fl.dock_state = dock_manager_->saveState();
// Active panel — whichever dock widget currently has focus.
diff --git a/fincept-qt/src/app/main.cpp b/fincept-qt/src/app/main.cpp
index 97478f02c..78c98a476 100644
--- a/fincept-qt/src/app/main.cpp
+++ b/fincept-qt/src/app/main.cpp
@@ -1,5 +1,7 @@
#include "algo_engine/AlgoEngineProducer.h"
#include "algo_engine/ScanMonitor.h"
+#include "algo_engine/UniverseScanSelftest.h"
+#include "algo_engine/fno/FnoAlgoSelftest.h"
#include "services/llm/LlmService.h"
#include "ui/notifications/DesktopNotifier.h"
#include "app/MonitorPickerDialog.h"
@@ -18,6 +20,7 @@
#include "core/currency/CurrencyManager.h"
#include "core/i18n/LanguageManager.h"
#include "core/keys/KeyConfigManager.h"
+#include "core/layout/DockLayoutSelftest.h"
#include "core/logging/Logger.h"
#include "core/session/ScreenStateManager.h"
#include "core/session/SessionManager.h"
@@ -27,6 +30,7 @@
#include "mcp/McpInit.h"
#include "mcp/ToolSelfTest.h"
#include "services/feeds/FeedSelfTest.h"
+#include "trading/PaperTradingSelftest.h"
#include "network/http/HttpClient.h"
#include "python/PythonSetupManager.h"
#include "screens/launchpad/LaunchpadScreen.h"
@@ -72,6 +76,7 @@
#include "trading/AccountManager.h"
#include "trading/DataStreamManager.h"
#include "trading/ExchangeService.h"
+#include "trading/PaperMarkService.h"
#include "trading/ExchangeSessionManager.h"
#include "storage/HistoricalDataStore.h"
#include "storage/repositories/NewsArticleRepository.h"
@@ -715,6 +720,8 @@ int main(int argc, char* argv[]) {
fincept::register_migration_v042();
fincept::register_migration_v043();
fincept::register_migration_v044();
+ fincept::register_migration_v045();
+ fincept::register_migration_v046();
// Open main database
QString db_path = fincept::AppPaths::data() + "/fincept.db";
@@ -870,6 +877,14 @@ int main(int argc, char* argv[]) {
return fincept::mcp::dump_tools_json();
if (qstrcmp(argv[i], "--selftest-feeds") == 0)
return fincept::feeds::run_feed_selftest();
+ if (qstrcmp(argv[i], "--selftest-dock-layout") == 0)
+ return fincept::layout::run_dock_layout_selftest();
+ if (qstrcmp(argv[i], "--selftest-fno-algo") == 0)
+ return fincept::algo::fno::run_fno_algo_selftest();
+ if (qstrcmp(argv[i], "--selftest-universe-scan") == 0)
+ return fincept::algo::run_universe_scan_selftest();
+ if (qstrcmp(argv[i], "--selftest-paper") == 0)
+ return fincept::trading::run_paper_trading_selftest();
}
// Start the scan-watch background service. Runs after Database::open() (which
@@ -881,6 +896,13 @@ int main(int argc, char* argv[]) {
// REST / native Yahoo), so it does not require the Python env to be ready.
fincept::algo::ScanMonitor::instance().start();
+ // Centralized paper mark-to-market + order matching. Runs independent of which
+ // screen is open so paper positions (equity AND F&O) keep their P&L live and
+ // resting limit/stop/SL-TP orders fill continuously — not only while the
+ // Equity tab is focused. Placed alongside ScanMonitor (after the self-test
+ // early-returns, so it stays off in headless --selftest runs).
+ fincept::trading::PaperMarkService::instance().start();
+
// Native desktop notifications (Win toast / macOS Notification Center / Linux
// libnotify) via a tray icon — also surfaces every in-app ToastService toast.
fincept::ui::DesktopNotifier::instance().init();
diff --git a/fincept-qt/src/core/identity/Uuid.h b/fincept-qt/src/core/identity/Uuid.h
index bc4e7096c..fd0656737 100644
--- a/fincept-qt/src/core/identity/Uuid.h
+++ b/fincept-qt/src/core/identity/Uuid.h
@@ -34,6 +34,19 @@ class TypedUuid {
/// Generate a fresh random uuid (v4).
static TypedUuid generate() { return TypedUuid(QUuid::createUuid()); }
+ /// Deterministic name-based uuid (v5): the same `name` always yields the
+ /// same uuid, stable across process restarts. Use when an id must survive
+ /// persistence WITHOUT being stored separately — e.g. a panel's instance id
+ /// derived from "window+dock id" so its saved UI state still matches after
+ /// a relaunch (a random generate() would mint a new id every launch and the
+ /// saved state would never be found again).
+ static TypedUuid from_name(const QString& name) {
+ // Fixed app namespace — arbitrary but constant so names map stably.
+ static const QUuid kNamespace(
+ QStringLiteral("{6b3f8a1e-2c4d-5e6f-8a9b-0c1d2e3f4a5b}"));
+ return TypedUuid(QUuid::createUuidV5(kNamespace, name.toUtf8()));
+ }
+
/// Parse from canonical 8-4-4-4-12 string. Returns a null TypedUuid on
/// failure — call is_null() to discriminate.
static TypedUuid from_string(const QString& s) {
diff --git a/fincept-qt/src/core/layout/DockLayoutSelftest.cpp b/fincept-qt/src/core/layout/DockLayoutSelftest.cpp
new file mode 100644
index 000000000..5cb1b3a3f
--- /dev/null
+++ b/fincept-qt/src/core/layout/DockLayoutSelftest.cpp
@@ -0,0 +1,258 @@
+#include "core/layout/DockLayoutSelftest.h"
+
+#include <cstdio>
+
+#include <QByteArray>
+#include <QList>
+#include <QRegularExpression>
+#include <QString>
+#include <QStringList>
+#include <QTextStream>
+#include <QWidget>
+
+#include <DockAreaWidget.h>
+#include <DockManager.h>
+#include <DockWidget.h>
+
+namespace fincept::layout {
+
+namespace {
+
+QTextStream& out() {
+ static QTextStream s(stdout);
+ return s;
+}
+
+// Count <Area> elements and how many of them hold >1 <Widget> (i.e. a tab
+// group). saveState() emits XML by default for our config.
+struct LayoutShape {
+ int areas = 0;
+ int tab_groups = 0; // areas with >= 2 widgets
+ int widget_areas = 0; // total single-widget areas
+ QStringList tabbed_sets; // human-readable widget lists for each tab group
+ QStringList single_names; // widget name of each single-widget area
+};
+
+LayoutShape analyze(const QByteArray& state) {
+ LayoutShape shape;
+ // ADS saveState() qCompress()es the XML by default (XmlCompressionEnabled),
+ // exactly as it lands in QSettings. Mirror restoreState's own check.
+ const QByteArray raw = state.startsWith("<?xml") ? state : qUncompress(state);
+ QString xml = QString::fromUtf8(raw);
+ static const QRegularExpression area_re(QStringLiteral("<Area\\b[^>]*>(.*?)</Area>"),
+ QRegularExpression::DotMatchesEverythingOption);
+ static const QRegularExpression widget_re(QStringLiteral("<Widget\\s+Name=\"([^\"]+)\""));
+ auto it = area_re.globalMatch(xml);
+ while (it.hasNext()) {
+ auto m = it.next();
+ const QString body = m.captured(1);
+ QStringList names;
+ auto wit = widget_re.globalMatch(body);
+ while (wit.hasNext())
+ names << wit.next().captured(1);
+ shape.areas++;
+ if (names.size() >= 2) {
+ shape.tab_groups++;
+ shape.tabbed_sets << names.join('+');
+ } else if (names.size() == 1) {
+ shape.widget_areas++;
+ shape.single_names << names.first();
+ }
+ }
+ return shape;
+}
+
+ads::CDockWidget* make_widget(ads::CDockManager* mgr, const QString& id) {
+ auto* dw = new ads::CDockWidget(mgr, id);
+ dw->setObjectName(id);
+ dw->setWidget(new QWidget);
+ return dw;
+}
+
+// All screen ids the real app registers via ensure_all_registered(). The bug
+// is sensitive to the parking-area population, so we mirror a realistic set.
+const QStringList& all_ids() {
+ static const QStringList ids = {
+ "dashboard", "markets", "portfolio", "news", "report_builder",
+ "settings", "profile", "about", "support", "fno",
+ "watchlist", "forum", "economics", "ai_chat", "crypto_trading",
+ "equity_trading", "backtesting", "algo_trading", "node_editor", "code_editor"};
+ return ids;
+}
+
+} // namespace
+
+int run_dock_layout_selftest() {
+ // Unbuffered stdout so progress survives an abnormal exit mid-case.
+ setvbuf(stdout, nullptr, _IONBF, 0);
+ int failures = 0;
+ auto check = [&](bool cond, const QString& msg) {
+ out() << (cond ? " PASS " : " FAIL ") << msg << "\n";
+ out().flush();
+ if (!cond)
+ failures++;
+ };
+
+ out() << "=== Dock layout persistence self-test ===\n\n";
+
+ // ── Case 1: raw ADS — can a tab group even be saved as a tab group? ───────
+ QByteArray tabbed_blob;
+ {
+ QWidget host;
+ auto* mgr = new ads::CDockManager(&host);
+ auto* area = mgr->addDockWidget(ads::CenterDockWidgetArea, make_widget(mgr, "settings"));
+ mgr->addDockWidget(ads::CenterDockWidgetArea, make_widget(mgr, "fno"), area);
+ tabbed_blob = mgr->saveState();
+ LayoutShape s = analyze(tabbed_blob);
+ out() << "[1] raw tab group save: areas=" << s.areas << " tab_groups=" << s.tab_groups
+ << " sets=[" << s.tabbed_sets.join(", ") << "]\n";
+ check(s.tab_groups == 1 && s.tabbed_sets.contains("settings+fno"),
+ "settings+fno saves as ONE tabbed area");
+ }
+
+ // ── Case 2: parking-area + restore (the ensure_all_registered path) ───────
+ // Reproduces the real restore sequence: pre-create EVERY screen tabbed into
+ // one parking area (all hidden), then restoreState() the tabbed blob, then
+ // saveState() again. Asserts the tab group survives and no phantom closed
+ // single-widget areas leak into the re-saved blob.
+ {
+ QWidget host;
+ auto* mgr = new ads::CDockManager(&host);
+ ads::CDockAreaWidget* park = nullptr;
+ for (const QString& id : all_ids()) {
+ auto* dw = make_widget(mgr, id);
+ if (park)
+ mgr->addDockWidget(ads::CenterDockWidgetArea, dw, park);
+ else
+ park = mgr->addDockWidget(ads::CenterDockWidgetArea, dw);
+ dw->toggleView(false);
+ }
+ const bool restored = mgr->restoreState(tabbed_blob);
+ QByteArray re_saved = mgr->saveState();
+ LayoutShape s = analyze(re_saved);
+ out() << "\n[2] parking-area + restore + re-save: restored=" << restored
+ << " areas=" << s.areas << " tab_groups=" << s.tab_groups
+ << " single_areas=" << s.widget_areas << " sets=[" << s.tabbed_sets.join(", ")
+ << "]\n";
+ check(restored, "restoreState() succeeds");
+ check(s.tab_groups == 1 && s.tabbed_sets.contains("settings+fno"),
+ "settings+fno SURVIVES round-trip as a tab group");
+ check(s.widget_areas == 0,
+ "no phantom closed single-widget areas leak into re-saved blob");
+ }
+
+ // ── Case 3: the real bug — closed panels accumulate as phantom areas, and ─
+ // prune_hidden_panels() restores a clean, faithfully-saved grid.
+ // This mirrors the live state the app builds: a visible left|right grid
+ // (fno | equity_trading) plus a pile of closed single-widget areas left
+ // behind by earlier navigate/close cycles. We assert the bug exists before
+ // pruning, then that the inline prune (identical to
+ // DockScreenRouter::prune_hidden_panels — removeDockWidget on every closed
+ // widget) yields a blob containing ONLY the visible grid.
+ {
+ QWidget host;
+ auto* mgr = new ads::CDockManager(&host);
+ // Visible grid: fno (left) | equity_trading (right) — retile n==2 shape.
+ auto* left = mgr->addDockWidget(ads::CenterDockWidgetArea, make_widget(mgr, "fno"));
+ mgr->addDockWidget(ads::RightDockWidgetArea, make_widget(mgr, "equity_trading"), left);
+ // Phantom build-up: every other screen opened-then-closed over time,
+ // each stranded in its own area.
+ for (const QString& id : all_ids()) {
+ if (id == "fno" || id == "equity_trading")
+ continue;
+ auto* dw = make_widget(mgr, id);
+ mgr->addDockWidget(ads::BottomDockWidgetArea, dw);
+ dw->toggleView(false);
+ }
+
+ LayoutShape before = analyze(mgr->saveState());
+ out() << "\n[3] accumulated state: areas=" << before.areas
+ << " visible_grid=2 phantom_closed=" << (before.widget_areas - 2) << "\n";
+ check(before.widget_areas > 2, "BUG reproduced: phantom closed areas pollute the save");
+
+ // --- the fix: prune every closed dock widget (mirror of the method) ---
+ QList<ads::CDockWidget*> closed;
+ for (auto* dw : mgr->dockWidgetsMap())
+ if (dw && dw->isClosed())
+ closed.append(dw);
+ for (auto* dw : closed)
+ mgr->removeDockWidget(dw);
+
+ LayoutShape after = analyze(mgr->saveState());
+ out() << " after prune: areas=" << after.areas << " single=[" << after.single_names.join(", ")
+ << "]\n";
+ check(after.areas == 2 && after.widget_areas == 2,
+ "after prune: saved blob holds ONLY the 2 visible panels");
+ check(after.single_names.contains("fno") && after.single_names.contains("equity_trading"),
+ "after prune: the fno | equity_trading grid is preserved");
+ check(!after.single_names.contains("dashboard") && !after.single_names.contains("markets"),
+ "after prune: no phantom closed panels remain in the blob");
+ }
+
+ // Build the parking area (ensure_all_registered) then restore `blob` and
+ // re-save — the exact app restore path. Returns the re-saved blob.
+ // Stack host → the manager is a child and is destroyed at scope exit while
+ // QApplication is still alive (a static/deleteLater'd manager would be torn
+ // down at program exit after QApplication is gone → segfault).
+ auto parking_restore_resave = [](const QByteArray& blob) -> QByteArray {
+ QWidget host;
+ auto* mgr = new ads::CDockManager(&host);
+ ads::CDockAreaWidget* park = nullptr;
+ for (const QString& id : all_ids()) {
+ auto* dw = make_widget(mgr, id);
+ if (park)
+ mgr->addDockWidget(ads::CenterDockWidgetArea, dw, park);
+ else
+ park = mgr->addDockWidget(ads::CenterDockWidgetArea, dw);
+ dw->toggleView(false);
+ }
+ mgr->restoreState(blob);
+ return mgr->saveState(); // host (and its child mgr) destroyed after the copy
+ };
+
+ // ── Case 4: the 2x2 quad grid round-trips with no phantom leakage ─────────
+ {
+ QWidget host;
+ auto* mgr = new ads::CDockManager(&host);
+ // Mirror retile_grid's n==4 sequence exactly.
+ auto* tl = mgr->addDockWidget(ads::CenterDockWidgetArea, make_widget(mgr, "fno"));
+ mgr->addDockWidget(ads::RightDockWidgetArea, make_widget(mgr, "equity_trading"), tl);
+ auto* bl = mgr->addDockWidget(ads::BottomDockWidgetArea, make_widget(mgr, "markets"), tl);
+ mgr->addDockWidget(ads::RightDockWidgetArea, make_widget(mgr, "news"), bl);
+
+ LayoutShape rt = analyze(parking_restore_resave(mgr->saveState()));
+ out() << "\n[4] 2x2 grid round-trip: areas=" << rt.areas << " single=[" << rt.single_names.join(", ")
+ << "]\n";
+ const QStringList want = {"fno", "equity_trading", "markets", "news"};
+ bool all_present = true;
+ for (const QString& w : want)
+ all_present = all_present && rt.single_names.contains(w);
+ check(rt.areas == 4 && rt.widget_areas == 4, "4-panel grid restores as exactly 4 areas");
+ check(all_present, "all four panels survive the round-trip");
+ }
+
+ // ── Case 5: a floating (torn-off) panel survives the round-trip ───────────
+ {
+ QWidget host;
+ auto* mgr = new ads::CDockManager(&host);
+ mgr->addDockWidget(ads::CenterDockWidgetArea, make_widget(mgr, "fno"));
+ mgr->addDockWidgetFloating(make_widget(mgr, "equity_trading"));
+
+ QByteArray rt = parking_restore_resave(mgr->saveState());
+ LayoutShape s = analyze(rt);
+ const QString xml = QString::fromUtf8(rt.startsWith("<?xml") ? rt : qUncompress(rt));
+ const int containers = static_cast<int>(xml.count("<Container "));
+ out() << "\n[5] floating panel round-trip: containers=" << containers << " areas=" << s.areas
+ << " single=[" << s.single_names.join(", ") << "]\n";
+ check(containers >= 2, "floating panel restores as its own (2nd) container");
+ check(s.single_names.contains("fno") && s.single_names.contains("equity_trading"),
+ "both docked and floating panels survive");
+ }
+
+ out() << "\n=== " << (failures == 0 ? "ALL PASS" : QString("%1 FAILURE(S)").arg(failures))
+ << " ===\n";
+ out().flush();
+ return failures == 0 ? 0 : 1;
+}
+
+} // namespace fincept::layout
diff --git a/fincept-qt/src/core/layout/DockLayoutSelftest.h b/fincept-qt/src/core/layout/DockLayoutSelftest.h
new file mode 100644
index 000000000..15a198dfd
--- /dev/null
+++ b/fincept-qt/src/core/layout/DockLayoutSelftest.h
@@ -0,0 +1,16 @@
+#pragma once
+
+namespace fincept::layout {
+
+// Headless reproduction harness for the dock-layout persistence bug.
+//
+// Reproduces the "tabbed panels come back split, plus phantom closed areas
+// accumulate" corruption deterministically without a GUI, using raw ADS
+// against the real save/restore code paths. Run with:
+//
+// QT_QPA_PLATFORM=offscreen ./FinceptTerminal --selftest-dock-layout
+//
+// Exits 0 if every arrangement round-trips faithfully, 1 if any case fails.
+int run_dock_layout_selftest();
+
+} // namespace fincept::layout
diff --git a/fincept-qt/src/core/market/MarketHours.h b/fincept-qt/src/core/market/MarketHours.h
new file mode 100644
index 000000000..e176c9d8f
--- /dev/null
+++ b/fincept-qt/src/core/market/MarketHours.h
@@ -0,0 +1,29 @@
+#pragma once
+// MarketHours — lightweight NSE session clock.
+//
+// Header-only so it can be used from any layer without a CMake/unity entry.
+// v1 covers only the regular cash + F&O session window by weekday + clock;
+// there is NO holiday calendar yet, so NSE trading holidays read as "open"
+// and callers gracefully fall through to their REST/fallback path (a stale
+// snapshot, not a crash). Add a holiday source here when one is maintained.
+
+#include <QDateTime>
+#include <QTime>
+
+namespace fincept::core::market {
+
+// True during the NSE regular equity/F&O session: Mon–Fri, 09:15–15:30 IST.
+// IST is derived by shifting the UTC instant by +5:30 (no tz database needed),
+// matching the existing DataStreamManager token-expiry convention.
+inline bool nse_fo_market_open() {
+ const QDateTime ist = QDateTime::currentDateTimeUtc().addSecs((5 * 3600) + (30 * 60));
+ const int dow = ist.date().dayOfWeek(); // 1=Mon … 7=Sun
+ if (dow == 6 || dow == 7)
+ return false;
+ const QTime t = ist.time();
+ static const QTime kOpen(9, 15, 0);
+ static const QTime kClose(15, 30, 0);
+ return t >= kOpen && t <= kClose;
+}
+
+} // namespace fincept::core::market
diff --git a/fincept-qt/src/core/session/ScreenStateManager.cpp b/fincept-qt/src/core/session/ScreenStateManager.cpp
index 3e7bb6b53..43594ecd7 100644
--- a/fincept-qt/src/core/session/ScreenStateManager.cpp
+++ b/fincept-qt/src/core/session/ScreenStateManager.cpp
@@ -197,6 +197,44 @@ void ScreenStateManager::write_async_by_uuid(const QString& instance_uuid,
});
}
+// ── Synchronous saves (shutdown only) ────────────────────────────────────────
+
+namespace {
+QJsonObject to_json_obj(const QVariantMap& state) {
+ QJsonObject obj;
+ for (auto it = state.constBegin(); it != state.constEnd(); ++it)
+ obj.insert(it.key(), QJsonValue::fromVariant(it.value()));
+ return obj;
+}
+} // namespace
+
+void ScreenStateManager::save_now_sync(screens::IStatefulScreen* screen) {
+ if (!screen)
+ return;
+ screen->flush_pending_state();
+ const QString key = screen->state_key();
+ pending_saves_.remove(key);
+ auto r = TabSessionStore::instance().save_screen_state(
+ key, to_json_obj(screen->save_state()), screen->state_version(), session_id_);
+ if (r.is_err())
+ LOG_WARN("ScreenState", "save_now_sync failed for '" + key + "': " + QString::fromStdString(r.error()));
+}
+
+void ScreenStateManager::save_now_by_uuid_sync(screens::IStatefulScreen* screen,
+ const QString& instance_uuid) {
+ if (!screen || instance_uuid.isEmpty())
+ return;
+ screen->flush_pending_state();
+ const QString screen_key = screen->state_key();
+ pending_uuid_saves_.remove(instance_uuid);
+ auto r = TabSessionStore::instance().save_screen_state_by_uuid(
+ instance_uuid, screen_key, to_json_obj(screen->save_state()), screen->state_version(),
+ session_id_);
+ if (r.is_err())
+ LOG_WARN("ScreenState", QString("save_now_by_uuid_sync failed for %1 (%2): %3")
+ .arg(instance_uuid, screen_key, QString::fromStdString(r.error())));
+}
+
// ── UUID-keyed public API ────────────────────────────────────────────────────
void ScreenStateManager::restore_by_uuid(screens::IStatefulScreen* screen,
diff --git a/fincept-qt/src/core/session/ScreenStateManager.h b/fincept-qt/src/core/session/ScreenStateManager.h
index cf5ba264d..4fca15d8c 100644
--- a/fincept-qt/src/core/session/ScreenStateManager.h
+++ b/fincept-qt/src/core/session/ScreenStateManager.h
@@ -87,6 +87,17 @@ class ScreenStateManager : public QObject {
/// closes permanently (vs. temporary dematerialisation).
void erase_by_uuid(const QString& instance_uuid);
+ // ── Synchronous saves for shutdown ───────────────────────────────────────
+ //
+ // save_now*/notify_changed* dispatch the SQLite write via QtConcurrent so
+ // the UI thread never blocks. That's correct at runtime but WRONG on quit:
+ // panels visible at close never receive visibilityChanged(false), and an
+ // async write fired from closeEvent races process exit and is usually lost.
+ // These variants write on the CALLING thread (blocking, no QtConcurrent) so
+ // the row is on disk before the app exits. Use ONLY from shutdown paths.
+ void save_now_sync(screens::IStatefulScreen* screen);
+ void save_now_by_uuid_sync(screens::IStatefulScreen* screen, const QString& instance_uuid);
+
private:
explicit ScreenStateManager(QObject* parent = nullptr);
diff --git a/fincept-qt/src/screens/ai_chat/AiChatBubble.cpp b/fincept-qt/src/screens/ai_chat/AiChatBubble.cpp
index 501275ea0..bf5830b30 100644
--- a/fincept-qt/src/screens/ai_chat/AiChatBubble.cpp
+++ b/fincept-qt/src/screens/ai_chat/AiChatBubble.cpp
@@ -538,7 +538,11 @@ void AiChatBubble::on_send() {
[self, chunk, done, first_chunk]() {
if (!self)
return;
- if (*first_chunk && !chunk.isEmpty()) {
+ // A leading reasoning chunk (think_stream_prefix) shouldn't
+ // spawn the answer bubble — the floating bubble omits
+ // chain-of-thought entirely.
+ if (*first_chunk && !chunk.isEmpty() &&
+ !chunk.startsWith(ai_chat::think_stream_prefix())) {
*first_chunk = false;
self->streaming_bubble_ = self->add_streaming_bubble();
}
@@ -550,6 +554,11 @@ void AiChatBubble::on_send() {
}
void AiChatBubble::on_stream_chunk(const QString& chunk, bool done) {
+ Q_UNUSED(done)
+ // The compact floating bubble doesn't surface chain-of-thought — drop
+ // reasoning chunks so the sentinel never leaks into the visible text.
+ if (chunk.startsWith(ai_chat::think_stream_prefix()))
+ return;
QLabel* bubble = streaming_bubble_;
if (!bubble)
return;
@@ -557,7 +566,6 @@ void AiChatBubble::on_stream_chunk(const QString& chunk, bool done) {
fincept::ai_chat::ChatBubbleFactory::append_streaming_chunk(bubble, chunk);
scroll_to_bottom();
}
- Q_UNUSED(done)
}
void AiChatBubble::on_streaming_done(ai_chat::LlmResponse response) {
diff --git a/fincept-qt/src/screens/ai_chat/AiChatScreen.h b/fincept-qt/src/screens/ai_chat/AiChatScreen.h
index 878b50f6d..98ad3a1f0 100644
--- a/fincept-qt/src/screens/ai_chat/AiChatScreen.h
+++ b/fincept-qt/src/screens/ai_chat/AiChatScreen.h
@@ -128,6 +128,15 @@ class AiChatScreen : public QWidget, public IStatefulScreen, public fincept::IGr
int total_tokens_ = 0;
int total_messages_ = 0;
+ // ── Per-stream "Thinking" (chain-of-thought) section ─────────────────────
+ // Reasoning models stream their thoughts on a separate channel (see
+ // think_stream_prefix()). We collect them into a collapsible card inserted
+ // ABOVE the answer bubble so the answer stays clean. Reset between messages.
+ QPointer<QWidget> thinking_card_;
+ QPointer<QPushButton> thinking_header_;
+ QPointer<QLabel> thinking_body_;
+ QString thinking_text_;
+
// ── Build ────────────────────────────────────────────────────────────
void build_ui();
void retranslateUi();
@@ -145,6 +154,11 @@ class AiChatScreen : public QWidget, public IStatefulScreen, public fincept::IGr
void create_new_session();
void add_message_bubble(const QString& role, const QString& content, const QString& timestamp = {});
QLabel* add_streaming_bubble();
+ // Collapsible "Thinking" card for the in-flight assistant message.
+ void append_thinking_chunk(const QString& text);
+ void create_thinking_card();
+ void finalize_thinking_card();
+ void reset_thinking_state();
void clear_messages();
void scroll_to_bottom();
void set_input_enabled(bool enabled);
diff --git a/fincept-qt/src/screens/ai_chat/AiChatScreen_Messaging.cpp b/fincept-qt/src/screens/ai_chat/AiChatScreen_Messaging.cpp
index 451ac8d26..d89e41a5f 100644
--- a/fincept-qt/src/screens/ai_chat/AiChatScreen_Messaging.cpp
+++ b/fincept-qt/src/screens/ai_chat/AiChatScreen_Messaging.cpp
@@ -157,6 +157,10 @@ void AiChatScreen::on_send() {
show_typing(true);
scroll_to_bottom();
+ // Fresh Thinking section for this message (reasoning chunks land in a
+ // collapsible card created lazily by on_stream_chunk).
+ reset_thinking_state();
+
std::vector<ai_chat::ConversationMessage> hist_copy = history_;
const QString provider = ai_chat::LlmService::instance().active_provider();
if (ai_chat::provider_supports_streaming(provider)) {
@@ -169,12 +173,13 @@ void AiChatScreen::on_send() {
[self, chunk, done, first_chunk]() {
if (!self)
return;
- // On first chunk: hide typing indicator, show streaming bubble
+ // On first chunk: hide the typing indicator. The answer
+ // bubble and Thinking card are created lazily inside
+ // on_stream_chunk so a leading reasoning chunk doesn't
+ // spawn an empty answer bubble above the card.
if (*first_chunk && !chunk.isEmpty()) {
*first_chunk = false;
self->show_typing(false);
- self->streaming_bubble_ = self->add_streaming_bubble();
- self->scroll_to_bottom();
}
self->on_stream_chunk(chunk, done);
},
@@ -198,29 +203,45 @@ void AiChatScreen::on_send() {
}
void AiChatScreen::on_stream_chunk(const QString& chunk, bool done) {
- // Snapshot QPointer to local — prevents TOCTOU between null-check and use.
- QLabel* bubble = streaming_bubble_;
- if (!bubble)
- return;
+ Q_UNUSED(done)
- // Tool-call clear sentinel: reset bubble content (removes partial XML)
- if (chunk.startsWith("\x01__TOOL_CALL_CLEAR__")) {
- fincept::ai_chat::ChatBubbleFactory::replace_streaming_text(bubble, tr("Calling tool..."));
+ // Chain-of-thought chunk → separate, collapsible Thinking section (kept out
+ // of the answer bubble). Routed in-band via the think_stream_prefix sentinel.
+ const QString think_prefix = ai_chat::think_stream_prefix();
+ if (chunk.startsWith(think_prefix)) {
+ append_thinking_chunk(chunk.mid(think_prefix.size()));
scroll_to_bottom();
return;
}
- if (!chunk.isEmpty()) {
- fincept::ai_chat::ChatBubbleFactory::append_streaming_chunk(bubble, chunk);
+ // Tool-call clear sentinel: reset bubble content (removes partial XML).
+ if (chunk.startsWith("\x01__TOOL_CALL_CLEAR__")) {
+ if (!streaming_bubble_)
+ streaming_bubble_ = add_streaming_bubble();
+ fincept::ai_chat::ChatBubbleFactory::replace_streaming_text(streaming_bubble_, tr("Calling tool..."));
scroll_to_bottom();
+ return;
}
- Q_UNUSED(done)
+
+ if (chunk.isEmpty())
+ return;
+
+ // Lazily create the answer bubble on the first real answer chunk so it lands
+ // below any Thinking card that arrived first.
+ if (!streaming_bubble_)
+ streaming_bubble_ = add_streaming_bubble();
+ fincept::ai_chat::ChatBubbleFactory::append_streaming_chunk(streaming_bubble_, chunk);
+ scroll_to_bottom();
}
void AiChatScreen::on_streaming_done(ai_chat::LlmResponse response) {
streaming_ = false;
show_typing(false);
+ // Lock in the Thinking card (swap the live "Thinking…" header for its final
+ // label) and stop tracking it so the next message starts a fresh one.
+ finalize_thinking_card();
+
// Ensure a bubble exists for any terminal state (success + content,
// failure with an error message, or success-but-empty). Without this,
// a kimi/openai response that arrives via the non-streaming fallback
@@ -314,10 +335,96 @@ QLabel* AiChatScreen::add_streaming_bubble() {
return b.body;
}
+// ── Thinking (chain-of-thought) card ────────────────────────────────────────────
+// Reasoning models stream their thoughts on a separate channel (see
+// think_stream_prefix()). We collect them into a collapsed dropdown shown ABOVE
+// the answer bubble so the answer itself stays clean and unmixed.
+
+void AiChatScreen::create_thinking_card() {
+ if (thinking_card_)
+ return;
+
+ auto* card = new QWidget;
+ card->setMaximumWidth(kAiColMaxWidth);
+ card->setStyleSheet(QString("background:%1;border:1px solid %2;").arg(col::BG_SURFACE(), col::BORDER_DIM()));
+ auto* vl = new QVBoxLayout(card);
+ vl->setContentsMargins(10, 6, 10, 6);
+ vl->setSpacing(4);
+
+ // Collapsed by default — header toggles the body. The leading chevron (▸/▾)
+ // reflects expanded state; the body holds the dimmed, selectable reasoning.
+ auto* header = new QPushButton(QChar(0x25B8) + (QStringLiteral(" ") + QString::fromUtf8("\xF0\x9F\x92\xAD") + QStringLiteral(" ")) + tr("Thinking…"));
+ header->setCursor(Qt::PointingHandCursor);
+ header->setStyleSheet(QString("QPushButton{background:transparent;color:%1;border:none;"
+ "font-size:%2px;font-weight:600;text-align:left;padding:0;}"
+ "QPushButton:hover{color:%3;}")
+ .arg(col::TEXT_TERTIARY())
+ .arg(fnt::SMALL)
+ .arg(col::TEXT_SECONDARY()));
+ vl->addWidget(header);
+
+ auto* body = new QLabel;
+ body->setWordWrap(true);
+ body->setTextInteractionFlags(Qt::TextSelectableByMouse);
+ body->setVisible(false);
+ body->setStyleSheet(QString("QLabel{color:%1;font-size:%2px;font-style:italic;background:transparent;}")
+ .arg(col::TEXT_DIM())
+ .arg(fnt::SMALL));
+ vl->addWidget(body);
+
+ // Capture raw pointers (not the QPointer members, which get nulled when the
+ // stream finishes) so the finished card stays toggleable.
+ QObject::connect(header, &QPushButton::clicked, card, [header, body]() {
+ const bool show = !body->isVisible();
+ body->setVisible(show);
+ QString t = header->text();
+ if (!t.isEmpty())
+ t.replace(0, 1, show ? QChar(0x25BE) : QChar(0x25B8));
+ header->setText(t);
+ });
+
+ // Insert just before the trailing stretch so it sits above the answer bubble
+ // (which is created lazily on the first answer chunk and lands below it).
+ messages_layout_->insertWidget(messages_layout_->count() - 1, card, 0, Qt::AlignLeft);
+ thinking_card_ = card;
+ thinking_header_ = header;
+ thinking_body_ = body;
+}
+
+void AiChatScreen::append_thinking_chunk(const QString& text) {
+ if (text.isEmpty())
+ return;
+ show_typing(false); // the card now signals activity
+ if (!thinking_card_)
+ create_thinking_card();
+ thinking_text_ += text;
+ if (thinking_body_)
+ thinking_body_->setText(thinking_text_);
+}
+
+void AiChatScreen::finalize_thinking_card() {
+ if (thinking_header_) {
+ const bool expanded = thinking_body_ && thinking_body_->isVisible();
+ const QChar chev = expanded ? QChar(0x25BE) : QChar(0x25B8);
+ thinking_header_->setText(chev + (QStringLiteral(" ") + QString::fromUtf8("\xF0\x9F\x92\xAD") + QStringLiteral(" ")) + tr("Thoughts"));
+ }
+ reset_thinking_state();
+}
+
+void AiChatScreen::reset_thinking_state() {
+ // Stops tracking the current card (the widget itself remains in the
+ // transcript); the next message creates a fresh one.
+ thinking_card_ = nullptr;
+ thinking_header_ = nullptr;
+ thinking_body_ = nullptr;
+ thinking_text_.clear();
+}
+
// ── Helpers ───────────────────────────────────────────────────────────────────
void AiChatScreen::clear_messages() {
streaming_bubble_.clear();
+ reset_thinking_state(); // card widgets are deleted by the loop below
while (messages_layout_->count() > 1) {
QLayoutItem* item = messages_layout_->takeAt(0);
if (item->widget())
diff --git a/fincept-qt/src/screens/algo_trading/AlgoTradingScreen.cpp b/fincept-qt/src/screens/algo_trading/AlgoTradingScreen.cpp
index 3f330deec..ac06d0270 100644
--- a/fincept-qt/src/screens/algo_trading/AlgoTradingScreen.cpp
+++ b/fincept-qt/src/screens/algo_trading/AlgoTradingScreen.cpp
@@ -9,6 +9,7 @@
#include "screens/algo_trading/ScannerPanel.h"
#include "screens/algo_trading/StrategyBuilderPanel.h"
#include "screens/algo_trading/StrategyListPanel.h"
+#include "screens/algo_trading/UniverseScannerPanel.h"
#include "services/algo_trading/AlgoTradingService.h"
#include "ui/theme/Theme.h"
@@ -71,12 +72,14 @@ void AlgoTradingScreen::build_ui() {
scanner_ = new ScannerPanel(this);
alerts_ = new AlertsPanel(this);
dashboard_ = new DeploymentDashboard(this);
+ universe_ = new UniverseScannerPanel(this);
content_stack_->addWidget(builder_); // 0
content_stack_->addWidget(strategies_); // 1
content_stack_->addWidget(scanner_); // 2
content_stack_->addWidget(alerts_); // 3
content_stack_->addWidget(dashboard_); // 4
+ content_stack_->addWidget(universe_); // 5
root->addWidget(content_stack_, 1);
// "Edit" in My Strategies opens the Builder (tab 0) pre-filled with that strategy.
@@ -133,8 +136,8 @@ QWidget* AlgoTradingScreen::build_top_bar() {
hl->addWidget(div);
// Tab buttons
- QStringList tabs = {tr("BUILDER"), tr("MY STRATEGIES"), tr("SCANNER"), tr("ALERTS"), tr("DASHBOARD")};
- QStringList colors = {"#FF6B35", "#00E5FF", "#FFC400", "#FF4081", "#00D66F"};
+ QStringList tabs = {tr("BUILDER"), tr("MY STRATEGIES"), tr("SCANNER"), tr("ALERTS"), tr("DASHBOARD"), tr("UNIVERSE")};
+ QStringList colors = {"#FF6B35", "#00E5FF", "#FFC400", "#FF4081", "#00D66F", "#A78BFA"};
for (int i = 0; i < tabs.size(); ++i) {
auto* btn = new QPushButton(tabs[i], bar);
@@ -208,7 +211,7 @@ void AlgoTradingScreen::on_tab_changed(int index) {
}
void AlgoTradingScreen::update_tab_buttons() {
- QStringList colors = {"#FF6B35", "#00E5FF", "#FFC400", "#FF4081", "#00D66F"};
+ QStringList colors = {"#FF6B35", "#00E5FF", "#FFC400", "#FF4081", "#00D66F", "#A78BFA"};
for (int i = 0; i < tab_buttons_.size(); ++i) {
bool active = (i == active_tab_);
tab_buttons_[i]->setStyleSheet(
@@ -241,12 +244,13 @@ void AlgoTradingScreen::retranslateUi() {
if (deploy_count_label_) deploy_count_label_->setText(tr("%1 LIVE").arg(active_deployments_));
// Tab button labels — fixed order matches build_top_bar().
- if (tab_buttons_.size() == 5) {
+ if (tab_buttons_.size() == 6) {
tab_buttons_[0]->setText(tr("BUILDER"));
tab_buttons_[1]->setText(tr("MY STRATEGIES"));
tab_buttons_[2]->setText(tr("SCANNER"));
tab_buttons_[3]->setText(tr("ALERTS"));
tab_buttons_[4]->setText(tr("DASHBOARD"));
+ tab_buttons_[5]->setText(tr("UNIVERSE"));
}
}
diff --git a/fincept-qt/src/screens/algo_trading/AlgoTradingScreen.h b/fincept-qt/src/screens/algo_trading/AlgoTradingScreen.h
index b01351a97..4721fffba 100644
--- a/fincept-qt/src/screens/algo_trading/AlgoTradingScreen.h
+++ b/fincept-qt/src/screens/algo_trading/AlgoTradingScreen.h
@@ -19,9 +19,10 @@ class StrategyBuilderPanel;
class StrategyListPanel;
class ScannerPanel;
class DeploymentDashboard;
+class UniverseScannerPanel;
-/// Algo Trading screen — 5-tab trading system builder.
-/// Tabs: Builder, My Strategies, Scanner, Alerts, Dashboard
+/// Algo Trading screen — 6-tab trading system builder.
+/// Tabs: Builder, My Strategies, Scanner, Alerts, Dashboard, Universe
class AlgoTradingScreen : public QWidget, public IStatefulScreen {
Q_OBJECT
public:
@@ -53,6 +54,7 @@ class AlgoTradingScreen : public QWidget, public IStatefulScreen {
ScannerPanel* scanner_ = nullptr;
AlertsPanel* alerts_ = nullptr;
DeploymentDashboard* dashboard_ = nullptr;
+ UniverseScannerPanel* universe_ = nullptr;
QVector<QPushButton*> tab_buttons_;
int active_tab_ = 0;
diff --git a/fincept-qt/src/screens/algo_trading/UniverseScannerPanel.cpp b/fincept-qt/src/screens/algo_trading/UniverseScannerPanel.cpp
new file mode 100644
index 000000000..48d9d292a
--- /dev/null
+++ b/fincept-qt/src/screens/algo_trading/UniverseScannerPanel.cpp
@@ -0,0 +1,390 @@
+// src/screens/algo_trading/UniverseScannerPanel.cpp
+#include "screens/algo_trading/UniverseScannerPanel.h"
+
+#include "algo_engine/AlgoEngine.h"
+#include "algo_engine/ScanMonitor.h"
+#include "core/logging/Logger.h"
+#include "screens/algo_trading/AlgoDeployDialog.h"
+#include "services/algo_trading/AlgoTradingService.h"
+#include "storage/repositories/ScanWatchRepository.h"
+#include "trading/AccountManager.h"
+#include "ui/theme/Theme.h"
+
+#include <QHBoxLayout>
+#include <QHeaderView>
+#include <QJsonObject>
+#include <QScrollArea>
+#include <QVBoxLayout>
+
+namespace fincept::screens {
+
+using namespace fincept::services::algo;
+
+namespace {
+QString uMono() { return QString("font-family: %1;").arg(fincept::ui::fonts::DATA_FAMILY); }
+QString uLabel() {
+ return QString("color: %1; font-size: %2px; font-weight: 700; letter-spacing: 0.5px; %3"
+ " background: transparent; border: none;")
+ .arg(fincept::ui::colors::TEXT_SECONDARY())
+ .arg(fincept::ui::fonts::TINY)
+ .arg(uMono());
+}
+QString uCombo() {
+ return QString("QComboBox { background: %1; color: %2; border: 1px solid %3; padding: 4px 8px;"
+ " font-size: %4px; %5 }"
+ "QComboBox QAbstractItemView { background: %1; color: %2; border: 1px solid %3;"
+ " selection-background-color: %6; %5 }")
+ .arg(fincept::ui::colors::BG_SURFACE(), fincept::ui::colors::TEXT_PRIMARY(),
+ fincept::ui::colors::BORDER_DIM())
+ .arg(fincept::ui::fonts::SMALL)
+ .arg(uMono())
+ .arg(fincept::ui::colors::BG_HOVER());
+}
+} // namespace
+
+UniverseScannerPanel::UniverseScannerPanel(QWidget* parent) : QWidget(parent) {
+ build_ui();
+
+ connect(&AlgoTradingService::instance(), &AlgoTradingService::strategies_loaded,
+ this, &UniverseScannerPanel::on_strategies_loaded);
+ connect(&fincept::algo::ScanMonitor::instance(), &fincept::algo::ScanMonitor::realtime_match,
+ this, &UniverseScannerPanel::on_match);
+
+ // Purge orphaned realtime watches left over from a prior session. ScanMonitor
+ // intentionally skips mode=='realtime' watches at launch (they are started on
+ // demand here), so any active realtime row is a stale leftover that would
+ // otherwise accumulate silently.
+ if (auto active = fincept::ScanWatchRepository::instance().list_active(); active.is_ok())
+ for (const auto& w : active.value())
+ if (w.mode == QStringLiteral("realtime"))
+ fincept::ScanWatchRepository::instance().remove(w.id);
+
+ AlgoTradingService::instance().list_strategies();
+ LOG_INFO("AlgoTrading", "UniverseScannerPanel constructed");
+}
+
+void UniverseScannerPanel::build_ui() {
+ auto* root = new QVBoxLayout(this);
+ root->setContentsMargins(0, 0, 0, 0);
+ root->setSpacing(0);
+
+ auto* scroll = new QScrollArea(this);
+ scroll->setWidgetResizable(true);
+ scroll->setFrameShape(QFrame::NoFrame);
+
+ auto* content = new QWidget(this);
+ content->setStyleSheet(QString("background: %1;").arg(fincept::ui::colors::BG_BASE()));
+ auto* vl = new QVBoxLayout(content);
+ vl->setContentsMargins(16, 12, 16, 12);
+ vl->setSpacing(8);
+
+ // Strategy picker
+ auto* strat_lbl = new QLabel(tr("STRATEGY"), content);
+ strat_lbl->setStyleSheet(uLabel());
+ vl->addWidget(strat_lbl);
+ strategy_combo_ = new QComboBox(content);
+ strategy_combo_->setStyleSheet(uCombo());
+ strategy_combo_->setFixedHeight(30);
+ vl->addWidget(strategy_combo_);
+
+ // Universe selector
+ auto* uni_lbl = new QLabel(tr("UNIVERSE"), content);
+ uni_lbl->setStyleSheet(uLabel());
+ vl->addWidget(uni_lbl);
+ universe_combo_ = new QComboBox(content);
+ universe_combo_->setStyleSheet(uCombo());
+ universe_combo_->setFixedHeight(30);
+ universe_combo_->addItem(tr("All NSE Equity"), "NSE_EQ");
+ universe_combo_->addItem(tr("All BSE Equity"), "BSE_EQ");
+ universe_combo_->addItem(tr("NIFTY 50"), "NIFTY50");
+ universe_combo_->addItem(tr("Custom symbols"), "CUSTOM");
+ vl->addWidget(universe_combo_);
+ connect(universe_combo_, QOverload<int>::of(&QComboBox::currentIndexChanged),
+ this, &UniverseScannerPanel::on_universe_changed);
+
+ // Custom symbols (hidden unless Custom)
+ symbols_label_ = new QLabel(tr("CUSTOM SYMBOLS"), content);
+ symbols_label_->setStyleSheet(uLabel());
+ vl->addWidget(symbols_label_);
+ symbols_input_ = new fincept::ui::algo::SymbolChipInput(content);
+ symbols_input_->setMinimumHeight(48);
+ vl->addWidget(symbols_input_);
+ symbols_label_->setVisible(false);
+ symbols_input_->setVisible(false);
+
+ // Broker account (required — realtime needs a live feed)
+ auto* acct_lbl = new QLabel(tr("BROKER ACCOUNT"), content);
+ acct_lbl->setStyleSheet(uLabel());
+ vl->addWidget(acct_lbl);
+ account_combo_ = new QComboBox(content);
+ account_combo_->setStyleSheet(uCombo());
+ account_combo_->setFixedHeight(30);
+ for (const auto& acct : fincept::trading::AccountManager::instance().list_accounts())
+ account_combo_->addItem(QString("%1 (%2)").arg(acct.display_name, acct.broker_id),
+ acct.account_id);
+ vl->addWidget(account_combo_);
+
+ // Sweep + cooldown row
+ auto* knobs = new QHBoxLayout;
+ knobs->setSpacing(12);
+ auto* sweep_lbl = new QLabel(tr("EVAL SWEEP (ms)"), content);
+ sweep_lbl->setStyleSheet(uLabel());
+ sweep_spin_ = new QSpinBox(content);
+ sweep_spin_->setRange(200, 5000);
+ sweep_spin_->setSingleStep(100);
+ sweep_spin_->setValue(500);
+ sweep_spin_->setFixedHeight(30);
+ sweep_spin_->setStyleSheet(uCombo());
+ auto* cd_lbl = new QLabel(tr("COOLDOWN (min)"), content);
+ cd_lbl->setStyleSheet(uLabel());
+ cooldown_spin_ = new QSpinBox(content);
+ cooldown_spin_->setRange(0, 240);
+ cooldown_spin_->setValue(5);
+ cooldown_spin_->setFixedHeight(30);
+ cooldown_spin_->setStyleSheet(uCombo());
+ knobs->addWidget(sweep_lbl);
+ knobs->addWidget(sweep_spin_);
+ knobs->addWidget(cd_lbl);
+ knobs->addWidget(cooldown_spin_);
+ knobs->addStretch();
+ vl->addLayout(knobs);
+
+ // Start/Stop
+ start_btn_ = new QPushButton(tr("START SCAN"), content);
+ start_btn_->setCursor(Qt::PointingHandCursor);
+ start_btn_->setFixedHeight(38);
+ start_btn_->setStyleSheet(QString("QPushButton { background: rgba(167,139,250,0.12); color: #A78BFA;"
+ " border: 1px solid #A78BFA; font-size: %1px; font-weight: 700; %2"
+ " padding: 6px 24px; } QPushButton:hover { background: #A78BFA;"
+ " color: %3; }")
+ .arg(fincept::ui::fonts::DATA)
+ .arg(uMono())
+ .arg(fincept::ui::colors::BG_BASE()));
+ connect(start_btn_, &QPushButton::clicked, this, &UniverseScannerPanel::on_start_stop);
+ vl->addWidget(start_btn_);
+
+ status_label_ = new QLabel("", content);
+ status_label_->setWordWrap(true);
+ status_label_->setStyleSheet(QString("color: %1; font-size: %2px; %3 background: transparent;")
+ .arg(fincept::ui::colors::TEXT_TERTIARY())
+ .arg(fincept::ui::fonts::SMALL)
+ .arg(uMono()));
+ vl->addWidget(status_label_);
+
+ // Matches
+ auto* m_lbl = new QLabel(tr("LIVE MATCHES"), content);
+ m_lbl->setStyleSheet(QString("color: %1; font-size: %2px; font-weight: 700; %3")
+ .arg(fincept::ui::colors::AMBER())
+ .arg(fincept::ui::fonts::TINY)
+ .arg(uMono()));
+ vl->addWidget(m_lbl);
+
+ matches_table_ = new QTableWidget(0, 5, content);
+ matches_table_->setHorizontalHeaderLabels(
+ {tr("SYMBOL"), tr("SIGNAL"), tr("PRICE"), tr("MATCHED RULES"), tr("DEPLOY")});
+ matches_table_->horizontalHeader()->setSectionResizeMode(3, QHeaderView::Stretch);
+ matches_table_->setColumnWidth(0, 110);
+ matches_table_->setColumnWidth(1, 90);
+ matches_table_->setColumnWidth(2, 90);
+ matches_table_->setColumnWidth(4, 90);
+ matches_table_->setEditTriggers(QAbstractItemView::NoEditTriggers);
+ matches_table_->setSelectionBehavior(QAbstractItemView::SelectRows);
+ matches_table_->verticalHeader()->setVisible(false);
+ matches_table_->setMinimumHeight(200);
+ matches_table_->setStyleSheet(
+ QString("QTableWidget { background: %1; border: 1px solid %2; gridline-color: %2;"
+ " font-size: %3px; font-family: %4; color: %5; }"
+ "QHeaderView::section { background: %6; color: %7; font-size: %3px;"
+ " font-weight: 700; font-family: %4; padding: 4px 8px; border: none;"
+ " border-bottom: 1px solid %2; }")
+ .arg(fincept::ui::colors::BG_BASE(), fincept::ui::colors::BORDER_DIM())
+ .arg(fincept::ui::fonts::SMALL)
+ .arg(fincept::ui::fonts::DATA_FAMILY)
+ .arg(fincept::ui::colors::TEXT_PRIMARY())
+ .arg(fincept::ui::colors::BG_RAISED())
+ .arg(fincept::ui::colors::TEXT_TERTIARY()));
+ vl->addWidget(matches_table_);
+ vl->addStretch();
+
+ scroll->setWidget(content);
+ root->addWidget(scroll);
+}
+
+void UniverseScannerPanel::set_status(const QString& text, const QString& color) {
+ status_label_->setText(text);
+ status_label_->setStyleSheet(QString("color: %1; font-size: %2px; %3 background: transparent;")
+ .arg(color)
+ .arg(fincept::ui::fonts::SMALL)
+ .arg(uMono()));
+}
+
+void UniverseScannerPanel::on_universe_changed(int) {
+ const bool custom = universe_combo_->currentData().toString() == "CUSTOM";
+ symbols_label_->setVisible(custom);
+ symbols_input_->setVisible(custom);
+}
+
+void UniverseScannerPanel::on_strategies_loaded(QVector<AlgoStrategy> strategies) {
+ strategies_ = strategies;
+ const QString prev = strategy_combo_->currentData().toString();
+ strategy_combo_->clear();
+ for (const auto& s : strategies_)
+ strategy_combo_->addItem(s.name, s.id);
+ const int idx = strategy_combo_->findData(prev);
+ if (idx >= 0)
+ strategy_combo_->setCurrentIndex(idx);
+}
+
+bool UniverseScannerPanel::current_strategy(AlgoStrategy* out) const {
+ const QString id = strategy_combo_->currentData().toString();
+ for (const auto& s : strategies_) {
+ if (s.id == id) {
+ *out = s;
+ return true;
+ }
+ }
+ return false;
+}
+
+void UniverseScannerPanel::on_start_stop() {
+ if (running_) {
+ // Stop: tear down the runner and remove the persisted config (alert history
+ // in scan_watch_events is kept).
+ fincept::algo::ScanMonitor::instance().stop_watch(watch_id_);
+ if (!watch_id_.isEmpty())
+ fincept::ScanWatchRepository::instance().remove(watch_id_);
+ watch_id_.clear();
+ running_ = false;
+ start_btn_->setText(tr("START SCAN"));
+ set_status(tr("Stopped."), fincept::ui::colors::TEXT_TERTIARY());
+ return;
+ }
+
+ AlgoStrategy strat;
+ if (!current_strategy(&strat)) {
+ set_status(tr("Select a strategy first."), fincept::ui::colors::NEGATIVE());
+ return;
+ }
+ if (strat.entry_conditions.isEmpty()) {
+ set_status(tr("The selected strategy has no entry conditions."),
+ fincept::ui::colors::NEGATIVE());
+ return;
+ }
+ const QString account_id = account_combo_->currentData().toString();
+ if (account_id.isEmpty()) {
+ set_status(tr("Select a connected broker account (live feed required)."),
+ fincept::ui::colors::NEGATIVE());
+ return;
+ }
+
+ const QString universe = universe_combo_->currentData().toString();
+ const QString tf = strat.timeframe.isEmpty() ? QStringLiteral("5m") : strat.timeframe;
+
+ fincept::ScanWatch w;
+ w.name = QString("Universe: %1").arg(strat.name);
+ w.conditions = strat.entry_conditions;
+ w.logic = strat.entry_logic;
+ w.universe = universe;
+ w.symbols = (universe == "CUSTOM") ? symbols_input_->symbols() : QStringList();
+ w.timeframe = tf;
+ w.lookback_days = algo_default_lookback_days(tf == "live" ? QStringLiteral("1m") : tf);
+ w.data_source = QStringLiteral("Broker");
+ w.account_id = account_id;
+ w.broker_id = fincept::trading::AccountManager::instance().get_account(account_id).broker_id;
+ w.mode = QStringLiteral("realtime");
+ w.cooldown_min = cooldown_spin_->value();
+ QJsonObject actions;
+ actions["toast"] = true;
+ actions["providers"] = false;
+ actions["sweep_ms"] = sweep_spin_->value();
+ actions["strategy_id"] = strat.id;
+ w.actions = actions;
+ w.active = true;
+
+ if (universe == "CUSTOM" && w.symbols.isEmpty()) {
+ set_status(tr("Enter custom symbols or pick a universe."),
+ fincept::ui::colors::NEGATIVE());
+ return;
+ }
+
+ auto r = fincept::ScanWatchRepository::instance().create(w);
+ if (r.is_err()) {
+ set_status(tr("Could not save scan: %1").arg(QString::fromStdString(r.error())),
+ fincept::ui::colors::NEGATIVE());
+ return;
+ }
+ watch_id_ = r.value().id;
+ matches_table_->setRowCount(0);
+ fincept::algo::ScanMonitor::instance().reload(watch_id_);
+
+ running_ = true;
+ start_btn_->setText(tr("STOP SCAN"));
+ set_status(tr("Scanning live — warming history, matches will appear below."),
+ "#A78BFA");
+}
+
+void UniverseScannerPanel::on_match(const QString& watch_id, const QString& symbol,
+ double price, const QString& detail) {
+ if (watch_id != watch_id_ || watch_id_.isEmpty())
+ return;
+
+ const int row = matches_table_->rowCount();
+ matches_table_->insertRow(row);
+
+ auto* sym_item = new QTableWidgetItem(symbol);
+ sym_item->setForeground(QColor(fincept::ui::colors::AMBER()));
+ matches_table_->setItem(row, 0, sym_item);
+
+ // Bullish/bearish from the detail's operators (best-effort).
+ QString sig = tr("MATCH"), sig_color = fincept::ui::colors::TEXT_SECONDARY();
+ if (detail.contains('>') || detail.contains("crosses_above")) {
+ sig = tr("BULLISH");
+ sig_color = fincept::ui::colors::POSITIVE();
+ } else if (detail.contains('<') || detail.contains("crosses_below")) {
+ sig = tr("BEARISH");
+ sig_color = fincept::ui::colors::NEGATIVE();
+ }
+ auto* sig_item = new QTableWidgetItem(sig);
+ sig_item->setForeground(QColor(sig_color));
+ matches_table_->setItem(row, 1, sig_item);
+
+ matches_table_->setItem(row, 2,
+ new QTableWidgetItem(price > 0 ? QString::number(price, 'f', 2)
+ : QStringLiteral("—")));
+ matches_table_->setItem(row, 3, new QTableWidgetItem(detail));
+
+ auto* deploy_btn = new QPushButton(tr("DEPLOY"), matches_table_);
+ deploy_btn->setCursor(Qt::PointingHandCursor);
+ deploy_btn->setStyleSheet(QString("QPushButton { background: transparent; color: %1;"
+ " border: 1px solid %2; font-size: %3px; %4 padding: 2px 8px; }"
+ "QPushButton:hover { color: %5; border-color: %5; }")
+ .arg(fincept::ui::colors::TEXT_SECONDARY(),
+ fincept::ui::colors::BORDER_DIM())
+ .arg(fincept::ui::fonts::TINY)
+ .arg(uMono())
+ .arg(fincept::ui::colors::POSITIVE()));
+ connect(deploy_btn, &QPushButton::clicked, this, [this, symbol]() { deploy_symbol(symbol); });
+ matches_table_->setCellWidget(row, 4, deploy_btn);
+
+ matches_table_->scrollToBottom();
+}
+
+void UniverseScannerPanel::deploy_symbol(const QString& symbol) {
+ AlgoStrategy strat;
+ if (!current_strategy(&strat)) {
+ set_status(tr("Strategy no longer selected — cannot deploy."),
+ fincept::ui::colors::NEGATIVE());
+ return;
+ }
+ auto* dlg = new AlgoDeployDialog(strat, this);
+ dlg->set_symbol(symbol);
+ if (dlg->exec() == QDialog::Accepted) {
+ auto dep = dlg->deployment();
+ AlgoTradingService::instance().save_strategy(strat);
+ fincept::algo::AlgoEngine::instance().start_deployment(dep, strat);
+ set_status(tr("Deployed %1.").arg(symbol), fincept::ui::colors::POSITIVE());
+ }
+ dlg->deleteLater();
+}
+
+} // namespace fincept::screens
diff --git a/fincept-qt/src/screens/algo_trading/UniverseScannerPanel.h b/fincept-qt/src/screens/algo_trading/UniverseScannerPanel.h
new file mode 100644
index 000000000..e34c34914
--- /dev/null
+++ b/fincept-qt/src/screens/algo_trading/UniverseScannerPanel.h
@@ -0,0 +1,54 @@
+// src/screens/algo_trading/UniverseScannerPanel.h
+#pragma once
+#include "services/algo_trading/AlgoTradingTypes.h"
+#include "ui/widgets/algo/SymbolChipInput.h"
+
+#include <QComboBox>
+#include <QLabel>
+#include <QPushButton>
+#include <QSpinBox>
+#include <QString>
+#include <QTableWidget>
+#include <QVector>
+#include <QWidget>
+
+namespace fincept::screens {
+
+/// Universe tab — run a saved strategy live across all NSE/BSE equities (or NIFTY 50
+/// / a custom list). Alerts on every match; each match row has a Deploy button that
+/// opens the existing single-symbol AlgoDeployDialog.
+class UniverseScannerPanel : public QWidget {
+ Q_OBJECT
+ public:
+ explicit UniverseScannerPanel(QWidget* parent = nullptr);
+
+ private slots:
+ void on_strategies_loaded(QVector<fincept::services::algo::AlgoStrategy> strategies);
+ void on_start_stop();
+ void on_match(const QString& watch_id, const QString& symbol, double price,
+ const QString& detail);
+ void on_universe_changed(int index);
+
+ private:
+ void build_ui();
+ void set_status(const QString& text, const QString& color);
+ void deploy_symbol(const QString& symbol);
+ bool current_strategy(fincept::services::algo::AlgoStrategy* out) const;
+
+ QComboBox* strategy_combo_ = nullptr;
+ QComboBox* universe_combo_ = nullptr;
+ fincept::ui::algo::SymbolChipInput* symbols_input_ = nullptr;
+ QLabel* symbols_label_ = nullptr;
+ QComboBox* account_combo_ = nullptr;
+ QSpinBox* sweep_spin_ = nullptr;
+ QSpinBox* cooldown_spin_ = nullptr;
+ QPushButton* start_btn_ = nullptr;
+ QTableWidget* matches_table_ = nullptr;
+ QLabel* status_label_ = nullptr;
+
+ QVector<fincept::services::algo::AlgoStrategy> strategies_;
+ QString watch_id_; // non-empty while a scan is running
+ bool running_ = false;
+};
+
+} // namespace fincept::screens
diff --git a/fincept-qt/src/screens/common/PaperBlotterPanel.cpp b/fincept-qt/src/screens/common/PaperBlotterPanel.cpp
new file mode 100644
index 000000000..ad4bad4fa
--- /dev/null
+++ b/fincept-qt/src/screens/common/PaperBlotterPanel.cpp
@@ -0,0 +1,317 @@
+// PaperBlotterPanel.cpp — shared paper-trading blotter (positions/orders/trades).
+#include "screens/common/PaperBlotterPanel.h"
+
+#include "core/logging/Logger.h"
+#include "trading/AccountManager.h"
+#include "trading/PaperTrading.h"
+#include "trading/PaperMarkService.h"
+#include "trading/TradingTypes.h"
+#include "trading/UnifiedTrading.h"
+#include "ui/theme/Theme.h"
+
+#include <QDateTime>
+#include <QHBoxLayout>
+#include <QHeaderView>
+#include <QLabel>
+#include <QMessageBox>
+#include <QPushButton>
+#include <QShowEvent>
+#include <QTabWidget>
+#include <QTableWidget>
+#include <QTimer>
+#include <QVBoxLayout>
+
+namespace fincept::screens::common {
+
+using namespace fincept::trading;
+namespace colors = fincept::ui::colors;
+
+namespace {
+
+// Coalesce live mark-to-market refreshes — a burst of ticks should trigger at
+// most one table rebuild per this window.
+constexpr int kRefreshThrottleMs = 400;
+
+QString currency_glyph(const QString& code) {
+ if (code.compare(QLatin1String("INR"), Qt::CaseInsensitive) == 0)
+ return QStringLiteral("₹"); // ₹
+ if (code.compare(QLatin1String("USD"), Qt::CaseInsensitive) == 0 || code.isEmpty())
+ return QStringLiteral("$");
+ return code + QLatin1Char(' ');
+}
+
+QTableWidget* make_table(const QStringList& headers) {
+ auto* t = new QTableWidget;
+ t->setColumnCount(headers.size());
+ t->setHorizontalHeaderLabels(headers);
+ t->verticalHeader()->setVisible(false);
+ t->setEditTriggers(QAbstractItemView::NoEditTriggers);
+ t->setSelectionBehavior(QAbstractItemView::SelectRows);
+ t->setSelectionMode(QAbstractItemView::NoSelection);
+ t->setAlternatingRowColors(false);
+ t->setShowGrid(false);
+ t->horizontalHeader()->setStretchLastSection(true);
+ t->horizontalHeader()->setDefaultAlignment(Qt::AlignLeft | Qt::AlignVCenter);
+ return t;
+}
+
+QTableWidgetItem* cell(const QString& text, const QColor& fg = QColor()) {
+ auto* it = new QTableWidgetItem(text);
+ if (fg.isValid())
+ it->setForeground(fg);
+ return it;
+}
+
+} // namespace
+
+PaperBlotterPanel::PaperBlotterPanel(QWidget* parent) : QWidget(parent) {
+ build_ui();
+
+ // Live updates: the centralized mark service tells us when prices were marked
+ // or a fill changed positions/orders. Coalesce bursts into one rebuild.
+ connect(&PaperMarkService::instance(), &PaperMarkService::prices_marked, this,
+ [this](const QString&) { schedule_refresh(); });
+ connect(&PaperMarkService::instance(), &PaperMarkService::portfolio_changed, this,
+ [this](const QString&) { schedule_refresh(); });
+
+ // Safety-net poll so the view stays fresh even if no marks arrive (e.g. a
+ // closed market), but only while actually visible.
+ auto* poll = new QTimer(this);
+ poll->setInterval(2500);
+ connect(poll, &QTimer::timeout, this, [this]() {
+ if (isVisible())
+ refresh();
+ });
+ poll->start();
+}
+
+void PaperBlotterPanel::build_ui() {
+ setObjectName("paperBlotter");
+ setStyleSheet(QStringLiteral("#paperBlotter { background:%1; } "
+ "QTableWidget { background:%1; color:%2; border:none; "
+ " gridline-color:%3; font-size:11px; } "
+ "QHeaderView::section { background:%1; color:%4; border:none; "
+ " border-bottom:1px solid %3; padding:5px 8px; font-size:10px; "
+ " font-weight:700; } "
+ "QTabWidget::pane { border:none; } "
+ "QTabBar::tab { background:transparent; color:%4; padding:6px 14px; "
+ " font-size:10px; font-weight:700; } "
+ "QTabBar::tab:selected { color:%5; border-bottom:2px solid %6; }")
+ .arg(colors::BG_BASE(), colors::TEXT_PRIMARY(), colors::BORDER_DIM(),
+ colors::TEXT_SECONDARY(), colors::TEXT_PRIMARY(), colors::AMBER()));
+
+ auto* root = new QVBoxLayout(this);
+ root->setContentsMargins(0, 0, 0, 0);
+ root->setSpacing(0);
+
+ // Header bar: summary + square-off-all.
+ auto* bar = new QWidget(this);
+ auto* bar_lay = new QHBoxLayout(bar);
+ bar_lay->setContentsMargins(10, 6, 10, 6);
+ summary_ = new QLabel(tr("No open paper positions"), bar);
+ summary_->setStyleSheet(QStringLiteral("color:%1;font-size:11px;font-weight:600;background:transparent;")
+ .arg(colors::TEXT_SECONDARY()));
+ bar_lay->addWidget(summary_);
+ bar_lay->addStretch(1);
+ square_all_btn_ = new QPushButton(tr("SQUARE OFF ALL"), bar);
+ square_all_btn_->setCursor(Qt::PointingHandCursor);
+ square_all_btn_->setStyleSheet(QStringLiteral("QPushButton { background:%1; color:#fff; border:none; "
+ " padding:5px 14px; font-size:10px; font-weight:700; } "
+ "QPushButton:disabled { background:%2; color:%3; }")
+ .arg(colors::NEGATIVE(), colors::BG_HOVER(), colors::TEXT_DIM()));
+ connect(square_all_btn_, &QPushButton::clicked, this, &PaperBlotterPanel::square_off_all);
+ bar_lay->addWidget(square_all_btn_);
+ root->addWidget(bar);
+
+ tabs_ = new QTabWidget(this);
+ positions_ = make_table({tr("Account"), tr("Symbol"), tr("Product"), tr("Side"), tr("Qty"), tr("Avg"),
+ tr("LTP"), tr("P&L"), tr("P&L %"), QString()});
+ orders_ = make_table({tr("Account"), tr("Symbol"), tr("Product"), tr("Side"), tr("Type"), tr("Qty"),
+ tr("Price"), tr("Status"), tr("Time")});
+ trades_ = make_table({tr("Symbol"), tr("Side"), tr("Qty"), tr("Price"), tr("P&L"), tr("Time")});
+ tabs_->addTab(positions_, tr("Positions"));
+ tabs_->addTab(orders_, tr("Orders"));
+ tabs_->addTab(trades_, tr("Trades"));
+ root->addWidget(tabs_, 1);
+}
+
+void PaperBlotterPanel::showEvent(QShowEvent* e) {
+ QWidget::showEvent(e);
+ refresh();
+}
+
+void PaperBlotterPanel::schedule_refresh() {
+ if (refresh_armed_ || !isVisible())
+ return;
+ refresh_armed_ = true;
+ if (!refresh_timer_) {
+ refresh_timer_ = new QTimer(this);
+ refresh_timer_->setSingleShot(true);
+ connect(refresh_timer_, &QTimer::timeout, this, [this]() {
+ refresh_armed_ = false;
+ refresh();
+ });
+ }
+ refresh_timer_->start(kRefreshThrottleMs);
+}
+
+void PaperBlotterPanel::refresh() {
+ const QColor pos_color(colors::POSITIVE());
+ const QColor neg_color(colors::NEGATIVE());
+
+ struct Acct {
+ QString id;
+ QString name;
+ QString pid;
+ QString glyph;
+ };
+ QVector<Acct> accts;
+ for (const auto& a : AccountManager::instance().active_accounts()) {
+ if (a.trading_mode != QLatin1String("paper") || a.paper_portfolio_id.isEmpty())
+ continue;
+ const QString glyph = currency_glyph(pt_get_portfolio(a.paper_portfolio_id).currency);
+ accts.push_back({a.account_id, a.display_name.isEmpty() ? a.account_id : a.display_name,
+ a.paper_portfolio_id, glyph});
+ }
+
+ // ── Positions ───────────────────────────────────────────────────────────
+ positions_->setRowCount(0);
+ double total_pnl = 0.0;
+ int open_count = 0;
+ for (const auto& acct : accts) {
+ for (const auto& p : pt_get_positions(acct.pid)) {
+ if (p.quantity == 0.0)
+ continue;
+ const int r = positions_->rowCount();
+ positions_->insertRow(r);
+ const QColor pc = p.unrealized_pnl >= 0 ? pos_color : neg_color;
+ positions_->setItem(r, 0, cell(acct.name));
+ positions_->setItem(r, 1, cell(p.symbol));
+ positions_->setItem(r, 2, cell(p.product.isEmpty() ? QStringLiteral("MIS") : p.product.toUpper()));
+ positions_->setItem(r, 3, cell(p.side.toUpper(),
+ p.side.compare(QLatin1String("long"), Qt::CaseInsensitive) == 0
+ ? pos_color
+ : neg_color));
+ positions_->setItem(r, 4, cell(QString::number(p.quantity, 'f', 0)));
+ positions_->setItem(r, 5, cell(QString::number(p.entry_price, 'f', 2)));
+ positions_->setItem(r, 6, cell(QString::number(p.current_price, 'f', 2)));
+ positions_->setItem(r, 7, cell(acct.glyph + QString::number(p.unrealized_pnl, 'f', 2), pc));
+ const double notional = p.entry_price * p.quantity;
+ const double pct = notional != 0.0 ? (p.unrealized_pnl / notional) * 100.0 : 0.0;
+ positions_->setItem(r, 8, cell(QString::number(pct, 'f', 2) + QLatin1Char('%'), pc));
+
+ auto* exit_btn = new QPushButton(tr("Exit"));
+ exit_btn->setCursor(Qt::PointingHandCursor);
+ exit_btn->setStyleSheet(QStringLiteral("QPushButton { background:transparent; color:%1; "
+ " border:1px solid %1; padding:2px 10px; font-size:10px; "
+ " font-weight:700; } QPushButton:hover { background:%1; color:#fff; }")
+ .arg(colors::NEGATIVE()));
+ const QString aid = acct.id, sym = p.symbol, prod = p.product;
+ connect(exit_btn, &QPushButton::clicked, this,
+ [this, aid, sym, prod]() { square_off_one(aid, sym, prod); });
+ positions_->setCellWidget(r, 9, exit_btn);
+
+ total_pnl += p.unrealized_pnl;
+ ++open_count;
+ }
+ }
+ positions_->resizeColumnsToContents();
+ square_all_btn_->setEnabled(open_count > 0);
+
+ if (open_count == 0) {
+ summary_->setText(tr("No open paper positions"));
+ summary_->setStyleSheet(QStringLiteral("color:%1;font-size:11px;font-weight:600;background:transparent;")
+ .arg(colors::TEXT_SECONDARY()));
+ } else {
+ const QString glyph = accts.isEmpty() ? QStringLiteral("$") : accts.first().glyph;
+ summary_->setText(tr("%1 open · unrealized %2%3")
+ .arg(open_count)
+ .arg(glyph)
+ .arg(total_pnl, 0, 'f', 2));
+ summary_->setStyleSheet(QStringLiteral("color:%1;font-size:11px;font-weight:700;background:transparent;")
+ .arg(total_pnl >= 0 ? colors::POSITIVE() : colors::NEGATIVE()));
+ }
+
+ // ── Working orders (pending only) ─────────────────────────────────────────
+ orders_->setRowCount(0);
+ for (const auto& acct : accts) {
+ for (const auto& o : pt_get_orders(acct.pid, QStringLiteral("pending"))) {
+ const int r = orders_->rowCount();
+ orders_->insertRow(r);
+ orders_->setItem(r, 0, cell(acct.name));
+ orders_->setItem(r, 1, cell(o.symbol));
+ orders_->setItem(r, 2, cell(o.product.isEmpty() ? QStringLiteral("MIS") : o.product.toUpper()));
+ orders_->setItem(r, 3, cell(o.side.toUpper()));
+ orders_->setItem(r, 4, cell(o.order_type.toUpper()));
+ orders_->setItem(r, 5, cell(QString::number(o.quantity, 'f', 0)));
+ orders_->setItem(r, 6, cell(o.price ? QString::number(*o.price, 'f', 2) : tr("MKT")));
+ orders_->setItem(r, 7, cell(o.status.toUpper()));
+ const QDateTime dt = QDateTime::fromString(o.created_at, Qt::ISODate).toLocalTime();
+ orders_->setItem(r, 8, cell(dt.isValid() ? dt.toString("HH:mm:ss") : o.created_at));
+ }
+ }
+ orders_->resizeColumnsToContents();
+
+ // ── Executed trades (recent) ──────────────────────────────────────────────
+ trades_->setRowCount(0);
+ for (const auto& acct : accts) {
+ for (const auto& t : pt_get_trades(acct.pid, 50)) {
+ const int r = trades_->rowCount();
+ trades_->insertRow(r);
+ trades_->setItem(r, 0, cell(t.symbol));
+ trades_->setItem(r, 1, cell(t.side.toUpper()));
+ trades_->setItem(r, 2, cell(QString::number(t.quantity, 'f', 0)));
+ trades_->setItem(r, 3, cell(QString::number(t.price, 'f', 2)));
+ const QColor tc = t.pnl >= 0 ? pos_color : neg_color;
+ trades_->setItem(r, 4, cell(acct.glyph + QString::number(t.pnl, 'f', 2), tc));
+ const QDateTime dt = QDateTime::fromString(t.timestamp, Qt::ISODate).toLocalTime();
+ trades_->setItem(r, 5, cell(dt.isValid() ? dt.toString("MM-dd HH:mm") : t.timestamp));
+ }
+ }
+ trades_->resizeColumnsToContents();
+}
+
+void PaperBlotterPanel::square_off_one(const QString& account_id, const QString& symbol, const QString& product) {
+ // Paper close is a fast local DB op (UnifiedTrading routes paper accounts to
+ // the pt_* engine, no broker round-trip). Exchange is left empty so the engine
+ // matches by the stored bare symbol.
+ auto resp = UnifiedTrading::instance().close_position(account_id, symbol, QString(), product);
+ if (!resp.success)
+ LOG_WARN("PaperBlotter", QString("Square-off %1 failed: %2").arg(symbol, resp.error));
+ refresh();
+}
+
+void PaperBlotterPanel::square_off_all() {
+ // Collect every open paper position currently shown, then close each.
+ struct Target {
+ QString account_id;
+ QString symbol;
+ QString product;
+ };
+ QVector<Target> targets;
+ for (const auto& a : AccountManager::instance().active_accounts()) {
+ if (a.trading_mode != QLatin1String("paper") || a.paper_portfolio_id.isEmpty())
+ continue;
+ for (const auto& p : pt_get_positions(a.paper_portfolio_id))
+ if (p.quantity != 0.0)
+ targets.push_back({a.account_id, p.symbol, p.product});
+ }
+ if (targets.isEmpty())
+ return;
+
+ if (QMessageBox::question(this, tr("Square off all"),
+ tr("Close all %1 open paper position(s) at market?").arg(targets.size()))
+ != QMessageBox::Yes)
+ return;
+
+ int ok = 0;
+ for (const auto& t : targets) {
+ auto resp = UnifiedTrading::instance().close_position(t.account_id, t.symbol, QString(), t.product);
+ if (resp.success)
+ ++ok;
+ }
+ LOG_INFO("PaperBlotter", QString("Square-off all: closed %1/%2").arg(ok).arg(targets.size()));
+ refresh();
+}
+
+} // namespace fincept::screens::common
diff --git a/fincept-qt/src/screens/common/PaperBlotterPanel.h b/fincept-qt/src/screens/common/PaperBlotterPanel.h
new file mode 100644
index 000000000..9e627dd20
--- /dev/null
+++ b/fincept-qt/src/screens/common/PaperBlotterPanel.h
@@ -0,0 +1,52 @@
+#pragma once
+// PaperBlotterPanel — a reusable, screen-agnostic view of paper-trading state.
+//
+// Shows open positions, working orders, and executed trades for every ACTIVE
+// paper account, with per-row and bulk square-off. It reads straight from the
+// shared paper engine (pt_* / UnifiedTrading) and refreshes live off
+// PaperMarkService's mark-to-market signals, so it is asset-class agnostic and
+// stays correct no matter which screen hosts it. It is embedded as the F&O tab's
+// "Positions" sub-tab and is intended to be the single blotter the Equity (and
+// later Crypto) screens converge on, instead of each re-implementing the tables.
+
+#include <QHash>
+#include <QWidget>
+
+class QLabel;
+class QPushButton;
+class QTabWidget;
+class QTableWidget;
+class QTimer;
+
+namespace fincept::screens::common {
+
+class PaperBlotterPanel : public QWidget {
+ Q_OBJECT
+ public:
+ explicit PaperBlotterPanel(QWidget* parent = nullptr);
+
+ public slots:
+ // Reload all tables from the paper engine. Cheap; safe to call often.
+ void refresh();
+
+ protected:
+ void showEvent(QShowEvent* e) override;
+
+ private:
+ void build_ui();
+ void schedule_refresh(); // coalesce bursts of mark signals into one reload
+ void square_off_all();
+ void square_off_one(const QString& account_id, const QString& symbol, const QString& product);
+
+ QTabWidget* tabs_ = nullptr;
+ QTableWidget* positions_ = nullptr;
+ QTableWidget* orders_ = nullptr;
+ QTableWidget* trades_ = nullptr;
+ QLabel* summary_ = nullptr;
+ QPushButton* square_all_btn_ = nullptr;
+
+ QTimer* refresh_timer_ = nullptr; // throttle live refreshes
+ bool refresh_armed_ = false;
+};
+
+} // namespace fincept::screens::common
diff --git a/fincept-qt/src/screens/equity_trading/EquityBottomPanel.cpp b/fincept-qt/src/screens/equity_trading/EquityBottomPanel.cpp
index 69fdec707..aab436bc7 100644
--- a/fincept-qt/src/screens/equity_trading/EquityBottomPanel.cpp
+++ b/fincept-qt/src/screens/equity_trading/EquityBottomPanel.cpp
@@ -1,6 +1,7 @@
// EquityBottomPanel.cpp — tabbed portfolio display
#include "screens/equity_trading/EquityBottomPanel.h"
+#include "core/logging/Logger.h"
#include "ui/theme/Theme.h"
#include <QDate>
@@ -360,11 +361,24 @@ void EquityBottomPanel::setup_positions_tab() {
QMenu menu(this);
QAction* buy = menu.addAction(tr("Buy / Add %1").arg(symbol));
QAction* sell = menu.addAction(tr("Sell / Reduce %1").arg(symbol));
+ auto* qty_item = positions_table_->item(row, 4); // Qty column
+ const double held = qty_item ? qAbs(qty_item->text().toDouble()) : 0.0;
QAction* chosen = menu.exec(positions_table_->viewport()->mapToGlobal(p));
if (chosen == buy)
- emit trade_symbol_requested(symbol, product, true);
+ emit trade_symbol_requested(symbol, product, true, 0.0); // add → ticket defaults to 1
else if (chosen == sell)
- emit trade_symbol_requested(symbol, product, false);
+ emit trade_symbol_requested(symbol, product, false, held); // reduce → pre-fill held qty
+ });
+
+ // Left-click a position row → load that symbol's chart (parity with the
+ // watchlist). Clicks on the Action cell-widget (col 9) go to its buttons, not
+ // here, so the SELL button keeps working.
+ connect(positions_table_, &QTableWidget::cellClicked, this, [this](int row, int col) {
+ auto* sym_item = positions_table_->item(row, 0);
+ LOG_INFO("posdbg", QString("positions cellClicked row=%1 col=%2 sym='%3'")
+ .arg(row).arg(col).arg(sym_item ? sym_item->text() : QStringLiteral("<null>")));
+ if (sym_item && !sym_item->text().isEmpty())
+ emit chart_symbol_requested(sym_item->text());
});
vlay->addWidget(positions_table_, 1);
@@ -465,11 +479,13 @@ void EquityBottomPanel::setup_holdings_tab() {
QMenu menu(this);
QAction* buy = menu.addAction(tr("Buy / Add %1").arg(symbol));
QAction* sell = menu.addAction(tr("Sell / Reduce %1").arg(symbol));
+ auto* qty_item = holdings_table_->item(row, 1); // Qty column
+ const double held = qty_item ? qAbs(qty_item->text().toDouble()) : 0.0;
QAction* chosen = menu.exec(holdings_table_->viewport()->mapToGlobal(p));
if (chosen == buy)
- emit trade_symbol_requested(symbol, QStringLiteral("CNC"), true);
+ emit trade_symbol_requested(symbol, QStringLiteral("CNC"), true, 0.0);
else if (chosen == sell)
- emit trade_symbol_requested(symbol, QStringLiteral("CNC"), false);
+ emit trade_symbol_requested(symbol, QStringLiteral("CNC"), false, held);
});
v->addWidget(holdings_table_, 1);
@@ -734,26 +750,12 @@ void EquityBottomPanel::set_paper_positions(const QVector<trading::PtPosition>&
pct_item->setText(QString::number(pct, 'f', 2) + "%");
pct_item->setForeground(pct >= 0 ? pos_color : neg_color);
- // Col 9 — CONVERT to CNC (carry overnight). Only intraday (MIS) positions
- // can be converted to delivery; NRML/CNC show nothing.
- if (trading::product_is_intraday(p.product)) {
- auto* btn = new QPushButton(tr("→ CNC"));
- btn->setObjectName("eqTableBtn");
- btn->setFixedHeight(18);
- btn->setCursor(Qt::PointingHandCursor);
- btn->setToolTip(tr("Convert to CNC delivery (carry overnight, locks full cash)"));
- btn->setStyleSheet(QString("QPushButton#eqTableBtn{background:rgba(37,99,235,0.15);color:%1;"
- "border:1px solid %2;font-size:10px;padding:0 6px;border-radius:2px;}"
- "QPushButton#eqTableBtn:hover{background:rgba(37,99,235,0.30);}")
- .arg(fincept::ui::colors::INFO(), fincept::ui::colors::BORDER_MED()));
- const QString pid = p.id;
- const QString sym = p.symbol;
- connect(btn, &QPushButton::clicked, this,
- [this, pid, sym]() { emit convert_position_requested(pid, sym, QStringLiteral("CNC")); });
- positions_table_->setCellWidget(i, 9, btn);
- } else {
- positions_table_->setCellWidget(i, 9, nullptr);
- }
+ // Col 9 — Action: SELL (exit, pre-filled qty) + for intraday (MIS), a
+ // "→ CNC" convert-to-delivery button. NRML/CNC rows get SELL only.
+ positions_table_->setCellWidget(
+ i, 9,
+ make_positions_action_cell(p.symbol, p.product, p.quantity,
+ trading::product_is_intraday(p.product), p.id));
}
update_positions_summary();
}
@@ -857,6 +859,51 @@ void EquityBottomPanel::set_orders_date(const QDate& day) {
suppress_orders_date_signal_ = false;
}
+QWidget* EquityBottomPanel::make_positions_action_cell(const QString& symbol, const QString& product,
+ double qty, bool show_convert,
+ const QString& paper_pid) {
+ auto* cell = new QWidget;
+ auto* lay = new QHBoxLayout(cell);
+ lay->setContentsMargins(2, 0, 2, 0);
+ lay->setSpacing(4);
+
+ // SELL → opens the order ticket pre-filled with the held quantity (parity with
+ // the FNO tab's per-strike order button, instead of right-click-only).
+ auto* sell = new QPushButton(tr("SELL"));
+ sell->setObjectName("eqTableBtn");
+ sell->setFixedHeight(18);
+ sell->setCursor(Qt::PointingHandCursor);
+ sell->setToolTip(tr("Sell / exit %1 — opens an order ticket pre-filled with the held quantity").arg(symbol));
+ sell->setStyleSheet(QString("QPushButton#eqTableBtn{background:rgba(239,68,68,0.15);color:%1;"
+ "border:1px solid %2;font-size:10px;padding:0 6px;border-radius:2px;}"
+ "QPushButton#eqTableBtn:hover{background:rgba(239,68,68,0.30);}")
+ .arg(fincept::ui::colors::NEGATIVE(), fincept::ui::colors::BORDER_MED()));
+ const double held = qAbs(qty);
+ const QString prod = product.isEmpty() ? QStringLiteral("MIS") : product;
+ connect(sell, &QPushButton::clicked, this,
+ [this, symbol, prod, held]() { emit trade_symbol_requested(symbol, prod, false, held); });
+ lay->addWidget(sell);
+
+ // Paper intraday only: convert MIS → CNC (carry overnight).
+ if (show_convert && !paper_pid.isEmpty()) {
+ auto* cnc = new QPushButton(tr("→ CNC"));
+ cnc->setObjectName("eqTableBtn");
+ cnc->setFixedHeight(18);
+ cnc->setCursor(Qt::PointingHandCursor);
+ cnc->setToolTip(tr("Convert to CNC delivery (carry overnight, locks full cash)"));
+ cnc->setStyleSheet(QString("QPushButton#eqTableBtn{background:rgba(37,99,235,0.15);color:%1;"
+ "border:1px solid %2;font-size:10px;padding:0 6px;border-radius:2px;}"
+ "QPushButton#eqTableBtn:hover{background:rgba(37,99,235,0.30);}")
+ .arg(fincept::ui::colors::INFO(), fincept::ui::colors::BORDER_MED()));
+ connect(cnc, &QPushButton::clicked, this, [this, paper_pid, symbol]() {
+ emit convert_position_requested(paper_pid, symbol, QStringLiteral("CNC"));
+ });
+ lay->addWidget(cnc);
+ }
+ lay->addStretch();
+ return cell;
+}
+
void EquityBottomPanel::set_positions(const QVector<trading::BrokerPosition>& positions) {
last_positions_ = positions; // keep row-aligned for live-quote patching
const QColor pos_color(fincept::ui::colors::POSITIVE());
@@ -880,7 +927,9 @@ void EquityBottomPanel::set_positions(const QVector<trading::BrokerPosition>& po
pct_item->setText(QString("%1%").arg(p.pnl_pct, 0, 'f', 2));
pct_item->setForeground(p.pnl_pct >= 0 ? pos_color : neg_color);
- positions_table_->setCellWidget(i, 9, nullptr); // no convert action in live mode
+ // SELL (exit) action; no MIS→CNC convert in live mode (paper-only).
+ positions_table_->setCellWidget(
+ i, 9, make_positions_action_cell(p.symbol, p.product_type, p.quantity, false, QString()));
}
update_positions_summary();
}
@@ -961,6 +1010,26 @@ void EquityBottomPanel::update_quote(const QString& symbol, const trading::Broke
if (ltp <= 0.0 || symbol.isEmpty())
return; // ignore empty / zero-price ticks — keep the last good values
+ {
+ // [posdbg] throttled — which quote symbols arrive vs the position symbols.
+ static qint64 s_last = 0;
+ const qint64 now = QDateTime::currentMSecsSinceEpoch();
+ if (now - s_last > 3000) {
+ s_last = now;
+ QStringList ps;
+ if (is_paper_)
+ for (const auto& p : last_paper_positions_)
+ ps << p.symbol;
+ else
+ for (const auto& p : last_positions_)
+ ps << p.symbol;
+ LOG_INFO("posdbg", QString("update_quote sym='%1' ltp=%2 (%3) positions=[%4]")
+ .arg(symbol)
+ .arg(ltp, 0, 'f', 2)
+ .arg(is_paper_ ? "paper" : "live", ps.join(',')));
+ }
+ }
+
// Holdings (CNC) live the same quote stream as positions — patch them too.
update_holding_quote(symbol, ltp);
diff --git a/fincept-qt/src/screens/equity_trading/EquityBottomPanel.h b/fincept-qt/src/screens/equity_trading/EquityBottomPanel.h
index 1c58e4c53..4a3835ab6 100644
--- a/fincept-qt/src/screens/equity_trading/EquityBottomPanel.h
+++ b/fincept-qt/src/screens/equity_trading/EquityBottomPanel.h
@@ -81,8 +81,12 @@ class EquityBottomPanel : public QWidget {
void orders_day_changed(const QDate& day);
// Square off the subset of open positions by P&L sign (+1 winners, -1 losers).
void square_off_group_requested(const QString& account_id, int sign);
- // Right-click Buy(add)/Sell(reduce) on a position or holding row.
- void trade_symbol_requested(const QString& symbol, const QString& product, bool is_buy);
+ // Buy(add)/Sell(reduce) on a position or holding row — from the right-click
+ // menu or the per-row SELL button. `qty` pre-fills the order ticket (the held
+ // quantity for a reduce/exit; 0 = let the ticket default to 1).
+ void trade_symbol_requested(const QString& symbol, const QString& product, bool is_buy, double qty);
+ // Click a position/holding row → load that symbol's chart (like the watchlist).
+ void chart_symbol_requested(const QString& symbol);
protected:
void changeEvent(QEvent* event) override;
@@ -110,6 +114,12 @@ class EquityBottomPanel : public QWidget {
static QTableWidgetItem* ensure_item(QTableWidget* table, int row, int col);
+ // Build the Positions "Action" cell: a SELL button (opens an order ticket
+ // pre-filled with the held qty) plus, for paper intraday rows, a "→ CNC"
+ // convert button. `paper_pid` is empty for live rows (no convert).
+ QWidget* make_positions_action_cell(const QString& symbol, const QString& product, double qty,
+ bool show_convert, const QString& paper_pid);
+
QTabWidget* tabs_ = nullptr;
// Collapsible bottom-sheet state
diff --git a/fincept-qt/src/screens/equity_trading/EquityTradingScreen.cpp b/fincept-qt/src/screens/equity_trading/EquityTradingScreen.cpp
index fe71fad51..370bf5af9 100644
--- a/fincept-qt/src/screens/equity_trading/EquityTradingScreen.cpp
+++ b/fincept-qt/src/screens/equity_trading/EquityTradingScreen.cpp
@@ -438,6 +438,10 @@ void EquityTradingScreen::setup_ui() {
&EquityTradingScreen::on_square_off_group);
connect(bottom_panel_, &EquityBottomPanel::trade_symbol_requested, this,
&EquityTradingScreen::on_trade_symbol_requested);
+ // Click a position/holding row → load that symbol on the chart (same slot the
+ // watchlist uses, so it sets the selected symbol, fetches candles + orderbook).
+ connect(bottom_panel_, &EquityBottomPanel::chart_symbol_requested, this,
+ &EquityTradingScreen::on_symbol_selected);
connect(chart_, &EquityChartPanel::timeframe_changed, this, [this](const QString& tf) {
auto* stream = DataStreamManager::instance().stream_for(focused_account_id_);
if (stream)
@@ -563,7 +567,7 @@ void EquityTradingScreen::on_instruments_ready(const QString& broker_id) {
auto* stream = DataStreamManager::instance().stream_for(focused_account_id_);
if (stream) {
stream->set_selected_symbol(selected_symbol_, selected_exchange_);
- stream->subscribe_symbols(QStringLiteral("equity:watchlist"), watchlist_symbols_);
+ stream->subscribe_symbols(QStringLiteral("equity:watchlist"), effective_symbols());
stream->fetch_candles(selected_symbol_, chart_->current_timeframe());
stream->fetch_orderbook(selected_symbol_);
stream->fetch_time_sales(selected_symbol_);
@@ -711,7 +715,7 @@ void EquityTradingScreen::init_focused_account() {
auto* stream = dsm.stream_for(focused_account_id_);
if (stream) {
stream->set_selected_symbol(selected_symbol_, selected_exchange_);
- stream->subscribe_symbols(QStringLiteral("equity:watchlist"), watchlist_symbols_);
+ stream->subscribe_symbols(QStringLiteral("equity:watchlist"), effective_symbols());
stream->fetch_candles(selected_symbol_, chart_->current_timeframe());
stream->fetch_orderbook(selected_symbol_);
stream->fetch_time_sales(selected_symbol_);
diff --git a/fincept-qt/src/screens/equity_trading/EquityTradingScreen.h b/fincept-qt/src/screens/equity_trading/EquityTradingScreen.h
index 50d85ed77..04d2501fc 100644
--- a/fincept-qt/src/screens/equity_trading/EquityTradingScreen.h
+++ b/fincept-qt/src/screens/equity_trading/EquityTradingScreen.h
@@ -88,8 +88,9 @@ class EquityTradingScreen : public QWidget, public IGroupLinked, public IStatefu
void on_orders_day_changed(const QDate& day);
// Square off the subset of open positions by P&L sign (+1 winners, -1 losers).
void on_square_off_group(const QString& account_id, int sign);
- // Right-click Buy/Sell on a position or holding → open an order ticket.
- void on_trade_symbol_requested(const QString& symbol, const QString& product, bool is_buy);
+ // Buy/Sell on a position or holding (right-click or per-row SELL button) →
+ // open an order ticket. `qty` pre-fills the ticket (held qty on a reduce/exit).
+ void on_trade_symbol_requested(const QString& symbol, const QString& product, bool is_buy, double qty);
// EXIT clicked on the chart's position card → confirm + square off the symbol.
void on_chart_exit_position(const QString& symbol, const QString& exchange,
const QString& product_type, const QString& side, double qty);
@@ -149,7 +150,8 @@ class EquityTradingScreen : public QWidget, public IGroupLinked, public IStatefu
void open_chart_order_ticket(bool is_buy, double price);
// Generalized order ticket for an arbitrary symbol/product (right-click trade
// from the positions/holdings tables). Routes through on_order_submitted().
- void open_order_ticket_for(const QString& symbol, const QString& exchange, const QString& product, bool is_buy);
+ void open_order_ticket_for(const QString& symbol, const QString& exchange, const QString& product, bool is_buy,
+ double qty = 0.0);
// Re-reads the focused account's paper portfolio into the panels. No-op for
// live accounts (their data flows from AccountDataStream via the hub).
void refresh_paper_panels();
@@ -161,6 +163,15 @@ class EquityTradingScreen : public QWidget, public IGroupLinked, public IStatefu
void hub_subscribe_quotes();
QString broker_id_for_focused() const;
+ // Mark held F&O option positions to market. Fyers' live HSM tick feed spells
+ // an option ("NIFTY09JUN26C23200") differently from its REST position symbol
+ // ("NIFTY2660923200CE"), so option ticks never match the per-symbol quote
+ // topics. This router reconciles the two by (underlying, strike, side) and
+ // patches the position/holding row + paper P&L. Bound to the focused stream
+ // (opt_quote_conn_) only while an option position is actually held.
+ void route_option_quote(const QString& account_id, const QString& symbol,
+ const trading::BrokerQuote& quote);
+
// Named-watchlist controller (WatchlistRepository). load_watchlists() refreshes
// the combo + seeds a default from the broker's default_watchlist on first run;
// apply_active_watchlist() pushes the active list's symbols into the view and
@@ -234,6 +245,9 @@ class EquityTradingScreen : public QWidget, public IGroupLinked, public IStatefu
// UPDATE per tick. SL/TP + limit matching still run every tick (in-memory).
QHash<QString, double> pending_paper_prices_;
bool paper_flush_armed_ = false;
+ // Focused stream → route_option_quote, bound only while an F&O option position
+ // is held (Fyers' HSM tick symbol can't match the per-symbol quote topics).
+ QMetaObject::Connection opt_quote_conn_;
// Async guards
std::atomic<bool> token_expired_shown_{false};
diff --git a/fincept-qt/src/screens/equity_trading/EquityTradingScreen_Handlers.cpp b/fincept-qt/src/screens/equity_trading/EquityTradingScreen_Handlers.cpp
index ee0d5c3d0..917aa8a75 100644
--- a/fincept-qt/src/screens/equity_trading/EquityTradingScreen_Handlers.cpp
+++ b/fincept-qt/src/screens/equity_trading/EquityTradingScreen_Handlers.cpp
@@ -85,6 +85,11 @@ void EquityTradingScreen::on_account_changed(const QString& account_id) {
if (account.account_id.isEmpty())
return;
+ // Wire the positions/orders header buttons (square-off winners/losers,
+ // SQUARE OFF ALL, cancel-all-orders) to this account. Without this the panel's
+ // account_id_ stays empty and every one of those buttons silently no-ops.
+ bottom_panel_->set_account_id(account_id);
+
account_btn_->setText(account.display_name.toUpper());
// Configure UI from broker profile
@@ -150,7 +155,7 @@ void EquityTradingScreen::on_account_changed(const QString& account_id) {
auto* stream = dsm.stream_for(account_id);
if (stream) {
stream->set_selected_symbol(selected_symbol_, selected_exchange_);
- stream->subscribe_symbols(QStringLiteral("equity:watchlist"), watchlist_symbols_);
+ stream->subscribe_symbols(QStringLiteral("equity:watchlist"), effective_symbols());
stream->fetch_candles(selected_symbol_, chart_->current_timeframe());
stream->fetch_orderbook(selected_symbol_);
// US-only market data — skip for Indian/other brokers (no tape/calendar).
@@ -182,6 +187,8 @@ void EquityTradingScreen::on_account_changed(const QString& account_id) {
}
void EquityTradingScreen::on_symbol_selected(const QString& symbol) {
+ LOG_INFO("posdbg", QString("on_symbol_selected sym='%1' (current='%2' exch='%3')")
+ .arg(symbol, selected_symbol_, selected_exchange_));
if (symbol.isEmpty() || symbol == selected_symbol_)
return;
switch_symbol(symbol);
@@ -367,7 +374,7 @@ void EquityTradingScreen::on_accounts_clicked() {
auto* stream = DataStreamManager::instance().stream_for(account_id);
if (stream && account_id == focused_account_id_) {
stream->set_selected_symbol(selected_symbol_, selected_exchange_);
- stream->subscribe_symbols(QStringLiteral("equity:watchlist"), watchlist_symbols_);
+ stream->subscribe_symbols(QStringLiteral("equity:watchlist"), effective_symbols());
}
AccountManager::instance().set_connection_state(account_id, ConnectionState::Connected);
update_connection_status();
@@ -831,13 +838,14 @@ void EquityTradingScreen::on_square_off_group(const QString& account_id, int sig
});
}
-void EquityTradingScreen::on_trade_symbol_requested(const QString& symbol, const QString& product, bool is_buy) {
+void EquityTradingScreen::on_trade_symbol_requested(const QString& symbol, const QString& product, bool is_buy,
+ double qty) {
// Exchange isn't carried on the row; default to the screen's current exchange.
- open_order_ticket_for(symbol, QString(), product, is_buy);
+ open_order_ticket_for(symbol, QString(), product, is_buy, qty);
}
void EquityTradingScreen::open_order_ticket_for(const QString& symbol, const QString& exchange,
- const QString& product, bool is_buy) {
+ const QString& product, bool is_buy, double qty) {
if (focused_account_id_.isEmpty()) {
order_entry_->show_order_status(tr("No account selected — add one via ACCOUNTS"), false);
return;
@@ -862,7 +870,9 @@ void EquityTradingScreen::open_order_ticket_for(const QString& symbol, const QSt
auto* qty_spin = new QSpinBox(&dlg);
qty_spin->setRange(1, 10000000);
- qty_spin->setValue(1);
+ // Pre-fill with the held quantity on a reduce/exit (qty > 0); otherwise default
+ // to 1. Lets "Sell" exit the whole position in one click, like the FNO ticket.
+ qty_spin->setValue(qty > 0.0 ? static_cast<int>(qty) : 1);
form->addRow(tr("Qty"), qty_spin);
auto* px_spin = new QDoubleSpinBox(&dlg);
@@ -972,27 +982,55 @@ void EquityTradingScreen::on_close_all_positions() {
order_entry_->show_order_status(tr("No account selected — add one via ACCOUNTS"), false);
return;
}
+ auto account = AccountManager::instance().get_account(focused_account_id_);
+
+ // SQUARE OFF ALL acts on the POSITIONS tab only (intraday MIS/NRML). CNC /
+ // delivery exposure lives in Holdings and is squared off separately — this
+ // button never touches it. (The shared UnifiedTrading::close_all_positions
+ // closes everything, so we collect intraday-only targets and close each.)
+ struct Target {
+ QString symbol;
+ QString exchange;
+ QString product;
+ };
+ QVector<Target> targets;
+ if (account.trading_mode == "paper" && !account.paper_portfolio_id.isEmpty()) {
+ for (const auto& p : pt_get_positions(account.paper_portfolio_id)) {
+ if (p.quantity == 0.0 || product_is_delivery(p.product))
+ continue; // CNC/delivery -> Holdings, not squared here
+ targets.push_back({p.symbol, QString(), p.product});
+ }
+ } else {
+ // live_positions_ is the Positions tab feed (broker get_positions);
+ // Holdings come from a separate holdings feed and are not included.
+ for (const auto& p : live_positions_)
+ targets.push_back({p.symbol, p.exchange, p.product_type});
+ }
+ if (targets.isEmpty()) {
+ order_entry_->show_order_status(tr("No open positions to square off"), false);
+ return;
+ }
+
const QString acct_id = focused_account_id_;
QPointer<EquityTradingScreen> self = this;
- (void)QtConcurrent::run([self, acct_id]() {
+ (void)QtConcurrent::run([self, acct_id, targets]() {
if (!self)
return;
- auto result = UnifiedTrading::instance().close_all_positions(acct_id);
+ int ok = 0, fail = 0;
+ for (const auto& t : targets) {
+ auto r = UnifiedTrading::instance().close_position(acct_id, t.symbol, t.exchange, t.product);
+ r.success ? ++ok : ++fail;
+ }
QMetaObject::invokeMethod(
self,
- [self, result]() {
+ [self, ok, fail]() {
if (!self)
return;
- if (result.success && result.data) {
- const auto& r = *result.data;
- self->order_entry_->show_order_status(
- self->tr("Closed %1 position(s)%2")
- .arg(r.closed_symbols.size())
- .arg(r.failed.isEmpty() ? QString() : self->tr(", %1 failed").arg(r.failed.size())),
- r.failed.isEmpty());
- } else {
- self->order_entry_->show_order_status(result.error, false);
- }
+ self->order_entry_->show_order_status(
+ self->tr("Closed %1 position(s)%2")
+ .arg(ok)
+ .arg(fail > 0 ? self->tr(", %1 failed").arg(fail) : QString()),
+ fail == 0);
self->refresh_paper_panels();
},
Qt::QueuedConnection);
diff --git a/fincept-qt/src/screens/equity_trading/EquityTradingScreen_Streams.cpp b/fincept-qt/src/screens/equity_trading/EquityTradingScreen_Streams.cpp
index 1c9ba3504..34eb13111 100644
--- a/fincept-qt/src/screens/equity_trading/EquityTradingScreen_Streams.cpp
+++ b/fincept-qt/src/screens/equity_trading/EquityTradingScreen_Streams.cpp
@@ -26,6 +26,7 @@
#include "trading/DataStreamManager.h"
#include "trading/OrderMatcher.h"
#include "trading/PaperTrading.h"
+#include "trading/websocket/FyersTickTypes.h"
#include <QTimer>
@@ -160,6 +161,8 @@ void EquityTradingScreen::hub_subscribe_quotes() {
for (const auto& s : position_symbols_) // held symbols get live quotes too
symbols.insert(s);
+ LOG_INFO("posdbg", QString("subscribing %1 quote topics for acct=%2: [%3]")
+ .arg(symbols.size()).arg(aid, QStringList(symbols.begin(), symbols.end()).join(',')));
for (const auto& sym : symbols) {
const QString topic = broker_topic(bid, aid, QStringLiteral("quote"), sym);
hub.subscribe(this, topic, [this, sym](const QVariant& v) {
@@ -216,6 +219,70 @@ void EquityTradingScreen::hub_subscribe_quotes() {
}
}
+void EquityTradingScreen::route_option_quote(const QString& account_id, const QString& symbol,
+ const BrokerQuote& quote) {
+ // The live tick arrives in Fyers' HSM/brsymbol spelling ("NIFTY09JUN26C23200")
+ // which carries a parseable strike; equity ticks (e.g. "RELIANCE") don't parse
+ // as options and are ignored here.
+ const auto tick = trading::fyers_parse_option(symbol);
+ if (tick.valid) {
+ // [posdbg] throttled — confirm the router fires for option ticks, on which
+ // account, and what it tries to match. Remove once F&O pricing is verified.
+ static qint64 s_last = 0;
+ const qint64 now = QDateTime::currentMSecsSinceEpoch();
+ if (now - s_last > 3000) {
+ s_last = now;
+ LOG_INFO("posdbg", QString("route_option_quote tick='%1' acct=%2 focused=%3 pos=[%4]")
+ .arg(symbol, account_id, focused_account_id_,
+ position_symbols_.join(',')));
+ }
+ }
+ if (account_id != focused_account_id_ || quote.ltp <= 0.0)
+ return;
+ if (!tick.valid || tick.strike <= 0.0)
+ return;
+ const QString strike_str = QString::number(qRound64(tick.strike));
+
+ // Reconcile to a held position by (underlying, side, strike). The position
+ // symbol uses the REST "…<strike>CE" spelling, which never string-matches the
+ // tick's "…C<strike>" spelling — so match on the format-independent identity:
+ // same underlying root, same call/put, and the position's strike (trailing
+ // digits before CE/PE) equals the tick's strike.
+ for (const QString& pos_sym : position_symbols_) {
+ const auto leg = trading::fyers_parse_option(pos_sym);
+ if (!leg.valid || leg.is_call != tick.is_call || leg.underlying != tick.underlying)
+ continue;
+ QString core = pos_sym.section(QLatin1Char(':'), -1);
+ if (core.endsWith(QLatin1String("CE")) || core.endsWith(QLatin1String("PE")))
+ core.chop(2);
+ if (!core.endsWith(strike_str))
+ continue;
+
+ // Mark the position/holding row to market. Passing the position's OWN
+ // symbol lets update_quote's existing string match find the row.
+ bottom_panel_->update_quote(pos_sym, quote);
+
+ // Paper engine: buffer the option's price so funds/stats mark to market
+ // too, and run limit + SL/TP matching — the same coalesced-flush path the
+ // equity quote handler uses, keyed by the position's own symbol.
+ if (focused_is_paper_ && !focused_paper_portfolio_id_.isEmpty()) {
+ pending_paper_prices_[pos_sym] = quote.ltp;
+ if (!paper_flush_armed_) {
+ paper_flush_armed_ = true;
+ QTimer::singleShot(kPaperPriceFlushMs, this, [this]() { flush_paper_prices(); });
+ }
+ PriceData pd;
+ pd.last = quote.ltp;
+ pd.bid = quote.bid;
+ pd.ask = quote.ask;
+ pd.timestamp = quote.timestamp;
+ OrderMatcher::instance().check_orders(pos_sym, pd, focused_paper_portfolio_id_);
+ OrderMatcher::instance().check_sl_tp_triggers(focused_paper_portfolio_id_, pos_sym, quote.ltp);
+ }
+ return;
+ }
+}
+
void EquityTradingScreen::hub_unsubscribe_all() {
if (!hub_active_)
return;
diff --git a/fincept-qt/src/screens/equity_trading/EquityTradingScreen_Watchlists.cpp b/fincept-qt/src/screens/equity_trading/EquityTradingScreen_Watchlists.cpp
index 7ae56dde1..2338bf144 100644
--- a/fincept-qt/src/screens/equity_trading/EquityTradingScreen_Watchlists.cpp
+++ b/fincept-qt/src/screens/equity_trading/EquityTradingScreen_Watchlists.cpp
@@ -15,6 +15,7 @@
#include "storage/repositories/WatchlistRepository.h"
#include "trading/BrokerRegistry.h"
#include "trading/DataStreamManager.h"
+#include "trading/websocket/FyersTickTypes.h"
#include <QPair>
#include <QVector>
@@ -157,6 +158,34 @@ void EquityTradingScreen::apply_active_watchlist(bool resubscribe) {
stream->subscribe_symbols(QStringLiteral("equity:watchlist"), eff);
stream->fetch_orderbook(selected_symbol_);
}
+
+ // (Re)bind the F&O option-position price router to the focused stream — but
+ // only while an option is actually held. Fyers' live HSM tick spells an
+ // option differently from its REST position symbol, so option ticks never
+ // arrive on the per-symbol quote topics; route_option_quote reconciles them
+ // by (underlying, strike, side). Keeping the binding off when no option is
+ // held avoids a per-tick parse on the equity hot path. See route_option_quote.
+ if (opt_quote_conn_) {
+ QObject::disconnect(opt_quote_conn_);
+ opt_quote_conn_ = {};
+ }
+ if (stream) {
+ bool has_option = false;
+ for (const auto& s : position_symbols_)
+ if (trading::fyers_parse_option(s).valid) {
+ has_option = true;
+ break;
+ }
+ if (has_option)
+ opt_quote_conn_ = connect(stream, &trading::AccountDataStream::quote_updated,
+ this, &EquityTradingScreen::route_option_quote);
+ LOG_INFO("posdbg", QString("opt route bind: has_option=%1 stream=%2 conn=%3 pos=[%4]")
+ .arg(has_option ? "Y" : "N")
+ .arg(stream ? "Y" : "N")
+ .arg(opt_quote_conn_ ? "Y" : "N")
+ .arg(position_symbols_.join(',')));
+ }
+
if (isVisible() && hub_active_)
hub_subscribe_streaming(); // re-point quote topics at the new symbol set
}
@@ -233,6 +262,7 @@ void EquityTradingScreen::update_position_symbols(const QStringList& syms) {
if (deduped == position_symbols_)
return; // unchanged — avoid resubscribe churn
position_symbols_ = deduped;
+ LOG_INFO("posdbg", QString("update_position_symbols: [%1]").arg(deduped.join(',')));
// Re-display + re-subscribe to the new active∪positions union so held symbols
// get live WebSocket prices. Deferred to the next tick because this can fire
// from inside a hub callback, and apply_active_watchlist re-subscribes the hub.
diff --git a/fincept-qt/src/screens/fno/BuilderSubTab.cpp b/fincept-qt/src/screens/fno/BuilderSubTab.cpp
index ddcdae2ca..a2656cf8a 100644
--- a/fincept-qt/src/screens/fno/BuilderSubTab.cpp
+++ b/fincept-qt/src/screens/fno/BuilderSubTab.cpp
@@ -12,7 +12,8 @@
#include "services/options/StrategyAnalytics.h"
#include "services/options/StrategyTemplates.h"
#include "storage/repositories/StrategiesRepository.h"
-#include "trading/PaperTrading.h"
+#include "trading/AccountManager.h"
+#include "trading/UnifiedTrading.h"
#include "ui/theme/StyleSheets.h"
#include "ui/theme/Theme.h"
@@ -333,23 +334,23 @@ void BuilderSubTab::update_trade_button_state() {
: tr("Build a strategy first — Trade All needs at least one active leg."));
}
-QString BuilderSubTab::ensure_paper_portfolio() {
- const QString name = QStringLiteral("F&O Paper");
- const QString exchange = QStringLiteral("NFO");
- auto existing = fincept::trading::pt_find_portfolio(name, exchange);
- if (existing.has_value())
- return existing->id;
- auto p = fincept::trading::pt_create_portfolio(name, /*balance*/ 1'000'000.0,
- /*currency*/ "INR",
- /*leverage*/ 1.0,
- /*margin_mode*/ "cross",
- /*fee_rate*/ 0.0005,
- /*exchange*/ exchange);
- LOG_INFO("FnoBuilder", QString("Created paper portfolio '%1' (id=%2)").arg(name, p.id));
- return p.id;
+namespace {
+// Resolve the trading account for the chain's broker so Builder strategy trades
+// land in the SAME paper portfolio as the chain's right-click Buy/Sell (one
+// unified F&O blotter), rather than a disconnected standalone "F&O Paper"
+// portfolio. Prefer an active account, else the first configured one. Mirrors
+// ChainSubTab::find_account_for_broker.
+QString find_account_for_broker(const QString& broker_id) {
+ auto accounts = fincept::trading::AccountManager::instance().list_accounts(broker_id);
+ for (const auto& acct : accounts)
+ if (acct.is_active)
+ return acct.account_id;
+ return accounts.isEmpty() ? QString{} : accounts[0].account_id;
}
+} // namespace
void BuilderSubTab::on_trade_clicked() {
+ using namespace fincept::trading;
const auto& legs = legs_view_->leg_model()->legs();
if (legs.isEmpty() || last_chain_.rows.isEmpty())
return;
@@ -368,22 +369,44 @@ void BuilderSubTab::on_trade_clicked() {
ribbon_->set_margin(val, /*estimated*/ false);
}
- const QString portfolio_id = ensure_paper_portfolio();
+ // Route every leg through the account-aware UnifiedTrading path (identical to
+ // the chain's right-click Buy/Sell). For paper this fills market orders
+ // immediately at the current premium, tags the position with its product
+ // (NRML), stores the bare symbol so it marks to market, and keeps every F&O
+ // paper position in ONE account portfolio so square-off and the shared
+ // blotter can see them. Previously each leg was a raw "limit" order that was
+ // never filled and lived in a separate portfolio nothing else could reach.
+ const QString broker = last_chain_.broker_id;
+ const QString account_id = find_account_for_broker(broker);
+ if (account_id.isEmpty()) {
+ QMessageBox::warning(
+ this, tr("Trade Strategy"),
+ tr("No connected %1 account. Connect one in Equity Trading to paper-trade this strategy.")
+ .arg(broker.isEmpty() ? tr("trading") : broker));
+ return;
+ }
+
int placed = 0;
int failed = 0;
QStringList failures;
for (const auto& leg : legs) {
if (!leg.is_active || leg.lots == 0)
continue;
- const QString side = leg.lots > 0 ? "buy" : "sell";
- const double qty = std::abs(double(leg.lots) * double(leg.lot_size));
- try {
- fincept::trading::pt_place_order(portfolio_id, leg.symbol, side, "limit", qty,
- leg.entry_price);
+ UnifiedOrder order;
+ order.symbol = leg.symbol;
+ order.exchange = QStringLiteral("NFO");
+ order.side = leg.lots > 0 ? OrderSide::Buy : OrderSide::Sell;
+ order.order_type = OrderType::Market; // paper: execute the strategy at current premiums
+ order.quantity = std::abs(double(leg.lots) * double(leg.lot_size));
+ order.price = leg.entry_price; // current leg premium → paper fill price
+ order.product_type = ProductType::Margin; // NRML (positional) for F&O
+ order.validity = QStringLiteral("DAY");
+ auto resp = UnifiedTrading::instance().place_order(account_id, order);
+ if (resp.success) {
++placed;
- } catch (const std::exception& e) {
+ } else {
++failed;
- failures.append(QString("%1: %2").arg(leg.symbol, e.what()));
+ failures.append(QString("%1: %2").arg(leg.symbol, resp.message));
}
}
diff --git a/fincept-qt/src/screens/fno/BuilderSubTab.h b/fincept-qt/src/screens/fno/BuilderSubTab.h
index 769af4d7a..4d8604d13 100644
--- a/fincept-qt/src/screens/fno/BuilderSubTab.h
+++ b/fincept-qt/src/screens/fno/BuilderSubTab.h
@@ -62,7 +62,6 @@ class BuilderSubTab : public QWidget {
void on_chain_published(const QString& topic, const QVariant& v);
void refresh_analytics();
fincept::services::options::Strategy current_strategy() const;
- static QString ensure_paper_portfolio();
void update_trade_button_state();
BuilderAnalyticsRibbon* ribbon_ = nullptr;
diff --git a/fincept-qt/src/screens/fno/ChainSubTab.cpp b/fincept-qt/src/screens/fno/ChainSubTab.cpp
index 9ef0a0d31..585f8e689 100644
--- a/fincept-qt/src/screens/fno/ChainSubTab.cpp
+++ b/fincept-qt/src/screens/fno/ChainSubTab.cpp
@@ -11,17 +11,27 @@
#include "services/databento/DatabentoService.h"
#include "services/options/OptionChainService.h"
#include "trading/AccountManager.h"
-#include "trading/AccountManager.h"
+#include "trading/UnifiedTrading.h"
#include "trading/instruments/InstrumentService.h"
#include "ui/theme/Theme.h"
#include <QSet>
+#include <QComboBox>
+#include <QDialog>
+#include <QDialogButtonBox>
+#include <QDoubleSpinBox>
+#include <QFormLayout>
#include <QHideEvent>
+#include <QMessageBox>
+#include <QPointer>
+#include <QPushButton>
#include <QShowEvent>
+#include <QSpinBox>
#include <QStackedLayout>
#include <QTimer>
#include <QVBoxLayout>
+#include <QtConcurrent/QtConcurrent>
namespace fincept::screens::fno {
@@ -76,6 +86,7 @@ ChainSubTab::ChainSubTab(QWidget* parent) : QWidget(parent) {
connect(header_, &FnoHeaderBar::underlying_changed, this, &ChainSubTab::on_underlying_changed);
connect(header_, &FnoHeaderBar::expiry_changed, this, &ChainSubTab::on_expiry_changed);
connect(header_, &FnoHeaderBar::refresh_requested, this, &ChainSubTab::on_refresh_clicked);
+ connect(table_, &OptionChainTable::order_requested, this, &ChainSubTab::on_order_requested);
connect(&InstrumentService::instance(), &InstrumentService::refresh_done,
this, [this](const QString& broker_id) {
@@ -88,21 +99,37 @@ ChainSubTab::ChainSubTab(QWidget* parent) : QWidget(parent) {
show_empty_state(tr("Failed to load %1 instruments: %2").arg(broker_id, error));
});
- // Populate broker picker from connected accounts + Databento (always visible).
+ // Populate broker picker. Prefer a live/connected trading broker; Databento
+ // is listed (last) but only auto-selected when no broker account exists —
+ // we never auto-open Databento while a broker is connected.
QTimer::singleShot(0, this, [this]() {
+ static const QString kDatabento = QStringLiteral("databento");
QStringList broker_ids;
- broker_ids.append(QStringLiteral("databento"));
+ QString connected_broker; // first account in ConnectionState::Connected
+ QString active_broker; // first active broker account (fallback)
for (const auto& acc : AccountManager::instance().active_accounts()) {
if (!broker_ids.contains(acc.broker_id))
broker_ids.append(acc.broker_id);
+ if (active_broker.isEmpty())
+ active_broker = acc.broker_id;
+ if (connected_broker.isEmpty() &&
+ AccountManager::instance().connection_state(acc.account_id) ==
+ fincept::trading::ConnectionState::Connected)
+ connected_broker = acc.broker_id;
}
- if (broker_ids.isEmpty()) {
- show_empty_state(tr("No broker accounts or data sources configured."));
- return;
- }
- const QString prefer = !last_broker_.isEmpty() && broker_ids.contains(last_broker_)
- ? last_broker_
- : broker_ids.first();
+ broker_ids.append(kDatabento); // always available, listed last
+
+ // Auto-select: sticky real-broker choice → connected → any active → Databento.
+ QString prefer;
+ if (!last_broker_.isEmpty() && last_broker_ != kDatabento && broker_ids.contains(last_broker_))
+ prefer = last_broker_;
+ if (prefer.isEmpty())
+ prefer = connected_broker;
+ if (prefer.isEmpty())
+ prefer = active_broker;
+ if (prefer.isEmpty())
+ prefer = kDatabento;
+
header_->set_brokers(broker_ids, prefer);
rebuild_picker_for_broker(prefer, /*keep_selection*/ true);
});
@@ -151,10 +178,15 @@ void ChainSubTab::showEvent(QShowEvent* e) {
void ChainSubTab::hideEvent(QHideEvent* e) {
QWidget::hideEvent(e);
is_visible_ = false;
+ auto& hub = fincept::datahub::DataHub::instance();
if (!active_topic_.isEmpty()) {
- fincept::datahub::DataHub::instance().unsubscribe(this, active_topic_);
+ hub.unsubscribe(this, active_topic_);
active_topic_.clear();
}
+ if (!tick_pattern_.isEmpty()) {
+ hub.unsubscribe_pattern(this, tick_pattern_);
+ tick_pattern_.clear();
+ }
}
void ChainSubTab::changeEvent(QEvent* event) {
@@ -373,6 +405,10 @@ void ChainSubTab::resubscribe() {
hub.unsubscribe(this, active_topic_);
active_topic_.clear();
}
+ if (!tick_pattern_.isEmpty()) {
+ hub.unsubscribe_pattern(this, tick_pattern_);
+ tick_pattern_.clear();
+ }
const QString topic = current_topic();
if (topic.isEmpty()) {
show_empty_state(tr("Pick a broker, underlying, and expiry."));
@@ -398,6 +434,22 @@ void ChainSubTab::resubscribe() {
self->show_empty_state(ChainSubTab::tr("Chain unavailable: %1").arg(err));
});
+ // Live per-leg ticks (WS fast path): the producer fans each strike's quote
+ // out on `option:tick:<broker>:<token>`. Patch just that cell in place via
+ // OptionChainModel::update_leg_quote — no full-table rebuild per tick.
+ const QString broker = header_->broker_id();
+ if (!broker.isEmpty()) {
+ tick_pattern_ = QStringLiteral("option:tick:") + broker + QStringLiteral(":*");
+ hub.subscribe_pattern(this, tick_pattern_, [self](const QString& t, const QVariant& v) {
+ if (!self || !v.canConvert<fincept::trading::BrokerQuote>())
+ return;
+ const qint64 token = t.section(QLatin1Char(':'), -1).toLongLong();
+ if (token == 0)
+ return;
+ self->table_->chain_model()->update_leg_quote(token, v.value<fincept::trading::BrokerQuote>());
+ });
+ }
+
// Cold-start: ask producer for an immediate refresh so the user doesn't
// wait for the next scheduler tick. Honours per-producer rate limit.
hub.request(topic, /*force*/ false);
@@ -430,4 +482,201 @@ QString ChainSubTab::current_topic() const {
return OptionChainService::instance().chain_topic(broker, under, exp);
}
+void ChainSubTab::on_order_requested(qint64 token, double strike, bool is_call, bool is_buy) {
+ using namespace fincept::trading;
+ Q_UNUSED(strike);
+
+ const QString broker = header_->broker_id();
+ if (broker.isEmpty() || broker == QStringLiteral("databento")) {
+ QMessageBox::warning(this, tr("Place Order"),
+ tr("Connect a trading broker to place F&O orders."));
+ return;
+ }
+ const QString account_id = find_account_for_broker(broker);
+ if (account_id.isEmpty()) {
+ QMessageBox::warning(this, tr("Place Order"),
+ tr("No connected %1 account. Connect one in Equity Trading.").arg(broker));
+ return;
+ }
+
+ // Resolve the leg's contract details from the live chain snapshot.
+ const auto& chain = table_->chain_model()->chain();
+ QString sym;
+ int lot = 0;
+ double ltp = 0;
+ for (const auto& r : chain.rows) {
+ if (is_call && r.ce_token == token) {
+ sym = r.ce_symbol; lot = r.lot_size; ltp = r.ce_quote.ltp; break;
+ }
+ if (!is_call && r.pe_token == token) {
+ sym = r.pe_symbol; lot = r.lot_size; ltp = r.pe_quote.ltp; break;
+ }
+ }
+ if (sym.isEmpty()) {
+ QMessageBox::warning(this, tr("Place Order"), tr("Could not resolve the contract for this strike."));
+ return;
+ }
+
+ // Broker-native symbol/exchange. Fyers chain symbols are already native
+ // ("NSE:...CE") and pass straight through place_order's to_fyers_sym; other
+ // brokers map via InstrumentService (normalized symbol → brsymbol/brexchange).
+ QString order_symbol = sym;
+ QString order_exchange = QStringLiteral("NFO");
+ if (auto inst = InstrumentService::instance().find(sym, QStringLiteral("NFO"), broker)) {
+ if (!inst->brsymbol.isEmpty())
+ order_symbol = inst->brsymbol;
+ if (!inst->brexchange.isEmpty())
+ order_exchange = inst->brexchange;
+ if (inst->lot_size > 0)
+ lot = inst->lot_size;
+ }
+ // Fyers' options-chain-v3 omits lot size (chain row lot is 0) and its
+ // "NSE:...CE" symbol won't match the master's normalized key — so backfill
+ // the lot from the underlying's NFO instruments (all share one lot size).
+ if (lot <= 0) {
+ const auto insts = InstrumentService::instance().find_options_for_underlying(
+ broker, header_->underlying(), header_->expiry(), QStringLiteral("NFO"));
+ for (const auto& in : insts) {
+ if (in.lot_size > 0) {
+ lot = in.lot_size;
+ break;
+ }
+ }
+ }
+ if (lot <= 0) {
+ QMessageBox::warning(this, tr("Place Order"), tr("Could not resolve the lot size for %1.").arg(sym));
+ return;
+ }
+
+ // Canonical bare symbol for the quote/position layer (matches the equity
+ // convention + the WS-published symbol): strip the "NSE:" exchange prefix and
+ // any segment suffix. Paper positions are stored under this so they mark to
+ // market against the live broker quote feed (broker:<id>:<acct>:quote:<bare>).
+ QString bare_sym = order_symbol;
+ if (const int c = bare_sym.indexOf(QLatin1Char(':')); c >= 0)
+ bare_sym = bare_sym.mid(c + 1);
+ for (const auto& suf : {QStringLiteral("-CE"), QStringLiteral("-PE"), QStringLiteral("-FUT"),
+ QStringLiteral("-EQ")}) {
+ if (bare_sym.endsWith(suf)) {
+ bare_sym.chop(int(suf.size()));
+ break;
+ }
+ }
+
+ const BrokerAccount acct = AccountManager::instance().get_account(account_id);
+ const bool is_paper = (acct.trading_mode != QStringLiteral("live"));
+ const QString acct_name = acct.display_name.isEmpty() ? account_id : acct.display_name;
+
+ // ── Order ticket (editable: type, lots, price, product) ──────────────────
+ QDialog dlg(this);
+ dlg.setWindowTitle(is_buy ? tr("Buy %1").arg(sym) : tr("Sell %1").arg(sym));
+ auto* form = new QFormLayout(&dlg);
+
+ auto* hdr = new QLabel(QStringLiteral("%1 %2").arg(is_buy ? tr("BUY") : tr("SELL"), sym), &dlg);
+ hdr->setStyleSheet(QStringLiteral("font-weight:700;font-size:13px;color:%1;")
+ .arg(is_buy ? colors::POSITIVE() : colors::NEGATIVE()));
+ form->addRow(hdr);
+
+ auto* type_combo = new QComboBox(&dlg);
+ type_combo->addItems({tr("Market"), tr("Limit")});
+ form->addRow(tr("Type"), type_combo);
+
+ auto* lots_spin = new QSpinBox(&dlg);
+ lots_spin->setRange(1, 100000);
+ lots_spin->setValue(1);
+ form->addRow(tr("Qty (lots)"), lots_spin);
+
+ auto* qty_label = new QLabel(&dlg);
+ qty_label->setStyleSheet(QStringLiteral("color:%1;font-size:11px;").arg(colors::TEXT_SECONDARY()));
+ auto update_qty = [qty_label, lots_spin, lot]() {
+ qty_label->setText(ChainSubTab::tr("= %1 qty (lot size %2)").arg(lots_spin->value() * lot).arg(lot));
+ };
+ update_qty();
+ connect(lots_spin, qOverload<int>(&QSpinBox::valueChanged), &dlg, [update_qty](int) { update_qty(); });
+ form->addRow(QString(), qty_label);
+
+ auto* px_spin = new QDoubleSpinBox(&dlg);
+ px_spin->setRange(0.05, 1.0e8);
+ px_spin->setDecimals(2);
+ px_spin->setValue(ltp > 0 ? ltp : 0.05);
+ form->addRow(tr("Limit price"), px_spin);
+
+ auto* product_combo = new QComboBox(&dlg);
+ product_combo->addItems({tr("NRML (positional)"), tr("MIS (intraday)")});
+ form->addRow(tr("Product"), product_combo);
+
+ // Market needs no price — hide the limit row unless Limit is selected.
+ auto sync_type = [form, px_spin](int idx) { form->setRowVisible(px_spin, idx == 1); };
+ connect(type_combo, qOverload<int>(&QComboBox::currentIndexChanged), &dlg, sync_type);
+ sync_type(type_combo->currentIndex());
+
+ auto* ctx = new QLabel(
+ QStringLiteral("%1 · LTP %2 · [%3]").arg(acct_name).arg(ltp, 0, 'f', 2).arg(is_paper ? tr("PAPER") : tr("LIVE")),
+ &dlg);
+ ctx->setStyleSheet(QStringLiteral("color:%1;font-size:11px;").arg(colors::TEXT_SECONDARY()));
+ form->addRow(ctx);
+
+ auto* buttons = new QDialogButtonBox(QDialogButtonBox::Cancel, &dlg);
+ QPushButton* ok = buttons->addButton(is_buy ? tr("Place Buy") : tr("Place Sell"), QDialogButtonBox::AcceptRole);
+ ok->setDefault(true);
+ connect(buttons, &QDialogButtonBox::accepted, &dlg, &QDialog::accept);
+ connect(buttons, &QDialogButtonBox::rejected, &dlg, &QDialog::reject);
+ form->addRow(buttons);
+
+ if (dlg.exec() != QDialog::Accepted)
+ return;
+
+ const bool is_market = (type_combo->currentIndex() == 0);
+ UnifiedOrder order;
+ // Live placement needs the broker-native symbol; paper stores the bare symbol
+ // so the position marks to market against the live quote feed.
+ order.symbol = is_paper ? bare_sym : order_symbol;
+ order.exchange = order_exchange;
+ order.side = is_buy ? OrderSide::Buy : OrderSide::Sell;
+ order.order_type = is_market ? OrderType::Market : OrderType::Limit;
+ order.quantity = double(lots_spin->value()) * double(lot);
+ order.price = is_market ? ltp : px_spin->value(); // ltp lets paper fill a market order; live ignores it
+ order.product_type = (product_combo->currentIndex() == 1) ? ProductType::Intraday : ProductType::Margin;
+ order.validity = QStringLiteral("DAY");
+ order.instrument_token = QString::number(token);
+ LOG_INFO("posdbg", QString("FNO order placed: sym='%1' (bare='%2' native='%3') qty=%4 %5 acct=%6 mode=%7")
+ .arg(order.symbol, bare_sym, order_symbol)
+ .arg(order.quantity)
+ .arg(is_buy ? "BUY" : "SELL", account_id, is_paper ? "paper" : "live"));
+
+ auto show_result = [this](const UnifiedOrderResponse& result) {
+ if (result.success)
+ QMessageBox::information(this, tr("Place Order"), tr("Order placed: %1").arg(result.order_id));
+ else
+ QMessageBox::warning(this, tr("Place Order"), tr("Order failed: %1").arg(result.message));
+ };
+
+ if (is_paper) {
+ // Paper placement is a fast local DB write + immediate fill — main thread.
+ show_result(UnifiedTrading::instance().place_order(account_id, order));
+ return;
+ }
+
+ // Live placement hits the broker REST synchronously — run off the UI thread.
+ QPointer<ChainSubTab> self = this;
+ (void)QtConcurrent::run([self, account_id, order]() {
+ auto result = UnifiedTrading::instance().place_order(account_id, order);
+ if (!self)
+ return;
+ QMetaObject::invokeMethod(
+ self,
+ [self, result]() {
+ if (!self)
+ return;
+ if (result.success)
+ QMessageBox::information(self, ChainSubTab::tr("Place Order"),
+ ChainSubTab::tr("Order placed: %1").arg(result.order_id));
+ else
+ QMessageBox::warning(self, ChainSubTab::tr("Place Order"),
+ ChainSubTab::tr("Order failed: %1").arg(result.message));
+ },
+ Qt::QueuedConnection);
+ });
+}
+
} // namespace fincept::screens::fno
diff --git a/fincept-qt/src/screens/fno/ChainSubTab.h b/fincept-qt/src/screens/fno/ChainSubTab.h
index 3ca0ffab6..c392901f9 100644
--- a/fincept-qt/src/screens/fno/ChainSubTab.h
+++ b/fincept-qt/src/screens/fno/ChainSubTab.h
@@ -65,6 +65,9 @@ class ChainSubTab : public QWidget {
void on_underlying_changed(const QString& underlying);
void on_expiry_changed(const QString& expiry);
void on_refresh_clicked();
+ /// Right-click Buy/Sell on a chain leg → build a 1-lot market order, confirm,
+ /// and route to the connected broker (live or paper per its trading mode).
+ void on_order_requested(qint64 token, double strike, bool is_call, bool is_buy);
private:
void retranslateUi();
@@ -85,6 +88,10 @@ class ChainSubTab : public QWidget {
/// Topic we're currently subscribed to. Empty when not subscribed.
QString active_topic_;
+ /// Per-leg live-tick pattern we're subscribed to (`option:tick:<broker>:*`),
+ /// used to patch single cells from the WS feed. Empty when not subscribed.
+ QString tick_pattern_;
+
/// Whether the widget is currently visible — gates re-subscribe paths
/// triggered by combo changes from non-visible state.
bool is_visible_ = false;
diff --git a/fincept-qt/src/screens/fno/FnoHeaderBar.cpp b/fincept-qt/src/screens/fno/FnoHeaderBar.cpp
index 0df96c59f..9af383f12 100644
--- a/fincept-qt/src/screens/fno/FnoHeaderBar.cpp
+++ b/fincept-qt/src/screens/fno/FnoHeaderBar.cpp
@@ -8,6 +8,7 @@
#include <QHBoxLayout>
#include <QLocale>
#include <QSignalBlocker>
+#include <QStyle>
#include <QVBoxLayout>
#include <algorithm>
@@ -190,12 +191,22 @@ void FnoHeaderBar::set_expiries(const QStringList& exps, const QString& selected
void FnoHeaderBar::update_from_chain(const OptionChain& chain) {
lbl_spot_->setText(chain.spot > 0 ? QString::number(chain.spot, 'f', 2) : "--");
- // Day change is derived from the underlying quote — but we don't carry
- // the underlying BrokerQuote in OptionChain (only spot). For Phase 2
- // we leave change blank; Phase 3's WS path will plumb spot quote +
- // day change through the chain payload.
- lbl_change_->setText("--");
- lbl_change_->setObjectName("fnoHdrValue");
+ // Day change — underlying's absolute + % move, plumbed through OptionChain
+ // from the spot quote (REST refresh; WS keeps option legs current). Coloured
+ // green/red via the #fnoHdrValuePos / #fnoHdrValueNeg style selectors.
+ if (chain.spot_change != 0.0 || chain.spot_change_pct != 0.0) {
+ const bool up = chain.spot_change >= 0.0;
+ const QString sign = up ? QStringLiteral("+") : QString();
+ lbl_change_->setText(sign + QString::number(chain.spot_change, 'f', 2) + " (" + sign +
+ QString::number(chain.spot_change_pct, 'f', 2) + "%)");
+ lbl_change_->setObjectName(up ? "fnoHdrValuePos" : "fnoHdrValueNeg");
+ } else {
+ lbl_change_->setText("--");
+ lbl_change_->setObjectName("fnoHdrValue");
+ }
+ // objectName drives the QSS colour selector — re-polish so it repaints.
+ lbl_change_->style()->unpolish(lbl_change_);
+ lbl_change_->style()->polish(lbl_change_);
lbl_atm_->setText(chain.atm_strike > 0 ? QString::number(chain.atm_strike, 'f', 0) : "--");
lbl_pcr_->setText(chain.pcr > 0 ? QString::number(chain.pcr, 'f', 3) : "--");
@@ -237,8 +248,11 @@ void FnoHeaderBar::update_from_chain(const OptionChain& chain) {
.arg(pctile, 0, 'f', 0)
.arg(hist.size()));
} else {
- lbl_iv_pctile_->setText("—");
- lbl_iv_pctile_->setToolTip(tr("Needs ≥30 days of data — have %1.").arg(hist.size()));
+ // Not enough history yet — show accumulation progress instead
+ // of a blank dash so it's clear it's building, not broken.
+ lbl_iv_pctile_->setText(tr("…%1/30").arg(hist.size()));
+ lbl_iv_pctile_->setToolTip(
+ tr("Building IV history — %1 of 30 days needed for a percentile.").arg(hist.size()));
}
} else {
lbl_iv_pctile_->setText("—");
diff --git a/fincept-qt/src/screens/fno/FnoScreen.cpp b/fincept-qt/src/screens/fno/FnoScreen.cpp
index ee7b344a9..c846ea616 100644
--- a/fincept-qt/src/screens/fno/FnoScreen.cpp
+++ b/fincept-qt/src/screens/fno/FnoScreen.cpp
@@ -9,6 +9,7 @@
#include "screens/fno/OISubTab.h"
#include "screens/fno/OptionChainTable.h"
#include "screens/fno/ScreenerSubTab.h"
+#include "screens/common/PaperBlotterPanel.h"
#include "services/options/OptionChainService.h"
#include "ui/theme/Theme.h"
@@ -52,6 +53,7 @@ QString FnoScreen::tab_label_for(int index) {
case TabMultiStraddle: return tr("Multi-Stra");
case TabFiiDii: return tr("FII / DII");
case TabScreener: return tr("Screener");
+ case TabPositions: return tr("Positions");
default: return {};
}
}
@@ -64,6 +66,7 @@ QString FnoScreen::tab_detail_for(int index) {
case TabMultiStraddle: return tr("Multi straddle / strangle charts (Phase 9)");
case TabFiiDii: return tr("Institutional flows (Phase 8)");
case TabScreener: return tr("Chain screener (Phase 9)");
+ case TabPositions: return tr("Paper positions, orders & square-off");
default: return {};
}
}
@@ -203,6 +206,14 @@ void FnoScreen::ensure_tab_built(SubTab which) {
replace_placeholder<ScreenerSubTab>(stack_, tabs_, TabScreener, p, this);
screener_tab_ = p;
}
+ if (which == TabPositions && !positions_tab_) {
+ // Shared paper blotter: open positions / working orders / trades for every
+ // active paper account, with square-off. Self-populating and live via
+ // PaperMarkService — no per-screen marking wiring needed here.
+ common::PaperBlotterPanel* p = nullptr;
+ replace_placeholder<common::PaperBlotterPanel>(stack_, tabs_, TabPositions, p, this);
+ positions_tab_ = p;
+ }
// Phase 9: all six F&O sub-tabs are real (no more placeholders).
}
diff --git a/fincept-qt/src/screens/fno/FnoScreen.h b/fincept-qt/src/screens/fno/FnoScreen.h
index d05ddd388..f38b12016 100644
--- a/fincept-qt/src/screens/fno/FnoScreen.h
+++ b/fincept-qt/src/screens/fno/FnoScreen.h
@@ -29,6 +29,10 @@
#include <functional>
+namespace fincept::screens::common {
+class PaperBlotterPanel;
+}
+
namespace fincept::screens::fno {
class BuilderSubTab;
@@ -67,6 +71,7 @@ class FnoScreen : public QWidget,
TabMultiStraddle = 3,
TabFiiDii = 4,
TabScreener = 5,
+ TabPositions = 6,
TabCount
};
@@ -105,6 +110,7 @@ class FnoScreen : public QWidget,
QPointer<class FiiDiiSubTab> fii_dii_tab_;
QPointer<class MultiStraddleSubTab> multi_straddle_tab_;
QPointer<class ScreenerSubTab> screener_tab_;
+ QPointer<fincept::screens::common::PaperBlotterPanel> positions_tab_;
// Group G is the "yellow" slot in the default palette (per SymbolGroup.h
// line 16). Plan called for Yellow as the F&O default — that's slot G.
diff --git a/fincept-qt/src/screens/fno/OptionChainModel.cpp b/fincept-qt/src/screens/fno/OptionChainModel.cpp
index c1b54607f..a348efa96 100644
--- a/fincept-qt/src/screens/fno/OptionChainModel.cpp
+++ b/fincept-qt/src/screens/fno/OptionChainModel.cpp
@@ -136,6 +136,26 @@ QVariant OptionChainModel::headerData(int section, Qt::Orientation orient, int r
}
void OptionChainModel::set_chain(const OptionChain& chain) {
+ // When the strike/token structure is unchanged (same expiry republished —
+ // e.g. a WS-driven live re-publish or a periodic reconcile), merge in place
+ // and repaint instead of resetting the model. A full reset would drop the
+ // user's scroll position and selection on every refresh; this keeps them.
+ bool same_structure = chain.rows.size() == chain_.rows.size() && !chain_.rows.isEmpty();
+ if (same_structure) {
+ for (int i = 0; i < chain.rows.size(); ++i) {
+ if (chain.rows[i].ce_token != chain_.rows[i].ce_token ||
+ chain.rows[i].pe_token != chain_.rows[i].pe_token) {
+ same_structure = false;
+ break;
+ }
+ }
+ }
+ if (same_structure) {
+ chain_ = chain;
+ recompute_oi_bounds();
+ emit dataChanged(index(0, 0), index(chain_.rows.size() - 1, ColCount - 1));
+ return;
+ }
beginResetModel();
chain_ = chain;
recompute_oi_bounds();
diff --git a/fincept-qt/src/screens/fno/OptionChainTable.cpp b/fincept-qt/src/screens/fno/OptionChainTable.cpp
index 290f80ced..bd9174776 100644
--- a/fincept-qt/src/screens/fno/OptionChainTable.cpp
+++ b/fincept-qt/src/screens/fno/OptionChainTable.cpp
@@ -3,7 +3,9 @@
#include "screens/fno/OptionChainModel.h"
#include "ui/theme/Theme.h"
+#include <QContextMenuEvent>
#include <QHeaderView>
+#include <QMenu>
#include <QMouseEvent>
#include <QPainter>
#include <QStyledItemDelegate>
@@ -140,21 +142,69 @@ OptionChainTable::OptionChainTable(QWidget* parent) : QTableView(parent) {
}
void OptionChainTable::mousePressEvent(QMouseEvent* e) {
- QModelIndex idx = indexAt(e->pos());
- if (idx.isValid()) {
- const int col = idx.column();
- const bool is_ce_ltp = (col == OptionChainModel::ColCeLtp);
- const bool is_pe_ltp = (col == OptionChainModel::ColPeLtp);
- if (is_ce_ltp || is_pe_ltp) {
- const qint64 token = is_ce_ltp ? idx.data(OptionChainModel::CeTokenRole).toLongLong()
- : idx.data(OptionChainModel::PeTokenRole).toLongLong();
- const double strike = idx.data(OptionChainModel::StrikeRole).toDouble();
- const int lots = (e->button() == Qt::RightButton) ? -1 : 1;
- if (token != 0)
- emit leg_clicked(token, strike, is_ce_ltp, lots);
+ // Left-click an LTP cell adds the leg to the strategy builder. Right-click
+ // is handled by contextMenuEvent (Buy/Sell/Add-to-Builder), so it must NOT
+ // also fire leg_clicked here.
+ if (e->button() == Qt::LeftButton) {
+ QModelIndex idx = indexAt(e->pos());
+ if (idx.isValid()) {
+ const int col = idx.column();
+ const bool is_ce_ltp = (col == OptionChainModel::ColCeLtp);
+ const bool is_pe_ltp = (col == OptionChainModel::ColPeLtp);
+ if (is_ce_ltp || is_pe_ltp) {
+ const qint64 token = is_ce_ltp ? idx.data(OptionChainModel::CeTokenRole).toLongLong()
+ : idx.data(OptionChainModel::PeTokenRole).toLongLong();
+ const double strike = idx.data(OptionChainModel::StrikeRole).toDouble();
+ if (token != 0)
+ emit leg_clicked(token, strike, is_ce_ltp, 1);
+ }
}
}
QTableView::mousePressEvent(e);
}
+void OptionChainTable::contextMenuEvent(QContextMenuEvent* e) {
+ const QModelIndex idx = indexAt(e->pos());
+ if (!idx.isValid() || !model_) {
+ QTableView::contextMenuEvent(e);
+ return;
+ }
+ const int col = idx.column();
+ const bool ce_side = (col >= OptionChainModel::ColCeOi && col <= OptionChainModel::ColCeLtp);
+ const bool pe_side = (col >= OptionChainModel::ColPeLtp && col <= OptionChainModel::ColPeOi);
+ if (!ce_side && !pe_side) { // strike pivot — nothing to trade
+ QTableView::contextMenuEvent(e);
+ return;
+ }
+ const bool is_call = ce_side;
+ const qint64 token = idx.data(is_call ? OptionChainModel::CeTokenRole : OptionChainModel::PeTokenRole).toLongLong();
+ const double strike = idx.data(OptionChainModel::StrikeRole).toDouble();
+ if (token == 0) {
+ QTableView::contextMenuEvent(e);
+ return;
+ }
+
+ // Prefer the broker contract symbol for the menu label; fall back to strike+side.
+ QString label = QString::number(strike, 'f', 0) + (is_call ? QStringLiteral(" CE") : QStringLiteral(" PE"));
+ const auto& rows = model_->chain().rows;
+ if (idx.row() >= 0 && idx.row() < rows.size()) {
+ const QString sym = is_call ? rows[idx.row()].ce_symbol : rows[idx.row()].pe_symbol;
+ if (!sym.isEmpty())
+ label = sym;
+ }
+
+ QMenu menu(this);
+ QAction* buy = menu.addAction(tr("Buy %1").arg(label));
+ QAction* sell = menu.addAction(tr("Sell %1").arg(label));
+ menu.addSeparator();
+ QAction* to_builder = menu.addAction(tr("Add to Builder"));
+ QAction* chosen = menu.exec(e->globalPos());
+ if (chosen == buy)
+ emit order_requested(token, strike, is_call, /*is_buy=*/true);
+ else if (chosen == sell)
+ emit order_requested(token, strike, is_call, /*is_buy=*/false);
+ else if (chosen == to_builder)
+ emit leg_clicked(token, strike, is_call, 1);
+}
+
} // namespace fincept::screens::fno
diff --git a/fincept-qt/src/screens/fno/OptionChainTable.h b/fincept-qt/src/screens/fno/OptionChainTable.h
index c5fed859a..5ec3e9150 100644
--- a/fincept-qt/src/screens/fno/OptionChainTable.h
+++ b/fincept-qt/src/screens/fno/OptionChainTable.h
@@ -20,14 +20,19 @@ class OptionChainTable : public QTableView {
OptionChainModel* chain_model() const { return model_; }
signals:
- /// Emitted when the user clicks a CE or PE LTP cell — used by the
- /// strategy builder (Phase 5) to add a leg.
- /// `is_call=true` means CE side. `lots` is +1 (buy) for left-click,
- /// -1 (sell) for right-click.
+ /// Emitted when the user left-clicks a CE or PE LTP cell (or picks
+ /// "Add to Builder") — used by the strategy builder (Phase 5) to add a
+ /// leg. `is_call=true` means CE side. `lots` is +1 (buy).
void leg_clicked(qint64 token, double strike, bool is_call, int lots);
+ /// Emitted when the user picks Buy/Sell from a leg's right-click menu.
+ /// `is_buy=false` means Sell. ChainSubTab routes it to the broker (live
+ /// or paper, per the connected account's trading mode).
+ void order_requested(qint64 token, double strike, bool is_call, bool is_buy);
+
protected:
void mousePressEvent(QMouseEvent* e) override;
+ void contextMenuEvent(QContextMenuEvent* e) override;
private:
OptionChainModel* model_ = nullptr;
diff --git a/fincept-qt/src/screens/settings/LlmConfigSection.cpp b/fincept-qt/src/screens/settings/LlmConfigSection.cpp
index c2e782b18..2961a518d 100644
--- a/fincept-qt/src/screens/settings/LlmConfigSection.cpp
+++ b/fincept-qt/src/screens/settings/LlmConfigSection.cpp
@@ -35,7 +35,7 @@ static constexpr const char* TAG = "LlmConfigSection";
const QStringList LlmConfigSection::KNOWN_PROVIDERS = {"openai", "anthropic", "gemini", "groq", "deepseek",
"openrouter", "minimax", "kimi", "ollama", "xai", "fincept",
- "astraflow", "astraflow_cn", "aihubmix"};
+ "astraflow", "astraflow_cn", "aihubmix", "atlascloud"};
QString LlmConfigSection::default_base_url(const QString& provider) {
const QString p = provider.toLower();
@@ -67,6 +67,8 @@ QString LlmConfigSection::default_base_url(const QString& provider) {
return "https://api.modelverse.cn/v1"; // Astraflow China endpoint (UCloud)
if (p == "aihubmix")
return "https://aihubmix.com/v1"; // AIHubMix — OpenAI-compatible aggregator (500+ models)
+ if (p == "atlascloud")
+ return "https://api.atlascloud.ai/v1"; // AtlasCloud — OpenAI-compatible aggregator (300+ open models)
return {};
}
@@ -126,6 +128,16 @@ QStringList LlmConfigSection::fallback_models(const QString& provider) {
"gemini-2.5-flash", "gemini-2.5-pro",
"deepseek-chat", "deepseek-reasoner",
"qwen-max", "qwen-plus", "grok-4"};
+ if (p == "atlascloud")
+ // AtlasCloud — OpenAI-compatible aggregator (300+ models). Model ids are
+ // HuggingFace-style "org/model" strings (NOT short aliases). Note: a few ids
+ // listed by /v1/models are unprovisioned and return 400 (e.g. google/gemini-2.0-flash,
+ // openai/gpt-4o*). The list below is a verified-working starter set; use the
+ // Fetch button for the full live catalog (/v1/models).
+ return {"deepseek-ai/DeepSeek-V3.1", "deepseek-ai/deepseek-r1-0528",
+ "qwen/qwen3-32b", "Qwen/Qwen3-235B-A22B-Instruct-2507",
+ "zai-org/GLM-4.6", "moonshotai/Kimi-K2-Instruct", "MiniMaxAI/MiniMax-M2",
+ "google/gemini-2.5-flash", "anthropic/claude-haiku-4.5-20251001"};
return {};
}
diff --git a/fincept-qt/src/services/algo_trading/AlgoTradingService.cpp b/fincept-qt/src/services/algo_trading/AlgoTradingService.cpp
index ae43246dc..9c984bb12 100644
--- a/fincept-qt/src/services/algo_trading/AlgoTradingService.cpp
+++ b/fincept-qt/src/services/algo_trading/AlgoTradingService.cpp
@@ -40,22 +40,26 @@ void AlgoTradingService::save_strategy(const AlgoStrategy& strategy) {
QString::fromUtf8(QJsonDocument(strategy.entry_conditions).toJson(QJsonDocument::Compact));
const QString exit_json =
QString::fromUtf8(QJsonDocument(strategy.exit_conditions).toJson(QJsonDocument::Compact));
+ const QString legs_json =
+ QString::fromUtf8(QJsonDocument(strategy.legs).toJson(QJsonDocument::Compact));
// is_active=1 in the UPDATE branch so re-saving a soft-deleted strategy revives it.
auto r = fincept::Database::instance().execute(
"INSERT INTO algo_strategies "
"(id, name, description, timeframe, entry_conditions, exit_conditions, "
- " entry_logic, exit_logic, stop_loss, take_profit, trailing_stop, updated_at) "
- "VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, CURRENT_TIMESTAMP) "
+ " entry_logic, exit_logic, stop_loss, take_profit, trailing_stop, "
+ " instrument_type, legs_json, updated_at) "
+ "VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, CURRENT_TIMESTAMP) "
"ON CONFLICT(id) DO UPDATE SET "
" name=excluded.name, description=excluded.description, timeframe=excluded.timeframe, "
" entry_conditions=excluded.entry_conditions, exit_conditions=excluded.exit_conditions, "
" entry_logic=excluded.entry_logic, exit_logic=excluded.exit_logic, "
" stop_loss=excluded.stop_loss, take_profit=excluded.take_profit, "
- " trailing_stop=excluded.trailing_stop, is_active=1, updated_at=CURRENT_TIMESTAMP",
+ " trailing_stop=excluded.trailing_stop, instrument_type=excluded.instrument_type, "
+ " legs_json=excluded.legs_json, is_active=1, updated_at=CURRENT_TIMESTAMP",
{resolved_id, strategy.name, strategy.description, strategy.timeframe, entry_json, exit_json,
strategy.entry_logic, strategy.exit_logic, strategy.stop_loss, strategy.take_profit,
- strategy.trailing_stop});
+ strategy.trailing_stop, strategy.instrument_type, legs_json});
if (r.is_err()) {
LOG_ERROR("AlgoTrading", QString("save_strategy failed: %1").arg(QString::fromStdString(r.error())));
@@ -71,7 +75,7 @@ static QVector<AlgoStrategy> load_dsl_strategies_from_db() {
auto q = fincept::Database::instance().execute(
"SELECT id, name, description, timeframe, entry_conditions, exit_conditions, "
"entry_logic, exit_logic, stop_loss, take_profit, trailing_stop, "
- "created_at, updated_at "
+ "created_at, updated_at, instrument_type, legs_json "
"FROM algo_strategies WHERE is_active = 1 ORDER BY created_at DESC", {});
if (q.is_err())
return result;
@@ -91,6 +95,8 @@ static QVector<AlgoStrategy> load_dsl_strategies_from_db() {
s.trailing_stop = query.value(10).toDouble();
s.created_at = query.value(11).toString();
s.updated_at = query.value(12).toString();
+ s.instrument_type = query.value(13).isNull() ? QStringLiteral("equity") : query.value(13).toString();
+ s.legs = QJsonDocument::fromJson(query.value(14).toString().toUtf8()).array();
result.append(s);
}
return result;
diff --git a/fincept-qt/src/services/algo_trading/AlgoTradingTypes.h b/fincept-qt/src/services/algo_trading/AlgoTradingTypes.h
index 16bf37fdf..508e49f03 100644
--- a/fincept-qt/src/services/algo_trading/AlgoTradingTypes.h
+++ b/fincept-qt/src/services/algo_trading/AlgoTradingTypes.h
@@ -58,8 +58,10 @@ struct AlgoStrategy {
QString name;
QString description;
QString timeframe; // live, 1m, 5m, 15m, 1h, 4h, 1d
+ QString instrument_type = "equity"; // equity | option | future
QJsonArray entry_conditions;
QJsonArray exit_conditions;
+ QJsonArray legs; // F&O leg-rule definitions (see fno::fno_legs_to_json); empty for equity
QString entry_logic = "AND"; // AND, OR
QString exit_logic = "AND";
double stop_loss = 0;
@@ -83,6 +85,10 @@ struct AlgoDeployment {
QString strategy_kind = "dsl"; // 'dsl' | 'qc' — cached from strategy_id prefix at deploy time
QString symbol;
QString exchange; // e.g. "NSE", "NASDAQ" — from broker profile
+ QString instrument_type = "equity"; // equity | option | future
+ QString underlying; // F&O underlying, e.g. "NIFTY" (option/future only)
+ QString resolved_expiry; // concrete expiry chosen at entry, "DD-MMM-YY"
+ QJsonArray resolved_legs; // concrete contracts placed at entry (restart reattach)
QString product_type; // e.g. "MIS", "CNC" — broker-specific
QString mode; // paper | live
QString entry_side = "BUY"; // BUY | SELL — direction of the entry signal
diff --git a/fincept-qt/src/services/llm/LlmHttpHelpers.cpp b/fincept-qt/src/services/llm/LlmHttpHelpers.cpp
index 4c91aa0cd..cd95e87af 100644
--- a/fincept-qt/src/services/llm/LlmHttpHelpers.cpp
+++ b/fincept-qt/src/services/llm/LlmHttpHelpers.cpp
@@ -157,7 +157,7 @@ QString strip_think_blocks(QString content) {
}
// ── SSE chunk → text ───────────────────────────────────────────────────────
-QString LlmService::parse_sse_chunk(const QString& data, const QString& provider) {
+LlmService::SseDelta LlmService::parse_sse_chunk(const QString& data, const QString& provider) {
auto doc = QJsonDocument::fromJson(data.toUtf8());
if (doc.isNull() || !doc.isObject())
return {};
@@ -167,15 +167,16 @@ QString LlmService::parse_sse_chunk(const QString& data, const QString& provider
// delta is a tagged union. text_delta carries the final answer;
// thinking_delta carries the chain-of-thought for extended-thinking
// models (claude-3-7 / claude-opus-4+ with `thinking` param). Surfacing
- // both keeps the UI responsive during long reasoning phases. Other
- // delta types (input_json_delta, signature_delta) must not be rendered.
+ // both keeps the UI responsive during long reasoning phases, but they
+ // must stay on SEPARATE channels so the UI doesn't mix reasoning into the
+ // answer. Other delta types (input_json_delta, signature_delta) aren't rendered.
if (j["type"].toString() == "content_block_delta") {
QJsonObject delta = j["delta"].toObject();
const QString dtype = delta["type"].toString();
if (dtype == "text_delta")
- return delta["text"].toString();
+ return {delta["text"].toString(), false};
if (dtype == "thinking_delta")
- return delta["thinking"].toString();
+ return {delta["thinking"].toString(), true};
}
return {};
}
@@ -187,22 +188,22 @@ QString LlmService::parse_sse_chunk(const QString& data, const QString& provider
if (!delta["content"].isNull() && !delta["content"].isUndefined()) {
QString s = delta["content"].toString();
if (!s.isEmpty())
- return s;
+ return {s, false};
}
// Reasoning models (kimi-k2.5 / kimi-k2.6 / kimi-k2-thinking*, deepseek-reasoner,
- // grok-4 reasoning variants) stream their chain-of-thought as
+ // GLM / MiniMax / grok-4 reasoning variants) stream their chain-of-thought as
// `delta.reasoning_content` and only emit `delta.content` after reasoning
- // completes. Surface reasoning deltas so the user sees progress instead
- // of a blank bubble for 10+ seconds.
+ // completes. Tag it as reasoning so the caller routes it to the separate,
+ // collapsible Thinking section instead of concatenating it into the answer.
if (!delta["reasoning_content"].isNull() && !delta["reasoning_content"].isUndefined()) {
QString s = delta["reasoning_content"].toString();
if (!s.isEmpty())
- return s;
+ return {s, true};
}
// Refusal deltas — newer OpenAI and some Groq safety paths stream a
// `refusal` field in place of `content` when the model declines.
if (!delta["refusal"].isNull() && !delta["refusal"].isUndefined())
- return delta["refusal"].toString();
+ return {delta["refusal"].toString(), false};
}
return {};
}
diff --git a/fincept-qt/src/services/llm/LlmModelsApi.cpp b/fincept-qt/src/services/llm/LlmModelsApi.cpp
index 2adcc5d71..03bd59764 100644
--- a/fincept-qt/src/services/llm/LlmModelsApi.cpp
+++ b/fincept-qt/src/services/llm/LlmModelsApi.cpp
@@ -69,6 +69,7 @@ QString LlmService::get_models_url(const QString& provider, const QString& api_k
if (p == "xai") return "https://api.x.ai/v1/models";
if (p == "kimi") return "https://api.moonshot.ai/v1/models";
if (p == "aihubmix") return "https://aihubmix.com/v1/models"; // fallback if prefilled base_url was cleared
+ if (p == "atlascloud") return "https://api.atlascloud.ai/v1/models"; // fallback if prefilled base_url was cleared
if (p == "fincept") return fincept::AppConfig::instance().api_base_url() + "/research/llm/models";
// minimax has no public /v1/models — caller falls back to known models.
return {};
diff --git a/fincept-qt/src/services/llm/LlmService.cpp b/fincept-qt/src/services/llm/LlmService.cpp
index e2d6a7a9d..d72855202 100644
--- a/fincept-qt/src/services/llm/LlmService.cpp
+++ b/fincept-qt/src/services/llm/LlmService.cpp
@@ -386,6 +386,9 @@ QString LlmService::get_endpoint_url() const {
// Fallback for when the prefilled base_url was cleared; the custom-base_url
// branch above wins whenever it's set (incl. regional/proxy overrides).
return "https://aihubmix.com/v1/chat/completions";
+ if (p == "atlascloud")
+ // Fallback if the prefilled base_url was cleared; custom-base_url branch wins otherwise.
+ return "https://api.atlascloud.ai/v1/chat/completions";
return {};
}
@@ -841,9 +844,12 @@ LlmResponse LlmService::do_streaming_request(const QString& user_message,
// `delta.content` wrapped in <think> tags. The user shouldn't see that —
// only the answer. State persists across SSE chunks because tags can
// straddle the chunk boundary ("<thi" + "nk>...").
+ // Returns the visible (answer) text; any reasoning found inside <think>…</think>
+ // is appended to *think_out so the caller can route it to the Thinking channel
+ // rather than dropping it.
bool in_think = false;
QString think_pending;
- auto filter_think = [&](const QString& chunk) -> QString {
+ auto filter_think = [&](const QString& chunk, QString* think_out) -> QString {
QString out;
QString work = think_pending + chunk;
think_pending.clear();
@@ -855,9 +861,13 @@ LlmResponse LlmService::do_streaming_request(const QString& user_message,
if (end < 0) {
// Hold last 8 chars in case </think> straddles.
qsizetype safe = std::max<qsizetype>(pos, n - 8);
+ if (think_out)
+ *think_out += work.mid(pos, safe - pos);
think_pending = work.mid(safe);
return out;
}
+ if (think_out)
+ *think_out += work.mid(pos, end - pos);
in_think = false;
pos = end + 8;
} else {
@@ -978,9 +988,15 @@ LlmResponse LlmService::do_streaming_request(const QString& user_message,
}
}
- QString chunk = parse_sse_chunk(data, provider_);
- if (!chunk.isEmpty()) {
- accumulated += chunk;
+ const SseDelta delta = parse_sse_chunk(data, provider_);
+ if (delta.is_reasoning) {
+ // Chain-of-thought (reasoning_content / Anthropic thinking_delta).
+ // Route to the UI's separate Thinking channel via the sentinel
+ // prefix; never accumulate it into the answer or stored content.
+ if (!delta.text.isEmpty())
+ on_chunk(think_stream_prefix() + delta.text, false);
+ } else if (!delta.text.isEmpty()) {
+ accumulated += delta.text;
// Some providers stream tool calls as XML/text markup — detect, suppress output, fall back to do_request.
// Patterns covered: <tool_call>, </tool_call>, <minimax:tool_call>, <invoke name=,
@@ -1000,7 +1016,13 @@ LlmResponse LlmService::do_streaming_request(const QString& user_message,
}
}
- const QString visible = filter_think(chunk);
+ // Inline <think>…</think> reasoning (MiniMax M2.7, DeepSeek-R1
+ // derivatives) gets split out here: think_seg → Thinking channel,
+ // visible → answer bubble.
+ QString think_seg;
+ const QString visible = filter_think(delta.text, &think_seg);
+ if (!think_seg.isEmpty())
+ on_chunk(think_stream_prefix() + think_seg, false);
if (!visible.isEmpty())
on_chunk(visible, false);
}
@@ -1056,7 +1078,10 @@ LlmResponse LlmService::do_streaming_request(const QString& user_message,
resp.error = reply->errorString();
LOG_ERROR(kLlmSvcTag, "Stream request failed: " + resp.error);
} else if (status >= 200 && status < 300) {
- resp.content = accumulated;
+ // `accumulated` holds only answer deltas (reasoning_content was routed to
+ // the Thinking channel and never added here). Strip any inline <think>…
+ // </think> blocks so the persisted/replayed content is the answer alone.
+ resp.content = strip_think_blocks(accumulated);
resp.success = true;
if (!final_usage_obj.isEmpty()) {
QJsonObject wrap{{"usage", final_usage_obj}};
diff --git a/fincept-qt/src/services/llm/LlmService.h b/fincept-qt/src/services/llm/LlmService.h
index 9b4c7d29a..fa73f395b 100644
--- a/fincept-qt/src/services/llm/LlmService.h
+++ b/fincept-qt/src/services/llm/LlmService.h
@@ -24,13 +24,26 @@ inline bool provider_supports_streaming(const QString& provider) {
return provider == "openai" || provider == "anthropic" || provider == "gemini" || provider == "google" ||
provider == "groq" || provider == "deepseek" || provider == "openrouter" || provider == "minimax" ||
provider == "kimi" || provider == "ollama" || provider == "xai" || provider == "fincept" ||
- provider == "astraflow" || provider == "astraflow_cn" || provider == "aihubmix";
+ provider == "astraflow" || provider == "astraflow_cn" || provider == "aihubmix" ||
+ provider == "atlascloud";
}
inline bool provider_requires_api_key(const QString& provider) {
return provider != "ollama" && provider != "fincept";
}
+/// In-band sentinel prefixed onto a streamed chunk to mark it as chain-of-thought
+/// ("thinking") rather than answer text. Reasoning models (DeepSeek-R1, GLM, Kimi,
+/// MiniMax, …) stream `reasoning_content` (and Anthropic streams `thinking_delta`)
+/// before the real answer. The AI Chat tab strips this prefix and routes the
+/// remainder into a separate, collapsible Thinking section so it never mixes into
+/// the answer bubble; the floating Quick-Chat bubble simply drops these chunks.
+/// Uses STX (\x02) so it can't collide with model text — mirrors the existing
+/// \x01 __TOOL_CALL_CLEAR__ sentinel style.
+inline QString think_stream_prefix() {
+ return QStringLiteral("\x02__THINK__");
+}
+
struct ConversationMessage {
QString role; // system | user | assistant
QString content;
@@ -173,7 +186,14 @@ class LlmService : public QObject {
static QMap<QString, QString> get_models_headers(const QString& provider, const QString& api_key);
static QStringList parse_models_response(const QString& provider, const QByteArray& body);
- static QString parse_sse_chunk(const QString& data, const QString& provider);
+ /// One parsed SSE delta. `is_reasoning` is true for chain-of-thought text
+ /// (OpenAI-compat `reasoning_content`, Anthropic `thinking_delta`) so the
+ /// streaming loop can route it to the Thinking channel instead of the answer.
+ struct SseDelta {
+ QString text;
+ bool is_reasoning = false;
+ };
+ static SseDelta parse_sse_chunk(const QString& data, const QString& provider);
static void parse_usage(LlmResponse& resp, const QJsonObject& rj, const QString& provider);
diff --git a/fincept-qt/src/services/llm/ModelCatalog.cpp b/fincept-qt/src/services/llm/ModelCatalog.cpp
index 2b7b1a819..5883b096c 100644
--- a/fincept-qt/src/services/llm/ModelCatalog.cpp
+++ b/fincept-qt/src/services/llm/ModelCatalog.cpp
@@ -159,6 +159,12 @@ const CatalogEntry kCatalog[] = {
// (user max_tokens still applies).
{"aihubmix", "*", kNoPublishedCap},
+ // ── AtlasCloud (OpenAI-compatible aggregator) ───────────────────────────
+ // https://www.atlascloud.ai/docs/models/llm — serves 300+ open models
+ // (DeepSeek, Qwen, GLM, Kimi, MiniMax, Llama, ...); per-model cap varies and
+ // can't be derived from the id, so use a generous default (user max_tokens applies).
+ {"atlascloud", "*", kNoPublishedCap},
+
// ── Fincept (proxies upstream) ──────────────────────────────────────
// Fincept's /research/llm/async wraps various upstream models. We
// don't know which one is selected server-side, so go with a generous
diff --git a/fincept-qt/src/services/options/OptionChainService.cpp b/fincept-qt/src/services/options/OptionChainService.cpp
index 0104eecd5..a1143613d 100644
--- a/fincept-qt/src/services/options/OptionChainService.cpp
+++ b/fincept-qt/src/services/options/OptionChainService.cpp
@@ -1,6 +1,7 @@
#include "services/options/OptionChainService.h"
#include "core/logging/Logger.h"
+#include "core/market/MarketHours.h"
#include "datahub/DataHub.h"
#include "datahub/DataHubMetaTypes.h"
#include "datahub/TopicPolicy.h"
@@ -9,9 +10,11 @@
#include "services/databento/DatabentoService.h"
#include "storage/repositories/IvHistoryRepository.h"
#include "storage/repositories/SettingsRepository.h"
+#include "trading/AccountDataStream.h"
#include "trading/AccountManager.h"
#include "trading/BrokerInterface.h"
#include "trading/BrokerRegistry.h"
+#include "trading/DataStreamManager.h"
#include "trading/brokers/BrokerHttp.h"
#include "trading/instruments/InstrumentService.h"
@@ -49,6 +52,12 @@ constexpr int kChainTimeoutMs = 30'000;
constexpr int kAtmIvTtlMs = 5'000;
constexpr int kAtmIvMinIntervalMs = 3'000;
+// WS-first streaming: a chain is considered "live" while a tick arrived within
+// kWsStaleMs; past that the REST poll resumes as the fallback. The WS feed
+// covers ATM ± kWsWindowStrikes strikes per side (≈31 strikes ≈ 62 option legs).
+constexpr int kWsStaleMs = 12'000;
+constexpr int kWsWindowStrikes = 15;
+
const QString kChainPrefix = QStringLiteral("option:chain:");
const QString kTickPrefix = QStringLiteral("option:tick:");
const QString kAtmIvPrefix = QStringLiteral("option:atm_iv:");
@@ -67,6 +76,30 @@ QString cache_key(const QString& broker, const QString& underlying) {
return broker + "|" + underlying;
}
+// Canonical per-leg routing key: strike (2dp) + side. Format-independent so the
+// REST chain and the live WS feed agree regardless of how each spells the option
+// symbol (options-chain-v3 vs the HSM brsymbol differ — e.g. "...CE" vs "...C").
+QString opt_leg_key(double strike, bool is_call) {
+ return QString::number(strike, 'f', 2) + (is_call ? QLatin1Char('C') : QLatin1Char('P'));
+}
+
+// Parse a Fyers F&O brsymbol (e.g. "NIFTY09JUN26C22650") into strike + call/put.
+// The strike is the trailing digit run; the char immediately before it is C/P.
+bool parse_fyers_opt_symbol(const QString& sym, double& strike, bool& is_call) {
+ int i = int(sym.size()) - 1;
+ while (i >= 0 && sym.at(i).isDigit())
+ --i;
+ if (i < 0 || i == int(sym.size()) - 1)
+ return false; // no trailing strike digits
+ const QChar cp = sym.at(i);
+ if (cp != QLatin1Char('C') && cp != QLatin1Char('P'))
+ return false;
+ bool ok = false;
+ strike = QStringView(sym).mid(i + 1).toDouble(&ok);
+ is_call = (cp == QLatin1Char('C'));
+ return ok;
+}
+
} // namespace
OptionChainService& OptionChainService::instance() {
@@ -140,6 +173,26 @@ void OptionChainService::refresh(const QStringList& topics) {
fincept::datahub::DataHub::instance().publish_error(topic, "malformed topic");
continue;
}
+ // WS-first: while a fresh native WebSocket feed drives this chain,
+ // stand the REST poll down. on_ws_quote keeps last_chain_ current,
+ // so re-publishing it clears in_flight + warms the TTL (the hub
+ // scheduler won't re-poll for another TTL window) without a broker
+ // round-trip. PCR / max-pain are recomputed from the live OI.
+ if (ws_feed_fresh(topic) &&
+ chain_topic(last_chain_.broker_id, last_chain_.underlying, last_chain_.expiry) == topic) {
+ double tce = 0, tpe = 0;
+ last_chain_.pcr = compute_pcr(last_chain_.rows, tce, tpe);
+ last_chain_.total_ce_oi = tce;
+ last_chain_.total_pe_oi = tpe;
+ last_chain_.max_pain = compute_max_pain(last_chain_.rows);
+ auto& hub = fincept::datahub::DataHub::instance();
+ hub.publish(topic, QVariant::fromValue(last_chain_));
+ hub.publish(kPcrPrefix + broker + ":" + underlying + ":" + expiry,
+ QVariant::fromValue(last_chain_.pcr));
+ hub.publish(kMaxPainPrefix + broker + ":" + underlying + ":" + expiry,
+ QVariant::fromValue(last_chain_.max_pain));
+ continue;
+ }
in_flight_[topic] = true;
refresh_chain(broker, underlying, expiry);
} else if (topic.startsWith(kAtmIvPrefix)) {
@@ -352,13 +405,19 @@ void OptionChainService::refresh_chain(const QString& broker_id, const QString&
by_sym.insert(q.symbol, q);
}
- // Pull underlying spot — try index symbol first, then FUT fallback
- double spot = 0;
- if (auto it = by_sym.find(underlying_sym); it != by_sym.end())
+ // Pull underlying spot (+ day change) — index symbol first, FUT fallback
+ double spot = 0, spot_chg = 0, spot_chg_pct = 0;
+ if (auto it = by_sym.find(underlying_sym); it != by_sym.end()) {
spot = it->ltp;
+ spot_chg = it->change;
+ spot_chg_pct = it->change_pct;
+ }
if (spot <= 0 && !fut_sym.isEmpty()) {
- if (auto it = by_sym.find(fut_sym); it != by_sym.end())
+ if (auto it = by_sym.find(fut_sym); it != by_sym.end()) {
spot = it->ltp;
+ spot_chg = it->change;
+ spot_chg_pct = it->change_pct;
+ }
}
LOG_INFO("OptionChain", QString("spot=%1 (underlying_sym='%2', fut_sym='%3')")
.arg(spot).arg(underlying_sym, fut_sym));
@@ -387,6 +446,8 @@ void OptionChainService::refresh_chain(const QString& broker_id, const QString&
chain.underlying = underlying;
chain.expiry = expiry;
chain.spot = spot;
+ chain.spot_change = spot_chg;
+ chain.spot_change_pct = spot_chg_pct;
chain.kind = (underlying == "NIFTY" || underlying == "BANKNIFTY"
|| underlying == "FINNIFTY" || underlying == "MIDCPNIFTY")
? UnderlyingKind::Index
@@ -653,7 +714,7 @@ void OptionChainService::refresh_chain_fyers(const QString& broker_id, const QSt
auto arr = data.value("optionsChain").toArray();
LOG_INFO("OptionChain", QString("Fyers option chain: %1 entries").arg(arr.size()));
- double spot = 0;
+ double spot = 0, spot_chg = 0, spot_chg_pct = 0;
static const QSet<QString> kIdx = {"NIFTY","BANKNIFTY","FINNIFTY","MIDCPNIFTY"};
// Group by strike: CE + PE
@@ -670,6 +731,8 @@ void OptionChainService::refresh_chain_fyers(const QString& broker_id, const QSt
if (strike < 0 || opt_type.isEmpty()) {
spot = o.value("ltp").toDouble();
+ spot_chg = o.value("ltpch").toDouble();
+ spot_chg_pct = o.value("ltpchp").toDouble();
continue;
}
@@ -719,6 +782,8 @@ void OptionChainService::refresh_chain_fyers(const QString& broker_id, const QSt
chain.underlying = underlying;
chain.expiry = expiry;
chain.spot = spot;
+ chain.spot_change = spot_chg;
+ chain.spot_change_pct = spot_chg_pct;
chain.kind = kIdx.contains(underlying) ? UnderlyingKind::Index : UnderlyingKind::Stock;
chain.timestamp_ms = QDateTime::currentMSecsSinceEpoch();
chain.rows.reserve(by_strike.size());
@@ -726,6 +791,21 @@ void OptionChainService::refresh_chain_fyers(const QString& broker_id, const QSt
for (auto it = by_strike.constBegin(); it != by_strike.constEnd(); ++it)
chain.rows.append(it->row);
+ // options-chain-v3 omits lot size — backfill from the instrument
+ // master (all NFO legs of an underlying share one lot) so the chain,
+ // strategy builder, and right-click order path all have it.
+ int lot_size = 0;
+ for (const auto& in : InstrumentService::instance().find_options_for_underlying(
+ broker_id, underlying, expiry, QStringLiteral("NFO"))) {
+ if (in.lot_size > 0) {
+ lot_size = in.lot_size;
+ break;
+ }
+ }
+ if (lot_size > 0)
+ for (auto& row : chain.rows)
+ row.lot_size = lot_size;
+
chain.atm_strike = compute_atm(chain.rows, spot);
chain.pcr = compute_pcr(chain.rows, chain.total_ce_oi, chain.total_pe_oi);
chain.max_pain = compute_max_pain(chain.rows);
@@ -746,6 +826,10 @@ void OptionChainService::refresh_chain_fyers(const QString& broker_id, const QSt
self->last_chain_ = chain;
emit self->chain_published(chain);
+ // Hand off to the live WS feed (Fyers + market open + connected).
+ // While it stays fresh this REST path is suppressed in refresh().
+ self->maybe_start_ws_stream(chain, topic);
+
LOG_INFO("OptionChain",
QString("Fyers chain: %1 strikes, spot=%2, ATM=%3, PCR=%4, OI CE=%5 PE=%6")
.arg(chain.rows.size())
@@ -836,6 +920,192 @@ void OptionChainService::publish_per_leg_ticks(const OptionChain& chain) {
LOG_DEBUG("OptionChain", QString("Per-leg tick fan-out: %1 publishes").arg(published));
}
+// ── WS-first live streaming ────────────────────────────────────────────────
+
+bool OptionChainService::ws_feed_fresh(const QString& topic) const {
+ return !ws_topic_.isEmpty() && topic == ws_topic_ && ws_last_tick_ms_ > 0 &&
+ (QDateTime::currentMSecsSinceEpoch() - ws_last_tick_ms_) < kWsStaleMs;
+}
+
+void OptionChainService::maybe_start_ws_stream(const OptionChain& chain, const QString& topic) {
+ using fincept::trading::AccountManager;
+ using fincept::trading::ConnectionState;
+ using fincept::trading::DataStreamManager;
+
+ // Only Fyers exposes a native option WebSocket feed in this build; every
+ // other broker (and Databento) keeps the REST path. Market must be open and
+ // an account connected, else fall back to REST.
+ if (chain.broker_id != QLatin1String("fyers") || !fincept::core::market::nse_fo_market_open()) {
+ stop_ws_stream();
+ return;
+ }
+
+ QString account_id;
+ for (const auto& acct : AccountManager::instance().list_accounts(chain.broker_id)) {
+ if (AccountManager::instance().connection_state(acct.account_id) == ConnectionState::Connected) {
+ account_id = acct.account_id;
+ break;
+ }
+ }
+ if (account_id.isEmpty()) {
+ stop_ws_stream(); // not connected → REST fallback
+ return;
+ }
+
+ // ATM ± window. Find the ATM row, take kWsWindowStrikes either side.
+ int atm_idx = 0;
+ double best = std::numeric_limits<double>::max();
+ for (int i = 0; i < chain.rows.size(); ++i) {
+ const double d = std::abs(chain.rows[i].strike - chain.atm_strike);
+ if (d < best) { best = d; atm_idx = i; }
+ }
+ const int lo = std::max(0, atm_idx - kWsWindowStrikes);
+ const int hi = std::min(int(chain.rows.size()) - 1, atm_idx + kWsWindowStrikes);
+
+ auto fyers_sym = [](const QString& s) {
+ return s.contains(QLatin1Char(':')) ? s : QStringLiteral("NSE:") + s;
+ };
+
+ // Key the routing map by (strike, side) — see opt_leg_key. The WS subscribe
+ // still uses the broker symbol; only the tick→row match is format-agnostic.
+ QHash<QString, qint64> sym_token;
+ QStringList sub_syms;
+ for (int i = lo; i <= hi; ++i) {
+ const auto& r = chain.rows[i];
+ if (r.ce_token != 0 && !r.ce_symbol.isEmpty()) {
+ sub_syms.append(fyers_sym(r.ce_symbol));
+ sym_token.insert(opt_leg_key(r.strike, true), r.ce_token);
+ }
+ if (r.pe_token != 0 && !r.pe_symbol.isEmpty()) {
+ sub_syms.append(fyers_sym(r.pe_symbol));
+ sym_token.insert(opt_leg_key(r.strike, false), r.pe_token);
+ }
+ }
+ if (sub_syms.isEmpty()) {
+ stop_ws_stream();
+ return;
+ }
+
+ ws_topic_ = topic;
+ ws_account_id_ = account_id;
+ ws_sym_token_ = sym_token;
+
+ auto& dsm = DataStreamManager::instance();
+ dsm.start_stream(account_id); // idempotent: creates+starts or resume()s
+ auto* stream = dsm.stream_for(account_id);
+ if (!stream) {
+ stop_ws_stream();
+ return;
+ }
+
+ // One persistent binding to the account's quote feed; on_ws_quote filters
+ // by ws_account_id_ + ws_sym_token_. Rebind to the (possibly new) stream.
+ if (ws_quote_conn_)
+ disconnect(ws_quote_conn_);
+ ws_quote_conn_ = connect(stream, &fincept::trading::AccountDataStream::quote_updated,
+ this, &OptionChainService::on_ws_quote);
+
+ // Tear the feed down when the chain topic loses its last subscriber (the
+ // Chain tab was hidden or switched to another expiry/underlying).
+ if (!ws_idle_conn_) {
+ QPointer<OptionChainService> self = this;
+ ws_idle_conn_ = connect(&fincept::datahub::DataHub::instance(),
+ &fincept::datahub::DataHub::topic_idle, this,
+ [self](const QString& t) {
+ if (self && t == self->ws_topic_)
+ self->stop_ws_stream();
+ });
+ }
+
+ // Pushes immediately if the socket is already connected (it is, when the
+ // equity feed is live); otherwise the WS connect handler picks up the union.
+ stream->subscribe_symbols(QStringLiteral("fno:chain"), sub_syms);
+ LOG_INFO("OptionChain", QString("WS stream armed: %1 legs for %2 (acct=%3, ATM=%4)")
+ .arg(sub_syms.size())
+ .arg(topic, account_id)
+ .arg(chain.atm_strike, 0, 'f', 0));
+}
+
+void OptionChainService::on_ws_quote(const QString& account_id, const QString& symbol,
+ const fincept::trading::BrokerQuote& quote) {
+ if (account_id != ws_account_id_)
+ return;
+ // Match the live WS symbol to a chain leg by (strike, side). Equity-watchlist
+ // ticks (e.g. "RELIANCE") don't parse as options and are skipped here.
+ double k_strike = 0;
+ bool k_call = false;
+ if (!parse_fyers_opt_symbol(symbol, k_strike, k_call))
+ return;
+ auto it = ws_sym_token_.constFind(opt_leg_key(k_strike, k_call));
+ if (it == ws_sym_token_.constEnd()) {
+ static qint64 s_last_unmatched_ms = 0;
+ const qint64 t_now = QDateTime::currentMSecsSinceEpoch();
+ if (t_now - s_last_unmatched_ms > 5'000) {
+ s_last_unmatched_ms = t_now;
+ LOG_DEBUG("OptionChain", QString("WS tick unmatched: %1 (strike=%2 %3) not in window")
+ .arg(symbol).arg(k_strike, 0, 'f', 0).arg(k_call ? "CE" : "PE"));
+ }
+ return;
+ }
+ const qint64 token = it.value();
+
+ // Merge into last_chain_ so the suppressed-REST re-publish stays live.
+ // The Fyers `sf` tick has no prev-day OI baseline, so carry the seed's
+ // oi_change_pct forward; keep the last known OI if a lite tick omitted it.
+ fincept::trading::BrokerQuote q = quote;
+ bool matched = false;
+ for (auto& row : last_chain_.rows) {
+ if (row.ce_token == token) {
+ q.oi_change_pct = row.ce_quote.oi_change_pct;
+ if (q.oi == 0) q.oi = row.ce_quote.oi;
+ row.ce_quote = q;
+ matched = true;
+ break;
+ }
+ if (row.pe_token == token) {
+ q.oi_change_pct = row.pe_quote.oi_change_pct;
+ if (q.oi == 0) q.oi = row.pe_quote.oi;
+ row.pe_quote = q;
+ matched = true;
+ break;
+ }
+ }
+ if (!matched)
+ return;
+
+ const qint64 now = QDateTime::currentMSecsSinceEpoch();
+ // Throttled liveness log — confirms WS→chain routing without per-tick spam.
+ static qint64 s_last_ws_log_ms = 0;
+ if (now - s_last_ws_log_ms > 5'000) {
+ s_last_ws_log_ms = now;
+ LOG_INFO("OptionChain", QString("WS tick live: %1 ltp=%2 oi=%3 → token %4")
+ .arg(symbol).arg(q.ltp, 0, 'f', 2).arg(q.oi).arg(token));
+ }
+ ws_last_tick_ms_ = now;
+
+ // Fast path to the table: per-leg tick → OptionChainModel::update_leg_quote.
+ const QString t = kTickPrefix + last_chain_.broker_id + ":" + QString::number(token);
+ fincept::datahub::DataHub::instance().publish(t, QVariant::fromValue(q));
+}
+
+void OptionChainService::stop_ws_stream() {
+ if (ws_topic_.isEmpty())
+ return;
+ if (!ws_account_id_.isEmpty()) {
+ if (auto* stream = fincept::trading::DataStreamManager::instance().stream_for(ws_account_id_))
+ stream->unsubscribe_consumer(QStringLiteral("fno:chain"));
+ }
+ if (ws_quote_conn_) {
+ disconnect(ws_quote_conn_);
+ ws_quote_conn_ = {};
+ }
+ LOG_INFO("OptionChain", QString("WS stream stopped: %1").arg(ws_topic_));
+ ws_topic_.clear();
+ ws_account_id_.clear();
+ ws_sym_token_.clear();
+ ws_last_tick_ms_ = 0;
+}
+
void OptionChainService::publish_atm_iv(const OptionChain& chain) {
if (chain.atm_strike <= 0)
return;
diff --git a/fincept-qt/src/services/options/OptionChainService.h b/fincept-qt/src/services/options/OptionChainService.h
index 850d31ba0..d328fb830 100644
--- a/fincept-qt/src/services/options/OptionChainService.h
+++ b/fincept-qt/src/services/options/OptionChainService.h
@@ -128,6 +128,28 @@ class OptionChainService : public QObject, public fincept::datahub::Producer {
/// `option:atm_iv:<broker>:<underlying>` (decimal IV).
void publish_atm_iv(const fincept::services::options::OptionChain& chain);
+ // ── WS-first live streaming (Phase 3 fan-out) ──────────────────────────
+ // When the broker has a native option WebSocket (Fyers today), the market
+ // is open, and the account is connected, the chain switches from REST
+ // polling to a live WS feed: the ATM±window option symbols are subscribed
+ // on the account's shared AccountDataStream, and incoming ticks patch
+ // last_chain_ in place + fan out on `option:tick:<broker>:<token>`. REST is
+ // suppressed (see refresh()) while the feed stays fresh, and resumes as the
+ // fallback when the feed goes stale / market closes / account disconnects.
+
+ /// Subscribe the ATM±window legs of `chain` to the live WS and route ticks.
+ /// No-op (and tears down any existing feed) when not WS-eligible.
+ void maybe_start_ws_stream(const fincept::services::options::OptionChain& chain, const QString& topic);
+ /// Drop the WS subscription + tick routing for the active streamed topic.
+ void stop_ws_stream();
+ /// Tick handler — merges a live broker quote into last_chain_ and republishes
+ /// the affected leg on `option:tick:*`. Filters by account + symbol map.
+ void on_ws_quote(const QString& account_id, const QString& symbol,
+ const fincept::trading::BrokerQuote& quote);
+ /// True when `topic` is the streamed topic and a tick arrived within the
+ /// staleness window (so the REST poll should stand down).
+ bool ws_feed_fresh(const QString& topic) const;
+
/// Risk-free rate from settings (`fno.risk_free_rate`), default 0.067
/// (RBI 91-day T-bill ballpark). Cached after first read.
double risk_free_rate();
@@ -155,6 +177,14 @@ class OptionChainService : public QObject, public fincept::datahub::Producer {
bool risk_free_rate_loaded_ = false;
/// Cached Databento expiries per underlying (session-scoped).
QHash<QString, QStringList> databento_expiry_cache_;
+
+ // ── WS-first streaming state ───────────────────────────────────────────
+ QString ws_topic_; ///< chain topic currently WS-streamed ("" = none)
+ QString ws_account_id_; ///< account whose stream we subscribed
+ QHash<QString, qint64> ws_sym_token_; ///< bare WS option symbol → leg token
+ qint64 ws_last_tick_ms_ = 0; ///< last WS tick arrival (epoch ms)
+ QMetaObject::Connection ws_quote_conn_; ///< AccountDataStream::quote_updated binding
+ QMetaObject::Connection ws_idle_conn_; ///< DataHub::topic_idle teardown binding
};
} // namespace fincept::services::options
diff --git a/fincept-qt/src/services/options/OptionChainTypes.h b/fincept-qt/src/services/options/OptionChainTypes.h
index 807e587f4..d35b23402 100644
--- a/fincept-qt/src/services/options/OptionChainTypes.h
+++ b/fincept-qt/src/services/options/OptionChainTypes.h
@@ -78,6 +78,8 @@ struct OptionChain {
UnderlyingKind kind = UnderlyingKind::Unknown;
double spot = 0; // underlying LTP
+ double spot_change = 0; // underlying day change (absolute, ₹)
+ double spot_change_pct = 0; // underlying day change (%)
double atm_strike = 0; // strike closest to spot
double pcr = 0; // sum(PE oi) / sum(CE oi)
double max_pain = 0; // strike minimising total writer pain
diff --git a/fincept-qt/src/storage/repositories/PaperTradingRepository.cpp b/fincept-qt/src/storage/repositories/PaperTradingRepository.cpp
index d70564330..60c43dde6 100644
--- a/fincept-qt/src/storage/repositories/PaperTradingRepository.cpp
+++ b/fincept-qt/src/storage/repositories/PaperTradingRepository.cpp
@@ -1,5 +1,7 @@
#include "storage/repositories/PaperTradingRepository.h"
+#include <cmath>
+
namespace fincept {
using namespace trading;
@@ -272,6 +274,15 @@ Result<void> PaperTradingRepository::update_position(const QString& id, double q
Result<void> PaperTradingRepository::update_position_price(const QString& portfolio_id, const QString& symbol,
double price) {
+ // Guard against garbage/zero ticks. A non-finite or non-positive mark price
+ // is never a real trade — feeds occasionally emit 0.0 for an illiquid leg or
+ // a malformed packet. Writing it through recomputes unrealized_pnl as
+ // (entry - 0) * qty, which on a SHORT option surfaces the FULL premium as a
+ // phantom profit (the "square-off shows total trade value in profit" bug).
+ // Ignore it so the position keeps its last good price + P&L.
+ if (!std::isfinite(price) || price <= 0.0)
+ return Result<void>::ok();
+
// Update current_price AND recompute unrealized_pnl atomically
// long: (price - entry) * qty, short: (entry - price) * qty
return exec_write("UPDATE pt_positions SET current_price = ?, "
diff --git a/fincept-qt/src/storage/repositories/ScanWatchRepository.cpp b/fincept-qt/src/storage/repositories/ScanWatchRepository.cpp
index 8a1343e08..d3031e7fc 100644
--- a/fincept-qt/src/storage/repositories/ScanWatchRepository.cpp
+++ b/fincept-qt/src/storage/repositories/ScanWatchRepository.cpp
@@ -13,7 +13,7 @@ namespace {
const char* kCols =
"id, name, conditions_json, logic, symbols, timeframe, lookback_days,"
" data_source, broker_id, account_id, mode, interval_sec, cooldown_min,"
- " actions_json, active, status, last_eval_at, last_fired_at";
+ " actions_json, active, status, last_eval_at, last_fired_at, universe";
QString json_array_to_str(const QJsonArray& a) {
return QString::fromUtf8(QJsonDocument(a).toJson(QJsonDocument::Compact));
@@ -51,6 +51,7 @@ ScanWatch ScanWatchRepository::map_row(QSqlQuery& q) {
w.status = q.value(15).toString();
w.last_eval_at = q.value(16).toLongLong();
w.last_fired_at = q.value(17).toLongLong();
+ w.universe = q.value(18).toString();
return w;
}
@@ -62,12 +63,12 @@ Result<ScanWatch> ScanWatchRepository::create(const ScanWatch& in) {
auto r = exec_write(
"INSERT INTO scan_watches (id, name, conditions_json, logic, symbols, timeframe,"
" lookback_days, data_source, broker_id, account_id, mode, interval_sec, cooldown_min,"
- " actions_json, active, status, last_eval_at, last_fired_at, created_at, updated_at)"
- " VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)",
+ " actions_json, active, status, last_eval_at, last_fired_at, universe, created_at, updated_at)"
+ " VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)",
{nn(w.id), nn(w.name), nn(json_array_to_str(w.conditions)), nn(w.logic), nn(w.symbols.join('\n')),
nn(w.timeframe), w.lookback_days, nn(w.data_source), nn(w.broker_id), nn(w.account_id), nn(w.mode),
w.interval_sec, w.cooldown_min, nn(json_obj_to_str(w.actions)), w.active ? 1 : 0,
- nn(w.status), w.last_eval_at, w.last_fired_at, now, now});
+ nn(w.status), w.last_eval_at, w.last_fired_at, nn(w.universe), now, now});
if (r.is_err())
return Result<ScanWatch>::err(r.error());
SyncOutbox::record("scan_watch", w.id, "create");
@@ -79,10 +80,10 @@ Result<void> ScanWatchRepository::update(const ScanWatch& w) {
auto r = exec_write(
"UPDATE scan_watches SET name=?, conditions_json=?, logic=?, symbols=?, timeframe=?,"
" lookback_days=?, data_source=?, broker_id=?, account_id=?, mode=?, interval_sec=?,"
- " cooldown_min=?, actions_json=?, active=?, updated_at=? WHERE id=?",
+ " cooldown_min=?, actions_json=?, active=?, universe=?, updated_at=? WHERE id=?",
{nn(w.name), nn(json_array_to_str(w.conditions)), nn(w.logic), nn(w.symbols.join('\n')), nn(w.timeframe),
w.lookback_days, nn(w.data_source), nn(w.broker_id), nn(w.account_id), nn(w.mode), w.interval_sec,
- w.cooldown_min, nn(json_obj_to_str(w.actions)), w.active ? 1 : 0, now, nn(w.id)});
+ w.cooldown_min, nn(json_obj_to_str(w.actions)), w.active ? 1 : 0, nn(w.universe), now, nn(w.id)});
if (r.is_ok())
SyncOutbox::record("scan_watch", w.id, "update");
return r;
diff --git a/fincept-qt/src/storage/repositories/ScanWatchRepository.h b/fincept-qt/src/storage/repositories/ScanWatchRepository.h
index 90b5da21f..943afdfd8 100644
--- a/fincept-qt/src/storage/repositories/ScanWatchRepository.h
+++ b/fincept-qt/src/storage/repositories/ScanWatchRepository.h
@@ -16,6 +16,7 @@ struct ScanWatch {
QJsonArray conditions;
QString logic = QStringLiteral("AND");
QStringList symbols;
+ QString universe; // '' / 'CUSTOM' use symbols; 'NSE_EQ'/'BSE_EQ'/'NIFTY50' resolve live
QString timeframe = QStringLiteral("1m");
int lookback_days = 5;
QString data_source = QStringLiteral("Broker");
diff --git a/fincept-qt/src/storage/sqlite/migrations/MigrationRunner.h b/fincept-qt/src/storage/sqlite/migrations/MigrationRunner.h
index c754ad4e6..70c1eb15f 100644
--- a/fincept-qt/src/storage/sqlite/migrations/MigrationRunner.h
+++ b/fincept-qt/src/storage/sqlite/migrations/MigrationRunner.h
@@ -91,5 +91,7 @@ void register_migration_v041();
void register_migration_v042();
void register_migration_v043();
void register_migration_v044();
+void register_migration_v045();
+void register_migration_v046();
} // namespace fincept
diff --git a/fincept-qt/src/storage/sqlite/migrations/v045_scan_watch_universe.cpp b/fincept-qt/src/storage/sqlite/migrations/v045_scan_watch_universe.cpp
new file mode 100644
index 000000000..8499bcd2b
--- /dev/null
+++ b/fincept-qt/src/storage/sqlite/migrations/v045_scan_watch_universe.cpp
@@ -0,0 +1,40 @@
+// v045_scan_watch_universe — adds a `universe` selector column to scan_watches so a
+// realtime watch can track a *dynamic* symbol set (all NSE/BSE equities, NIFTY 50)
+// resolved live from the instrument master, instead of a frozen symbols list.
+//
+// '' / 'CUSTOM' → use the existing `symbols` column
+// 'NSE_EQ' / 'BSE_EQ' → resolve all EQ instruments for that exchange at runner start
+// 'NIFTY50' → resolve nifty50_symbols()
+// Existing rows default to '' so current poll watches are unaffected.
+
+#include "storage/sqlite/migrations/MigrationRunner.h"
+
+#include <QSqlError>
+#include <QSqlQuery>
+
+namespace fincept {
+namespace {
+
+Result<void> apply_v045(QSqlDatabase& db) {
+ // The column may already exist on re-run; ignore the duplicate-column error so
+ // the migration stays idempotent (same approach as v044's `persist` column).
+ QSqlQuery alter(db);
+ if (!alter.exec("ALTER TABLE scan_watches ADD COLUMN universe TEXT NOT NULL DEFAULT ''")) {
+ const QString err = alter.lastError().text();
+ if (!err.contains("duplicate column", Qt::CaseInsensitive))
+ return Result<void>::err(err.toStdString());
+ }
+ return Result<void>::ok();
+}
+
+} // anonymous namespace
+
+void register_migration_v045() {
+ static bool done = false;
+ if (done)
+ return;
+ done = true;
+ MigrationRunner::register_migration({45, "scan_watch_universe", apply_v045});
+}
+
+} // namespace fincept
diff --git a/fincept-qt/src/storage/sqlite/migrations/v046_fno_algo.cpp b/fincept-qt/src/storage/sqlite/migrations/v046_fno_algo.cpp
new file mode 100644
index 000000000..e81a7217c
--- /dev/null
+++ b/fincept-qt/src/storage/sqlite/migrations/v046_fno_algo.cpp
@@ -0,0 +1,53 @@
+// v046_fno_algo — adds F&O algo columns so an algo strategy/deployment can target
+// options or futures (multi-leg). The strategy carries leg *rules*; the deployment
+// carries the concrete contracts resolved at entry. Every column defaults to the
+// equity behavior, so existing rows are unaffected. Idempotent on re-run (ignores
+// the duplicate-column error, matching v044/v045). See
+// docs/superpowers/specs/2026-06-08-fno-algo-design.md.
+
+#include "storage/sqlite/migrations/MigrationRunner.h"
+
+#include <QSqlError>
+#include <QSqlQuery>
+
+namespace fincept {
+namespace {
+
+Result<void> add_column(QSqlDatabase& db, const QString& sql) {
+ QSqlQuery q(db);
+ if (!q.exec(sql)) {
+ const QString err = q.lastError().text();
+ if (!err.contains("duplicate column", Qt::CaseInsensitive))
+ return Result<void>::err(err.toStdString());
+ }
+ return Result<void>::ok();
+}
+
+Result<void> apply_v046(QSqlDatabase& db) {
+ const char* stmts[] = {
+ "ALTER TABLE algo_strategies ADD COLUMN instrument_type TEXT NOT NULL DEFAULT 'equity'",
+ "ALTER TABLE algo_strategies ADD COLUMN legs_json TEXT NOT NULL DEFAULT '[]'",
+ "ALTER TABLE algo_deployments ADD COLUMN instrument_type TEXT NOT NULL DEFAULT 'equity'",
+ "ALTER TABLE algo_deployments ADD COLUMN underlying TEXT NOT NULL DEFAULT ''",
+ "ALTER TABLE algo_deployments ADD COLUMN resolved_expiry TEXT NOT NULL DEFAULT ''",
+ "ALTER TABLE algo_deployments ADD COLUMN resolved_legs_json TEXT NOT NULL DEFAULT '[]'",
+ };
+ for (const char* s : stmts) {
+ auto r = add_column(db, QString::fromUtf8(s));
+ if (r.is_err())
+ return r;
+ }
+ return Result<void>::ok();
+}
+
+} // anonymous namespace
+
+void register_migration_v046() {
+ static bool done = false;
+ if (done)
+ return;
+ done = true;
+ MigrationRunner::register_migration({46, "fno_algo", apply_v046});
+}
+
+} // namespace fincept
diff --git a/fincept-qt/src/trading/AccountDataStream.cpp b/fincept-qt/src/trading/AccountDataStream.cpp
index 870fbf559..f8a906718 100644
--- a/fincept-qt/src/trading/AccountDataStream.cpp
+++ b/fincept-qt/src/trading/AccountDataStream.cpp
@@ -136,6 +136,9 @@ void AccountDataStream::resume() {
// ── Symbol management ───────────────────────────────────────────────────────
void AccountDataStream::subscribe_symbols(const QString& consumer_id, const QStringList& symbols) {
+ LOG_INFO("subdbg", QString("subscribe_symbols consumer='%1' (%2 syms): [%3] ws_connected=%4")
+ .arg(consumer_id).arg(symbols.size())
+ .arg(symbols.join(','), ws_connected() ? "Y" : "N"));
if (symbols.isEmpty())
consumer_symbols_.remove(consumer_id);
else
@@ -770,6 +773,7 @@ void AccountDataStream::ws_init() {
q.change = tick.ltp - tick.prev_close;
q.change_pct = tick.prev_close > 0 ? ((tick.ltp - tick.prev_close) / tick.prev_close) * 100.0 : 0;
q.timestamp = tick.timestamp;
+ q.oi = qint64(tick.oi); // F&O open interest; 0 for cash/equity ticks
quote_cache_[tick.symbol] = q;
emit quote_updated(account_id_, tick.symbol, q);
});
@@ -803,7 +807,19 @@ void AccountDataStream::ws_init() {
LOG_INFO(ADS_TAG, QString("Fyers HSM connected for %1").arg(account_id_));
emit connection_state_changed(account_id_, ConnectionState::Connected);
auto to_fyers = [](const QString& sym) {
- return sym.contains(':') ? sym : QStringLiteral("NSE:") + sym + QStringLiteral("-EQ");
+ // Strip any exchange prefix to inspect the bare contract: a held
+ // F&O option arrives as "NFO:NIFTY...CE" (paper) or "NIFTY...CE"
+ // (live) — both must resolve on Fyers' "NSE:" segment, NOT the
+ // equity "...-EQ" form, or the option never gets a live feed.
+ QString core = sym;
+ const int colon = core.indexOf(QLatin1Char(':'));
+ if (colon >= 0)
+ core = core.mid(colon + 1);
+ if (is_fyers_fno_symbol(core))
+ return QStringLiteral("NSE:") + core;
+ if (colon >= 0)
+ return sym; // already-qualified equity (e.g. "BSE:TCS")
+ return QStringLiteral("NSE:") + core + QStringLiteral("-EQ");
};
QStringList fyers_symbols;
if (!selected_symbol_.isEmpty())
@@ -811,6 +827,16 @@ void AccountDataStream::ws_init() {
for (const QString& s : subscribed_symbols())
fyers_symbols.append(to_fyers(s));
fyers_symbols.removeDuplicates();
+ {
+ QStringList fno;
+ for (const auto& s : fyers_symbols)
+ if (is_fyers_fno_symbol(s.section(QLatin1Char(':'), -1)))
+ fno << s;
+ LOG_INFO("subdbg", QString("[connect] consumers=%1 → %2 fyers syms (F&O: [%3]); raw subscribed=[%4]")
+ .arg(subscribed_symbols().size())
+ .arg(fyers_symbols.size())
+ .arg(fno.join(','), subscribed_symbols().join(',')));
+ }
if (auto* fws = qobject_cast<FyersWebSocket*>(ws_))
fws->subscribe(fyers_symbols);
});
@@ -1183,7 +1209,18 @@ bool AccountDataStream::ws_connected() const {
void AccountDataStream::ws_resubscribe() {
if (auto* fws = qobject_cast<FyersWebSocket*>(ws_)) {
auto to_fyers = [](const QString& sym) {
- return sym.contains(':') ? sym : QStringLiteral("NSE:") + sym + QStringLiteral("-EQ");
+ // Mirror the connect-handler mapping: strip any exchange prefix and
+ // route F&O options onto Fyers' "NSE:" segment (handles the paper
+ // "NFO:...CE" prefix too), equities to "NSE:<sym>-EQ".
+ QString core = sym;
+ const int colon = core.indexOf(QLatin1Char(':'));
+ if (colon >= 0)
+ core = core.mid(colon + 1);
+ if (is_fyers_fno_symbol(core))
+ return QStringLiteral("NSE:") + core;
+ if (colon >= 0)
+ return sym;
+ return QStringLiteral("NSE:") + core + QStringLiteral("-EQ");
};
QStringList fyers_symbols;
if (!selected_symbol_.isEmpty())
@@ -1191,6 +1228,16 @@ void AccountDataStream::ws_resubscribe() {
for (const QString& s : subscribed_symbols())
fyers_symbols.append(to_fyers(s));
fyers_symbols.removeDuplicates();
+ {
+ QStringList fno;
+ for (const auto& s : fyers_symbols)
+ if (is_fyers_fno_symbol(s.section(QLatin1Char(':'), -1)))
+ fno << s;
+ LOG_INFO("subdbg", QString("[ws_resubscribe] consumers=%1 → %2 fyers syms (F&O: [%3])")
+ .arg(subscribed_symbols().size())
+ .arg(fyers_symbols.size())
+ .arg(fno.join(',')));
+ }
fws->set_subscriptions(fyers_symbols);
}
diff --git a/fincept-qt/src/trading/PaperMarkService.cpp b/fincept-qt/src/trading/PaperMarkService.cpp
new file mode 100644
index 000000000..87abe1d13
--- /dev/null
+++ b/fincept-qt/src/trading/PaperMarkService.cpp
@@ -0,0 +1,195 @@
+#include "trading/PaperMarkService.h"
+
+#include "core/logging/Logger.h"
+#include "trading/AccountDataStream.h"
+#include "trading/AccountManager.h"
+#include "trading/DataStreamManager.h"
+#include "trading/OrderMatcher.h"
+#include "trading/PaperTrading.h"
+#include "trading/websocket/FyersTickTypes.h"
+
+#include <QTimer>
+
+namespace fincept::trading {
+
+namespace {
+const QString TAG = QStringLiteral("PaperMark");
+const QString kConsumer = QStringLiteral("paper-mark");
+// Re-evaluate tracked accounts/positions on this cadence (cheap: a few accounts,
+// a handful of positions each). Fills also trigger an immediate resync.
+constexpr int kResyncMs = 4000;
+// Persist marked prices to SQLite at most once per this window per burst of
+// ticks — one UPDATE per symbol per window instead of one per tick.
+constexpr int kFlushMs = 1000;
+} // namespace
+
+PaperMarkService& PaperMarkService::instance() {
+ static PaperMarkService s;
+ return s;
+}
+
+PaperMarkService::PaperMarkService() = default;
+
+void PaperMarkService::start() {
+ if (started_)
+ return;
+ started_ = true;
+
+ // A fill changes positions/orders. The callback can fire on a worker thread
+ // (e.g. square-off runs in QtConcurrent), so marshal to this object's thread
+ // before touching the bindings / emitting.
+ fill_cb_id_ = OrderMatcher::instance().on_order_fill([this](const OrderFillEvent&) {
+ QMetaObject::invokeMethod(
+ this,
+ [this]() {
+ resync();
+ for (auto it = bound_.cbegin(); it != bound_.cend(); ++it)
+ emit portfolio_changed(it->portfolio_id);
+ },
+ Qt::QueuedConnection);
+ });
+
+ resync_timer_ = new QTimer(this);
+ resync_timer_->setInterval(kResyncMs);
+ connect(resync_timer_, &QTimer::timeout, this, &PaperMarkService::resync);
+ resync_timer_->start();
+
+ resync();
+ LOG_INFO(TAG, "Paper mark-to-market service started");
+}
+
+void PaperMarkService::resync() {
+ auto& dsm = DataStreamManager::instance();
+ QSet<QString> should_track; // account_ids that currently warrant a binding
+
+ for (const auto& acct : AccountManager::instance().active_accounts()) {
+ if (acct.trading_mode != QLatin1String("paper") || acct.paper_portfolio_id.isEmpty())
+ continue;
+
+ const auto positions = pt_get_positions(acct.paper_portfolio_id);
+ QStringList syms;
+ QVector<PosLeg> legs;
+ for (const auto& p : positions) {
+ if (p.quantity == 0.0 || p.symbol.isEmpty())
+ continue;
+ syms << p.symbol;
+ const auto leg = fyers_parse_option(p.symbol);
+ if (leg.valid)
+ legs.push_back({leg.underlying, leg.is_call, p.symbol});
+ }
+ if (syms.isEmpty())
+ continue; // nothing to mark — don't force a stream up for an idle portfolio
+
+ should_track.insert(acct.account_id);
+ auto& b = bound_[acct.account_id];
+ b.portfolio_id = acct.paper_portfolio_id;
+ b.exact = QSet<QString>(syms.cbegin(), syms.cend());
+ b.legs = legs;
+
+ auto* stream = dsm.stream_for(acct.account_id);
+ if (!stream)
+ continue;
+
+ // (Re)bind quote_updated. Reconnect when the stream object changed — a
+ // token refresh runs restart_stream(), which destroys + recreates it; the
+ // stored connection would be dead and marking would silently stall.
+ if (b.stream != stream || !b.conn) {
+ if (b.conn)
+ QObject::disconnect(b.conn);
+ const QString pid = acct.paper_portfolio_id;
+ b.conn = connect(stream, &AccountDataStream::quote_updated, this,
+ [this, pid](const QString& aid, const QString& sym, const BrokerQuote& q) {
+ on_quote(aid, pid, sym, q);
+ });
+ b.stream = stream;
+ b.symbols.clear(); // force a fresh subscribe on the new stream
+ }
+
+ const QSet<QString> want(syms.cbegin(), syms.cend());
+ if (b.symbols != want) {
+ stream->subscribe_symbols(kConsumer, syms);
+ b.symbols = want;
+ }
+ dsm.start_stream(acct.account_id);
+ }
+
+ // Drop bindings for accounts that no longer hold positions / are no longer
+ // active paper, releasing their stream subscription.
+ for (auto it = bound_.begin(); it != bound_.end();) {
+ if (!should_track.contains(it.key())) {
+ if (it->conn)
+ QObject::disconnect(it->conn);
+ if (auto* s = dsm.stream_for(it.key()))
+ s->unsubscribe_consumer(kConsumer);
+ it = bound_.erase(it);
+ } else {
+ ++it;
+ }
+ }
+}
+
+void PaperMarkService::on_quote(const QString& account_id, const QString& portfolio_id, const QString& symbol,
+ const BrokerQuote& quote) {
+ if (quote.ltp <= 0.0)
+ return; // garbage/zero tick — the repo guard would drop it anyway; skip the work
+ auto it = bound_.constFind(account_id);
+ if (it == bound_.constEnd())
+ return;
+
+ // Reconcile the live quote symbol to a stored position symbol.
+ QString pos_sym;
+ if (it->exact.contains(symbol)) {
+ pos_sym = symbol; // exact match (equities + brokers that normalise identically)
+ } else {
+ // Option fallback: the live spelling ("…C<strike>") differs from the
+ // position spelling ("…<strike>CE"). Match by (underlying, side, strike).
+ const auto tick = fyers_parse_option(symbol);
+ if (tick.valid && tick.strike > 0.0) {
+ const QString strike_str = QString::number(qRound64(tick.strike));
+ for (const auto& leg : it->legs) {
+ if (leg.is_call != tick.is_call || leg.underlying != tick.underlying)
+ continue;
+ QString core = leg.symbol.section(QLatin1Char(':'), -1);
+ if (core.endsWith(QLatin1String("CE")) || core.endsWith(QLatin1String("PE")))
+ core.chop(2);
+ if (core.endsWith(strike_str)) {
+ pos_sym = leg.symbol;
+ break;
+ }
+ }
+ }
+ }
+ if (pos_sym.isEmpty())
+ return;
+
+ // Coalesce the SQLite write; the in-memory matcher sees every tick.
+ pending_[portfolio_id][pos_sym] = quote.ltp;
+ if (!flush_armed_) {
+ flush_armed_ = true;
+ QTimer::singleShot(kFlushMs, this, [this]() { flush_prices(); });
+ }
+
+ PriceData pd;
+ pd.last = quote.ltp;
+ pd.bid = quote.bid;
+ pd.ask = quote.ask;
+ pd.timestamp = quote.timestamp;
+ OrderMatcher::instance().check_orders(pos_sym, pd, portfolio_id);
+ OrderMatcher::instance().check_sl_tp_triggers(portfolio_id, pos_sym, quote.ltp);
+}
+
+void PaperMarkService::flush_prices() {
+ flush_armed_ = false;
+ if (pending_.isEmpty())
+ return;
+ const auto snapshot = pending_;
+ pending_.clear();
+ for (auto pit = snapshot.cbegin(); pit != snapshot.cend(); ++pit) {
+ const QString& pid = pit.key();
+ for (auto sit = pit.value().cbegin(); sit != pit.value().cend(); ++sit)
+ pt_update_position_price(pid, sit.key(), sit.value()); // repo guards price <= 0
+ emit prices_marked(pid);
+ }
+}
+
+} // namespace fincept::trading
diff --git a/fincept-qt/src/trading/PaperMarkService.h b/fincept-qt/src/trading/PaperMarkService.h
new file mode 100644
index 000000000..03217a32b
--- /dev/null
+++ b/fincept-qt/src/trading/PaperMarkService.h
@@ -0,0 +1,88 @@
+#pragma once
+// PaperMarkService — centralized, screen-independent mark-to-market + order
+// matching for paper-trading positions.
+//
+// The Equity screen used to be the ONLY place that marked paper positions to the
+// live feed and drove the OrderMatcher (limit/stop/SL-TP fills). So an F&O (or
+// any) position only updated its P&L — and its resting orders only filled —
+// while the Equity tab was open and focused. Open positions on any other tab
+// showed a frozen entry price (and, before the zero-price guard, a phantom
+// profit), and square-off acted on stale numbers.
+//
+// This service fixes that at the source: for every ACTIVE paper account that
+// holds open positions, it keeps the account's data stream subscribed to those
+// symbols, marks each position to the live quote (coalesced to SQLite, with the
+// repo's zero/garbage-price guard), and drives the OrderMatcher on every tick —
+// regardless of which screen, if any, is visible. It reconciles a broker's quote
+// symbol to the stored position symbol by exact match, falling back to an option
+// (underlying, side, strike) match for brokers whose live spelling differs from
+// the REST/position spelling (the Fyers "…C<strike>" vs "…<strike>CE" case).
+//
+// Screens observe prices_marked()/portfolio_changed() to refresh their blotter;
+// they no longer need to own the marking loop themselves.
+
+#include <QHash>
+#include <QObject>
+#include <QSet>
+#include <QString>
+#include <QVector>
+
+class QTimer;
+
+namespace fincept::trading {
+
+struct BrokerQuote;
+
+class PaperMarkService : public QObject {
+ Q_OBJECT
+ public:
+ static PaperMarkService& instance();
+
+ // Start the background loop. Idempotent. Call once after Database::open(),
+ // AccountManager::reload_from_db() and DataStreamManager are ready.
+ void start();
+
+ // Re-evaluate which paper accounts/positions to track and (re)bind their
+ // streams. Runs automatically on a timer and after every fill; call directly
+ // right after placing/closing an order for an immediate refresh.
+ void resync();
+
+ signals:
+ // The given paper portfolio's position prices were just marked to market
+ // (throttled to the flush cadence) — a cue to repaint P&L.
+ void prices_marked(const QString& portfolio_id);
+ // A fill changed the portfolio's positions/orders — a cue for a full reload.
+ void portfolio_changed(const QString& portfolio_id);
+
+ private:
+ PaperMarkService();
+
+ void on_quote(const QString& account_id, const QString& portfolio_id, const QString& symbol,
+ const BrokerQuote& quote);
+ void flush_prices();
+
+ // Parsed identity of an option position, for matching a live tick whose
+ // symbol spelling differs from the stored position symbol.
+ struct PosLeg {
+ QString underlying;
+ bool is_call = false;
+ QString symbol; // the stored position symbol (match target)
+ };
+ struct Bound {
+ QString portfolio_id;
+ QObject* stream = nullptr; // bound AccountDataStream (detect recreation on re-auth)
+ QMetaObject::Connection conn; // quote_updated → on_quote
+ QSet<QString> symbols; // currently subscribed on the stream
+ QSet<QString> exact; // position symbols for O(1) exact match
+ QVector<PosLeg> legs; // option positions for strike/side match
+ };
+
+ QHash<QString, Bound> bound_; // account_id → binding
+ QHash<QString, QHash<QString, double>> pending_; // portfolio_id → {symbol: ltp} (coalesced)
+ bool started_ = false;
+ bool flush_armed_ = false;
+ int fill_cb_id_ = -1;
+ QTimer* resync_timer_ = nullptr;
+};
+
+} // namespace fincept::trading
diff --git a/fincept-qt/src/trading/PaperTradingSelftest.cpp b/fincept-qt/src/trading/PaperTradingSelftest.cpp
new file mode 100644
index 000000000..f524d7039
--- /dev/null
+++ b/fincept-qt/src/trading/PaperTradingSelftest.cpp
@@ -0,0 +1,154 @@
+#include "trading/PaperTradingSelftest.h"
+
+#include "trading/PaperTrading.h"
+#include "trading/TradingTypes.h"
+
+#include <QString>
+
+#include <cmath>
+#include <cstdio>
+#include <optional>
+
+namespace fincept::trading {
+
+namespace {
+
+// Find an open position by exact symbol (selftest symbols are unambiguous).
+std::optional<PtPosition> position_for(const QString& portfolio_id, const QString& symbol) {
+ for (const auto& p : pt_get_positions(portfolio_id))
+ if (p.symbol == symbol)
+ return p;
+ return std::nullopt;
+}
+
+bool approx(double a, double b, double eps = 0.01) {
+ return std::fabs(a - b) <= eps;
+}
+
+} // namespace
+
+int run_paper_trading_selftest() {
+ int failures = 0;
+ auto check = [&](const char* label, bool ok) {
+ std::printf("[%s] %s\n", ok ? "PASS" : "FAIL", label);
+ if (!ok)
+ ++failures;
+ };
+
+ // Throwaway portfolio. fee_rate = 0 so realized/unrealized P&L is exact and
+ // assertable; INR + NFO so the option-leverage and instrument-type paths run.
+ const QString name = QStringLiteral("__selftest_paper__");
+ const QString pf_exchange = QStringLiteral("NFO");
+ if (auto existing = pt_find_portfolio(name, pf_exchange))
+ pt_delete_portfolio(existing->id);
+ PtPortfolio pf = pt_create_portfolio(name, /*balance=*/1'000'000.0, /*currency=*/QStringLiteral("INR"),
+ /*leverage=*/1.0, /*margin_mode=*/QStringLiteral("cross"),
+ /*fee_rate=*/0.0, /*exchange=*/pf_exchange);
+ const QString pid = pf.id;
+
+ // Place a market order and fill it immediately at `px` (the path every screen
+ // uses for a market order: place -> fill).
+ auto open_market = [&](const QString& sym, const QString& side, double qty, double px,
+ const QString& product, const QString& exchange) {
+ auto o = pt_place_order(pid, sym, side, QStringLiteral("market"), qty, px, std::nullopt,
+ /*reduce_only=*/false, exchange, product);
+ pt_fill_order(o.id, px);
+ };
+
+ const QString NSE = QStringLiteral("NSE");
+ const QString NFO = QStringLiteral("NFO");
+
+ // ── 1. Long equity marks to market with the right sign + magnitude ──────
+ {
+ const QString sym = QStringLiteral("RELIANCE");
+ open_market(sym, QStringLiteral("buy"), 10, 100.0, QStringLiteral("MIS"), NSE);
+ pt_update_position_price(pid, sym, 110.0);
+ auto p = position_for(pid, sym);
+ check("long: position opened", p.has_value());
+ check("long: side == long", p && p->side.compare(QStringLiteral("long"), Qt::CaseInsensitive) == 0);
+ check("long: unrealized P&L = +100 at 110", p && approx(p->unrealized_pnl, 100.0));
+ open_market(sym, QStringLiteral("sell"), 10, 110.0, QStringLiteral("MIS"), NSE);
+ check("long: exits on opposite fill", !position_for(pid, sym).has_value());
+ }
+
+ // ── 2. Short option opens flat (P&L 0 at entry) ─────────────────────────
+ const QString opt = QStringLiteral("NIFTY24DEC2450000CE");
+ {
+ open_market(opt, QStringLiteral("sell"), 50, 200.0, QStringLiteral("NRML"), NFO);
+ auto p = position_for(pid, opt);
+ check("short: position opened as short", p && p->side.compare(QStringLiteral("short"), Qt::CaseInsensitive) == 0);
+ check("short: unrealized P&L ~0 at entry", p && approx(p->unrealized_pnl, 0.0));
+ }
+
+ // ── 3. THE PHANTOM-PROFIT BUG: a zero/garbage tick on a short must NOT ───
+ // book the full premium (entry*qty) as profit. This is exactly what the
+ // user saw: "square up shows total trade value in profit". Pre-fix the
+ // engine writes unrealized = (200 - 0)*50 = +10000; post-fix the 0 tick
+ // is ignored and P&L holds at its last good value (~0 here).
+ {
+ pt_update_position_price(pid, opt, 0.0);
+ auto p = position_for(pid, opt);
+ check("zero-tick: P&L is NOT the full premium (+10000)",
+ p && !approx(p->unrealized_pnl, 10000.0, 1.0));
+ check("zero-tick: P&L holds at last good value (~0)", p && approx(p->unrealized_pnl, 0.0));
+
+ // A real tick still marks correctly: short 50 @ 200, now 150 -> +2500.
+ pt_update_position_price(pid, opt, 150.0);
+ p = position_for(pid, opt);
+ check("short: unrealized P&L = +2500 at 150", p && approx(p->unrealized_pnl, 2500.0));
+ }
+
+ // ── 4. Square-off a short: it actually exits AND books the right realized ──
+ {
+ // Close the short (50 @ 200, marked 150) with a buy 50 @ 150.
+ open_market(opt, QStringLiteral("buy"), 50, 150.0, QStringLiteral("NRML"), NFO);
+ check("square-off: short position exited", !position_for(pid, opt).has_value());
+ bool booked = false;
+ for (const auto& t : pt_get_trades(pid))
+ if (t.symbol == opt && t.side.compare(QStringLiteral("buy"), Qt::CaseInsensitive) == 0 &&
+ approx(t.pnl, 2500.0))
+ booked = true;
+ check("square-off: realized P&L = +2500 recorded", booked);
+ }
+
+ // ── 5. Netting: an equal opposite fill closes out, never leaves a phantom ──
+ // reverse position (the failure mode behind "doesn't exit").
+ {
+ const QString sym = QStringLiteral("TCS");
+ open_market(sym, QStringLiteral("buy"), 5, 1000.0, QStringLiteral("MIS"), NSE);
+ open_market(sym, QStringLiteral("sell"), 5, 1100.0, QStringLiteral("MIS"), NSE);
+ check("netting: flat after equal opposite fill", !position_for(pid, sym).has_value());
+ }
+
+ // ── 6. Multi-leg (builder-style) strategy: every leg actually fills ─────
+ {
+ const QString pe = QStringLiteral("NIFTY24DEC2449000PE");
+ const QString ce = QStringLiteral("NIFTY24DEC2451000CE");
+ open_market(pe, QStringLiteral("buy"), 50, 120.0, QStringLiteral("NRML"), NFO);
+ open_market(ce, QStringLiteral("sell"), 50, 90.0, QStringLiteral("NRML"), NFO);
+ check("multi-leg: both legs opened as positions",
+ position_for(pid, pe).has_value() && position_for(pid, ce).has_value());
+ }
+
+ // ── 7. Margin lock on open, full release (+P&L) on close ────────────────
+ {
+ const QString sym = QStringLiteral("INFY");
+ const double bal0 = pt_get_portfolio(pid).balance;
+ open_market(sym, QStringLiteral("buy"), 10, 500.0, QStringLiteral("CNC"), NSE); // CNC 1x -> locks 5000
+ const double bal1 = pt_get_portfolio(pid).balance;
+ check("margin: balance drops by locked margin on open", bal1 < bal0 - 4999.0);
+ pt_update_position_price(pid, sym, 520.0);
+ open_market(sym, QStringLiteral("sell"), 10, 520.0, QStringLiteral("CNC"), NSE); // realize +200, release
+ const double bal2 = pt_get_portfolio(pid).balance;
+ check("margin: balance restored + realized P&L on close", approx(bal2, bal0 + 200.0, 1.0));
+ }
+
+ // Clean up the throwaway portfolio (positions/orders/trades/blocks cascade).
+ pt_delete_portfolio(pid);
+
+ std::printf("\npaper-trading selftest: %s (%d failure%s)\n", failures == 0 ? "OK" : "FAILED",
+ failures, failures == 1 ? "" : "s");
+ return failures == 0 ? 0 : 1;
+}
+
+} // namespace fincept::trading
diff --git a/fincept-qt/src/trading/PaperTradingSelftest.h b/fincept-qt/src/trading/PaperTradingSelftest.h
new file mode 100644
index 000000000..e1fb205c1
--- /dev/null
+++ b/fincept-qt/src/trading/PaperTradingSelftest.h
@@ -0,0 +1,16 @@
+#pragma once
+// Headless self-test of the paper-trading engine (no GUI / network / broker /
+// LLM). Runs on a throwaway portfolio and asserts the core invariants that the
+// FNO + Equity paper-trading bugs violated: long/short mark-to-market P&L, the
+// zero-tick phantom-profit guard (a 0/garbage quote on a short must NOT book the
+// full premium as profit), square-off exit + realized P&L, opposite-fill netting
+// (no phantom reverse position), multi-leg fills, and margin lock/release.
+//
+// Run headless: QT_QPA_PLATFORM=offscreen FinceptTerminal --selftest-paper
+// Returns 0 when every assertion passes, 1 otherwise (CI / dev-loop gate).
+
+namespace fincept::trading {
+
+int run_paper_trading_selftest();
+
+} // namespace fincept::trading
diff --git a/fincept-qt/src/trading/UnifiedTrading.cpp b/fincept-qt/src/trading/UnifiedTrading.cpp
index a7fd19e43..f89f9c152 100644
--- a/fincept-qt/src/trading/UnifiedTrading.cpp
+++ b/fincept-qt/src/trading/UnifiedTrading.cpp
@@ -5,6 +5,7 @@
#include "core/logging/Logger.h"
#include "trading/AccountManager.h"
#include "trading/OrderValidator.h"
+#include "trading/OrderMatcher.h"
#include "trading/PaperTrading.h"
#include "trading/SmartOrderEngine.h"
#include "trading/StrategyPortfolio.h"
@@ -268,26 +269,50 @@ UnifiedOrderResponse UnifiedTrading::place_paper_order_for_account(const QString
if (account.paper_portfolio_id.isEmpty())
return {false, "", "No paper portfolio for this account", "paper"};
- QString symbol = order.exchange.isEmpty() ? order.symbol : order.exchange + ":" + order.symbol;
- QString side_str = order_side_str(order.side);
- QString type_str = order_type_str(order.order_type);
-
+ // Store the BARE symbol (no exchange prefix). Positions mark to market against
+ // the live quote feed published under the bare symbol (broker:<id>:<acct>:quote:
+ // <bare>), and this matches the Equity screen's convention. Re-prefixing here as
+ // "NFO:NIFTY…" was why F&O positions never marked (the prefix never matched a
+ // quote topic) and showed a frozen/garbage price.
+ const QString symbol = order.symbol;
+ const QString side_str = order_side_str(order.side);
+ const QString type_str = order_type_str(order.order_type);
+
+ // Forward the broker product (MIS/CNC/NRML) and exchange so the engine applies
+ // per-product leverage and TAGS the position with its real product. Without it
+ // the product defaulted to CNC (delivery), which made square-off-all skip the
+ // position entirely (it filters to intraday) — the "doesn't exit" bug.
+ const QString product = product_to_broker_str(order.product_type);
+
+ // Resolve the order's reference / fill price. Limit & stop-limit carry their own
+ // trigger; market and plain-stop fill at the caller-supplied live price
+ // (order.price = LTP at click time). A market order with no usable price is
+ // rejected with a clear message rather than the old hardcoded 1000.0 sentinel.
std::optional<double> price_opt;
- if (order.order_type == OrderType::Market)
- price_opt = 1000.0;
- else if (order.price > 0)
+ if (order.order_type == OrderType::Limit || order.order_type == OrderType::StopLossLimit) {
+ if (order.price > 0)
+ price_opt = order.price;
+ } else if (order.price > 0) {
price_opt = order.price;
-
+ }
std::optional<double> stop_opt;
if (order.stop_price > 0)
stop_opt = order.stop_price;
+ const bool is_market = (order.order_type == OrderType::Market);
+ if (is_market && !price_opt)
+ return {false, "", "No live price yet for a market fill — wait for quotes to load", "paper"};
+
try {
auto paper_order = pt_place_order(account.paper_portfolio_id, symbol, side_str, type_str, order.quantity,
- price_opt, stop_opt, false);
- if (order.order_type == OrderType::Market) {
- double fill_price = order.price > 0 ? order.price : 1000.0;
- pt_fill_order(paper_order.id, fill_price);
+ price_opt, stop_opt, /*reduce_only=*/false, order.exchange, product);
+ if (is_market) {
+ pt_fill_order(paper_order.id, *price_opt);
+ } else {
+ // Limit / stop / stop-limit: hand to the matcher so it fills on a real
+ // market touch (driven centrally off the quote feed). Previously these
+ // were placed and then left "pending" forever — never filled.
+ OrderMatcher::instance().add_order(paper_order);
}
return {true, paper_order.id, "Paper order placed", "paper"};
} catch (const std::exception& e) {
@@ -382,14 +407,24 @@ ApiResponse<CloseAllResult> UnifiedTrading::close_all_positions(const QString& a
for (const auto& pos : positions) {
if (pos.quantity == 0) continue;
result.total_positions++;
- auto side_str = (pos.quantity > 0) ? QString("sell") : QString("buy");
+ // Close with the OPPOSITE side. Paper positions store quantity as a
+ // positive magnitude with side="long"/"short", so the quantity sign is
+ // unreliable (shorts are +) — derive the direction from `side`. Using
+ // the sign sold a short instead of buying it back, so it never closed.
+ const QString dir = pos.side.toLower();
+ const bool is_short = dir == QLatin1String("short") || dir == QLatin1String("sell") || pos.quantity < 0;
+ const QString side_str = is_short ? QStringLiteral("buy") : QStringLiteral("sell");
+ const double fill = pos.current_price > 0.0 ? pos.current_price : pos.entry_price;
try {
auto paper_order = pt_place_order(account.paper_portfolio_id, pos.symbol,
- side_str, "market", std::abs(pos.quantity), pos.current_price, std::nullopt, false);
- pt_fill_order(paper_order.id, pos.current_price);
+ side_str, "market", std::abs(pos.quantity), fill, std::nullopt, false);
+ pt_fill_order(paper_order.id, fill);
result.closed_symbols.append(pos.symbol);
- } catch (...) {
- result.failed.append({pos.symbol, "Close failed"});
+ LOG_INFO("UnifiedTrading", QString("close_all paper: %1 %2 x%3 @ %4 (was %5)")
+ .arg(side_str, pos.symbol).arg(std::abs(pos.quantity)).arg(fill).arg(pos.side));
+ } catch (const std::exception& e) {
+ result.failed.append({pos.symbol, e.what()});
+ LOG_WARN("UnifiedTrading", QString("close_all paper failed for %1: %2").arg(pos.symbol, e.what()));
}
}
publish(AllPositionsClosedEvent{account_id, (int)result.closed_symbols.size(),
@@ -424,11 +459,16 @@ ApiResponse<OrderPlaceResponse> UnifiedTrading::close_position(
QString pos_sym = pos.symbol;
if (pos_sym == symbol || pos_sym == exchange + ":" + symbol) {
if (pos.quantity == 0) continue;
- auto side_str = (pos.quantity > 0) ? QString("sell") : QString("buy");
+ // Close by the OPPOSITE of the position's `side` (quantity is a
+ // positive magnitude; shorts are +, so the sign is unreliable).
+ const QString dir = pos.side.toLower();
+ const bool is_short = dir == QLatin1String("short") || dir == QLatin1String("sell") || pos.quantity < 0;
+ const QString side_str = is_short ? QStringLiteral("buy") : QStringLiteral("sell");
+ const double fill = pos.current_price > 0.0 ? pos.current_price : pos.entry_price;
try {
auto paper_order = pt_place_order(account.paper_portfolio_id, pos.symbol,
- side_str, "market", std::abs(pos.quantity), pos.current_price, std::nullopt, false);
- pt_fill_order(paper_order.id, pos.current_price);
+ side_str, "market", std::abs(pos.quantity), fill, std::nullopt, false);
+ pt_fill_order(paper_order.id, fill);
return {true, OrderPlaceResponse{true, paper_order.id, {}}, {}};
} catch (const std::exception& e) {
return {false, std::nullopt, QString("Close failed: %1").arg(e.what())};
@@ -623,30 +663,39 @@ void UnifiedTrading::place_basket_orders(const QString& account_id, const Basket
r.exchange = order.exchange;
if (is_paper) {
- QString symbol = order.exchange.isEmpty() ? order.symbol
- : order.exchange + ":" + order.symbol;
- QString side_str = order_side_str(order.side);
- QString type_str = order_type_str(order.order_type);
+ // Store the BARE symbol + forward exchange/product (same contract as
+ // place_paper_order_for_account) so each leg marks to market and
+ // squares off correctly. Market legs fill at the supplied price (no
+ // 1000.0 sentinel — a market leg with no price fails cleanly); limit/
+ // stop legs go to the matcher to fill on a real touch.
+ const QString side_str = order_side_str(order.side);
+ const QString type_str = order_type_str(order.order_type);
+ const QString product = product_to_broker_str(order.product_type);
+ const bool is_market = (order.order_type == OrderType::Market);
std::optional<double> price_opt;
- if (order.order_type == OrderType::Market)
- price_opt = 1000.0;
- else if (order.price > 0)
+ if (order.price > 0)
price_opt = order.price;
std::optional<double> stop_opt;
if (order.stop_price > 0)
stop_opt = order.stop_price;
- try {
- auto paper_order = pt_place_order(paper_portfolio_id, symbol, side_str, type_str,
- order.quantity, price_opt, stop_opt, false);
- if (order.order_type == OrderType::Market) {
- double fill_price = order.price > 0 ? order.price : 1000.0;
- pt_fill_order(paper_order.id, fill_price);
- }
- r.success = true;
- r.order_id = paper_order.id;
- } catch (const std::exception& e) {
+ if (is_market && !price_opt) {
r.success = false;
- r.error = QString("Paper order failed: %1").arg(e.what());
+ r.error = "No live price for market fill";
+ } else {
+ try {
+ auto paper_order = pt_place_order(paper_portfolio_id, order.symbol, side_str, type_str,
+ order.quantity, price_opt, stop_opt, false,
+ order.exchange, product);
+ if (is_market)
+ pt_fill_order(paper_order.id, *price_opt);
+ else
+ OrderMatcher::instance().add_order(paper_order);
+ r.success = true;
+ r.order_id = paper_order.id;
+ } catch (const std::exception& e) {
+ r.success = false;
+ r.error = QString("Paper order failed: %1").arg(e.what());
+ }
}
} else {
OrderPlaceResponse resp = broker->place_order(creds, order);
@@ -770,30 +819,36 @@ void UnifiedTrading::place_split_orders(const QString& account_id, const SplitOr
r.exchange = chunk.exchange;
if (is_paper) {
- QString symbol = chunk.exchange.isEmpty() ? chunk.symbol
- : chunk.exchange + ":" + chunk.symbol;
- QString side_str = order_side_str(chunk.side);
- QString type_str = order_type_str(chunk.order_type);
+ // Bare symbol + forwarded exchange/product (same contract as the
+ // keystone) so split chunks mark + square off; no 1000.0 sentinel.
+ const QString side_str = order_side_str(chunk.side);
+ const QString type_str = order_type_str(chunk.order_type);
+ const QString product = product_to_broker_str(chunk.product_type);
+ const bool is_market = (chunk.order_type == OrderType::Market);
std::optional<double> price_opt;
- if (chunk.order_type == OrderType::Market)
- price_opt = 1000.0;
- else if (chunk.price > 0)
+ if (chunk.price > 0)
price_opt = chunk.price;
std::optional<double> stop_opt;
if (chunk.stop_price > 0)
stop_opt = chunk.stop_price;
- try {
- auto paper_order = pt_place_order(paper_portfolio_id, symbol, side_str, type_str,
- chunk.quantity, price_opt, stop_opt, false);
- if (chunk.order_type == OrderType::Market) {
- double fill_price = chunk.price > 0 ? chunk.price : 1000.0;
- pt_fill_order(paper_order.id, fill_price);
- }
- r.success = true;
- r.order_id = paper_order.id;
- } catch (const std::exception& e) {
+ if (is_market && !price_opt) {
r.success = false;
- r.error = QString("Paper order failed: %1").arg(e.what());
+ r.error = "No live price for market fill";
+ } else {
+ try {
+ auto paper_order = pt_place_order(paper_portfolio_id, chunk.symbol, side_str, type_str,
+ chunk.quantity, price_opt, stop_opt, false,
+ chunk.exchange, product);
+ if (is_market)
+ pt_fill_order(paper_order.id, *price_opt);
+ else
+ OrderMatcher::instance().add_order(paper_order);
+ r.success = true;
+ r.order_id = paper_order.id;
+ } catch (const std::exception& e) {
+ r.success = false;
+ r.error = QString("Paper order failed: %1").arg(e.what());
+ }
}
} else {
OrderPlaceResponse resp = broker->place_order(creds, chunk);
diff --git a/fincept-qt/src/trading/brokers/fyers/FyersBroker.cpp b/fincept-qt/src/trading/brokers/fyers/FyersBroker.cpp
index 0ba829a7f..0ebfcfbbe 100644
--- a/fincept-qt/src/trading/brokers/fyers/FyersBroker.cpp
+++ b/fincept-qt/src/trading/brokers/fyers/FyersBroker.cpp
@@ -29,14 +29,25 @@ static QString to_fyers_sym(const QString& sym) {
return QStringLiteral("NSE:") + sym + QStringLiteral("-EQ");
}
-// Strip Fyers format back to plain symbol: NSE:RELIANCE-EQ → RELIANCE
+// Strip Fyers format back to plain symbol: NSE:RELIANCE-EQ → RELIANCE.
+// F&O contracts come back with "-CE"/"-PE"/"-FUT"; strip those too so a position
+// symbol matches the bare HSM symbol the WS feed publishes (e.g.
+// "NIFTY09JUN26C22650"), keeping option positions marked-to-market live. We strip
+// only known segment suffixes — NOT everything after the first '-', since names
+// like "BAJAJ-AUTO-EQ" legitimately contain hyphens.
static QString from_fyers_sym(const QString& fyers_sym) {
QString s = fyers_sym;
const int colon = s.indexOf(':');
if (colon >= 0)
s = s.mid(colon + 1);
- if (s.endsWith(QLatin1String("-EQ")))
- s.chop(3);
+ static const QStringList kSuffixes = {QStringLiteral("-EQ"), QStringLiteral("-CE"),
+ QStringLiteral("-PE"), QStringLiteral("-FUT")};
+ for (const auto& suf : kSuffixes) {
+ if (s.endsWith(suf)) {
+ s.chop(int(suf.size()));
+ break;
+ }
+ }
return s;
}
@@ -320,6 +331,16 @@ ApiResponse<QVector<BrokerPosition>> FyersBroker::get_positions(const BrokerCred
const QString raw_pos_sym = p.value("symbol").toString();
pos.symbol = from_fyers_sym(raw_pos_sym);
pos.exchange = exchange_of(raw_pos_sym, p.value("exchange").toInt(-1));
+ {
+ // [posdiag] one-shot per symbol — verify position symbol matches the
+ // WS quote symbol so option positions mark-to-market live.
+ static QSet<QString> s_seen_pos;
+ if (!s_seen_pos.contains(raw_pos_sym)) {
+ s_seen_pos.insert(raw_pos_sym);
+ LOG_INFO("FyersBroker", QString("[posdiag] raw='%1' → norm='%2' exch='%3'")
+ .arg(raw_pos_sym, pos.symbol, pos.exchange));
+ }
+ }
pos.product_type = p.value("productType").toString();
pos.quantity = p.value("netQty").toDouble();
pos.avg_price = p.value("netAvg").toDouble();
diff --git a/fincept-qt/src/trading/websocket/FyersTickTypes.h b/fincept-qt/src/trading/websocket/FyersTickTypes.h
index b8ef110c3..4b700573b 100644
--- a/fincept-qt/src/trading/websocket/FyersTickTypes.h
+++ b/fincept-qt/src/trading/websocket/FyersTickTypes.h
@@ -16,6 +16,7 @@ struct FyersTick {
double tot_sell_qty = 0.0;
double ltq = 0.0;
double atp = 0.0;
+ double oi = 0.0; // open interest (sf field 12); 0 for cash/equity
quint32 timestamp = 0;
quint64 fytoken = 0;
quint16 fy_code = 0;
@@ -25,4 +26,80 @@ struct FyersTick {
QString exchange; // e.g. "NSE"
};
+// ── Fyers F&O option symbol reconciliation ──────────────────────────────────
+//
+// Fyers spells the SAME option two ways, and the two never string-match:
+// • HSM / WebSocket tick feed : "NIFTY09JUN26C23200" (… C|P + strike)
+// • REST / chain-v3 / position: "NIFTY2660923200CE" (… strike + CE|PE)
+// So an option position cannot be marked-to-market by comparing the live tick's
+// symbol against the position's symbol the way equities are. Callers reconcile
+// the two by a format-independent leg identity — (underlying, strike, side).
+
+struct FyersOptionLeg {
+ QString underlying; // leading alphabetic root, e.g. "NIFTY", "BANKNIFTY"
+ double strike = 0.0; // 0 for the CE/PE spelling (its strike is positional —
+ // the caller matches it against the live tick's strike)
+ bool is_call = false; // true = CE/Call, false = PE/Put
+ bool valid = false; // false for non-options (equities, futures, indices)
+};
+
+// Parse a Fyers option symbol in EITHER spelling (an "NSE:"/"NFO:" prefix is
+// stripped first). The HSM/brsymbol form carries a parseable strike; the CE/PE
+// form yields underlying + side only. Returns {valid=false} for anything that
+// isn't an option — the digit-before-"CE"/"PE" guard keeps equities that merely
+// end in those letters (e.g. "RELIANCE", "ACE") from being misread as options.
+inline FyersOptionLeg fyers_parse_option(const QString& raw) {
+ FyersOptionLeg leg;
+ QString s = raw;
+ const qsizetype colon = s.lastIndexOf(QLatin1Char(':'));
+ if (colon >= 0)
+ s = s.mid(colon + 1);
+ const int n = int(s.size());
+ if (n < 4)
+ return leg;
+ int u = 0;
+ while (u < n && s.at(u).isLetter())
+ ++u; // underlying root (leading letters)
+ if (u == 0)
+ return leg;
+
+ // Form 1 — HSM/brsymbol: trailing strike digits, a 'C'/'P' before them, and a
+ // (date) digit before that: "NIFTY09JUN26C23200".
+ int i = n - 1;
+ while (i >= 0 && s.at(i).isDigit())
+ --i;
+ if (i > 0 && i < n - 1) {
+ const QChar cp = s.at(i);
+ if ((cp == QLatin1Char('C') || cp == QLatin1Char('P')) && s.at(i - 1).isDigit()) {
+ bool ok = false;
+ const double k = QStringView(s).mid(i + 1).toDouble(&ok);
+ if (ok && k > 0) {
+ leg.underlying = s.left(u);
+ leg.strike = k;
+ leg.is_call = (cp == QLatin1Char('C'));
+ leg.valid = true;
+ return leg;
+ }
+ }
+ }
+
+ // Form 2 — REST/chain/position: "…<strike>CE" / "…<strike>PE". Require a digit
+ // immediately before the CE/PE so equities ending in those letters don't match.
+ const QStringView suf = QStringView(s).right(2);
+ if ((suf == QLatin1String("CE") || suf == QLatin1String("PE")) && s.at(n - 3).isDigit()) {
+ leg.underlying = s.left(u);
+ leg.is_call = (suf == QLatin1String("CE"));
+ leg.valid = true; // strike stays 0 — see FyersOptionLeg
+ return leg;
+ }
+ return leg;
+}
+
+// True when `sym` is a Fyers F&O option symbol (either spelling). Used so the WS
+// subscribe path maps these to "NSE:<sym>" instead of the equity "NSE:<sym>-EQ"
+// form — otherwise option positions never resolve a live feed.
+inline bool is_fyers_fno_symbol(const QString& sym) {
+ return fyers_parse_option(sym).valid;
+}
+
} // namespace fincept::trading
diff --git a/fincept-qt/src/trading/websocket/FyersWebSocket.cpp b/fincept-qt/src/trading/websocket/FyersWebSocket.cpp
index 9b3a6bc2a..6bd950543 100644
--- a/fincept-qt/src/trading/websocket/FyersWebSocket.cpp
+++ b/fincept-qt/src/trading/websocket/FyersWebSocket.cpp
@@ -536,6 +536,10 @@ void FyersWebSocket::emit_tick(quint16 topic_id) {
tick.tot_buy_qty = val(9) != kSentinel ? static_cast<double>(val(9)) : 0;
tick.tot_sell_qty = val(10) != kSentinel ? static_cast<double>(val(10)) : 0;
tick.atp = price(11);
+ // Field 12 is open interest (contracts) for F&O sf topics — a raw count,
+ // not price-scaled. Lite updates only refresh ltp[0] so the last full
+ // snapshot's OI persists in f[12]; sentinel/short arrays leave oi at 0.
+ tick.oi = val(12) != kSentinel ? static_cast<double>(val(12)) : 0;
tick.low = price(13);
tick.high = price(14);
tick.open = price(19);
@@ -602,6 +606,18 @@ void FyersWebSocket::resolve_and_subscribe(const QStringList& symbols) {
for (const auto& s : fyers_syms) arr.append(s);
QJsonObject body;
body["symbols"] = arr;
+ {
+ // [subdbg] F&O symbols being sent for token resolution (equities omitted
+ // to keep the line readable). Lets us confirm a held option is actually
+ // requested — and below, whether Fyers resolved or rejected it.
+ QStringList fno;
+ for (const auto& s : fyers_syms)
+ if (!s.endsWith(QLatin1String("-EQ")) && (s.contains(QLatin1String("CE")) ||
+ s.contains(QLatin1String("PE")) || s.contains(QLatin1String("FUT"))))
+ fno << s;
+ LOG_INFO("subdbg", QString("resolve_and_subscribe: sending %1 syms, F&O=[%2]")
+ .arg(fyers_syms.size()).arg(fno.join(',')));
+ }
auto resp = BrokerHttp::instance().post_json(
QStringLiteral("https://api-t1.fyers.in/data/symbol-token"), body,
@@ -620,6 +636,15 @@ void FyersWebSocket::resolve_and_subscribe(const QStringList& symbols) {
topics.append(QStringLiteral("dp|%1|%2").arg(seg, exch_token));
}
LOG_INFO("FyersWS", QString("Resolved %1 symbols → %2 topics").arg(fyers_syms.size()).arg(topics.size()));
+ // [subdbg] any symbols we SENT that Fyers did NOT return as valid —
+ // these silently get no live feed (the suspected option failure mode).
+ QStringList unresolved;
+ for (const auto& s : fyers_syms)
+ if (!valid.contains(s))
+ unresolved << s;
+ if (!unresolved.isEmpty())
+ LOG_WARN("subdbg", QString("resolve_and_subscribe: %1 UNRESOLVED (no feed): [%2]")
+ .arg(unresolved.size()).arg(unresolved.join(',')));
for (const auto& t : topics)
LOG_DEBUG("FyersWS", QString(" topic: %1").arg(t));
} else {
diff --git a/fincept-qt/src/ui/navigation/FKeyBar.cpp b/fincept-qt/src/ui/navigation/FKeyBar.cpp
index 74b8e92e7..08577393c 100644
--- a/fincept-qt/src/ui/navigation/FKeyBar.cpp
+++ b/fincept-qt/src/ui/navigation/FKeyBar.cpp
@@ -20,8 +20,9 @@ TabBar::TabBar(QWidget* parent) : QWidget(parent) {
tab_layout_->setSpacing(2);
tab_defs_ = {
- {"dashboard", "DASHBOARD"}, {"markets", "MARKETS"}, {"crypto_trading", "CRYPTO"}, {"portfolio", "PORTFOLIO"},
- {"news", "NEWS"}, {"ai_chat", "AI CHAT"}, {"backtesting", "BACKTEST"}, {"algo_trading", "ALGO"},
+ {"dashboard", "DASHBOARD"}, {"markets", "MARKETS"}, {"crypto_trading", "CRYPTO"}, {"equity_trading", "EQUITY"},
+ {"portfolio", "PORTFOLIO"}, {"news", "NEWS"}, {"ai_chat", "AI CHAT"}, {"backtesting", "BACKTEST"},
+ {"algo_trading", "ALGO"},
{"node_editor", "NODES"}, {"code_editor", "CODE"}, {"ai_quant_lab", "QUANT LAB"}, {"quantlib", "QUANTLIB"},
{"settings", "SETTINGS"}, {"profile", "PROFILE"},
};