FinceptTerminal is a modern finance application offering advanced market analytics, investment research, and economic data tools, designed for interactive exploration and data-driven decision-making in a user-friendly environment.
C++ ai-agentsalgorithmic-tradingbloomberg-terminalcppfinancefinancial-marketsfintechgood-first-issueinvestmentinvestment-researchmachine-learningopensourcepythonqtquantitative-financestock-markettrading
Equity trading tab update
tilakpatel22e14f36c801ca
diff --git a/fincept-qt/CMakeLists.txt b/fincept-qt/CMakeLists.txtindex cb4750e8e..39d5c2fd2 100644--- a/fincept-qt/CMakeLists.txt+++ b/fincept-qt/CMakeLists.txt@@ -870,6 +870,7 @@ set(STORAGE_SOURCESsrc/storage/sqlite/migrations/v044_feed_items.cppsrc/storage/sqlite/migrations/v045_scan_watch_universe.cppsrc/storage/sqlite/migrations/v046_fno_algo.cpp+ src/storage/sqlite/migrations/v047_algo_multileg_trades.cpp# Historical OHLCV data store (Historify, Phase 3 §13)src/storage/HistoricalDataStore.cpp@@ -976,6 +977,8 @@ set(MCP_SOURCESset(TRADING_SOURCESsrc/trading/PaperTrading.cppsrc/trading/PaperTradingSelftest.cpp+ src/trading/replication/PortfolioReplicationService.cpp+ src/trading/replication/PortfolioReplicationSelftest.cppsrc/trading/PaperMarkService.cppsrc/trading/OrderMatcher.cppsrc/trading/BrokerRegistry.cpp@@ -1095,6 +1098,9 @@ set(ALGO_ENGINE_SOURCESsrc/algo_engine/fno/FnoAlgoTypes.cppsrc/algo_engine/fno/FnoAlgoSelftest.cppsrc/algo_engine/fno/FnoLegResolver.cpp+ src/algo_engine/fno/FnoStrategyPreview.cpp+ src/algo_engine/fno/FnoDataBridge.cpp+ src/algo_engine/fno/FnoExecution.cpp)# Services@@ -1368,6 +1374,7 @@ set(UI_SOURCESsrc/ui/widgets/algo/RiskManagementPanel.cppsrc/ui/widgets/algo/SymbolSearchCombo.cppsrc/ui/widgets/algo/SymbolChipInput.cpp+ src/ui/widgets/algo/FnoLegRuleEditor.cpp)# Screens@@ -1535,6 +1542,7 @@ set(SCREEN_SOURCESsrc/screens/equity_trading/AccountManagementDialog.cppsrc/screens/equity_trading/BroadcastOrderDialog.cppsrc/screens/equity_trading/OrderConfirmDialog.cpp+ src/screens/equity_trading/PortfolioReplicationDialog.cpp# Feed monitor (reusable across screens)src/screens/common/feeds/FeedCardView.cppsrc/screens/common/feeds/FeedTableView.cpp@@ -2008,6 +2016,7 @@ set_source_files_properties(src/screens/equity_trading/AccountManagementDialog.cppsrc/screens/equity_trading/BroadcastOrderDialog.cppsrc/screens/equity_trading/OrderConfirmDialog.cpp+ src/screens/equity_trading/PortfolioReplicationDialog.cpp# Feed monitor (reusable across screens)src/screens/common/feeds/FeedCardView.cppsrc/screens/common/feeds/FeedTableView.cpp@@ -2364,6 +2373,7 @@ set_source_files_properties(src/storage/sqlite/migrations/v044_feed_items.cppsrc/storage/sqlite/migrations/v045_scan_watch_universe.cppsrc/storage/sqlite/migrations/v046_fno_algo.cpp+ src/storage/sqlite/migrations/v047_algo_multileg_trades.cpp# Polymarket screen files — each defines static fmt_* helpers in same namespacesrc/screens/polymarket/PolymarketScreen.cppsrc/screens/polymarket/PolymarketCommandBar.cppdiff --git a/fincept-qt/src/algo_engine/AlgoEngine.cpp b/fincept-qt/src/algo_engine/AlgoEngine.cppindex 05ea9c98b..d47d328a8 100644--- a/fincept-qt/src/algo_engine/AlgoEngine.cpp+++ b/fincept-qt/src/algo_engine/AlgoEngine.cpp@@ -1,8 +1,11 @@// src/algo_engine/AlgoEngine.cpp#include "algo_engine/AlgoEngine.h"+#include "algo_engine/fno/FnoExecution.h"#include "core/logging/Logger.h"#include "datahub/DataHub.h"#include "storage/sqlite/Database.h"+#include "trading/AccountManager.h"+#include "trading/PaperTrading.h"#include "trading/UnifiedTrading.h"#include <QDateTime>@@ -28,6 +31,11 @@ AlgoEngine::AlgoEngine() {qRegisterMetaType<fincept::algo::AlgoMetrics>("fincept::algo::AlgoMetrics");qRegisterMetaType<fincept::algo::AlgoTradeRecord>("fincept::algo::AlgoTradeRecord");+ // Create the FnoDataBridge BEFORE moveToThread so it stays on the main thread.+ // Do NOT parent it to `this` — `this` moves to the engine thread, which would+ // carry fno_bridge_ along. Ownership: deleted in dtor.+ fno_bridge_ = new fincept::algo::fno::FnoDataBridge();+engine_thread_.setObjectName(QStringLiteral("AlgoEngineThread"));engine_thread_.start();moveToThread(&engine_thread_);@@ -37,6 +45,8 @@ AlgoEngine::~AlgoEngine() {stop_all();engine_thread_.quit();engine_thread_.wait(5000);+ delete fno_bridge_;+ fno_bridge_ = nullptr;}void AlgoEngine::start_deployment(const services::algo::AlgoDeployment& deployment,@@ -48,6 +58,7 @@ void AlgoEngine::start_deployment(const services::algo::AlgoDeployment& deployme}auto* runner = new DeploymentRunner(deployment, strategy);+ runner->set_fno_bridge(fno_bridge_);runner->moveToThread(&engine_thread_);connect(runner, &DeploymentRunner::trade_executed, this, &AlgoEngine::trade_executed);@@ -152,6 +163,12 @@ void AlgoEngine::on_order_requested(const AlgoOrderSignal& signal) {}void AlgoEngine::execute_order(const AlgoOrderSignal& signal) {+ // Multi-leg F&O basket → dedicated path (paper portfolio / live broker basket).+ if (!signal.legs.isEmpty()) {+ execute_basket(signal);+ return;+ }+QPointer<AlgoEngine> self = this;QString dep_id = signal.deployment_id;const double submitted_price = signal.price;@@ -214,6 +231,174 @@ void AlgoEngine::execute_order(const AlgoOrderSignal& signal) {});}+QString AlgoEngine::resolve_paper_portfolio_id(const AlgoOrderSignal& signal) {+ // 1) Explicit portfolio stamped on the signal from the deployment.+ if (!signal.paper_portfolio_id.isEmpty())+ return signal.paper_portfolio_id;++ // 2) The deployment account's linked paper portfolio.+ if (!signal.account_id.isEmpty()) {+ const auto acct = fincept::trading::AccountManager::instance().get_account(signal.account_id);+ if (!acct.paper_portfolio_id.isEmpty())+ return acct.paper_portfolio_id;+ }++ // 3) Reuse or create a shared "F&O Paper" portfolio (mirrors the F&O Builder).+ if (auto existing = fincept::trading::pt_find_portfolio(QStringLiteral("F&O Paper"),+ QStringLiteral("NFO")))+ return existing->id;+ const auto created = fincept::trading::pt_create_portfolio(+ QStringLiteral("F&O Paper"), 1000000.0, QStringLiteral("INR"),+ 1.0, QStringLiteral("cross"), 0.001, QStringLiteral("NFO"));+ LOG_INFO("AlgoEngine", QString("Created F&O Paper portfolio %1 for basket execution")+ .arg(created.id));+ return created.id;+}++void AlgoEngine::execute_basket(const AlgoOrderSignal& signal) {+ QPointer<AlgoEngine> self = this;+ const QString dep_id = signal.deployment_id;+ const QVector<AlgoOrderLeg> legs = signal.legs;++ // ── Paper: route every leg to the paper portfolio, NEVER the broker ──────────+ // Hard safety gate: a paper deployment carries a real broker account as its+ // data source, but its basket is simulated against pt_place_order. We never+ // call place_basket_orders here (it routes by ACCOUNT mode and could fire real+ // orders on a live data account).+ if (signal.mode != QStringLiteral("live")) {+ const QString portfolio_id = resolve_paper_portfolio_id(signal);+ if (portfolio_id.isEmpty()) {+ LOG_ERROR("AlgoEngine", QString("Deployment %1: PAPER basket: no portfolio").arg(dep_id));+ return;+ }+ QMetaObject::invokeMethod(this, [self, dep_id, legs, portfolio_id]() {+ if (!self) return;+ QMutexLocker lock(&self->mutex_);+ auto* runner = self->runners_.value(dep_id, nullptr);+ if (!runner) return;+ lock.unlock();++ // Place each leg; immediate fill at the leg's reference price. If any+ // leg fails, reverse the already-placed legs (reduce-only) and reject+ // the whole basket so the runner records no position (atomic entry).+ QVector<int> placed_ok;+ bool any_fail = false;+ for (int i = 0; i < legs.size(); ++i) {+ const auto& leg = legs[i];+ bool ok = true;+ try {+ // pt_place_order inserts a pending order; a market order is+ // filled explicitly at the leg's reference price (same as the+ // Equity/F&O paper paths — there is no implicit market fill).+ const auto po = fincept::trading::pt_place_order(+ portfolio_id, leg.symbol, leg.side.toLower(),+ QStringLiteral("market"), leg.quantity, leg.price,+ std::nullopt, false, QStringLiteral("NFO"), QStringLiteral("NRML"));+ fincept::trading::pt_fill_order(po.id, leg.price);+ } catch (const std::exception& e) {+ ok = false;+ any_fail = true;+ LOG_ERROR("AlgoEngine", QString("Deployment %1: PAPER leg %2 (%3) failed: %4")+ .arg(dep_id).arg(i).arg(leg.symbol, QString::fromUtf8(e.what())));+ }+ if (ok) placed_ok.append(i);+ }++ if (!any_fail) {+ for (int i = 0; i < legs.size(); ++i)+ runner->on_leg_filled(i, legs[i], legs[i].price, legs[i].quantity);+ return;+ }++ // Rollback the legs that did fill, then reject every leg.+ for (int i : std::as_const(placed_ok)) {+ const auto& leg = legs[i];+ const QString rev = (leg.side.toLower() == QStringLiteral("buy"))+ ? QStringLiteral("sell") : QStringLiteral("buy");+ try {+ const auto ro = fincept::trading::pt_place_order(+ portfolio_id, leg.symbol, rev, QStringLiteral("market"),+ leg.quantity, leg.price, std::nullopt, true,+ QStringLiteral("NFO"), QStringLiteral("NRML"));+ fincept::trading::pt_fill_order(ro.id, leg.price);+ } catch (const std::exception& e) {+ LOG_ERROR("AlgoEngine", QString("Deployment %1: PAPER rollback leg %2 failed: %3")+ .arg(dep_id).arg(i).arg(QString::fromUtf8(e.what())));+ }+ }+ for (int i = 0; i < legs.size(); ++i)+ runner->on_leg_rejected(i, QStringLiteral("paper basket aborted (partial fill)"));+ }, Qt::QueuedConnection);+ LOG_INFO("AlgoEngine", QString("Deployment %1: PAPER basket %2 legs -> portfolio %3")+ .arg(dep_id).arg(legs.size()).arg(portfolio_id));+ return;+ }++ // ── Live: broker basket (ONLY signal.mode == "live") ─────────────────────────+ const QString account_id = signal.account_id;+ const fincept::trading::BasketOrderRequest basket =+ fincept::algo::fno::build_basket_request(legs, signal.product_type);++ fincept::trading::UnifiedTrading::instance().place_basket_orders(+ account_id, basket,+ [self, dep_id, legs, account_id](const fincept::trading::BasketOrderResult& res) {+ if (!self) return;+ QMetaObject::invokeMethod(self, [self, dep_id, legs, account_id, res]() {+ if (!self) return;+ QMutexLocker lock(&self->mutex_);+ auto* runner = self->runners_.value(dep_id, nullptr);+ if (!runner) return;+ lock.unlock();++ // place_basket_orders reorders (BUY-first) and batches, so map each+ // leg to its result by symbol rather than by index.+ auto leg_succeeded = [&res](const QString& sym) -> bool {+ for (const auto& r : res.results)+ if (r.symbol == sym) return r.success;+ return false;+ };++ QVector<int> filled_idx;+ bool any_fail = false;+ for (int i = 0; i < legs.size(); ++i) {+ if (leg_succeeded(legs[i].symbol)) filled_idx.append(i);+ else any_fail = true;+ }++ if (!any_fail) {+ // Fills carry no price; mark at the leg's reference LTP (P3.5+ // replaces this with live leg-quote marks).+ for (int i = 0; i < legs.size(); ++i)+ runner->on_leg_filled(i, legs[i], legs[i].price, legs[i].quantity);+ return;+ }++ // Rollback: close the legs that filled, then reject the basket so no+ // position is recorded, and surface the error.+ if (!filled_idx.isEmpty()) {+ QVector<AlgoOrderLeg> reverse;+ for (int i : std::as_const(filled_idx)) {+ AlgoOrderLeg rl = legs[i];+ rl.side = (legs[i].side == QLatin1String("BUY"))+ ? QStringLiteral("SELL") : QStringLiteral("BUY");+ reverse.append(rl);+ }+ const auto rb = fincept::algo::fno::build_basket_request(reverse, QString());+ fincept::trading::UnifiedTrading::instance().place_basket_orders(+ account_id, rb, [dep_id](const fincept::trading::BasketOrderResult&) {+ LOG_WARN("AlgoEngine", QString("Deployment %1: entry basket rolled back")+ .arg(dep_id));+ });+ }+ for (int i = 0; i < legs.size(); ++i)+ runner->on_leg_rejected(i, QStringLiteral("live basket aborted (partial fill)"));+ emit self->error_occurred(dep_id, QStringLiteral("F&O entry basket partially failed; rolled back"));+ }, Qt::QueuedConnection);+ });+ LOG_INFO("AlgoEngine", QString("Deployment %1: LIVE basket %2 legs -> account %3")+ .arg(dep_id).arg(legs.size()).arg(account_id));+}+void AlgoEngine::persist_deployment(const services::algo::AlgoDeployment& d) {auto db = fincept::Database::instance().connection();QSqlQuery q(db);@@ -221,8 +406,9 @@ void AlgoEngine::persist_deployment(const services::algo::AlgoDeployment& d) {"INSERT OR REPLACE INTO algo_deployments ""(id, strategy_id, strategy_name, strategy_kind, symbol, exchange, product_type, "" mode, entry_side, backend, broker_id, broker_account_id, paper_portfolio_id, "- " timeframe, quantity, max_order_value, max_daily_loss, status, created_at, updated_at) "- "VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?, datetime('now'), datetime('now'))"));+ " timeframe, quantity, max_order_value, max_daily_loss, "+ " instrument_type, underlying, status, created_at, updated_at) "+ "VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?, datetime('now'), datetime('now'))"));q.addBindValue(d.id);q.addBindValue(d.strategy_id);q.addBindValue(d.strategy_name);@@ -240,6 +426,8 @@ void AlgoEngine::persist_deployment(const services::algo::AlgoDeployment& d) {q.addBindValue(d.quantity);q.addBindValue(d.max_order_value);q.addBindValue(d.max_daily_loss);+ q.addBindValue(d.instrument_type); // F&O: option|future — drives the multi-leg path on resume+ q.addBindValue(d.underlying); // F&O underlying for chain lookup on resumeq.addBindValue(QStringLiteral("starting"));if (!q.exec())LOG_ERROR("AlgoEngine",@@ -270,6 +458,9 @@ void AlgoEngine::list_deployments() {d.backend = q.value("backend").toString();d.broker_id = q.value("broker_id").toString();d.broker_account_id = q.value("broker_account_id").toString();+ d.instrument_type = q.value("instrument_type").toString();+ d.underlying = q.value("underlying").toString();+ d.resolved_expiry = q.value("resolved_expiry").toString();d.status = q.value("status").toString();d.error_message = q.value("error_message").toString();d.timeframe = q.value("timeframe").toString();@@ -339,6 +530,11 @@ void AlgoEngine::recover_orphaned() {d.quantity = q.value("quantity").toDouble();d.max_order_value = q.value("max_order_value").toDouble();d.max_daily_loss = q.value("max_daily_loss").toDouble();+ // F&O: needed so the resumed runner takes the multi-leg path and can+ // reattach its open basket (resolved_legs_json read in restore_state_from_db).+ d.instrument_type = q.value("instrument_type").toString();+ d.underlying = q.value("underlying").toString();+ d.resolved_expiry = q.value("resolved_expiry").toString();to_resume.append(d);}diff --git a/fincept-qt/src/algo_engine/AlgoEngine.h b/fincept-qt/src/algo_engine/AlgoEngine.hindex c830e1c01..4bf6b5de7 100644--- a/fincept-qt/src/algo_engine/AlgoEngine.h+++ b/fincept-qt/src/algo_engine/AlgoEngine.h@@ -2,6 +2,7 @@#pragma once#include "algo_engine/AlgoEngineTypes.h"#include "algo_engine/DeploymentRunner.h"+#include "algo_engine/fno/FnoDataBridge.h"#include "services/algo_trading/AlgoTradingTypes.h"#include <QHash>@@ -40,6 +41,11 @@ public:bool has_active_duplicate(const QString& strategy_id, const QString& symbol,const QString& mode, const QString& entry_side) const;+ // GUI-thread bridge for option-chain data. Created before moveToThread so it+ // stays on the main thread. Accessible to callers that need to check its state+ // from the main thread (e.g. the F&O Algo deploy dialog).+ fincept::algo::fno::FnoDataBridge* fno_bridge() const { return fno_bridge_; }+signals:void deployment_started(const QString& deployment_id);void deployment_stopped(const QString& deployment_id);@@ -60,6 +66,15 @@ private:Q_DISABLE_COPY(AlgoEngine)void execute_order(const AlgoOrderSignal& signal);+ // Multi-leg F&O basket execution (P3.4). Dispatched from execute_order when+ // signal.legs is non-empty. Paper (signal.mode != "live") routes every leg to+ // the deployment's paper portfolio via pt_place_order — NEVER the broker, even+ // on a live account (the safety gate). Live (signal.mode == "live" only) sends+ // a broker basket and rolls back filled legs if any leg fails on entry.+ void execute_basket(const AlgoOrderSignal& signal);+ // Resolve the paper portfolio for a basket: the signal's paper_portfolio_id,+ // else the deployment account's, else a reused/created "F&O Paper" portfolio.+ QString resolve_paper_portfolio_id(const AlgoOrderSignal& signal);// Writes the deployment row to algo_deployments so the Dashboard (which reads// that table) can see it. Without this the runner starts in memory only and// the deploy is invisible to the UI.@@ -71,6 +86,7 @@ private:QThread engine_thread_;mutable QMutex mutex_;QHash<QString, DeploymentRunner*> runners_;+ fincept::algo::fno::FnoDataBridge* fno_bridge_ = nullptr;};} // namespace fincept::algodiff --git a/fincept-qt/src/algo_engine/AlgoEngineTypes.h b/fincept-qt/src/algo_engine/AlgoEngineTypes.hindex 6b35a681e..8e803fd90 100644--- a/fincept-qt/src/algo_engine/AlgoEngineTypes.h+++ b/fincept-qt/src/algo_engine/AlgoEngineTypes.h@@ -116,6 +116,19 @@ struct AlgoPosition {double lowest_since_entry = 0;};+// One leg of an open multi-leg F&O basket position (P3).+struct AlgoLegPosition {+ QString symbol; // broker-native option symbol+ qint64 instrument_token = 0;+ bool is_call = true;+ double strike = 0;+ int side_sign = 1; // +1 long/BUY, -1 short/SELL+ double quantity = 0; // contracts (lots × lot_size)+ double entry_price = 0; // premium per contract at entry+ double current_price = 0; // live mark+ double unrealized_pnl = 0;+};+// ── Risk ────────────────────────────────────────────────────────────────────struct RiskState {@@ -140,6 +153,11 @@ struct AlgoTradeRecord {int64_t timestamp = 0;QString broker_order_id;int64_t latency_ms = 0;+ // Multi-leg F&O basket fills (P3.4): one trade row per leg. leg_symbol is the+ // broker-native contract; leg_index is its position in the basket. Empty/-1 for+ // the single-symbol equity path.+ QString leg_symbol;+ int leg_index = -1;};// ── Metrics ─────────────────────────────────────────────────────────────────@@ -185,6 +203,7 @@ struct AlgoOrderSignal {double trigger_price = 0;QString reason;QString mode = "paper"; // paper | live — paper simulates the fill, live routes to the broker+ QString paper_portfolio_id; // PtPortfolio id for the paper basket path (stamped by the runner)QVector<AlgoOrderLeg> legs; // multi-leg F&O orders; empty = single-symbol equity path};diff --git a/fincept-qt/src/algo_engine/DeploymentRunner.cpp b/fincept-qt/src/algo_engine/DeploymentRunner.cppindex 9a1bc6eff..84bbf58a0 100644--- a/fincept-qt/src/algo_engine/DeploymentRunner.cpp+++ b/fincept-qt/src/algo_engine/DeploymentRunner.cpp@@ -2,8 +2,10 @@#include "algo_engine/DeploymentRunner.h"#include "algo_engine/CandleDataFetcher.h"#include "algo_engine/ConditionEvaluator.h"+#include "algo_engine/fno/FnoExecution.h"#include "core/logging/Logger.h"#include "datahub/DataHub.h"+#include "services/options/OptionChainService.h"#include "storage/sqlite/Database.h"using fincept::Database;@@ -14,7 +16,10 @@ using fincept::Database;#include "trading/DataStreamManager.h"#include "trading/TradingTypes.h"+#include <QDate>#include <QDateTime>+#include <QJsonArray>+#include <QJsonDocument>#include <QPointer>#include <QSqlQuery>#include <QUuid>@@ -148,6 +153,20 @@ void DeploymentRunner::start_market_data() {if (self && self->running_.load() && !self->paused_.load())self->on_tick_data(QVariant::fromValue(q));});++ // F&O basket reattached across a restart: re-establish the chain stream and+ // re-pin the open legs so their LTPs flow for live marking. (On a fresh deploy+ // legs aren't open yet — evaluate_entry does the ensure_chain + pin at entry.)+ if (deployment_.instrument_type != QLatin1String("equity") && fno_bridge_+ && position_mgr_->has_legs()) {+ fno_bridge_->ensure_chain(deployment_.broker_id, deployment_.underlying, resolved_expiry_);+ QStringList syms;+ for (const auto& l : position_mgr_->legs())+ syms << l.symbol;+ fno_bridge_->pin_legs(deployment_.broker_id, deployment_.underlying, resolved_expiry_, syms);+ LOG_INFO("AlgoEngine", QString("Deployment %1: re-pinned %2 reattached F&O legs")+ .arg(deployment_.id).arg(syms.size()));+ }}void DeploymentRunner::stop_market_data() {@@ -187,16 +206,40 @@ void DeploymentRunner::on_tick_data(const QVariant& data) {.arg(deployment_.broker_id));}- position_mgr_->update_price(price);-- auto risk_signal = position_mgr_->check_risk(price);- if (risk_signal) {- risk_signal->account_id = deployment_.broker_account_id;- risk_signal->symbol = deployment_.symbol;- risk_signal->exchange = deployment_.exchange;- risk_signal->product_type = deployment_.product_type;- risk_signal->price = price; // current market price for the simulated/real exit- emit_order_signal(*risk_signal);+ // ── F&O multi-leg basket: mark each leg from the chain snapshot, then run+ // basket risk (SL/TP/trailing). The single-symbol update_price() must be+ // SKIPPED here — it writes the single-position unrealized P&L (0 for a+ // basket) over the basket marks. ───────────────────────────────────────────+ const bool fno_basket = deployment_.instrument_type != QLatin1String("equity")+ && fno_bridge_ && position_mgr_->has_legs();+ if (fno_basket) {+ const auto chain = fno_bridge_->snapshot(deployment_.broker_id,+ deployment_.underlying, resolved_expiry_);+ const auto marks = fincept::algo::fno::leg_marks_from_chain(position_mgr_->legs(), chain);+ for (auto it = marks.constBegin(); it != marks.constEnd(); ++it)+ position_mgr_->update_leg_price(it.key(), it.value());++ auto risk_signal = position_mgr_->check_risk(price); // basket branch ignores price+ if (risk_signal) {+ risk_signal->account_id = deployment_.broker_account_id;+ risk_signal->symbol = deployment_.underlying;+ risk_signal->exchange = deployment_.exchange;+ risk_signal->product_type = deployment_.product_type;+ risk_signal->legs = fincept::algo::fno::build_exit_legs(position_mgr_->legs());+ emit_order_signal(*risk_signal);+ }+ } else {+ position_mgr_->update_price(price);++ auto risk_signal = position_mgr_->check_risk(price);+ if (risk_signal) {+ risk_signal->account_id = deployment_.broker_account_id;+ risk_signal->symbol = deployment_.symbol;+ risk_signal->exchange = deployment_.exchange;+ risk_signal->product_type = deployment_.product_type;+ risk_signal->price = price; // current market price for the simulated/real exit+ emit_order_signal(*risk_signal);+ }}aggregator_->on_tick(price, volume, timestamp);@@ -238,12 +281,16 @@ void DeploymentRunner::evaluate_live(double price) {auto candles = live_eval_window(price);if (candles.size() < 2)return;- if (position_mgr_->has_position())+ if (in_position())evaluate_exit(candles);elseevaluate_entry(candles);}+bool DeploymentRunner::in_position() const {+ return position_mgr_->has_position() || position_mgr_->has_legs();+}+namespace {QString pretty_op(const QString& op) {if (op == "crosses_above") return QStringLiteral("crosses above");@@ -306,7 +353,7 @@ void DeploymentRunner::on_candle_closed(const OhlcvCandle& /*candle*/) {auto candles = aggregator_->closed_candles();if (candles.size() < 20) return;- if (position_mgr_->has_position()) {+ if (in_position()) {evaluate_exit(candles);} else {evaluate_entry(candles);@@ -326,15 +373,64 @@ void DeploymentRunner::evaluate_entry(const QVector<OhlcvCandle>& candles) {AlgoOrderSignal signal;signal.deployment_id = deployment_.id;signal.account_id = deployment_.broker_account_id;- signal.symbol = deployment_.symbol;signal.exchange = deployment_.exchange;signal.product_type = deployment_.product_type;- signal.side = deployment_.entry_side;- signal.quantity = deployment_.quantity;signal.order_type = "MARKET";signal.price = candles.last().close; // fill reference for paper sim / P&Lsignal.reason = "entry_signal";+ // ── F&O multi-leg branch ────────────────────────────────────────────────+ // Resolve expiry rule + chain snapshot + leg contracts, then emit a multi-+ // leg order basket. The equity single-symbol path below is left untouched.+ if (deployment_.instrument_type != QLatin1String("equity") && fno_bridge_) {+ // Determine expiry rule from the first leg rule (single-expiry v1).+ QString exp_mode = QStringLiteral("WEEKLY");+ QString exp_val;+ {+ const auto rules = fincept::algo::fno::fno_legs_from_json(strategy_.legs);+ if (!rules.isEmpty()) {+ exp_mode = rules.first().expiry_mode;+ exp_val = rules.first().expiry_value;+ }+ }++ const QString expiry = fincept::algo::fno::resolve_expiry(+ exp_mode, exp_val,+ fincept::services::options::OptionChainService::instance().list_expiries(+ deployment_.broker_id, deployment_.underlying),+ QDate::currentDate());+ resolved_expiry_ = expiry; // keep for live leg marks + restart reattach++ fno_bridge_->ensure_chain(deployment_.broker_id, deployment_.underlying, expiry);+ const auto chain = fno_bridge_->snapshot(deployment_.broker_id,+ deployment_.underlying, expiry);+ auto legs = fincept::algo::fno::resolve_entry_legs(chain, strategy_.legs);++ if (legs.isEmpty()) {+ LOG_WARN("AlgoEngine",+ QString("Deployment %1: F&O entry: no resolvable legs (chain not ready?)")+ .arg(deployment_.id));+ return;+ }++ // Pin the resolved leg symbols into the live WS subscription window so+ // they stay fresh for mark-to-market during the life of the position.+ QStringList syms;+ for (const auto& l : legs)+ syms << l.symbol;+ fno_bridge_->pin_legs(deployment_.broker_id, deployment_.underlying, expiry, syms);++ signal.symbol = deployment_.underlying; // underlying for bookkeeping+ signal.legs = legs;+ emit_order_signal(signal);+ return; // skip the equity single-symbol path below+ }+ // ── Equity single-symbol path (unchanged) ───────────────────────────────++ signal.symbol = deployment_.symbol;+ signal.side = deployment_.entry_side;+ signal.quantity = deployment_.quantity;+if (!position_mgr_->validate_order_value(signal.quantity, candles.last().close)) {LOG_WARN("AlgoEngine", QString("Deployment %1: order value exceeds limit, skipping entry").arg(deployment_.id));@@ -350,19 +446,31 @@ void DeploymentRunner::evaluate_exit(const QVector<OhlcvCandle>& candles) {if (!result.triggered) return;- auto pos = position_mgr_->position();AlgoOrderSignal signal;signal.deployment_id = deployment_.id;signal.account_id = deployment_.broker_account_id;- signal.symbol = deployment_.symbol;signal.exchange = deployment_.exchange;signal.product_type = deployment_.product_type;- signal.side = (pos.side == PositionSide::Long) ? "SELL" : "BUY";- signal.quantity = pos.quantity;signal.order_type = "MARKET";- signal.price = candles.last().close; // fill reference for paper sim / P&L+ signal.price = candles.last().close;signal.reason = "exit_signal";+ // ── F&O multi-leg exit branch ───────────────────────────────────────────+ if (deployment_.instrument_type != QLatin1String("equity")+ && fno_bridge_+ && position_mgr_->has_legs()) {+ signal.symbol = deployment_.underlying;+ signal.legs = fincept::algo::fno::build_exit_legs(position_mgr_->legs());+ emit_order_signal(signal);+ return; // skip the equity single-symbol exit path below+ }+ // ── Equity single-symbol exit path (unchanged) ──────────────────────────++ auto pos = position_mgr_->position();+ signal.symbol = deployment_.symbol;+ signal.side = (pos.side == PositionSide::Long) ? "SELL" : "BUY";+ signal.quantity = pos.quantity;+emit_order_signal(signal);}@@ -379,6 +487,7 @@ void DeploymentRunner::emit_order_signal(const AlgoOrderSignal& signal_in) {// (the account is its data source).AlgoOrderSignal signal = signal_in;signal.mode = deployment_.mode;+ signal.paper_portfolio_id = deployment_.paper_portfolio_id; // paper basket targetif (signal.price <= 0)signal.price = position_mgr_->metrics().current_price;@@ -451,6 +560,114 @@ void DeploymentRunner::on_order_rejected(const QString& /*broker_order_id*/,.arg(deployment_.id, reason));}+// ── Multi-leg F&O basket fills (P3.4) ───────────────────────────────────────+// One call per leg from AlgoEngine::execute_basket. Fills accumulate in+// basket_fills_ / basket_rejected_ until the whole in-flight basket is+// accounted for, then finalize_basket_if_complete() records or abandons it.++void DeploymentRunner::on_leg_filled(int leg_index, const AlgoOrderLeg& leg,+ double fill_price, double fill_qty) {+ if (pending_orders_.isEmpty())+ return;+ const PendingOrder& pending = pending_orders_.first();+ const bool is_entry = (pending.signal.reason == "entry_signal");+ const int64_t now = QDateTime::currentMSecsSinceEpoch();++ if (is_entry) {+ // Record the fill as an open leg position; P&L marks come from leg quotes.+ AlgoLegPosition lp;+ lp.symbol = leg.symbol;+ lp.instrument_token = leg.instrument_token;+ lp.side_sign = (leg.side == QLatin1String("BUY")) ? 1 : -1;+ lp.quantity = fill_qty;+ lp.entry_price = fill_price;+ lp.current_price = fill_price;+ lp.unrealized_pnl = 0;+ basket_fills_.append(lp);+ } else {+ // Exit fill: mark the matching open leg at the exit price so the realized+ // basket P&L (computed in record_exit_legs from the open legs' marks)+ // reflects the exit fills. Count it for completion via basket_fills_.+ position_mgr_->update_leg_price(leg.symbol, fill_price);+ AlgoLegPosition lp;+ lp.symbol = leg.symbol;+ lp.quantity = fill_qty;+ basket_fills_.append(lp);+ }++ // Persist one trade row per leg (symbol = underlying for grouping; leg_symbol+ // = the concrete contract; pnl is attached to the basket at finalize).+ AlgoTradeRecord trade;+ trade.id = QUuid::createUuid().toString(QUuid::WithoutBraces);+ trade.deployment_id = deployment_.id;+ trade.symbol = deployment_.underlying.isEmpty() ? deployment_.symbol+ : deployment_.underlying;+ trade.side = leg.side;+ trade.quantity = fill_qty;+ trade.price = fill_price;+ trade.pnl = 0;+ trade.reason = pending.signal.reason;+ trade.timestamp = now;+ trade.broker_order_id = QString();+ trade.latency_ms = now - pending.submitted_ms;+ trade.leg_symbol = leg.symbol;+ trade.leg_index = leg_index;+ persist_trade(trade);+ emit trade_executed(trade);++ finalize_basket_if_complete();+}++void DeploymentRunner::on_leg_rejected(int leg_index, const QString& reason) {+ basket_rejected_++;+ LOG_ERROR("AlgoEngine", QString("Deployment %1: basket leg %2 rejected: %3")+ .arg(deployment_.id).arg(leg_index).arg(reason));+ finalize_basket_if_complete();+}++void DeploymentRunner::finalize_basket_if_complete() {+ if (pending_orders_.isEmpty())+ return;+ const PendingOrder& pending = pending_orders_.first();+ const int expected = pending.signal.legs.size();+ if (expected <= 0)+ return;+ if (basket_fills_.size() + basket_rejected_ < expected)+ return; // still waiting on legs++ const bool is_entry = (pending.signal.reason == "entry_signal");+ const int64_t now = QDateTime::currentMSecsSinceEpoch();+ pending_orders_.removeFirst(); // release the in-flight guard++ double pnl = 0;+ if (is_entry) {+ if (basket_rejected_ == 0 && !basket_fills_.isEmpty()) {+ position_mgr_->record_entry_legs(basket_fills_, now);+ persist_resolved_legs(); // so a restart reattaches to the open basket+ emit_live_snapshot(0, QStringLiteral("ENTRY basket filled (%1 legs)")+ .arg(basket_fills_.size()));+ } else {+ // Partial entry: the engine has rolled back the filled legs at the+ // broker; record no position so we stay flat.+ LOG_WARN("AlgoEngine",+ QString("Deployment %1: entry basket aborted (%2 filled, %3 rejected) — no position recorded")+ .arg(deployment_.id).arg(basket_fills_.size()).arg(basket_rejected_));+ emit_live_snapshot(0, QStringLiteral("ENTRY basket aborted — rolled back"));+ }+ } else {+ // Exit: open legs were marked at their exit fills in on_leg_filled.+ pnl = position_mgr_->record_exit_legs(now);+ clear_resolved_legs(); // basket closed — nothing to reattach on restart+ resolved_expiry_.clear();+ emit_live_snapshot(0, QStringLiteral("EXIT basket closed, P&L %1")+ .arg(pnl, 0, 'f', 2));+ }++ basket_fills_.clear();+ basket_rejected_ = 0;+ emit metrics_updated(deployment_.id, position_mgr_->metrics());+}+void DeploymentRunner::on_heartbeat() {if (!running_.load()) return;int64_t now = QDateTime::currentMSecsSinceEpoch();@@ -497,8 +714,8 @@ void DeploymentRunner::persist_trade(const AlgoTradeRecord& trade) {QSqlQuery q(db);q.prepare(QStringLiteral("INSERT INTO algo_trades (id, deployment_id, symbol, side, quantity, price, pnl, "- "reason, broker_order_id, latency_ms, created_at) "- "VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, datetime('now'))"));+ "reason, broker_order_id, latency_ms, leg_symbol, leg_index, created_at) "+ "VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, datetime('now'))"));q.addBindValue(trade.id);q.addBindValue(trade.deployment_id);q.addBindValue(trade.symbol);@@ -509,6 +726,8 @@ void DeploymentRunner::persist_trade(const AlgoTradeRecord& trade) {q.addBindValue(trade.reason);q.addBindValue(trade.broker_order_id);q.addBindValue(QVariant::fromValue(trade.latency_ms));+ q.addBindValue(trade.leg_symbol);+ q.addBindValue(trade.leg_index);if (!q.exec())LOG_ERROR("AlgoEngine", QString("Failed to persist trade: %1").arg(q.lastError().text()));}@@ -536,8 +755,61 @@ void DeploymentRunner::persist_metrics() {LOG_ERROR("AlgoEngine", QString("Failed to persist metrics: %1").arg(q.lastError().text()));}+void DeploymentRunner::persist_resolved_legs() {+ const QJsonArray arr = fincept::algo::fno::leg_positions_to_json(position_mgr_->legs());+ const QString json = QString::fromUtf8(QJsonDocument(arr).toJson(QJsonDocument::Compact));+ auto db = Database::instance().connection();+ QSqlQuery q(db);+ q.prepare(QStringLiteral(+ "UPDATE algo_deployments SET resolved_legs_json = ?, resolved_expiry = ?, "+ "underlying = ?, instrument_type = ?, updated_at = datetime('now') WHERE id = ?"));+ q.addBindValue(json);+ q.addBindValue(resolved_expiry_);+ q.addBindValue(deployment_.underlying);+ q.addBindValue(deployment_.instrument_type);+ q.addBindValue(deployment_.id);+ if (!q.exec())+ LOG_ERROR("AlgoEngine", QString("Failed to persist resolved legs: %1").arg(q.lastError().text()));+}++void DeploymentRunner::clear_resolved_legs() {+ auto db = Database::instance().connection();+ QSqlQuery q(db);+ q.prepare(QStringLiteral(+ "UPDATE algo_deployments SET resolved_legs_json = '[]', resolved_expiry = '', "+ "updated_at = datetime('now') WHERE id = ?"));+ q.addBindValue(deployment_.id);+ q.exec();+}+void DeploymentRunner::restore_state_from_db() {auto db = Database::instance().connection();++ // ── F&O: reattach an open multi-leg basket persisted before the restart ──────+ // Done first (and independently of algo_metrics) so a basket-open deployment+ // resumes its legs even if the metrics row is missing. Marks refresh on the+ // next tick; metrics (total_pnl etc.) are restored from algo_metrics below.+ if (deployment_.instrument_type != QLatin1String("equity")) {+ QSqlQuery lq(db);+ lq.prepare(QStringLiteral(+ "SELECT resolved_legs_json, resolved_expiry FROM algo_deployments WHERE id = ?"));+ lq.addBindValue(deployment_.id);+ if (lq.exec() && lq.next()) {+ const QString legs_json = lq.value("resolved_legs_json").toString();+ const auto doc = QJsonDocument::fromJson(legs_json.toUtf8());+ if (doc.isArray()) {+ const auto restored = fincept::algo::fno::leg_positions_from_json(doc.array());+ if (!restored.isEmpty()) {+ resolved_expiry_ = lq.value("resolved_expiry").toString();+ position_mgr_->record_entry_legs(restored, QDateTime::currentMSecsSinceEpoch());+ LOG_INFO("AlgoEngine",+ QString("Deployment %1: reattached open F&O basket (%2 legs, expiry %3) across restart")+ .arg(deployment_.id).arg(restored.size()).arg(resolved_expiry_));+ }+ }+ }+ }+QSqlQuery q(db);q.prepare(QStringLiteral("SELECT total_pnl, total_trades, win_rate, max_drawdown, current_position_qty, "diff --git a/fincept-qt/src/algo_engine/DeploymentRunner.h b/fincept-qt/src/algo_engine/DeploymentRunner.hindex 2801829c3..5230afdf8 100644--- a/fincept-qt/src/algo_engine/DeploymentRunner.h+++ b/fincept-qt/src/algo_engine/DeploymentRunner.h@@ -3,6 +3,7 @@#include "algo_engine/AlgoEngineTypes.h"#include "algo_engine/CandleAggregator.h"#include "algo_engine/PositionManager.h"+#include "algo_engine/fno/FnoDataBridge.h"#include "services/algo_trading/AlgoTradingTypes.h"#include <QObject>@@ -29,6 +30,11 @@ public:bool is_paused() const { return paused_.load(); }QString deployment_id() const { return deployment_.id; }+ // Set the GUI-thread FnoDataBridge so F&O runners can request chain snapshots+ // and pin their legs. Called from AlgoEngine::start_deployment on the calling+ // thread before the runner is moved to the engine thread. Consumption is P3.3.+ void set_fno_bridge(fincept::algo::fno::FnoDataBridge* bridge) { fno_bridge_ = bridge; }+AlgoMetrics metrics() const;AlgoPosition position() const;@@ -44,6 +50,14 @@ signals:public slots:void on_order_filled(const QString& broker_order_id, double fill_price, double fill_qty);void on_order_rejected(const QString& broker_order_id, const QString& reason);+ // Multi-leg F&O basket fills (P3.4). One call per leg from AlgoEngine::execute_basket.+ // Fills accumulate; once every leg of the in-flight basket is accounted for, an+ // entry records the basket position (record_entry_legs) and an exit realizes it+ // (record_exit_legs). If any leg was rejected on entry the basket is abandoned+ // (the engine has already rolled back the filled legs at the broker).+ void on_leg_filled(int leg_index, const fincept::algo::AlgoOrderLeg& leg,+ double fill_price, double fill_qty);+ void on_leg_rejected(int leg_index, const QString& reason);private slots:void on_candle_closed(const fincept::algo::OhlcvCandle& candle);@@ -71,6 +85,15 @@ private:void emit_order_signal(const AlgoOrderSignal& signal);void persist_trade(const AlgoTradeRecord& trade);void persist_metrics();+ // True when the runner holds an open position of EITHER kind — a single-symbol+ // equity position or a multi-leg F&O basket. Entry/exit routing must treat a+ // basket as "in position" or it would keep re-entering (has_position() alone+ // only sees the single-symbol path).+ bool in_position() const;+ // Persist / clear the open F&O basket on the algo_deployments row so a+ // restarted runner reattaches to it (resolved_legs_json + resolved_expiry).+ void persist_resolved_legs();+ void clear_resolved_legs();// Re-seed position + metrics from algo_metrics so a resumed deployment continues// its open position across restarts (no-op for a fresh deploy — no row yet).void restore_state_from_db();@@ -79,6 +102,8 @@ private:fincept::services::algo::AlgoDeployment deployment_;fincept::services::algo::AlgoStrategy strategy_;Timeframe timeframe_;+ fincept::algo::fno::FnoDataBridge* fno_bridge_ = nullptr; // not owned; lives on main thread+ QString resolved_expiry_; // F&O: expiry chosen at entry; used to key the chain snapshot for leg marksstd::unique_ptr<CandleAggregator> aggregator_;std::unique_ptr<PositionManager> position_mgr_;@@ -92,12 +117,22 @@ private:int64_t last_emit_ms_ = 0; // throttle for live_update emissiondouble last_tick_price_ = 0; // previous tick price → tick-to-tick crossovers+ // Finalize the in-flight multi-leg basket once every leg has reported a+ // fill or rejection (called from on_leg_filled / on_leg_rejected).+ void finalize_basket_if_complete();+struct PendingOrder {QString broker_order_id;AlgoOrderSignal signal;int64_t submitted_ms = 0;};QVector<PendingOrder> pending_orders_;++ // In-flight multi-leg basket accumulator (only one order is in flight at a+ // time — see the guard in emit_order_signal). Entry fills become open leg+ // positions; rejections are counted so a partial entry records nothing.+ QVector<AlgoLegPosition> basket_fills_;+ int basket_rejected_ = 0;};} // namespace fincept::algodiff --git a/fincept-qt/src/algo_engine/PositionManager.cpp b/fincept-qt/src/algo_engine/PositionManager.cppindex 751ac8fef..d2502fc66 100644--- a/fincept-qt/src/algo_engine/PositionManager.cpp+++ b/fincept-qt/src/algo_engine/PositionManager.cpp@@ -25,6 +25,63 @@ PositionManager::PositionManager(const QString& deployment_id,std::optional<AlgoOrderSignal> PositionManager::check_risk(double current_price) {QMutexLocker lock(&mutex_);+ // ── Multi-leg basket branch (P3) ────────────────────────────────────────+ // Entered ONLY when legs are active. Single-position logic below is UNCHANGED.+ if (multi_leg_) {+ if (legs_.isEmpty())+ return std::nullopt;++ // Compute current basket P&L from cached unrealized_pnl on each leg.+ double basket_pnl = 0;+ for (const auto& leg : std::as_const(legs_))+ basket_pnl += leg.unrealized_pnl;++ double basket_pnl_pct = basket_entry_value_ > 1e-10+ ? basket_pnl / basket_entry_value_ * 100.0 : 0;++ // Daily loss limit+ if (max_daily_loss_ > 0 && risk_.daily_pnl <= -std::abs(max_daily_loss_)) {+ risk_.paused_by_loss_limit = true;+ AlgoOrderSignal sig;+ sig.deployment_id = deployment_id_;+ sig.reason = "daily_loss_limit";+ return sig;+ }++ // Stop loss+ if (stop_loss_pct_ > 0 && basket_pnl_pct <= -std::abs(stop_loss_pct_)) {+ AlgoOrderSignal sig;+ sig.deployment_id = deployment_id_;+ sig.reason = "stop_loss";+ return sig;+ }++ // Take profit+ if (take_profit_pct_ > 0 && basket_pnl_pct >= std::abs(take_profit_pct_)) {+ AlgoOrderSignal sig;+ sig.deployment_id = deployment_id_;+ sig.reason = "take_profit";+ return sig;+ }++ // Trailing stop — track peak basket P&L+ if (trailing_stop_pct_ > 0) {+ if (basket_pnl > basket_peak_pnl_)+ basket_peak_pnl_ = basket_pnl;+ double peak_pct = basket_entry_value_ > 1e-10+ ? basket_peak_pnl_ / basket_entry_value_ * 100.0 : 0;+ if (peak_pct - basket_pnl_pct >= trailing_stop_pct_) {+ AlgoOrderSignal sig;+ sig.deployment_id = deployment_id_;+ sig.reason = "trailing_stop";+ return sig;+ }+ }++ return std::nullopt;+ }+ // ── End multi-leg branch ────────────────────────────────────────────────+if (position_.side == PositionSide::None)return std::nullopt;@@ -99,6 +156,7 @@ std::optional<AlgoOrderSignal> PositionManager::check_risk(double current_price)void PositionManager::record_entry(PositionSide side, double qty, double price, int64_t time_ms) {QMutexLocker lock(&mutex_);+ Q_ASSERT(!multi_leg_); // invariant: single-leg path must not be called while a basket is activeposition_.side = side;position_.quantity = qty;position_.entry_price = price;@@ -221,4 +279,86 @@ void PositionManager::reset_daily() {risk_.day_start_epoch = QDateTime::currentMSecsSinceEpoch();}+// ── Multi-leg basket methods (P3) ───────────────────────────────────────────++void PositionManager::record_entry_legs(const QVector<fincept::algo::AlgoLegPosition>& legs,+ int64_t time_ms) {+ QMutexLocker lock(&mutex_);+ Q_ASSERT(position_.side == PositionSide::None); // invariant: multi-leg path must not be called while a single-leg position is open+ legs_ = legs;+ multi_leg_ = true;+ basket_peak_pnl_ = 0;++ // Compute entry value: Σ |entry_price * quantity| (unsigned, used as denominator)+ basket_entry_value_ = 0;+ double total_qty = 0;+ for (const auto& leg : std::as_const(legs_)) {+ basket_entry_value_ += std::abs(leg.entry_price * leg.quantity);+ total_qty += leg.quantity;+ }++ metrics_.current_position_side = QStringLiteral("BASKET");+ metrics_.current_position_qty = total_qty;+ metrics_.last_trade_time = time_ms;+}++double PositionManager::record_exit_legs(int64_t time_ms) {+ QMutexLocker lock(&mutex_);+ double pnl = 0;+ for (const auto& leg : std::as_const(legs_))+ pnl += leg.unrealized_pnl;++ metrics_.total_pnl += pnl;+ metrics_.total_trades++;+ if (pnl > 0) metrics_.winning_trades++;+ else if (pnl < 0) metrics_.losing_trades++;+ metrics_.win_rate = metrics_.total_trades > 0+ ? static_cast<double>(metrics_.winning_trades) / metrics_.total_trades * 100.0 : 0;+ metrics_.last_trade_time = time_ms;+ metrics_.unrealized_pnl = 0;++ risk_.daily_pnl += pnl;+ update_drawdown();++ legs_.clear();+ multi_leg_ = false;+ basket_entry_value_ = 0;+ basket_peak_pnl_ = 0;++ metrics_.current_position_side = QString();+ metrics_.current_position_qty = 0;++ return pnl;+}++void PositionManager::update_leg_price(const QString& symbol, double ltp) {+ QMutexLocker lock(&mutex_);+ bool found = false;+ for (auto& leg : legs_) {+ if (leg.symbol == symbol) {+ leg.current_price = ltp;+ leg.unrealized_pnl = (ltp - leg.entry_price) * leg.quantity * leg.side_sign;+ found = true;+ break;+ }+ }+ if (!found)+ qWarning() << "PositionManager::update_leg_price: symbol not in basket:" << symbol;+ // Recompute basket unrealized P&L+ double basket_pnl = 0;+ for (const auto& leg : std::as_const(legs_))+ basket_pnl += leg.unrealized_pnl;+ metrics_.unrealized_pnl = basket_pnl;+}++bool PositionManager::has_legs() const {+ QMutexLocker lock(&mutex_);+ return multi_leg_ && !legs_.isEmpty();+}++QVector<fincept::algo::AlgoLegPosition> PositionManager::legs() const {+ QMutexLocker lock(&mutex_);+ return legs_;+}+} // namespace fincept::algodiff --git a/fincept-qt/src/algo_engine/PositionManager.h b/fincept-qt/src/algo_engine/PositionManager.hindex 676007dca..8adcb9c6b 100644--- a/fincept-qt/src/algo_engine/PositionManager.h+++ b/fincept-qt/src/algo_engine/PositionManager.h@@ -35,6 +35,13 @@ public:void update_price(double price);void reset_daily();+ // Multi-leg (F&O basket) mode — parallel to the single-position equity path.+ void record_entry_legs(const QVector<fincept::algo::AlgoLegPosition>& legs, int64_t time_ms);+ double record_exit_legs(int64_t time_ms); // realizes basket P&L, clears legs+ void update_leg_price(const QString& symbol, double ltp); // marks one leg, recomputes basket unrealized+ bool has_legs() const; // multi_leg_ && !legs_.isEmpty()+ QVector<fincept::algo::AlgoLegPosition> legs() const; // mutex copy+private:void update_drawdown();@@ -49,6 +56,12 @@ private:double max_order_value_;double max_daily_loss_;+ // Multi-leg basket state (P3)+ QVector<fincept::algo::AlgoLegPosition> legs_;+ bool multi_leg_ = false;+ double basket_entry_value_ = 0; // Σ |entry_price * quantity| at entry+ double basket_peak_pnl_ = 0; // trailing-stop high-water mark (basket P&L)+mutable QMutex mutex_;};diff --git a/fincept-qt/src/algo_engine/fno/FnoAlgoSelftest.cpp b/fincept-qt/src/algo_engine/fno/FnoAlgoSelftest.cppindex 1de17ebc7..1727aaca5 100644--- a/fincept-qt/src/algo_engine/fno/FnoAlgoSelftest.cpp+++ b/fincept-qt/src/algo_engine/fno/FnoAlgoSelftest.cpp@@ -1,10 +1,19 @@#include "algo_engine/fno/FnoAlgoSelftest.h"#include "algo_engine/fno/FnoAlgoTypes.h"+#include "algo_engine/fno/FnoDataBridge.h"+#include "algo_engine/fno/FnoExecution.h"+#include "ui/widgets/algo/FnoLegRuleEditor.h"#include "algo_engine/fno/FnoLegResolver.h"+#include "algo_engine/fno/FnoStrategyPreview.h"+#include "algo_engine/PositionManager.h"+#include "algo_engine/AlgoEngineTypes.h"+#include "trading/instruments/InstrumentTypes.h"#include "services/algo_trading/AlgoTradingService.h"#include "services/algo_trading/AlgoTradingTypes.h"+#include "services/options/OptionChainService.h"#include "storage/sqlite/Database.h"+#include "trading/PaperTrading.h"#include <QJsonDocument>#include <QtGlobal>@@ -125,6 +134,11 @@ fincept::services::options::OptionChain make_synthetic_chain() {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.lot_size = 50;+ r.ce_quote.ltp = 100.0 + i;+ r.pe_quote.ltp = 90.0 + i;+ r.ce_iv = 0.15;+ r.pe_iv = 0.16;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@@ -174,6 +188,416 @@ void test_leg_resolver() {check(!missing.valid, "missing contract (token 0) -> invalid");}+void test_preview_bridge() {+ std::fprintf(stdout, "[5] preview strategy bridge\n");+ const auto chain = make_synthetic_chain();+ QVector<AlgoFnoLeg> legs;+ AlgoFnoLeg ce; ce.kind = "CE"; ce.side = "BUY"; ce.lots = 1; ce.strike_mode = "ATM";+ AlgoFnoLeg pe; pe.kind = "PE"; pe.side = "SELL"; pe.lots = 2; pe.strike_mode = "ABSOLUTE"; pe.strike_value = 23000;+ AlgoFnoLeg fut; fut.kind = "FUT"; // unresolved -> skipped+ legs << ce << pe << fut;++ const auto s = build_preview_strategy(legs, chain);+ check(s.legs.size() == 2, "two resolvable legs converted (FUT skipped)");+ if (s.legs.size() == 2) {+ check(qFuzzyCompare(s.legs[0].strike, 23200.0) && s.legs[0].lots == 1 &&+ s.legs[0].lot_size == 50 && s.legs[0].type == fincept::trading::InstrumentType::CE &&+ qFuzzyCompare(s.legs[0].entry_price, 104.0) && qFuzzyCompare(s.legs[0].iv_at_entry, 0.15),+ "CE ATM BUY leg correct (entry/iv from row)");+ check(qFuzzyCompare(s.legs[1].strike, 23000.0) && s.legs[1].lots == -2 &&+ s.legs[1].type == fincept::trading::InstrumentType::PE &&+ qFuzzyCompare(s.legs[1].entry_price, 92.0) && qFuzzyCompare(s.legs[1].iv_at_entry, 0.16),+ "PE ABSOLUTE SELL leg has signed lots -2 (entry/iv from row)");+ }+}++void test_leg_rule_editor() {+ std::fprintf(stdout, "[6] FnoLegRuleEditor model\n");+ fincept::ui::algo::FnoLegRuleEditor editor;+ QVector<AlgoFnoLeg> in;+ AlgoFnoLeg a; a.kind = "CE"; a.side = "BUY"; a.lots = 1; a.strike_mode = "ATM";+ AlgoFnoLeg b; b.kind = "PE"; b.side = "SELL"; b.lots = 2; b.strike_mode = "ABSOLUTE"; b.strike_value = 23000;+ in << a << b;+ editor.set_legs(in);+ const auto out = editor.legs();+ check(out.size() == 2, "set_legs/legs preserves count");+ if (out.size() == 2) {+ check(out[0].kind == "CE" && out[0].side == "BUY" && out[0].lots == 1 &&+ out[0].strike_mode == "ATM",+ "leg 0 round-trips");+ check(out[1].kind == "PE" && out[1].side == "SELL" && out[1].lots == 2 &&+ out[1].strike_mode == "ABSOLUTE" && qFuzzyCompare(out[1].strike_value, 23000.0),+ "leg 1 round-trips");+ }+}++void test_fno_data_bridge() {+ std::fprintf(stdout, "[7a] FnoDataBridge snapshot + pinning\n");+ fincept::algo::fno::FnoDataBridge bridge;+ auto chain = make_synthetic_chain(); // broker "fyers", underlying "NIFTY", expiry "26-JUN-25"+ bridge.ingest_chain(chain);+ const auto snap = bridge.snapshot("fyers", "NIFTY", "26-JUN-25");+ check(snap.rows.size() == chain.rows.size() && snap.underlying == "NIFTY",+ "bridge caches + returns chain snapshot copy");++ using fincept::services::options::OptionChainService;+ const QString topic = OptionChainService::instance().chain_topic("fyers", "NIFTY", "26-JUN-25");+ OptionChainService::instance().pin_contracts(topic, {"NIFTY26JUN25C23000", "NIFTY26JUN25P23000"});+ const auto pins = OptionChainService::instance().pinned_contracts_for(topic);+ check(pins.contains("NIFTY26JUN25C23000") && pins.contains("NIFTY26JUN25P23000"),+ "pin_contracts stores pinned symbols for the topic");+ OptionChainService::instance().pin_contracts(topic, {}); // cleanup+}++void test_position_manager_multileg() {+ using fincept::algo::PositionManager;+ using fincept::algo::AlgoLegPosition;+ std::fprintf(stdout, "[7b] PositionManager multi-leg basket\n");++ // Construct: sl=30%, tp=50%, trail=0, maxOrderVal=0, maxDailyLoss=0+ PositionManager pm("test", 30.0, 50.0, 0.0, 0.0, 0.0);++ // Build a long straddle: CE long, PE long, each qty=50 entry=100+ QVector<AlgoLegPosition> legs;+ AlgoLegPosition ce;+ ce.symbol = "CE_SYM";+ ce.is_call = true;+ ce.side_sign = 1; // long+ ce.quantity = 50;+ ce.entry_price = 100.0;+ ce.current_price = 100.0;++ AlgoLegPosition pe;+ pe.symbol = "PE_SYM";+ pe.is_call = false;+ pe.side_sign = 1; // long+ pe.quantity = 50;+ pe.entry_price = 100.0;+ pe.current_price = 100.0;++ legs << ce << pe;+ pm.record_entry_legs(legs, 0);++ check(pm.has_legs(), "has_legs() true after record_entry_legs");++ // CE +30, PE -10 → basket unrealized = (30*50) + (-10*50) = 1500 - 500 = 1000+ pm.update_leg_price("CE_SYM", 130.0);+ pm.update_leg_price("PE_SYM", 90.0);++ const double unrealized = pm.metrics().unrealized_pnl;+ check(std::abs(unrealized - 1000.0) < 1e-6, "basket unrealized_pnl == 1000");++ // check_risk at this point: basket_pnl=1000, entry_value=|100*50|+|100*50|=10000+ // basket_pnl_pct = 1000/10000*100 = 10% → no trigger+ {+ auto sig = pm.check_risk(0);+ check(!sig.has_value(), "no risk trigger at +10% basket P&L");+ }++ // Drive a stop: set both legs to loss so basket_pnl_pct <= -30%+ // Need basket_pnl <= -30% of 10000 = -3000+ // CE: (50-100)*50 = -2500, PE: (50-100)*50 = -2500 → total = -5000 (-50%) → triggers SL+ pm.update_leg_price("CE_SYM", 50.0);+ pm.update_leg_price("PE_SYM", 50.0);++ {+ auto sig = pm.check_risk(0);+ check(sig.has_value() && sig->reason == "stop_loss",+ "stop_loss fires when basket P&L <= -30%");+ }++ // record_exit_legs returns realized P&L and clears legs.+ // Expected basket P&L: CE (50-100)*50*1 + PE (50-100)*50*1 = -2500 + -2500 = -5000+ const double expected_realized = -5000.0;+ const double realized = pm.record_exit_legs(1000);+ check(std::abs(realized - expected_realized) < 1e-6, "record_exit_legs returns correct realized P&L (-5000)");++ // Multi-leg state must be fully cleared after exit+ check(!pm.has_legs(), "has_legs() false after record_exit_legs");+ check(pm.legs().isEmpty(), "legs() returns empty vector after record_exit_legs");+ check(pm.metrics().unrealized_pnl == 0.0, "unrealized_pnl reset to 0 after record_exit_legs");+ check(pm.metrics().total_trades == 1, "total_trades incremented");+ check(std::abs(pm.metrics().total_pnl - expected_realized) < 1e-6,+ "metrics total_pnl reflects basket realized P&L");++ // Verify single-position equity path is unaffected (it was never touched by multi-leg ops)+ check(!pm.has_position(), "single-position path untouched: no position after multi-leg exit");+}++void test_fno_execution() {+ using fincept::algo::fno::resolve_expiry;+ using fincept::algo::fno::resolve_entry_legs;+ using fincept::algo::fno::build_exit_legs;+ using fincept::algo::AlgoLegPosition;++ std::fprintf(stdout, "[7c] FnoExecution helpers\n");++ // ── resolve_expiry ────────────────────────────────────────────────────────+ // Fixed available expiries and today = 2025-06-01.+ // "26-JUN-25" → DTE 25+ // "03-JUL-25" → DTE 32+ // "31-JUL-25" → DTE 60+ // "28-AUG-25" → DTE 88+ const QStringList expiries{+ QStringLiteral("26-JUN-25"),+ QStringLiteral("03-JUL-25"),+ QStringLiteral("31-JUL-25"),+ QStringLiteral("28-AUG-25"),+ };+ const QDate today(2025, 6, 1);++ // WEEKLY → first future expiry+ check(resolve_expiry(QStringLiteral("WEEKLY"), QString(), expiries, today)+ == QStringLiteral("26-JUN-25"),+ "resolve_expiry WEEKLY -> 26-JUN-25");++ // NEAREST_DTE "40" → first expiry with DTE >= 40 → 31-JUL-25 (DTE=60)+ check(resolve_expiry(QStringLiteral("NEAREST_DTE"), QStringLiteral("40"), expiries, today)+ == QStringLiteral("31-JUL-25"),+ "resolve_expiry NEAREST_DTE 40 -> 31-JUL-25");++ // ABSOLUTE → returned as-is+ check(resolve_expiry(QStringLiteral("ABSOLUTE"), QStringLiteral("28-AUG-25"), expiries, today)+ == QStringLiteral("28-AUG-25"),+ "resolve_expiry ABSOLUTE 28-AUG-25 -> 28-AUG-25");++ // MONTHLY → earliest future month (June) has only 26-JUN-25 → last of June = 26-JUN-25+ check(resolve_expiry(QStringLiteral("MONTHLY"), QString(), expiries, today)+ == QStringLiteral("26-JUN-25"),+ "resolve_expiry MONTHLY -> 26-JUN-25 (last of earliest month)");++ // Edge: empty list → ""+ check(resolve_expiry(QStringLiteral("WEEKLY"), QString(), QStringList{}, today).isEmpty(),+ "resolve_expiry empty list -> empty string");++ // Edge: NEAREST_DTE where all DTEs are below threshold → returns farthest expiry+ check(resolve_expiry(QStringLiteral("NEAREST_DTE"), QStringLiteral("365"), expiries, today)+ == QStringLiteral("28-AUG-25"),+ "resolve_expiry NEAREST_DTE 365 (none qualifies) -> farthest expiry");++ // ── resolve_entry_legs ────────────────────────────────────────────────────+ // Straddle: CE ATM BUY 1 lot + PE ATM SELL 1 lot against make_synthetic_chain().+ // ATM strike = 23200 (index 4). lot_size=50.+ // CE token=1004, symbol="NIFTY26JUN25C23200", ce_quote.ltp = 100+4 = 104.0+ // PE token=2004, symbol="NIFTY26JUN25P23200", pe_quote.ltp = 90+4 = 94.0+ const auto chain = make_synthetic_chain();++ QVector<AlgoFnoLeg> straddle_rules;+ AlgoFnoLeg ce_rule; ce_rule.kind = "CE"; ce_rule.side = "BUY"; ce_rule.lots = 1;+ ce_rule.strike_mode = "ATM";+ AlgoFnoLeg pe_rule; pe_rule.kind = "PE"; pe_rule.side = "SELL"; pe_rule.lots = 1;+ pe_rule.strike_mode = "ATM";+ straddle_rules << ce_rule << pe_rule;++ const QJsonArray straddle_json = fno_legs_to_json(straddle_rules);+ const auto entry_legs = resolve_entry_legs(chain, straddle_json);++ check(entry_legs.size() == 2, "resolve_entry_legs: straddle produces 2 legs");+ if (entry_legs.size() == 2) {+ const auto& el_ce = entry_legs[0];+ check(el_ce.symbol == QStringLiteral("NIFTY26JUN25C23200") &&+ el_ce.side == QStringLiteral("BUY") &&+ qFuzzyCompare(el_ce.quantity, 50.0) &&+ qFuzzyCompare(el_ce.price, 104.0),+ "resolve_entry_legs: CE leg correct (symbol, side, qty=50, price=104)");++ const auto& el_pe = entry_legs[1];+ check(el_pe.symbol == QStringLiteral("NIFTY26JUN25P23200") &&+ el_pe.side == QStringLiteral("SELL") &&+ qFuzzyCompare(el_pe.quantity, 50.0) &&+ qFuzzyCompare(el_pe.price, 94.0),+ "resolve_entry_legs: PE leg correct (symbol, side, qty=50, price=94)");+ }++ // ── build_exit_legs ───────────────────────────────────────────────────────+ // One long leg (side_sign=+1) → exit side = SELL+ AlgoLegPosition long_leg;+ long_leg.symbol = QStringLiteral("NIFTY26JUN25C23200");+ long_leg.instrument_token = 1004;+ long_leg.is_call = true;+ long_leg.side_sign = 1; // long BUY+ long_leg.quantity = 50;+ long_leg.entry_price = 104.0;+ long_leg.current_price = 120.0; // mark has moved++ QVector<AlgoLegPosition> open_positions;+ open_positions << long_leg;++ const auto exit_legs = build_exit_legs(open_positions);+ check(exit_legs.size() == 1, "build_exit_legs: 1 open leg -> 1 exit leg");+ if (exit_legs.size() == 1) {+ const auto& xl = exit_legs[0];+ check(xl.symbol == QStringLiteral("NIFTY26JUN25C23200") &&+ xl.side == QStringLiteral("SELL") &&+ qFuzzyCompare(xl.quantity, 50.0) &&+ qFuzzyCompare(xl.price, 120.0),+ "build_exit_legs: long leg flips to SELL, preserves qty + current_price");+ }++ // Short leg (side_sign=-1) → exit side = BUY+ AlgoLegPosition short_leg;+ short_leg.symbol = QStringLiteral("NIFTY26JUN25P23200");+ short_leg.instrument_token = 2004;+ short_leg.is_call = false;+ short_leg.side_sign = -1; // short SELL+ short_leg.quantity = 50;+ short_leg.entry_price = 94.0;+ short_leg.current_price = 80.0;++ const auto exit2 = build_exit_legs({short_leg});+ check(exit2.size() == 1 && exit2[0].side == QStringLiteral("BUY"),+ "build_exit_legs: short leg flips to BUY");+}++// Paper multi-leg basket flow. Drives the exact production seam that+// AlgoEngine::execute_basket (paper branch) uses — resolve legs → build the+// basket request (live helper) → pt_place_order + pt_fill_order per leg into a+// paper portfolio → PositionManager basket entry/mark/exit — without the engine+// QThread/event-loop wiring (build-verified separately). Asserts 2 paper legs+// fill, the basket position is recorded, P&L marks, and exit closes both.+void test_paper_basket_flow() {+ using namespace fincept::trading;+ using fincept::algo::fno::resolve_entry_legs;+ using fincept::algo::fno::build_basket_request;+ using fincept::algo::AlgoLegPosition;+ using fincept::algo::PositionManager;++ std::fprintf(stdout, "[8] paper multi-leg basket flow\n");++ // v047 leg columns must exist (per-leg trade persistence).+ {+ auto has_col = [](const QString& col) -> bool {+ auto q = fincept::Database::instance().execute("PRAGMA table_info(algo_trades)", {});+ 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("leg_symbol") && has_col("leg_index"),+ "v047: algo_trades has leg_symbol + leg_index");+ }++ // Resolve a straddle (CE ATM BUY 1 lot + PE ATM SELL 1 lot) on the synthetic+ // chain: CE NIFTY26JUN25C23200 @104 qty50, PE NIFTY26JUN25P23200 @94 qty50.+ const auto chain = make_synthetic_chain();+ QVector<AlgoFnoLeg> rules;+ AlgoFnoLeg ce; ce.kind = "CE"; ce.side = "BUY"; ce.lots = 1; ce.strike_mode = "ATM";+ AlgoFnoLeg pe; pe.kind = "PE"; pe.side = "SELL"; pe.lots = 1; pe.strike_mode = "ATM";+ rules << ce << pe;+ const auto legs = resolve_entry_legs(chain, fno_legs_to_json(rules));+ check(legs.size() == 2, "resolved 2 entry legs for the straddle");+ if (legs.size() != 2) return;++ // build_basket_request (live broker helper): one NFO market order per leg.+ const auto basket = build_basket_request(legs, QStringLiteral("NRML"));+ check(basket.orders.size() == 2 &&+ basket.orders[0].exchange == QStringLiteral("NFO") &&+ basket.orders[0].side == OrderSide::Buy &&+ basket.orders[1].side == OrderSide::Sell &&+ basket.orders[0].product_type == ProductType::Margin,+ "build_basket_request: 2 NFO margin orders, BUY then SELL");++ // ── Paper placement: place + fill each leg into a fresh paper portfolio ──────+ const auto pf = pt_create_portfolio(QStringLiteral("FNO_ALGO_SELFTEST"), 1000000.0,+ QStringLiteral("INR"), 1.0,+ QStringLiteral("cross"), 0.0, QStringLiteral("NFO"));+ bool placed_ok = true;+ for (const auto& leg : legs) {+ try {+ const auto po = pt_place_order(pf.id, leg.symbol, leg.side.toLower(),+ QStringLiteral("market"), leg.quantity, leg.price,+ std::nullopt, false,+ QStringLiteral("NFO"), QStringLiteral("NRML"));+ pt_fill_order(po.id, leg.price);+ } catch (const std::exception& e) {+ placed_ok = false;+ std::fprintf(stdout, " place/fill failed: %s\n", e.what());+ }+ }+ check(placed_ok, "both paper legs placed + filled without throwing");+ check(pt_get_positions(pf.id).size() == 2, "paper portfolio holds 2 open leg positions");++ // ── Basket position lifecycle in PositionManager (sl=50%, tp=100%) ───────────+ QVector<AlgoLegPosition> basket_legs;+ for (const auto& el : legs) {+ AlgoLegPosition lp;+ lp.symbol = el.symbol;+ lp.side_sign = (el.side == QLatin1String("BUY")) ? 1 : -1;+ lp.quantity = el.quantity;+ lp.entry_price = el.price;+ lp.current_price = el.price;+ basket_legs << lp;+ }+ PositionManager pm("t8", 50.0, 100.0, 0.0, 0.0, 0.0);+ pm.record_entry_legs(basket_legs, 0);+ check(pm.has_legs(), "PositionManager records the basket position");++ // Mark CE 104->120 (+16*50 = +800) and PE 94->80 (short: (80-94)*50*-1 = +700).+ pm.update_leg_price(QStringLiteral("NIFTY26JUN25C23200"), 120.0);+ pm.update_leg_price(QStringLiteral("NIFTY26JUN25P23200"), 80.0);+ check(std::abs(pm.metrics().unrealized_pnl - 1500.0) < 1e-6,+ "basket marks: unrealized P&L == +1500");++ const double realized = pm.record_exit_legs(1);+ check(std::abs(realized - 1500.0) < 1e-6, "exit closes both legs, realized P&L == +1500");+ check(!pm.has_legs(), "basket flat after exit");++ pt_delete_portfolio(pf.id); // keep the selftest DB clean+}++// Multi-leg market data + restart reattach helpers (P3.5): leg-position JSON+// round-trip (used for resolved_legs_json persistence) and chain-snapshot leg+// marking (used to mark an open basket live on each underlying tick).+void test_fno_leg_marks_and_persistence() {+ using fincept::algo::fno::leg_positions_to_json;+ using fincept::algo::fno::leg_positions_from_json;+ using fincept::algo::fno::leg_marks_from_chain;+ using fincept::algo::AlgoLegPosition;++ std::fprintf(stdout, "[9] F&O leg marks + resolved-legs persistence\n");++ // ── JSON round-trip (resolved_legs_json) ────────────────────────────────────+ AlgoLegPosition ce;+ ce.symbol = "NIFTY26JUN25C23200"; ce.instrument_token = 1004; ce.is_call = true;+ ce.strike = 23200; ce.side_sign = 1; ce.quantity = 50; ce.entry_price = 104.0;+ ce.current_price = 130.0; ce.unrealized_pnl = 1300.0;+ AlgoLegPosition pe;+ pe.symbol = "NIFTY26JUN25P23200"; pe.instrument_token = 2004; pe.is_call = false;+ pe.strike = 23200; pe.side_sign = -1; pe.quantity = 50; pe.entry_price = 94.0;+ pe.current_price = 80.0; pe.unrealized_pnl = 700.0;+ QVector<AlgoLegPosition> basket; basket << ce << pe;++ const auto back = leg_positions_from_json(leg_positions_to_json(basket));+ check(back.size() == 2, "leg_positions JSON round-trip preserves count");+ if (back.size() == 2) {+ check(back[0].symbol == ce.symbol && back[0].instrument_token == 1004 &&+ back[0].is_call && back[0].side_sign == 1 &&+ qFuzzyCompare(back[0].quantity, 50.0) && qFuzzyCompare(back[0].entry_price, 104.0) &&+ qFuzzyCompare(back[0].current_price, 104.0) && back[0].unrealized_pnl == 0.0,+ "CE leg round-trips (current_price=entry, unrealized=0 on restore)");+ check(back[1].instrument_token == 2004 && !back[1].is_call && back[1].side_sign == -1 &&+ qFuzzyCompare(back[1].entry_price, 94.0),+ "PE leg round-trips (token, is_call=false, side_sign=-1)");+ }++ // ── leg_marks_from_chain: match by token, return symbol->LTP ─────────────────+ const auto chain = make_synthetic_chain(); // CE 1004 ltp=104, PE 2004 ltp=94+ const auto marks = leg_marks_from_chain(basket, chain);+ check(marks.size() == 2 &&+ qFuzzyCompare(marks.value("NIFTY26JUN25C23200"), 104.0) &&+ qFuzzyCompare(marks.value("NIFTY26JUN25P23200"), 94.0),+ "leg_marks_from_chain: both legs marked at chain LTP (CE 104, PE 94)");++ // A leg whose token is not in the chain is omitted (never marked to a stale 0).+ AlgoLegPosition ghost;+ ghost.symbol = "GHOST"; ghost.instrument_token = 999999; ghost.is_call = true;+ const auto marks2 = leg_marks_from_chain({ghost}, chain);+ check(marks2.isEmpty(), "leg_marks_from_chain: unknown-token leg omitted (no stale 0 mark)");+}+} // namespaceint run_fno_algo_selftest() {@@ -184,6 +608,13 @@ int run_fno_algo_selftest() {test_v046_schema();test_persistence_roundtrip();test_leg_resolver();+ test_preview_bridge();+ test_leg_rule_editor();+ test_fno_data_bridge();+ test_position_manager_multileg();+ test_fno_execution();+ test_paper_basket_flow();+ test_fno_leg_marks_and_persistence();std::fprintf(stdout, "\n%s (%d failure(s))\n", g_failures == 0 ? "OVERALL PASS" : "OVERALL FAIL",g_failures);return g_failures == 0 ? 0 : 1;diff --git a/fincept-qt/src/algo_engine/fno/FnoDataBridge.cpp b/fincept-qt/src/algo_engine/fno/FnoDataBridge.cppnew file mode 100644index 000000000..7d2679404--- /dev/null+++ b/fincept-qt/src/algo_engine/fno/FnoDataBridge.cpp@@ -0,0 +1,89 @@+// src/algo_engine/fno/FnoDataBridge.cpp+#include "algo_engine/fno/FnoDataBridge.h"++#include "datahub/DataHub.h"+#include "datahub/DataHubMetaTypes.h"+#include "services/options/OptionChainService.h"++#include <QMutexLocker>+#include <QThread>++namespace {++// Reproduces OptionChainService::chain_topic() byte-for-byte without touching+// the singleton, so it is safe to call from the engine thread.+// Format: "option:chain:<broker>:<underlying>:<expiry>"+QString make_chain_topic(const QString& broker, const QString& underlying, const QString& expiry) {+ return QStringLiteral("option:chain:") + broker + QLatin1Char(':') + underlying + QLatin1Char(':') + expiry;+}++} // namespace++namespace fincept::algo::fno {++using fincept::services::options::OptionChain;+using fincept::services::options::OptionChainService;++FnoDataBridge::FnoDataBridge(QObject* parent) : QObject(parent) {+ // This object lives on the main thread. chain_published fires on the main thread+ // (OptionChainService publishes from there), so this direct connection is safe.+ connect(&OptionChainService::instance(), &OptionChainService::chain_published,+ this, &FnoDataBridge::ingest_chain);+}++void FnoDataBridge::ingest_chain(const OptionChain& chain) {+ const QString topic = make_chain_topic(chain.broker_id, chain.underlying, chain.expiry);+ QMutexLocker l(&mutex_);+ chains_[topic] = chain;+}++OptionChain FnoDataBridge::snapshot(const QString& broker, const QString& underlying,+ const QString& expiry) const {+ const QString topic = make_chain_topic(broker, underlying, expiry);+ QMutexLocker l(&mutex_);+ return chains_.value(topic);+}++void FnoDataBridge::ensure_chain(const QString& broker, const QString& underlying,+ const QString& expiry) {+ const QString topic = make_chain_topic(broker, underlying, expiry);+ if (QThread::currentThread() != thread()) {+ QMetaObject::invokeMethod(this, [this, topic]() { do_ensure_chain(topic); },+ Qt::QueuedConnection);+ } else {+ do_ensure_chain(topic);+ }+}++void FnoDataBridge::pin_legs(const QString& broker, const QString& underlying,+ const QString& expiry, const QStringList& symbols) {+ const QString topic = make_chain_topic(broker, underlying, expiry);+ if (QThread::currentThread() != thread()) {+ QMetaObject::invokeMethod(this, [this, topic, symbols]() { do_pin(topic, symbols); },+ Qt::QueuedConnection);+ } else {+ do_pin(topic, symbols);+ }+}++void FnoDataBridge::do_ensure_chain(const QString& topic) {+ // Called on the main thread. If not yet subscribed, subscribe to the topic+ // so the DataHub producer wakes up and starts publishing. The chain_published+ // signal connection (ctor) caches whatever is produced into chains_.+ if (subscribed_.value(topic, false))+ return;+ subscribed_[topic] = true;+ auto& hub = fincept::datahub::DataHub::instance();+ // Subscribe with this as owner so the hub can unsubscribe on destruction.+ // Callback is a no-op since ingest_chain (via chain_published signal) already+ // caches the data. The subscribe call is what wakes the producer.+ hub.subscribe(this, topic, [](const QVariant&) {});+ hub.request(topic, /*force*/ false);+}++void FnoDataBridge::do_pin(const QString& topic, const QStringList& symbols) {+ // Called on the main thread.+ OptionChainService::instance().pin_contracts(topic, symbols);+}++} // namespace fincept::algo::fnodiff --git a/fincept-qt/src/algo_engine/fno/FnoDataBridge.h b/fincept-qt/src/algo_engine/fno/FnoDataBridge.hnew file mode 100644index 000000000..d7fa046e8--- /dev/null+++ b/fincept-qt/src/algo_engine/fno/FnoDataBridge.h@@ -0,0 +1,45 @@+// src/algo_engine/fno/FnoDataBridge.h+#pragma once+#include "services/options/OptionChainTypes.h"+#include <QHash>+#include <QMutex>+#include <QObject>+#include <QString>+#include <QStringList>++namespace fincept::algo::fno {++// GUI/hub-thread adapter so the algo ENGINE THREAD can safely read option-chain+// snapshots and pin its legs into OptionChainService's live WS window. Lives on+// the main thread (created before AlgoEngine::moveToThread). Engine-thread callers+// use ensure_chain()/snapshot()/pin_legs(); mutating calls marshal to this object's+// (main) thread; snapshot() returns a mutex-guarded COPY.+class FnoDataBridge : public QObject {+ Q_OBJECT+ public:+ explicit FnoDataBridge(QObject* parent = nullptr);++ // Engine-thread-safe. Ensures a chain for (broker,underlying,expiry) is being+ // produced + cached (subscribes to its topic on the main thread).+ void ensure_chain(const QString& broker, const QString& underlying, const QString& expiry);+ // Engine-thread-safe. Returns a COPY of the last cached chain (empty if none yet).+ fincept::services::options::OptionChain snapshot(const QString& broker, const QString& underlying,+ const QString& expiry) const;+ // Engine-thread-safe. Pins concrete contract symbols into the live WS window.+ void pin_legs(const QString& broker, const QString& underlying, const QString& expiry,+ const QStringList& symbols);++ // Test/seam hook — ingest a chain as if chain_published fired (used by the+ // headless selftest; also the slot connected to OptionChainService).+ void ingest_chain(const fincept::services::options::OptionChain& chain);++ private:+ void do_ensure_chain(const QString& topic);+ void do_pin(const QString& topic, const QStringList& symbols);++ mutable QMutex mutex_;+ QHash<QString, fincept::services::options::OptionChain> chains_; // keyed by topic; guarded by mutex_+ QHash<QString, bool> subscribed_; // main-thread-only (always accessed in do_ensure_chain); no mutex needed+};++} // namespace fincept::algo::fnodiff --git a/fincept-qt/src/algo_engine/fno/FnoExecution.cpp b/fincept-qt/src/algo_engine/fno/FnoExecution.cppnew file mode 100644index 000000000..af92db5cd--- /dev/null+++ b/fincept-qt/src/algo_engine/fno/FnoExecution.cpp@@ -0,0 +1,288 @@+// src/algo_engine/fno/FnoExecution.cpp+#include "algo_engine/fno/FnoExecution.h"+#include "algo_engine/fno/FnoLegResolver.h"++#include <QJsonObject>++#include <algorithm>++namespace fincept::algo::fno {++// ---------------------------------------------------------------------------+// resolve_expiry+// ---------------------------------------------------------------------------++// Parse "DD-MMM-YY" (uppercase month, e.g. "26-JUN-25") to a QDate.+//+// Two issues to handle:+// 1. Qt6's QDate::fromString("dd-MMM-yy") uses the C locale which expects+// title-case month abbreviations ("Jun" not "JUN").+// 2. Qt6 interprets "yy" as 1900+yy (so "25" → 1925, not 2025). We fix+// this by parsing the 4-digit year explicitly after converting "YY" to+// "20YY" for years 00-99.+//+// Approach: convert "DD-MMM-YY" → "DD-MMM-20YY" and parse with "dd-MMM-yyyy".+static QDate parse_expiry_date(const QString& s) {+ // Expected format: "DD-MMM-YY" (length 9, e.g. "26-JUN-25").+ if (s.length() >= 9 && s[2] == QChar('-') && s[6] == QChar('-')) {+ const QString day = s.left(2);+ const QString month = s.mid(3, 3); // e.g. "JUN"+ const QString yy = s.mid(7, 2); // e.g. "25"++ // Title-case the month (Qt C-locale fromString expects "Jun" not "JUN").+ const QString month_tc = month.left(1).toUpper() + month.mid(1).toLower();++ // Expand 2-digit year to 4-digit (20xx) — all NSE/BSE options expire well within 2099.+ const QString four_digit = QStringLiteral("20") + yy;++ const QString normalised = day + QChar('-') + month_tc + QChar('-') + four_digit;+ const QDate d = QDate::fromString(normalised, QStringLiteral("dd-MMM-yyyy"));+ if (d.isValid())+ return d;+ }+ // Fallback for other formats (yyyy-MM-dd, already title-cased, etc.).+ QDate d = QDate::fromString(s, QStringLiteral("dd-MMM-yy"));+ // Fix Qt "yy" → 1900+yy issue in fallback path.+ if (d.isValid() && d.year() < 2000)+ d = d.addYears(100);+ return d;+}++QString resolve_expiry(const QString& mode, const QString& value,+ const QStringList& available_expiries,+ const QDate& today) {+ if (available_expiries.isEmpty())+ return QString();++ // ABSOLUTE: return the value directly (it is an explicit "DD-MMM-YY" string).+ // We still validate it parses — if it doesn't we return it as-is (best-effort).+ if (mode == QLatin1String("ABSOLUTE")) {+ return value;+ }++ // Build a sorted list of (date, original-string) for future expiries only.+ using DateStr = std::pair<QDate, QString>;+ QVector<DateStr> future;+ future.reserve(available_expiries.size());+ for (const QString& e : available_expiries) {+ const QDate d = parse_expiry_date(e);+ if (d.isValid() && d >= today)+ future.append({d, e});+ }+ if (future.isEmpty())+ return QString();++ std::sort(future.begin(), future.end(),+ [](const DateStr& a, const DateStr& b) { return a.first < b.first; });++ if (mode == QLatin1String("WEEKLY")) {+ // Nearest future expiry.+ return future.first().second;+ }++ if (mode == QLatin1String("NEAREST_DTE")) {+ const int min_dte = value.toInt();+ for (const auto& [date, str] : future) {+ const int dte = static_cast<int>(today.daysTo(date));+ if (dte >= min_dte)+ return str;+ }+ // Nothing meets the DTE; return the farthest-out expiry as best-effort.+ return future.last().second;+ }++ if (mode == QLatin1String("MONTHLY")) {+ // Group future expiries by (year, month). Pick the earliest such group+ // and return its maximum date (last expiry of that month).+ // The list is already sorted ascending so the first group's last element+ // is the maximum date within that group.+ const int first_year = future.first().first.year();+ const int first_month = future.first().first.month();+ QString best;+ QDate best_date;+ for (const auto& [date, str] : future) {+ if (date.year() != first_year || date.month() != first_month)+ break; // moved past the earliest future month+ if (!best_date.isValid() || date > best_date) {+ best_date = date;+ best = str;+ }+ }+ return best;+ }++ // Unknown mode: fall back to nearest future expiry.+ return future.first().second;+}++// ---------------------------------------------------------------------------+// resolve_entry_legs+// ---------------------------------------------------------------------------++QVector<fincept::algo::AlgoOrderLeg>+resolve_entry_legs(const fincept::services::options::OptionChain& chain,+ const QJsonArray& strategy_legs) {+ using fincept::algo::AlgoOrderLeg;+ using fincept::services::options::OptionChainRow;++ const QVector<AlgoFnoLeg> leg_rules = fno_legs_from_json(strategy_legs);+ const QVector<ResolvedLeg> resolved = FnoLegResolver::resolve(leg_rules, chain);++ QVector<AlgoOrderLeg> out;+ out.reserve(resolved.size());++ for (int i = 0; i < resolved.size(); ++i) {+ const ResolvedLeg& rl = resolved[i];+ if (!rl.valid)+ continue;++ const bool is_call = (rl.kind == QLatin1String("CE"));++ // Find the chain row whose CE or PE token matches the resolved token.+ const OptionChainRow* row = nullptr;+ for (const auto& r : chain.rows) {+ const qint64 tok = is_call ? r.ce_token : r.pe_token;+ if (tok == rl.token) {+ row = &r;+ break;+ }+ }+ if (!row)+ continue; // token not found in chain (shouldn't happen after valid resolve)++ AlgoOrderLeg leg;+ leg.symbol = rl.symbol;+ leg.instrument_token = rl.token;+ leg.side = rl.side;+ leg.quantity = static_cast<double>(rl.lots) * row->lot_size;+ leg.price = is_call ? row->ce_quote.ltp : row->pe_quote.ltp;+ out.append(leg);+ }++ return out;+}++// ---------------------------------------------------------------------------+// build_exit_legs+// ---------------------------------------------------------------------------++QVector<fincept::algo::AlgoOrderLeg>+build_exit_legs(const QVector<fincept::algo::AlgoLegPosition>& open_legs) {+ using fincept::algo::AlgoOrderLeg;++ QVector<AlgoOrderLeg> out;+ out.reserve(open_legs.size());++ for (const auto& leg : open_legs) {+ AlgoOrderLeg el;+ el.symbol = leg.symbol;+ el.instrument_token = leg.instrument_token;+ // Flip the side: long (side_sign > 0) exits as SELL; short exits as BUY.+ el.side = (leg.side_sign > 0) ? QStringLiteral("SELL")+ : QStringLiteral("BUY");+ el.quantity = leg.quantity;+ el.price = leg.current_price;+ out.append(el);+ }++ return out;+}++// ---------------------------------------------------------------------------+// build_basket_request+// ---------------------------------------------------------------------------++fincept::trading::BasketOrderRequest+build_basket_request(const QVector<fincept::algo::AlgoOrderLeg>& legs,+ const QString& product_type) {+ using namespace fincept::trading;++ const ProductType product =+ (product_type == QLatin1String("CNC") || product_type == QLatin1String("delivery"))+ ? ProductType::Delivery+ : ProductType::Margin; // F&O baskets are margin/NRML++ BasketOrderRequest basket;+ basket.strategy_name = QStringLiteral("algo_fno_basket");+ basket.orders.reserve(legs.size());+ for (const auto& leg : legs) {+ UnifiedOrder o;+ o.symbol = leg.symbol;+ o.exchange = QStringLiteral("NFO");+ o.side = (leg.side == QLatin1String("BUY")) ? OrderSide::Buy : OrderSide::Sell;+ o.order_type = OrderType::Market;+ o.quantity = leg.quantity;+ o.price = 0; // market+ o.product_type = product;+ basket.orders.append(o);+ }+ return basket;+}++// ---------------------------------------------------------------------------+// leg_positions_to_json / leg_positions_from_json+// ---------------------------------------------------------------------------++QJsonArray+leg_positions_to_json(const QVector<fincept::algo::AlgoLegPosition>& legs) {+ QJsonArray arr;+ for (const auto& l : legs) {+ QJsonObject o;+ o["symbol"] = l.symbol;+ o["token"] = static_cast<double>(l.instrument_token);+ o["is_call"] = l.is_call;+ o["strike"] = l.strike;+ o["side_sign"] = l.side_sign;+ o["quantity"] = l.quantity;+ o["entry_price"] = l.entry_price;+ arr.append(o);+ }+ return arr;+}++QVector<fincept::algo::AlgoLegPosition>+leg_positions_from_json(const QJsonArray& arr) {+ using fincept::algo::AlgoLegPosition;+ QVector<AlgoLegPosition> out;+ out.reserve(arr.size());+ for (const auto& v : arr) {+ const QJsonObject o = v.toObject();+ AlgoLegPosition l;+ l.symbol = o.value("symbol").toString();+ l.instrument_token = static_cast<qint64>(o.value("token").toDouble());+ l.is_call = o.value("is_call").toBool();+ l.strike = o.value("strike").toDouble();+ l.side_sign = o.value("side_sign").toInt();+ l.quantity = o.value("quantity").toDouble();+ l.entry_price = o.value("entry_price").toDouble();+ l.current_price = l.entry_price; // re-marked on the next tick+ l.unrealized_pnl = 0;+ out.append(l);+ }+ return out;+}++// ---------------------------------------------------------------------------+// leg_marks_from_chain+// ---------------------------------------------------------------------------++QHash<QString, double>+leg_marks_from_chain(const QVector<fincept::algo::AlgoLegPosition>& legs,+ const fincept::services::options::OptionChain& chain) {+ QHash<QString, double> marks;+ for (const auto& leg : legs) {+ double ltp = 0;+ for (const auto& r : chain.rows) {+ const qint64 tok = leg.is_call ? r.ce_token : r.pe_token;+ if (tok == leg.instrument_token) {+ ltp = leg.is_call ? r.ce_quote.ltp : r.pe_quote.ltp;+ break;+ }+ }+ if (ltp > 0)+ marks.insert(leg.symbol, ltp);+ }+ return marks;+}++} // namespace fincept::algo::fnodiff --git a/fincept-qt/src/algo_engine/fno/FnoExecution.h b/fincept-qt/src/algo_engine/fno/FnoExecution.hnew file mode 100644index 000000000..f1a337d62--- /dev/null+++ b/fincept-qt/src/algo_engine/fno/FnoExecution.h@@ -0,0 +1,104 @@+// src/algo_engine/fno/FnoExecution.h+// Pure F&O execution helpers: expiry-rule resolution, entry/exit leg construction.+// No I/O, no Qt event loop dependencies. All helpers are free functions in the+// fincept::algo::fno namespace so they can be tested headlessly without a broker.+#pragma once+#include "algo_engine/AlgoEngineTypes.h"+#include "algo_engine/fno/FnoAlgoTypes.h"+#include "services/options/OptionChainTypes.h"+#include "trading/TradingTypes.h"++#include <QDate>+#include <QHash>+#include <QJsonArray>+#include <QString>+#include <QStringList>+#include <QVector>++namespace fincept::algo::fno {++// ---------------------------------------------------------------------------+// resolve_expiry+// ---------------------------------------------------------------------------+// Resolve an expiry RULE against the list of available expiries returned by+// OptionChainService::list_expiries() (format "DD-MMM-YY", e.g. "26-JUN-25").+//+// ABSOLUTE -> return value as-is if it appears in the list; return value+// anyway (best-effort) if the list doesn't contain it.+// NEAREST_DTE -> first future expiry (date >= today) whose DTE (in calendar+// days, inclusive of expiry date) is >= value.toInt().+// WEEKLY -> first future expiry (date >= today) — nearest expiry.+// MONTHLY -> among future expiries, pick the last expiry of the earliest+// calendar month that has at least one future expiry.+//+// "Future" means date >= today. The list is arbitrary-ordered on input; the+// function sorts internally.+//+// Returns "" when the list is empty or no expiry satisfies the rule.+QString resolve_expiry(const QString& mode, const QString& value,+ const QStringList& available_expiries,+ const QDate& today);++// ---------------------------------------------------------------------------+// resolve_entry_legs+// ---------------------------------------------------------------------------+// Translate a QJsonArray of AlgoFnoLeg rules (strategy_.legs) into concrete+// AlgoOrderLeg objects suitable for submitting as an entry order basket.+//+// For each valid resolved leg the chain row is looked up by instrument token+// (ce_token for CE legs, pe_token for PE legs) and the order quantity is+// computed as resolved.lots * row.lot_size. The price field is set to the+// current LTP from the chain (entry reference for the paper simulator / P&L+// marking). Invalid/FUT legs and legs whose chain row cannot be found are+// silently skipped.+QVector<fincept::algo::AlgoOrderLeg>+resolve_entry_legs(const fincept::services::options::OptionChain& chain,+ const QJsonArray& strategy_legs);++// ---------------------------------------------------------------------------+// build_exit_legs+// ---------------------------------------------------------------------------+// Build exit order legs from open AlgoLegPosition entries by flipping the+// side (long BUY → exit SELL; short SELL → exit BUY). symbol, token, and+// quantity are preserved; price is taken from the leg's current_price mark.+QVector<fincept::algo::AlgoOrderLeg>+build_exit_legs(const QVector<fincept::algo::AlgoLegPosition>& open_legs);++// ---------------------------------------------------------------------------+// build_basket_request+// ---------------------------------------------------------------------------+// Build a UnifiedTrading BasketOrderRequest from resolved order legs for the+// LIVE broker path. Every leg becomes one NFO market UnifiedOrder; product_type+// maps "CNC"/"delivery" -> Delivery, anything else (NRML/MIS/"") -> Margin+// (F&O is always margin/NRML). Used only on the live branch of+// AlgoEngine::execute_basket; the paper branch never touches the broker.+fincept::trading::BasketOrderRequest+build_basket_request(const QVector<fincept::algo::AlgoOrderLeg>& legs,+ const QString& product_type);++// ---------------------------------------------------------------------------+// leg_positions_to_json / leg_positions_from_json+// ---------------------------------------------------------------------------+// Serialize an open multi-leg basket position to/from JSON so it can be stored+// on the algo_deployments row (resolved_legs_json) and reattached after an app+// restart. Round-trips symbol, instrument_token, is_call, strike, side_sign,+// quantity, entry_price. On parse, current_price seeds to entry_price and+// unrealized_pnl to 0 (re-marked live on the next tick).+QJsonArray+leg_positions_to_json(const QVector<fincept::algo::AlgoLegPosition>& legs);++QVector<fincept::algo::AlgoLegPosition>+leg_positions_from_json(const QJsonArray& arr);++// ---------------------------------------------------------------------------+// leg_marks_from_chain+// ---------------------------------------------------------------------------+// Map each open leg to its current LTP from a chain snapshot, matched by+// instrument token (ce_token for calls, pe_token for puts). Returns symbol->ltp+// for every leg whose contract is found with a positive LTP; legs not present in+// the snapshot (or with ltp<=0) are omitted so a stale 0 never overwrites a mark.+QHash<QString, double>+leg_marks_from_chain(const QVector<fincept::algo::AlgoLegPosition>& legs,+ const fincept::services::options::OptionChain& chain);++} // namespace fincept::algo::fnodiff --git a/fincept-qt/src/algo_engine/fno/FnoStrategyPreview.cpp b/fincept-qt/src/algo_engine/fno/FnoStrategyPreview.cppnew file mode 100644index 000000000..6ab0416cc--- /dev/null+++ b/fincept-qt/src/algo_engine/fno/FnoStrategyPreview.cpp@@ -0,0 +1,51 @@+#include "algo_engine/fno/FnoStrategyPreview.h"++#include "algo_engine/fno/FnoLegResolver.h"++namespace fincept::algo::fno {++using fincept::services::options::OptionChain;+using fincept::services::options::OptionChainRow;+using fincept::services::options::Strategy;+using fincept::services::options::StrategyLeg;+using fincept::trading::InstrumentType;++Strategy build_preview_strategy(const QVector<AlgoFnoLeg>& legs, const OptionChain& chain) {+ Strategy s;+ s.name = chain.underlying.isEmpty() ? QStringLiteral("Preview") : chain.underlying;+ s.underlying = chain.underlying;+ s.expiry = chain.expiry;++ const QVector<ResolvedLeg> resolved = FnoLegResolver::resolve(legs, chain);+ for (const auto& rl : resolved) {+ if (!rl.valid)+ continue; // skip FUT/unresolved legs in the preview+ const bool is_call = (rl.kind == QLatin1String("CE"));++ const OptionChainRow* row = nullptr;+ for (const auto& r : chain.rows) {+ if ((is_call ? r.ce_token : r.pe_token) == rl.token) {+ row = &r;+ break;+ }+ }+ if (!row)+ continue;++ StrategyLeg sl;+ sl.instrument_token = rl.token;+ sl.symbol = rl.symbol;+ sl.type = is_call ? InstrumentType::CE : InstrumentType::PE;+ sl.strike = rl.strike;+ sl.expiry = chain.expiry;+ sl.lot_size = row->lot_size;+ sl.lots = (rl.side == QLatin1String("SELL")) ? -rl.lots : rl.lots;+ sl.entry_price = is_call ? row->ce_quote.ltp : row->pe_quote.ltp;+ sl.iv_at_entry = is_call ? row->ce_iv : row->pe_iv;+ sl.is_active = true;+ s.legs.append(sl);+ }+ return s;+}++} // namespace fincept::algo::fnodiff --git a/fincept-qt/src/algo_engine/fno/FnoStrategyPreview.h b/fincept-qt/src/algo_engine/fno/FnoStrategyPreview.hnew file mode 100644index 000000000..5d201b4bc--- /dev/null+++ b/fincept-qt/src/algo_engine/fno/FnoStrategyPreview.h@@ -0,0 +1,18 @@+#pragma once++#include "algo_engine/fno/FnoAlgoTypes.h"+#include "services/options/OptionChainTypes.h"++#include <QVector>++namespace fincept::algo::fno {++// Resolve rule-based legs against a live chain and convert them to a concrete+// options::Strategy whose StrategyLegs (strike/lots/entry_price/iv/lot_size) feed+// the F&O analytics/payoff components for a live PREVIEW. Pure: no I/O, no globals.+// Unresolved legs (e.g. FUT, or a strike with no contract) are skipped.+fincept::services::options::Strategy+build_preview_strategy(const QVector<AlgoFnoLeg>& legs,+ const fincept::services::options::OptionChain& chain);++} // namespace fincept::algo::fnodiff --git a/fincept-qt/src/app/MonitorPickerDialog.cpp b/fincept-qt/src/app/MonitorPickerDialog.cppindex ba02f390c..8d6275a46 100644--- a/fincept-qt/src/app/MonitorPickerDialog.cpp+++ b/fincept-qt/src/app/MonitorPickerDialog.cpp@@ -227,8 +227,29 @@ QScreen* MonitorPickerDialog::pick(QWidget* parent, QScreen* current) {if (screens.size() <= 1)return screens.isEmpty() ? nullptr : screens.first();+ // Re-entrancy guard. exec() below spins a NESTED event loop, and the+ // secondary-instance relaunch path (InstanceLock::message_received →+ // new_window_on_next_monitor → here) is a QUEUED signal, so it gets+ // delivered *by that nested loop* while a picker is already open. Without+ // this guard, every relaunch stacks another modal picker on top of the+ // current one; the user then dismisses them one by one and each dismissal+ // spawns a window — looking like "the dialog won't close and keeps opening+ // windows". exec() is GUI-thread only, so a function-static pointer is the+ // right scope: surface the existing picker and drop the duplicate request+ // instead of stacking. (The InstanceLock deferred-emit only fixed the+ // crash this same re-entrancy used to cause, not the stacking.)+ static MonitorPickerDialog* s_active = nullptr;+ if (s_active) {+ s_active->raise();+ s_active->activateWindow();+ return nullptr;+ }+MonitorPickerDialog dlg(parent, current);- if (dlg.exec() == QDialog::Accepted)+ s_active = &dlg;+ const int rc = dlg.exec();+ s_active = nullptr;+ if (rc == QDialog::Accepted)return dlg.picked_screen();return nullptr;}diff --git a/fincept-qt/src/app/WindowFrame.cpp b/fincept-qt/src/app/WindowFrame.cppindex 5f6facd24..ca8409273 100644--- a/fincept-qt/src/app/WindowFrame.cpp+++ b/fincept-qt/src/app/WindowFrame.cpp@@ -521,6 +521,20 @@ WindowFrame::WindowFrame(int window_id, QWidget* parent, const WindowId& adoptedw->show();w->raise();w->activateWindow();+ } else if (action == "close_window") {+ // Same as the titlebar close button — WA_DeleteOnClose handles+ // teardown, closeEvent persists this window's layout. If this is+ // the last window, the app honours general.on_last_window_close+ // (quit or surface the Launchpad), exactly like a manual close.+ close();+ } else if (action == "close_all_windows") {+ // Snapshot the registry first: each close() schedules the frame's+ // destruction (WA_DeleteOnClose → deleteLater) which unregisters it,+ // so iterating the live registry would be unsafe. The copy is stable.+ const auto frames = WindowRegistry::instance().frames();+ for (WindowFrame* w : frames)+ if (w)+ w->close();} else if (action.startsWith("move_to_monitor:")) {// Move this window to the named monitor. We resolve by QScreen::name// (not index) because index ordering flips on plug/unplug events.diff --git a/fincept-qt/src/app/main.cpp b/fincept-qt/src/app/main.cppindex 78c98a476..4ea38d353 100644--- a/fincept-qt/src/app/main.cpp+++ b/fincept-qt/src/app/main.cpp@@ -7,7 +7,7 @@#include "app/MonitorPickerDialog.h"#include "app/WindowFrame.h"#include "app/TerminalShell.h"-#include "core/keys/WindowCycler.h"+#include "core/window/WindowRegistry.h"#include "auth/AuthManager.h"#include "auth/InactivityGuard.h"#include "auth/PinManager.h"@@ -31,6 +31,7 @@#include "mcp/ToolSelfTest.h"#include "services/feeds/FeedSelfTest.h"#include "trading/PaperTradingSelftest.h"+#include "trading/replication/PortfolioReplicationSelftest.h"#include "network/http/HttpClient.h"#include "python/PythonSetupManager.h"#include "screens/launchpad/LaunchpadScreen.h"@@ -123,21 +124,40 @@// Wire the two app-level lifecycle handlers that fire after the primary// window exists: InstanceLock::message_received (a re-launch of the exe-// asks us to open another WindowFrame — args ignored, the request itself is-// the trigger) and QApplication::lastWindowClosed (surface the Launchpad+// asks us to bring the running instance to the front — args ignored, the+// request itself is the trigger) and QApplication::lastWindowClosed (surface the Launchpad// instead of quitting; the Launchpad's own close handler quits explicitly).// Called from both the post-setup-screen path and the no-setup path so the// two branches stay in sync.static void wire_app_lifecycle(QApplication& app, fincept::InstanceLock& lock) {QObject::connect(&lock, &fincept::InstanceLock::message_received,[](const QStringList& /*args*/) {- // Route through the same picker the toolbar uses so- // secondary-instance launches respect the user's- // monitor choice on multi-monitor setups. Picker- // short-circuits on single-monitor systems, so this- // is a no-op cost there.- fincept::WindowCycler::instance().new_window_on_next_monitor();- LOG_INFO("App", "New window opened via secondary instance request");+ // Re-launching the exe while an instance is already+ // running means "bring the running instance forward" —+ // the standard single-instance behaviour — NOT "open a+ // new window". Opening a new window (and the monitor+ // picker that goes with it) stays an EXPLICIT action:+ // the toolbar "New Window", Ctrl+Shift+N, the Launchpad+ // button, and tear-off. Routing relaunches through the+ // picker surprised users by prompting for a monitor on+ // every open even when they never asked for a new window.+ const auto frames = fincept::WindowRegistry::instance().frames();+ if (!frames.isEmpty()) {+ // Lowest window_id (the primary) is the predictable+ // target. Activating one window pulls the whole app+ // forward on every platform we support.+ fincept::WindowFrame* target = frames.first();+ if (target->isMinimized())+ target->showNormal();+ target->raise();+ target->activateWindow();+ LOG_INFO("App", "Secondary instance request — raised existing window");+ } else {+ // No live frames (e.g. the user closed to the+ // Launchpad). Surface it instead of silently no-op'ing.+ fincept::screens::LaunchpadScreen::instance()->surface();+ LOG_INFO("App", "Secondary instance request — surfaced Launchpad");+ }});QObject::connect(&app, &QApplication::lastWindowClosed, &app, []() {// Settings → General → "On last window close" controls behaviour.@@ -722,6 +742,7 @@ int main(int argc, char* argv[]) {fincept::register_migration_v044();fincept::register_migration_v045();fincept::register_migration_v046();+ fincept::register_migration_v047();// Open main databaseQString db_path = fincept::AppPaths::data() + "/fincept.db";@@ -885,6 +906,8 @@ int main(int argc, char* argv[]) {return fincept::algo::run_universe_scan_selftest();if (qstrcmp(argv[i], "--selftest-paper") == 0)return fincept::trading::run_paper_trading_selftest();+ if (qstrcmp(argv[i], "--selftest-portfolio-replication") == 0)+ return fincept::trading::replication::run_portfolio_replication_selftest();}// Start the scan-watch background service. Runs after Database::open() (whichdiff --git a/fincept-qt/src/screens/algo_trading/AlgoDeployDialog.cpp b/fincept-qt/src/screens/algo_trading/AlgoDeployDialog.cppindex 8000f6939..e9704d43d 100644--- a/fincept-qt/src/screens/algo_trading/AlgoDeployDialog.cpp+++ b/fincept-qt/src/screens/algo_trading/AlgoDeployDialog.cpp@@ -47,6 +47,48 @@ void AlgoDeployDialog::set_symbol(const QString& symbol) {symbol_edit_->setText(symbol.trimmed().toUpper());}+void AlgoDeployDialog::set_fno_context(const QString& instrument_type, const QString& underlying,+ const QString& expiry_rule) {+ fno_instrument_type_ = instrument_type;+ fno_underlying_ = underlying;+ fno_expiry_rule_ = expiry_rule;++ if (instrument_type == QLatin1String("equity"))+ return;++ // F&O deployment: the symbol field is not a free-text instrument symbol.+ // Show the underlying and expiry rule as read-only context; disable editing.+ if (symbol_edit_) {+ QString label = underlying;+ if (!underlying.isEmpty() && !expiry_rule.isEmpty())+ label = underlying + QStringLiteral(" · ") + expiry_rule;+ else if (underlying.isEmpty())+ label = expiry_rule;+ symbol_edit_->setText(label);+ symbol_edit_->setEnabled(false);+ }+ if (symbol_label_)+ symbol_label_->setText(tr("Underlying:"));++ // Default exchange to NFO for F&O if available.+ if (exchange_combo_) {+ const int nfo_idx = exchange_combo_->findText(QStringLiteral("NFO"));+ if (nfo_idx >= 0)+ exchange_combo_->setCurrentIndex(nfo_idx);+ }++ // Default product type to NRML/Margin if available (case-insensitive search).+ if (product_type_combo_) {+ int nrml_idx = product_type_combo_->findText(QStringLiteral("NRML"),+ Qt::MatchFixedString | Qt::MatchCaseSensitive);+ if (nrml_idx < 0)+ nrml_idx = product_type_combo_->findText(QStringLiteral("Margin"),+ Qt::MatchFixedString | Qt::MatchCaseSensitive);+ if (nrml_idx >= 0)+ product_type_combo_->setCurrentIndex(nrml_idx);+ }+}+void AlgoDeployDialog::build_ui() {auto* root = new QVBoxLayout(this);root->setSpacing(12);@@ -202,10 +244,17 @@ void AlgoDeployDialog::populate_broker_fields(const QString& account_id) {}void AlgoDeployDialog::on_ok() {- if (symbol_edit_->text().trimmed().isEmpty()) {+ // For F&O deployments the symbol field holds a read-only context label, not a+ // tradeable symbol — skip the "symbol required" guard.+ const bool is_fno = (fno_instrument_type_ != QLatin1String("equity"));+ if (!is_fno && symbol_edit_->text().trimmed().isEmpty()) {QMessageBox::warning(this, tr("Validation"), tr("Symbol is required."));return;}+ if (is_fno && fno_underlying_.trimmed().isEmpty()) {+ QMessageBox::warning(this, tr("Deploy"), tr("Select an underlying for the F&O deployment."));+ return;+ }if (quantity_spin_->value() <= 0) {QMessageBox::warning(this, tr("Validation"), tr("Quantity must be > 0."));return;@@ -255,6 +304,17 @@ void AlgoDeployDialog::on_ok() {result_.backend = backend_to_string(mode == "live" ? TradingBackend::EquityBroker: TradingBackend::Paper);+ // F&O override: set instrument_type/underlying/resolved_expiry and clear symbol.+ // Concrete legs and expiry are resolved at entry-time by the runner (P3).+ // The equity branch (is_fno == false) is unaffected.+ if (is_fno) {+ result_.instrument_type = fno_instrument_type_;+ result_.underlying = fno_underlying_;+ result_.resolved_expiry = fno_expiry_rule_; // expiry RULE; concrete expiry resolved at entry (P3)+ // Multi-leg F&O has no single symbol; concrete legs are resolved at entry by the runner (P3).+ result_.symbol.clear();+ }+accept();}diff --git a/fincept-qt/src/screens/algo_trading/AlgoDeployDialog.h b/fincept-qt/src/screens/algo_trading/AlgoDeployDialog.hindex 4f1281ded..4be721eea 100644--- a/fincept-qt/src/screens/algo_trading/AlgoDeployDialog.h+++ b/fincept-qt/src/screens/algo_trading/AlgoDeployDialog.h@@ -25,6 +25,10 @@ class AlgoDeployDialog : public QDialog {// AlgoStrategy, so it's pushed in after construction).void set_symbol(const QString& symbol);+ // F&O context for option/future deployments (set by the StrategyBuilder before exec()).+ void set_fno_context(const QString& instrument_type, const QString& underlying,+ const QString& expiry_rule);+protected:void changeEvent(QEvent* event) override;@@ -42,6 +46,10 @@ class AlgoDeployDialog : public QDialog {QString strategy_id_;QString strategy_name_;+ QString fno_instrument_type_ = "equity";+ QString fno_underlying_;+ QString fno_expiry_rule_;+QLineEdit* symbol_edit_ = nullptr;QComboBox* mode_combo_ = nullptr;QComboBox* side_combo_ = nullptr;diff --git a/fincept-qt/src/screens/algo_trading/StrategyBuilderPanel.cpp b/fincept-qt/src/screens/algo_trading/StrategyBuilderPanel.cppindex 5fa5f67a3..325e9442d 100644--- a/fincept-qt/src/screens/algo_trading/StrategyBuilderPanel.cpp+++ b/fincept-qt/src/screens/algo_trading/StrategyBuilderPanel.cpp@@ -2,15 +2,23 @@#include "screens/algo_trading/StrategyBuilderPanel.h"#include "algo_engine/AlgoEngine.h"+#include "algo_engine/fno/FnoAlgoTypes.h"+#include "algo_engine/fno/FnoStrategyPreview.h"#include "core/currency/Currency.h"#include "core/events/EventBus.h"#include "core/logging/Logger.h"#include "screens/algo_trading/AlgoDeployDialog.h"+#include "screens/fno/BuilderAnalyticsRibbon.h"+#include "screens/fno/PayoffChartWidget.h"#include "services/algo_trading/AlgoTradingService.h"+#include "services/options/OptionChainService.h"+#include "services/options/StrategyAnalytics.h"#include "trading/AccountManager.h"+#include "trading/BrokerAccount.h"#include "trading/BrokerInterface.h"#include "trading/BrokerRegistry.h"#include "ui/theme/Theme.h"+#include "ui/widgets/algo/FnoLegRuleEditor.h"#include <QDate>#include <QDateEdit>@@ -25,6 +33,7 @@#include <QMessageBox>#include <QScrollArea>#include <QSet>+#include <QSignalBlocker>#include <QSplitter>#include <QTimer>#include <QUuid>@@ -286,6 +295,14 @@ QWidget* StrategyBuilderPanel::build_top_toolbar() {template_combo_->addItem(t.name);template_combo_->setToolTip(tr("Load a ready-made strategy as a starting point"));+ // ── Instrument-type selector (P2.3) ──+ instrument_type_combo_ = new QComboBox(this);+ instrument_type_combo_->setObjectName(QStringLiteral("builderInstrumentType"));+ instrument_type_combo_->addItem(tr("Equity"), QStringLiteral("equity"));+ instrument_type_combo_->addItem(tr("Option"), QStringLiteral("option"));+ instrument_type_combo_->addItem(tr("Future"), QStringLiteral("future"));+ instrument_type_combo_->setToolTip(tr("Instrument type this strategy trades"));+// ── State chip + primary actions ──state_chip_ = new QLabel(tr("NEW DRAFT"), this);state_chip_->setObjectName(QStringLiteral("builderStateChip"));@@ -314,6 +331,9 @@ QWidget* StrategyBuilderPanel::build_top_toolbar() {layout->addWidget(caption(tr("TF")));layout->addWidget(timeframe_combo_);layout->addWidget(template_combo_);+ layout->addWidget(divider());+ layout->addWidget(caption(tr("TYPE")));+ layout->addWidget(instrument_type_combo_);layout->addStretch();layout->addWidget(state_chip_);layout->addWidget(save_btn_);@@ -323,6 +343,8 @@ QWidget* StrategyBuilderPanel::build_top_toolbar() {connect(deploy_btn_, &QPushButton::clicked, this, &StrategyBuilderPanel::on_deploy);connect(template_combo_, QOverload<int>::of(&QComboBox::activated), this,&StrategyBuilderPanel::load_template);+ connect(instrument_type_combo_, QOverload<int>::of(&QComboBox::currentIndexChanged), this,+ &StrategyBuilderPanel::on_instrument_type_changed);return toolbar;}@@ -364,6 +386,7 @@ QWidget* StrategyBuilderPanel::build_right_panel() {// ── BACKTEST SETUP card — every test input in one place ──────────────────auto* setup_card = new QFrame(right);+ bt_setup_card_ = setup_card; // store for show/hide in on_instrument_type_changedsetup_card->setObjectName(QStringLiteral("builderSetupCard"));setup_card->setStyleSheet(QString("QFrame#builderSetupCard{background:%1;border:1px solid %2;""border-left:2px solid %3;border-radius:5px;}")@@ -442,6 +465,11 @@ QWidget* StrategyBuilderPanel::build_right_panel() {layout->addWidget(setup_card);+ // ── F&O section (P2.3) — hidden until instrument type != equity ──────────+ build_fno_section();+ layout->addWidget(fno_section_);+ fno_section_->setVisible(false); // equity is default+// ── RESULTS card — clearly separated from the controls above ─────────────auto* results_card = new QFrame(right);results_card->setObjectName(QStringLiteral("builderResultsCard"));@@ -467,6 +495,129 @@ QWidget* StrategyBuilderPanel::build_right_panel() {return right;}+// ── F&O Section (P2.3) ───────────────────────────────────────────────────────++void StrategyBuilderPanel::build_fno_section() {+ fno_section_ = new QWidget(this);+ fno_section_->setObjectName(QStringLiteral("builderFnoSection"));++ auto* layout = new QVBoxLayout(fno_section_);+ layout->setContentsMargins(0, 0, 0, 0);+ layout->setSpacing(6);++ // ── Header row: underlying + expiry mode ──+ auto* header_row = new QHBoxLayout();+ header_row->setSpacing(8);++ underlying_combo_ = new QComboBox(fno_section_);+ underlying_combo_->setObjectName(QStringLiteral("builderFnoUnderlying"));+ underlying_combo_->setToolTip(tr("Underlying instrument"));+ underlying_combo_->setMinimumWidth(100);+ populate_underlyings();++ expiry_mode_combo_ = new QComboBox(fno_section_);+ expiry_mode_combo_->setObjectName(QStringLiteral("builderFnoExpiryMode"));+ expiry_mode_combo_->setToolTip(tr("Expiry selection rule"));+ expiry_mode_combo_->addItem(tr("Weekly"), QStringLiteral("weekly"));+ expiry_mode_combo_->addItem(tr("Monthly"), QStringLiteral("monthly"));+ expiry_mode_combo_->addItem(tr("Nearest DTE"), QStringLiteral("nearest_dte"));+ expiry_mode_combo_->addItem(tr("Absolute"), QStringLiteral("absolute"));++ header_row->addWidget(field_label(tr("Underlying")));+ header_row->addWidget(underlying_combo_, 1);+ header_row->addWidget(field_label(tr("Expiry")));+ header_row->addWidget(expiry_mode_combo_, 1);+ layout->addLayout(header_row);++ // ── Leg rule editor ──+ leg_editor_ = new fincept::ui::algo::FnoLegRuleEditor(fno_section_);+ layout->addWidget(leg_editor_);++ // ── Analytics ribbon + payoff chart ──+ analytics_ribbon_ = new fincept::screens::fno::BuilderAnalyticsRibbon(fno_section_);+ layout->addWidget(analytics_ribbon_);++ payoff_chart_ = new fincept::screens::fno::PayoffChartWidget(fno_section_);+ payoff_chart_->setMinimumHeight(200);+ layout->addWidget(payoff_chart_, 1);++ // Connect all preview-trigger signals to refresh_fno_preview()+ connect(leg_editor_, &fincept::ui::algo::FnoLegRuleEditor::legs_changed,+ this, &StrategyBuilderPanel::refresh_fno_preview);+ connect(underlying_combo_, QOverload<int>::of(&QComboBox::currentIndexChanged),+ this, &StrategyBuilderPanel::refresh_fno_preview);+ connect(expiry_mode_combo_, QOverload<int>::of(&QComboBox::currentIndexChanged),+ this, &StrategyBuilderPanel::refresh_fno_preview);+ connect(&fincept::services::options::OptionChainService::instance(),+ &fincept::services::options::OptionChainService::chain_published,+ this, [this](const fincept::services::options::OptionChain&) {+ refresh_fno_preview();+ });+}++void StrategyBuilderPanel::populate_underlyings() {+ if (!underlying_combo_)+ return;+ const QStringList list =+ fincept::services::options::OptionChainService::instance().list_underlyings(fno_broker_id());+ {+ QSignalBlocker blocker(underlying_combo_);+ underlying_combo_->clear();+ if (list.isEmpty()) {+ underlying_combo_->addItem(tr("(connect broker)"));+ underlying_combo_->setEnabled(false);+ } else {+ for (const auto& u : list)+ underlying_combo_->addItem(u);+ underlying_combo_->setEnabled(true);+ }+ }+}++void StrategyBuilderPanel::refresh_fno_preview() {+ namespace an = fincept::services::options::analytics;+ const auto& chain = fincept::services::options::OptionChainService::instance().last_chain();+ const auto legs = leg_editor_->legs();+ if (legs.isEmpty() || chain.rows.isEmpty()) {+ analytics_ribbon_->clear();+ payoff_chart_->clear_payoff();+ return;+ }+ fincept::services::options::Strategy s = fincept::algo::fno::build_preview_strategy(legs, chain);+ an::PayoffComputeOptions opts;+ opts.current_spot = chain.spot;+ const auto curve = an::compute_payoff(s, opts);+ const auto bes = an::compute_breakevens(curve);+ const auto a = an::compute_all(s, chain, opts);+ payoff_chart_->set_payoff(curve, chain.spot, bes);+ analytics_ribbon_->update_from(s, a);+}++void StrategyBuilderPanel::on_instrument_type_changed() {+ if (!instrument_type_combo_)+ return;+ const QString type = instrument_type_combo_->currentData().toString();+ if (type == QLatin1String("equity")) {+ if (bt_setup_card_) bt_setup_card_->setVisible(true);+ if (fno_section_) fno_section_->setVisible(false);+ } else {+ if (bt_setup_card_) bt_setup_card_->setVisible(false);+ if (fno_section_) fno_section_->setVisible(true);+ if (underlying_combo_) populate_underlyings();+ refresh_fno_preview();+ }+}++QString StrategyBuilderPanel::fno_broker_id() const {+ // Mirror ChainSubTab: prefer a Connected account's broker_id, else "databento".+ for (const auto& acc : fincept::trading::AccountManager::instance().active_accounts()) {+ if (fincept::trading::AccountManager::instance().connection_state(acc.account_id) ==+ fincept::trading::ConnectionState::Connected)+ return acc.broker_id;+ }+ return QStringLiteral("databento");+}+void StrategyBuilderPanel::connect_service() {auto& svc = services::algo::AlgoTradingService::instance();connect(&svc, &services::algo::AlgoTradingService::backtest_result,@@ -496,6 +647,11 @@ services::algo::AlgoStrategy StrategyBuilderPanel::build_strategy() {strat.take_profit = risk_panel_->take_profit();strat.trailing_stop = risk_panel_->trailing_stop();strat.position_size_pct = risk_panel_->capital_pct();+ // P2.3: persist instrument type and F&O leg rules+ strat.instrument_type = instrument_type_combo_ ? instrument_type_combo_->currentData().toString()+ : QStringLiteral("equity");+ if (strat.instrument_type != QLatin1String("equity") && leg_editor_)+ strat.legs = fincept::algo::fno::fno_legs_to_json(leg_editor_->legs());return strat;}@@ -559,6 +715,11 @@ void StrategyBuilderPanel::on_deploy() {auto* dialog = new AlgoDeployDialog(strat, this);dialog->set_symbol(symbol_combo_->currentText()); // carry the builder's symbol in+ if (instrument_type_combo_ && instrument_type_combo_->currentData().toString() != QLatin1String("equity")) {+ dialog->set_fno_context(instrument_type_combo_->currentData().toString(),+ underlying_combo_ ? underlying_combo_->currentText() : QString(),+ expiry_mode_combo_ ? expiry_mode_combo_->currentData().toString() : QString());+ }if (dialog->exec() == QDialog::Accepted) {auto deployment = dialog->deployment();deployment.quantity = risk_panel_->quantity();@@ -651,6 +812,18 @@ void StrategyBuilderPanel::load_strategy(const services::algo::AlgoStrategy& s)exit_section_->set_conditions(s.exit_conditions, s.exit_logic.isEmpty() ? QStringLiteral("AND") : s.exit_logic);risk_panel_->set_values(s.stop_loss, s.take_profit, s.trailing_stop, 1.0, 0.0,s.position_size_pct > 0 ? s.position_size_pct : 100.0);+ // P2.3: restore instrument type and F&O leg rules+ if (instrument_type_combo_) {+ const int idx = instrument_type_combo_->findData(s.instrument_type.isEmpty()+ ? QStringLiteral("equity") : s.instrument_type);+ {+ QSignalBlocker blocker(instrument_type_combo_);+ instrument_type_combo_->setCurrentIndex(idx >= 0 ? idx : 0);+ }+ }+ if (leg_editor_)+ leg_editor_->set_legs(fincept::algo::fno::fno_legs_from_json(s.legs));+ on_instrument_type_changed();// Size the backtest range to the strategy's timeframe (daily needs years for// long indicators; intraday must stay under Yahoo's history cap).const QDate today = QDate::currentDate();diff --git a/fincept-qt/src/screens/algo_trading/StrategyBuilderPanel.h b/fincept-qt/src/screens/algo_trading/StrategyBuilderPanel.hindex a6ecafb33..e7dc118b8 100644--- a/fincept-qt/src/screens/algo_trading/StrategyBuilderPanel.h+++ b/fincept-qt/src/screens/algo_trading/StrategyBuilderPanel.h@@ -18,6 +18,14 @@#include <QString>#include <QWidget>+// Forward-declare F&O widgets to avoid pulling heavy headers into every TU+// that includes this header.+namespace fincept::ui::algo { class FnoLegRuleEditor; }+namespace fincept::screens::fno {+ class PayoffChartWidget;+ class BuilderAnalyticsRibbon;+}+namespace fincept::screens {class StrategyBuilderPanel : public QWidget {@@ -48,7 +56,8 @@ private slots:void on_backtest_result(const QJsonObject& data);void on_error(const QString& context, const QString& msg);-private:+private: // NOLINT(readability-redundant-access-specifiers) — needed to end private slots: section+ // --- F&O authoring (P2) ---void build_ui();void retranslateUi();void connect_service();@@ -65,12 +74,21 @@ private:// Returns a human-readable error if the strategy is unrunnable, else empty.QString validate() const;+ // F&O section builder + helpers+ void build_fno_section();+ void populate_underlyings();+ void refresh_fno_preview();+ void on_instrument_type_changed();+ QString fno_broker_id() const;+// Top toolbarQLineEdit* name_edit_ = nullptr;QLineEdit* desc_edit_ = nullptr;ui::algo::SymbolSearchCombo* symbol_combo_ = nullptr;QComboBox* timeframe_combo_ = nullptr;QComboBox* template_combo_ = nullptr;+ // Instrument-type selector added by P2.3+ QComboBox* instrument_type_combo_ = nullptr;QPushButton* save_btn_ = nullptr;QPushButton* backtest_btn_ = nullptr;QPushButton* deploy_btn_ = nullptr;@@ -83,6 +101,7 @@ private:ui::algo::RiskManagementPanel* risk_panel_ = nullptr;// Right panel — backtest setup card+ QWidget* bt_setup_card_ = nullptr; // kept so we can show/hide in on_instrument_type_changedQLabel* bt_header_ = nullptr;QLabel* bt_symbol_label_ = nullptr;QLabel* bt_capital_label_ = nullptr;@@ -102,6 +121,14 @@ private:// Inline validation banner shown above the builder when a guard fails.QLabel* validation_banner_ = nullptr;++ // F&O section (hidden for Equity instrument type)+ QWidget* fno_section_ = nullptr;+ QComboBox* underlying_combo_ = nullptr;+ QComboBox* expiry_mode_combo_ = nullptr;+ fincept::ui::algo::FnoLegRuleEditor* leg_editor_ = nullptr;+ fincept::screens::fno::PayoffChartWidget* payoff_chart_ = nullptr;+ fincept::screens::fno::BuilderAnalyticsRibbon* analytics_ribbon_ = nullptr;};} // namespace fincept::screensdiff --git a/fincept-qt/src/screens/equity_trading/EquityBottomPanel.cpp b/fincept-qt/src/screens/equity_trading/EquityBottomPanel.cppindex aab436bc7..d1cc2bb7b 100644--- a/fincept-qt/src/screens/equity_trading/EquityBottomPanel.cpp+++ b/fincept-qt/src/screens/equity_trading/EquityBottomPanel.cpp@@ -444,6 +444,13 @@ void EquityBottomPanel::setup_holdings_tab() {});strip_layout->addWidget(holdings_import_btn_);+ holdings_replicate_btn_ = new QPushButton(tr("REPLICATE → PAPER"));+ holdings_replicate_btn_->setCursor(Qt::PointingHandCursor);+ holdings_replicate_btn_->setStyleSheet(holdings_import_btn_->styleSheet());+ connect(holdings_replicate_btn_, &QPushButton::clicked, this,+ [this]() { emit replicate_portfolio_requested(); });+ strip_layout->addWidget(holdings_replicate_btn_);+v->addWidget(strip);holdings_table_ = new QTableWidget;diff --git a/fincept-qt/src/screens/equity_trading/EquityBottomPanel.h b/fincept-qt/src/screens/equity_trading/EquityBottomPanel.hindex 4a3835ab6..e75245969 100644--- a/fincept-qt/src/screens/equity_trading/EquityBottomPanel.h+++ b/fincept-qt/src/screens/equity_trading/EquityBottomPanel.h@@ -72,6 +72,7 @@ class EquityBottomPanel : public QWidget {void cancel_order_requested(const QString& order_id);void modify_order_requested(const QString& order_id, double new_qty, double new_price);void import_holdings_requested(const QVector<trading::BrokerHolding>& holdings);+ void replicate_portfolio_requested();void cancel_all_orders_requested(const QString& account_id);void close_all_positions_requested(const QString& account_id);// Paper: convert an open position's product in place (MIS -> CNC), identified@@ -165,6 +166,7 @@ class EquityBottomPanel : public QWidget {QLabel* holdings_pnl_caption_ = nullptr;QLabel* holdings_pnl_pct_caption_ = nullptr;class QPushButton* holdings_import_btn_ = nullptr;+ class QPushButton* holdings_replicate_btn_ = nullptr;QVector<trading::BrokerHolding> last_holdings_;QTableWidget* orders_table_ = nullptr;QDateEdit* orders_date_edit_ = nullptr; // per-day order book selectordiff --git a/fincept-qt/src/screens/equity_trading/EquityTradingScreen.cpp b/fincept-qt/src/screens/equity_trading/EquityTradingScreen.cppindex 370bf5af9..86594d8cb 100644--- a/fincept-qt/src/screens/equity_trading/EquityTradingScreen.cpp+++ b/fincept-qt/src/screens/equity_trading/EquityTradingScreen.cpp@@ -27,6 +27,7 @@#include "screens/equity_trading/EquityWatchlist.h"#include "screens/common/feeds/FeedPanel.h"#include "services/feeds/FeedMonitor.h"+#include "screens/equity_trading/PortfolioReplicationDialog.h"#include "services/portfolio/PortfolioService.h"#include "storage/repositories/SettingsRepository.h"#include "trading/AccountManager.h"@@ -431,6 +432,8 @@ void EquityTradingScreen::setup_ui() {connect(bottom_panel_, &EquityBottomPanel::close_all_positions_requested, this,[this](const QString&) { on_close_all_positions(); });connect(bottom_panel_, &EquityBottomPanel::import_holdings_requested, this, &EquityTradingScreen::on_import_holdings_requested);+ connect(bottom_panel_, &EquityBottomPanel::replicate_portfolio_requested, this,+ &EquityTradingScreen::on_replicate_portfolio_requested);connect(bottom_panel_, &EquityBottomPanel::convert_position_requested, this,&EquityTradingScreen::on_convert_position);connect(bottom_panel_, &EquityBottomPanel::orders_day_changed, this, &EquityTradingScreen::on_orders_day_changed);@@ -833,4 +836,12 @@ void EquityTradingScreen::restore_state(const QVariantMap& state) {load_watchlists();}+void EquityTradingScreen::on_replicate_portfolio_requested() {+ fincept::screens::PortfolioReplicationDialog dlg(this);+ dlg.exec();+ // Reflect any new paper positions/holdings/funds in the panels. Safe to call+ // unconditionally — it no-ops unless the focused account is paper.+ refresh_paper_panels();+}+} // namespace fincept::screensdiff --git a/fincept-qt/src/screens/equity_trading/EquityTradingScreen.h b/fincept-qt/src/screens/equity_trading/EquityTradingScreen.hindex 04d2501fc..bc8f7b8b9 100644--- a/fincept-qt/src/screens/equity_trading/EquityTradingScreen.h+++ b/fincept-qt/src/screens/equity_trading/EquityTradingScreen.h@@ -82,6 +82,8 @@ class EquityTradingScreen : public QWidget, public IGroupLinked, public IStatefuvoid on_strategy_submitted(const trading::BasketOrderRequest& basket); // options strategy → basketvoid on_ob_price_clicked(double price);void on_import_holdings_requested(const QVector<trading::BrokerHolding>& holdings);+ // Replicate a source account's portfolio into a paper account (opens dialog).+ void on_replicate_portfolio_requested();// Paper: convert a position's product in place (MIS -> CNC) then refresh.void on_convert_position(const QString& position_id, const QString& symbol, const QString& new_product);// Orders tab date-selector changed — show that IST day's paper order book.diff --git a/fincept-qt/src/screens/equity_trading/PortfolioReplicationDialog.cpp b/fincept-qt/src/screens/equity_trading/PortfolioReplicationDialog.cppnew file mode 100644index 000000000..756ecdf04--- /dev/null+++ b/fincept-qt/src/screens/equity_trading/PortfolioReplicationDialog.cpp@@ -0,0 +1,330 @@+#include "screens/equity_trading/PortfolioReplicationDialog.h"++#include "trading/AccountManager.h"+#include "trading/BrokerRegistry.h"+#include "trading/PaperTrading.h"+#include "trading/instruments/InstrumentService.h"+#include "ui/theme/Theme.h"++#include <QComboBox>+#include <QCheckBox>+#include <QTableWidget>+#include <QHeaderView>+#include <QLabel>+#include <QPushButton>+#include <QProgressBar>+#include <QVBoxLayout>+#include <QHBoxLayout>+#include <QFormLayout>+#include <QMessageBox>+#include <QPointer>+#include <QtConcurrent>++#include <cmath>++using namespace fincept::trading;+using namespace fincept::trading::replication;++namespace fincept::screens {++namespace {+QString fmt_money(double v) { return QStringLiteral("₹%L1").arg(v, 0, 'f', 2); }+} // namespace++PortfolioReplicationDialog::PortfolioReplicationDialog(QWidget* parent) : QDialog(parent) {+ setWindowTitle(tr("Replicate Portfolio → Paper"));+ setMinimumSize(820, 560);++ auto* root = new QVBoxLayout(this);++ // ── Pickers ──+ auto* form = new QFormLayout;+ source_combo_ = new QComboBox;+ target_combo_ = new QComboBox;+ form->addRow(tr("Source account"), source_combo_);+ form->addRow(tr("Target (paper)"), target_combo_);+ root->addLayout(form);++ // ── Scope toggles ──+ auto* scope = new QHBoxLayout;+ inc_holdings_ = new QCheckBox(tr("Holdings"));+ inc_positions_ = new QCheckBox(tr("Positions"));+ inc_holdings_->setChecked(true);+ inc_positions_->setChecked(true);+ scope->addWidget(new QLabel(tr("Include:")));+ scope->addWidget(inc_holdings_);+ scope->addWidget(inc_positions_);+ scope->addStretch(1);+ root->addLayout(scope);++ // ── Preview table ──+ table_ = new QTableWidget;+ table_->setColumnCount(8);+ table_->setHorizontalHeaderLabels({tr(""), tr("Type"), tr("Source"), tr("Target"),+ tr("Side"), tr("Qty"), tr("Est Price"), tr("Est Value / Note")});+ table_->horizontalHeader()->setStretchLastSection(true);+ table_->verticalHeader()->setVisible(false);+ table_->setEditTriggers(QAbstractItemView::NoEditTriggers);+ root->addWidget(table_, 1);++ // ── Footer (capital) ──+ auto* foot = new QHBoxLayout;+ footer_ = new QLabel;+ topup_btn_ = new QPushButton(tr("Top up paper balance"));+ topup_btn_->setEnabled(false);+ foot->addWidget(footer_, 1);+ foot->addWidget(topup_btn_);+ root->addLayout(foot);++ progress_ = new QProgressBar;+ progress_->setVisible(false);+ root->addWidget(progress_);+ status_ = new QLabel;+ root->addWidget(status_);++ // ── Buttons ──+ auto* btns = new QHBoxLayout;+ btns->addStretch(1);+ auto* cancel = new QPushButton(tr("Close"));+ replicate_btn_ = new QPushButton(tr("REPLICATE"));+ replicate_btn_->setStyleSheet(+ QString("QPushButton{background:%1;color:%2;border:1px solid %3;padding:6px 18px;"+ "font-weight:700;letter-spacing:0.5px;}QPushButton:hover{background:%2;color:#000;}"+ "QPushButton:disabled{color:%4;}")+ .arg(fincept::ui::colors::PANEL(), fincept::ui::colors::ORANGE(),+ fincept::ui::colors::BORDER(), fincept::ui::colors::TEXT_SECONDARY()));+ btns->addWidget(cancel);+ btns->addWidget(replicate_btn_);+ root->addLayout(btns);++ connect(cancel, &QPushButton::clicked, this, &QDialog::reject);+ connect(replicate_btn_, &QPushButton::clicked, this, &PortfolioReplicationDialog::do_replicate);+ connect(topup_btn_, &QPushButton::clicked, this, &PortfolioReplicationDialog::do_top_up);+ connect(source_combo_, qOverload<int>(&QComboBox::currentIndexChanged), this, &PortfolioReplicationDialog::reload_plan);+ connect(target_combo_, qOverload<int>(&QComboBox::currentIndexChanged), this, &PortfolioReplicationDialog::reload_plan);+ connect(inc_holdings_, &QCheckBox::toggled, this, &PortfolioReplicationDialog::reload_plan);+ connect(inc_positions_, &QCheckBox::toggled, this, &PortfolioReplicationDialog::reload_plan);++ populate_accounts();+}++void PortfolioReplicationDialog::populate_accounts() {+ source_combo_->blockSignals(true);+ target_combo_->blockSignals(true);+ source_combo_->clear();+ target_combo_->clear();+ for (const auto& a : AccountManager::instance().list_accounts()) {+ if (!a.is_active)+ continue;+ const QString label = QStringLiteral("%1 (%2)").arg(a.display_name, a.trading_mode);+ source_combo_->addItem(label, a.account_id);+ if (a.trading_mode == QStringLiteral("paper") && !a.paper_portfolio_id.isEmpty())+ target_combo_->addItem(a.display_name, a.account_id);+ }+ source_combo_->blockSignals(false);+ target_combo_->blockSignals(false);++ if (target_combo_->count() == 0) {+ status_->setText(tr("No paper accounts found. Create one via ACCOUNTS first."));+ replicate_btn_->setEnabled(false);+ }+ reload_plan();+}++ReplicationOptions PortfolioReplicationDialog::current_options() const {+ return {inc_holdings_->isChecked(), inc_positions_->isChecked()};+}++void PortfolioReplicationDialog::reload_plan() {+ if (loading_)+ return;+ const QString src_id = source_combo_->currentData().toString();+ const QString tgt_id = target_combo_->currentData().toString();+ if (src_id.isEmpty() || tgt_id.isEmpty())+ return;++ source_items_.clear();+ table_->setRowCount(0);+ status_->setText(tr("Loading source portfolio…"));++ const auto src = AccountManager::instance().get_account(src_id);+ const auto tgt = AccountManager::instance().get_account(tgt_id);++ // Make sure both brokers' instruments are available for symbol mapping.+ InstrumentService::instance().load_from_db(src.broker_id);+ InstrumentService::instance().load_from_db(tgt.broker_id);++ if (src.trading_mode == QStringLiteral("paper")) {+ apply_items(paper_source_items(src.paper_portfolio_id), QString());+ return;+ }++ // Live source: load creds on GUI thread, fetch on a worker, deliver back.+ auto creds = AccountManager::instance().load_credentials(src_id);+ if (creds.api_key.isEmpty()) {+ apply_items({}, tr("No credentials for source account"));+ return;+ }+ loading_ = true;+ const QString bid = src.broker_id;+ QPointer<PortfolioReplicationDialog> self = this;+ (void)QtConcurrent::run([self, bid, creds]() {+ auto* broker = BrokerRegistry::instance().get(bid);+ QVector<BrokerHolding> holdings;+ QVector<BrokerPosition> positions;+ QString err;+ if (broker) {+ auto h = broker->get_holdings(creds);+ if (h.success && h.data)+ holdings = *h.data;+ auto p = broker->get_positions(creds);+ if (p.success && p.data)+ positions = *p.data;+ if (!h.success && !p.success)+ err = h.error.isEmpty() ? p.error : h.error;+ } else {+ err = QStringLiteral("Broker unavailable");+ }+ auto items = to_source_items(holdings, positions);+ QMetaObject::invokeMethod(self, [self, items, err]() {+ if (!self)+ return;+ self->loading_ = false;+ self->apply_items(items, err);+ }, Qt::QueuedConnection);+ });+}++void PortfolioReplicationDialog::apply_items(const QVector<SourceItem>& items, const QString& error) {+ source_items_ = items;+ if (!error.isEmpty())+ status_->setText(error);+ else if (items.isEmpty())+ status_->setText(tr("Source account has no holdings or positions."));+ else+ status_->clear();+ fill_table();+}++void PortfolioReplicationDialog::fill_table() {+ const QString src_id = source_combo_->currentData().toString();+ const QString tgt_id = target_combo_->currentData().toString();+ const auto src = AccountManager::instance().get_account(src_id);+ const auto tgt = AccountManager::instance().get_account(tgt_id);++ double available = 0.0;+ if (!tgt.paper_portfolio_id.isEmpty()) {+ try {+ available = pt_get_portfolio(tgt.paper_portfolio_id).balance;+ } catch (...) {+ }+ }++ plan_ = build_plan(source_items_, current_options(), available, src_id, tgt_id,+ tgt.paper_portfolio_id, make_instrument_resolver(src.broker_id, tgt.broker_id));++ table_->setRowCount(plan_.orders.size());+ for (int row = 0; row < plan_.orders.size(); ++row) {+ const auto& po = plan_.orders[row];+ auto* chk = new QTableWidgetItem;+ chk->setFlags(Qt::ItemIsUserCheckable | Qt::ItemIsEnabled);+ chk->setCheckState(po.included ? Qt::Checked : Qt::Unchecked);+ table_->setItem(row, 0, chk);+ table_->setItem(row, 1, new QTableWidgetItem(po.kind == ItemKind::Holding ? tr("Holding") : tr("Position")));+ table_->setItem(row, 2, new QTableWidgetItem(po.src_symbol));+ table_->setItem(row, 3, new QTableWidgetItem(po.norm_symbol));+ table_->setItem(row, 4, new QTableWidgetItem(po.side.toUpper()));+ table_->setItem(row, 5, new QTableWidgetItem(QString::number(po.quantity, 'f', 0)));+ table_->setItem(row, 6, new QTableWidgetItem(QString::number(po.est_price, 'f', 2)));+ table_->setItem(row, 7, new QTableWidgetItem(po.warning.isEmpty() ? fmt_money(po.est_value) : po.warning));+ }++ // Re-derive included flags from checkboxes whenever the user toggles a row.+ disconnect(table_, &QTableWidget::itemChanged, nullptr, nullptr);+ connect(table_, &QTableWidget::itemChanged, this, [this](QTableWidgetItem* it) {+ if (it->column() != 0 || it->row() >= plan_.orders.size())+ return;+ plan_.orders[it->row()].included = (it->checkState() == Qt::Checked);+ recompute_footer();+ });++ recompute_footer();+}++void PortfolioReplicationDialog::recompute_footer() {+ double required = 0.0;+ int n = 0;+ for (const auto& po : plan_.orders)+ if (po.included) {+ required += po.est_value;+ ++n;+ }+ plan_.required_capital = required;+ const double avail = plan_.target_available;+ footer_->setText(tr("%1 stock(s) selected • Required %2 vs Paper available %3")+ .arg(n)+ .arg(fmt_money(required))+ .arg(fmt_money(avail)));+ const bool short_cash = required > avail;+ topup_btn_->setEnabled(short_cash && !plan_.target_paper_portfolio_id.isEmpty());+ topup_btn_->setText(short_cash ? tr("Top up paper balance to %1").arg(fmt_money(required))+ : tr("Top up paper balance"));+ replicate_btn_->setEnabled(n > 0);+}++void PortfolioReplicationDialog::do_top_up() {+ if (plan_.target_paper_portfolio_id.isEmpty())+ return;+ try {+ pt_set_balance(plan_.target_paper_portfolio_id, plan_.required_capital);+ plan_.target_available = plan_.required_capital;+ recompute_footer();+ status_->setText(tr("Paper balance set to %1").arg(fmt_money(plan_.required_capital)));+ } catch (const std::exception& e) {+ QMessageBox::warning(this, tr("Top up failed"), QString::fromUtf8(e.what()));+ }+}++void PortfolioReplicationDialog::do_replicate() {+ int n = 0;+ for (const auto& po : plan_.orders)+ if (po.included)+ ++n;+ if (n == 0)+ return;++ const auto ans = QMessageBox::question(+ this, tr("Confirm replication"),+ tr("Place %1 paper order(s) into the target account?\nThis is paper trading — no real money.").arg(n),+ QMessageBox::Yes | QMessageBox::No);+ if (ans != QMessageBox::Yes)+ return;++ progress_->setVisible(true);+ progress_->setRange(0, n);+ progress_->setValue(0);+ replicate_btn_->setEnabled(false);++ // GUI-thread execution (paper engine is not proven thread-safe off-main).+ ReplicationResult res = execute_plan(plan_);+ progress_->setValue(n);++ status_->setText(tr("Placed %1 • Failed %2 • Skipped %3")+ .arg(res.placed)+ .arg(res.failed)+ .arg(res.skipped));++ QString detail;+ for (const auto& r : res.rows)+ if (!r.ok && !r.error.isEmpty())+ detail += QStringLiteral("• %1: %2\n").arg(r.symbol, r.error);+ if (!detail.isEmpty())+ QMessageBox::information(this, tr("Replication results"),+ tr("Placed %1, failed %2, skipped %3.\n\n%4")+ .arg(res.placed).arg(res.failed).arg(res.skipped).arg(detail));++ replicate_btn_->setEnabled(true);+ reload_plan(); // refresh against new paper balance/positions+}++} // namespace fincept::screensdiff --git a/fincept-qt/src/screens/equity_trading/PortfolioReplicationDialog.h b/fincept-qt/src/screens/equity_trading/PortfolioReplicationDialog.hnew file mode 100644index 000000000..2f751ed48--- /dev/null+++ b/fincept-qt/src/screens/equity_trading/PortfolioReplicationDialog.h@@ -0,0 +1,53 @@+#pragma once+#include "trading/replication/PortfolioReplicationService.h"++#include <QDialog>+#include <QVector>++class QComboBox;+class QCheckBox;+class QTableWidget;+class QLabel;+class QPushButton;+class QProgressBar;++namespace fincept::screens {++// Replicate a source broker account's portfolio into a PAPER account as exact+// 1:1 orders. Target list is paper-only by construction. Shows every stock to be+// bought for confirmation, with a one-click paper-cash top-up when a large source+// portfolio exceeds the sandbox balance.+class PortfolioReplicationDialog : public QDialog {+ Q_OBJECT+ public:+ explicit PortfolioReplicationDialog(QWidget* parent = nullptr);++ private slots:+ void reload_plan(); // (re)fetch source + rebuild table for current pickers+ void recompute_footer(); // update required/available + top-up enablement+ void do_top_up();+ void do_replicate();++ private:+ void populate_accounts();+ void apply_items(const QVector<trading::replication::SourceItem>& items, const QString& error);+ void fill_table();+ trading::replication::ReplicationOptions current_options() const;++ QComboBox* source_combo_ = nullptr;+ QComboBox* target_combo_ = nullptr;+ QCheckBox* inc_holdings_ = nullptr;+ QCheckBox* inc_positions_ = nullptr;+ QTableWidget* table_ = nullptr;+ QLabel* footer_ = nullptr;+ QPushButton* topup_btn_ = nullptr;+ QPushButton* replicate_btn_ = nullptr;+ QProgressBar* progress_ = nullptr;+ QLabel* status_ = nullptr;++ QVector<trading::replication::SourceItem> source_items_;+ trading::replication::ReplicationPlan plan_;+ bool loading_ = false;+};++} // namespace fincept::screensdiff --git a/fincept-qt/src/services/options/OptionChainService.cpp b/fincept-qt/src/services/options/OptionChainService.cppindex a1143613d..12d84c242 100644--- a/fincept-qt/src/services/options/OptionChainService.cpp+++ b/fincept-qt/src/services/options/OptionChainService.cpp@@ -920,6 +920,24 @@ void OptionChainService::publish_per_leg_ticks(const OptionChain& chain) {LOG_DEBUG("OptionChain", QString("Per-leg tick fan-out: %1 publishes").arg(published));}+// ── Pin contracts ──────────────────────────────────────────────────────────++void OptionChainService::pin_contracts(const QString& topic, const QStringList& symbols) {+ if (symbols.isEmpty())+ pinned_contracts_.remove(topic);+ else+ pinned_contracts_[topic] = symbols;++ // If this is the currently-streamed topic, re-arm the stream so the newly+ // pinned symbols are subscribed immediately without waiting for next REST refresh.+ if (!ws_topic_.isEmpty() && ws_topic_ == topic && !last_chain_.rows.isEmpty()) {+ maybe_start_ws_stream(last_chain_, topic);+ } else {+ LOG_DEBUG("OptionChain", QString("pin_contracts: stored %1 pin(s) for %2 (applies at next WS refresh)")+ .arg(symbols.size()).arg(topic));+ }+}+// ── WS-first live streaming ────────────────────────────────────────────────bool OptionChainService::ws_feed_fresh(const QString& topic) const {@@ -986,6 +1004,14 @@ void OptionChainService::maybe_start_ws_stream(const OptionChain& chain, const Qreturn;}+ // Union in any extra symbols pinned by the algo engine (e.g. specific legs+ // for an active deployment). When nothing is pinned, sub_syms is unchanged.+ const QStringList& pins = pinned_contracts_.value(topic);+ for (const QString& pin : pins) {+ if (!pin.isEmpty() && !sub_syms.contains(pin))+ sub_syms.append(pin);+ }+ws_topic_ = topic;ws_account_id_ = account_id;ws_sym_token_ = sym_token;diff --git a/fincept-qt/src/services/options/OptionChainService.h b/fincept-qt/src/services/options/OptionChainService.hindex d328fb830..41d3171c7 100644--- a/fincept-qt/src/services/options/OptionChainService.h+++ b/fincept-qt/src/services/options/OptionChainService.h@@ -69,6 +69,13 @@ class OptionChainService : public QObject, public fincept::datahub::Producer {/// Async expiry fetch for Databento — calls Python script, caches result.void list_databento_expiries(const QString& underlying, std::function<void(QStringList)> callback);+ /// Pin extra contract symbols into the live WS subscription window for a chain+ /// topic. Replaces any prior pin set for that topic; an empty list clears pins.+ /// Call from the main thread only.+ void pin_contracts(const QString& topic, const QStringList& symbols);+ /// Returns the currently-pinned symbols for `topic` (empty when no pins set).+ QStringList pinned_contracts_for(const QString& topic) const { return pinned_contracts_.value(topic); }+signals:/// Emitted alongside the hub publish so callers can connect via Qt/// signals if they prefer that to subscribing on the hub.@@ -160,6 +167,9 @@ class OptionChainService : public QObject, public fincept::datahub::Producer {fincept::services::options::OptionChain last_chain_;bool hub_registered_ = false;+ /// Extra symbols pinned per topic (e.g. by FnoDataBridge for algo legs).+ /// Unioned into the WS subscription set inside maybe_start_ws_stream.+ QHash<QString, QStringList> pinned_contracts_;/// In-flight guard per topic to avoid duplicate refresh fan-out when the/// hub scheduler races with a manual request.QHash<QString, bool> in_flight_;diff --git a/fincept-qt/src/storage/sqlite/migrations/MigrationRunner.h b/fincept-qt/src/storage/sqlite/migrations/MigrationRunner.hindex 70c1eb15f..e372ae921 100644--- a/fincept-qt/src/storage/sqlite/migrations/MigrationRunner.h+++ b/fincept-qt/src/storage/sqlite/migrations/MigrationRunner.h@@ -93,5 +93,6 @@ void register_migration_v043();void register_migration_v044();void register_migration_v045();void register_migration_v046();+void register_migration_v047();} // namespace finceptdiff --git a/fincept-qt/src/storage/sqlite/migrations/v047_algo_multileg_trades.cpp b/fincept-qt/src/storage/sqlite/migrations/v047_algo_multileg_trades.cppnew file mode 100644index 000000000..6c1f8bc03--- /dev/null+++ b/fincept-qt/src/storage/sqlite/migrations/v047_algo_multileg_trades.cpp@@ -0,0 +1,49 @@+// v047_algo_multileg_trades — adds per-leg columns to algo_trades so a multi-leg+// F&O basket fill records one trade row per leg (leg_symbol = broker-native+// contract, leg_index = its slot in the basket). Both default to the equity+// behavior (empty / -1), so existing rows and the single-symbol path are+// unaffected. Idempotent on re-run (ignores the duplicate-column error, matching+// v044/v045/v046). See docs/superpowers/plans/2026-06-08-fno-algo-p3-execution.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_v047(QSqlDatabase& db) {+ const char* stmts[] = {+ "ALTER TABLE algo_trades ADD COLUMN leg_symbol TEXT NOT NULL DEFAULT ''",+ "ALTER TABLE algo_trades ADD COLUMN leg_index INTEGER NOT NULL DEFAULT -1",+ };+ 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_v047() {+ static bool done = false;+ if (done)+ return;+ done = true;+ MigrationRunner::register_migration({47, "algo_multileg_trades", apply_v047});+}++} // namespace finceptdiff --git a/fincept-qt/src/trading/PaperTrading.cpp b/fincept-qt/src/trading/PaperTrading.cppindex ec5502a96..4706d6043 100644--- a/fincept-qt/src/trading/PaperTrading.cpp+++ b/fincept-qt/src/trading/PaperTrading.cpp@@ -213,6 +213,14 @@ PtPortfolio pt_get_portfolio(const QString& id) {return r.value();}+void pt_set_balance(const QString& portfolio_id, double new_balance) {+ if (!std::isfinite(new_balance) || new_balance < 0.0)+ throw std::runtime_error("Invalid balance: must be finite and non-negative");+ auto r = repo().update_balance(portfolio_id, new_balance);+ if (r.is_err())+ throw std::runtime_error(r.error());+}+std::optional<PtPortfolio> pt_find_portfolio(const QString& name, const QString& exchange) {return repo().find_portfolio(name, exchange);}diff --git a/fincept-qt/src/trading/PaperTrading.h b/fincept-qt/src/trading/PaperTrading.hindex 2c4c5f10f..64f867885 100644--- a/fincept-qt/src/trading/PaperTrading.h+++ b/fincept-qt/src/trading/PaperTrading.h@@ -21,6 +21,12 @@ QVector<PtPortfolio> pt_list_portfolios(const QString& exchange = "");void pt_delete_portfolio(const QString& id);PtPortfolio pt_reset_portfolio(const QString& id);+// Set a paper portfolio's available cash directly (fake money). Used by the+// portfolio-replication "top up" action so an exact 1:1 copy of a large source+// portfolio always has enough simulated cash to fill. Persists immediately.+// Throws std::runtime_error on a non-finite/negative amount or DB error.+void pt_set_balance(const QString& portfolio_id, double new_balance);+// --- Leverage / Margin config (Phase 3 §4) ---// Per-portfolio leverage rules + market-hours enforcement live in an in-memory// config map (the existing pt_portfolios schema has no columns for them, and wediff --git a/fincept-qt/src/trading/replication/PortfolioReplicationSelftest.cpp b/fincept-qt/src/trading/replication/PortfolioReplicationSelftest.cppnew file mode 100644index 000000000..b88d8d0f9--- /dev/null+++ b/fincept-qt/src/trading/replication/PortfolioReplicationSelftest.cpp@@ -0,0 +1,76 @@+#include "trading/replication/PortfolioReplicationSelftest.h"++#include "trading/replication/PortfolioReplicationService.h"++#include <cmath>+#include <cstdio>++namespace fincept::trading::replication {++namespace {+bool approx(double a, double b, double eps = 0.01) { return std::fabs(a - b) <= eps; }+} // namespace++int run_portfolio_replication_selftest() {+ int failures = 0;+ auto check = [&](const char* label, bool ok) {+ std::printf("[%s] %s\n", ok ? "PASS" : "FAIL", label);+ if (!ok)+ ++failures;+ };++ // Synthetic source: 1 holding, 1 short MIS position, 1 unmappable holding.+ QVector<SourceItem> items;+ items.push_back({ItemKind::Holding, "RELIANCE", "NSE", "", "", 10, 2400, 2500});+ items.push_back({ItemKind::Position, "TCS", "NSE", "MIS", "SHORT", 5, 3500, 3600});+ items.push_back({ItemKind::Holding, "UNKNOWNX", "NSE", "", "", 3, 100, 110});++ // Resolver: identity-normalize, but UNKNOWNX is not tradable on target.+ SymbolResolver resolver = [](const QString& s, const QString&) -> ResolveResult {+ if (s == QStringLiteral("UNKNOWNX"))+ return {false, s};+ return {true, s};+ };++ ReplicationOptions both; // include_holdings + include_positions both true+ auto plan = build_plan(items, both, /*target_available=*/100000.0,+ "srcAcct", "tgtAcct", "tgtPortfolio", resolver);++ check("emits one row per in-scope item", plan.orders.size() == 3);++ const auto& r0 = plan.orders[0]; // RELIANCE holding+ check("holding -> buy", r0.side == QStringLiteral("buy"));+ check("holding -> CNC", r0.product == QStringLiteral("CNC"));+ check("quantity is exact 1:1", approx(r0.quantity, 10));+ check("est_value = qty*ltp", approx(r0.est_value, 25000.0)); // 10 * 2500+ check("mapped holding included", r0.included && r0.mapped);++ const auto& r1 = plan.orders[1]; // TCS short MIS+ check("short position -> sell", r1.side == QStringLiteral("sell"));+ check("position keeps product MIS", r1.product == QStringLiteral("MIS"));++ const auto& r2 = plan.orders[2]; // UNKNOWNX+ check("unmapped flagged", !r2.mapped);+ check("unmapped unchecked", !r2.included);+ check("unmapped has warning", !r2.warning.isEmpty());++ // required_capital counts included rows only: 25000 (RELIANCE) + 18000 (TCS).+ check("required_capital excludes unmapped", approx(plan.required_capital, 43000.0));++ // Scope toggle: holdings only → positions dropped entirely.+ ReplicationOptions holdings_only{true, false};+ auto plan2 = build_plan(items, holdings_only, 100000.0, "s", "t", "p", resolver);+ check("holdings-only drops positions", plan2.orders.size() == 2);+ bool any_pos = false;+ for (const auto& o : plan2.orders)+ if (o.kind == ItemKind::Position)+ any_pos = true;+ check("holdings-only has no position rows", !any_pos);++ std::printf(failures == 0 ? "\nportfolio-replication selftest: ALL PASS\n"+ : "\nportfolio-replication selftest: %d FAILURE(S)\n",+ failures);+ return failures == 0 ? 0 : 1;+}++} // namespace fincept::trading::replicationdiff --git a/fincept-qt/src/trading/replication/PortfolioReplicationSelftest.h b/fincept-qt/src/trading/replication/PortfolioReplicationSelftest.hnew file mode 100644index 000000000..0c87fc2a5--- /dev/null+++ b/fincept-qt/src/trading/replication/PortfolioReplicationSelftest.h@@ -0,0 +1,6 @@+#pragma once+namespace fincept::trading::replication {+// Headless self-test for the pure replication planner. No GUI / DB / network /+// API keys. Returns 0 on success, 1 on any failed assertion.+int run_portfolio_replication_selftest();+}diff --git a/fincept-qt/src/trading/replication/PortfolioReplicationService.cpp b/fincept-qt/src/trading/replication/PortfolioReplicationService.cppnew file mode 100644index 000000000..9348efec1--- /dev/null+++ b/fincept-qt/src/trading/replication/PortfolioReplicationService.cpp@@ -0,0 +1,178 @@+#include "trading/replication/PortfolioReplicationService.h"++#include "trading/PaperTrading.h"+#include "trading/instruments/InstrumentService.h"++#include <cmath>++namespace fincept::trading::replication {++namespace {++bool is_delivery_product(const QString& product) {+ // CNC = equity delivery. (NRML/MIS stay on the Positions side.)+ return product.compare(QStringLiteral("CNC"), Qt::CaseInsensitive) == 0;+}++bool is_short_side(const QString& side) {+ return side.compare(QStringLiteral("short"), Qt::CaseInsensitive) == 0 ||+ side.compare(QStringLiteral("sell"), Qt::CaseInsensitive) == 0;+}++} // namespace++QVector<SourceItem> to_source_items(const QVector<BrokerHolding>& holdings,+ const QVector<BrokerPosition>& positions) {+ QVector<SourceItem> out;+ out.reserve(holdings.size() + positions.size());+ for (const auto& h : holdings) {+ SourceItem s;+ s.kind = ItemKind::Holding;+ s.src_symbol = h.symbol;+ s.exchange = h.exchange;+ s.quantity = h.quantity;+ s.avg_price = h.avg_price;+ s.ltp = h.ltp > 0 ? h.ltp : h.avg_price;+ out.push_back(s);+ }+ for (const auto& p : positions) {+ if (p.quantity == 0)+ continue; // closed/net-flat intraday legs+ SourceItem s;+ s.kind = ItemKind::Position;+ s.src_symbol = p.symbol;+ s.exchange = p.exchange;+ s.product = p.product_type.isEmpty() ? QStringLiteral("MIS") : p.product_type;+ s.side = p.side;+ s.quantity = std::fabs(p.quantity);+ s.avg_price = p.avg_price;+ s.ltp = p.ltp > 0 ? p.ltp : p.avg_price;+ out.push_back(s);+ }+ return out;+}++QVector<SourceItem> paper_source_items(const QString& portfolio_id) {+ QVector<SourceItem> out;+ for (const auto& p : pt_get_positions(portfolio_id)) {+ if (p.quantity == 0)+ continue;+ SourceItem s;+ s.src_symbol = p.symbol;+ s.exchange = QStringLiteral("NSE"); // paper positions carry no exchange column+ s.quantity = std::fabs(p.quantity);+ s.avg_price = p.entry_price;+ s.ltp = p.current_price > 0 ? p.current_price : p.entry_price;+ if (is_delivery_product(p.product)) {+ s.kind = ItemKind::Holding;+ } else {+ s.kind = ItemKind::Position;+ s.product = p.product.isEmpty() ? QStringLiteral("MIS") : p.product;+ s.side = p.side;+ }+ out.push_back(s);+ }+ return out;+}++ReplicationPlan build_plan(const QVector<SourceItem>& items,+ const ReplicationOptions& opts,+ double target_available,+ const QString& source_account_id,+ const QString& target_account_id,+ const QString& target_paper_portfolio_id,+ const SymbolResolver& resolve) {+ ReplicationPlan plan;+ plan.source_account_id = source_account_id;+ plan.target_account_id = target_account_id;+ plan.target_paper_portfolio_id = target_paper_portfolio_id;+ plan.target_available = target_available;++ for (const auto& item : items) {+ if (item.kind == ItemKind::Holding && !opts.include_holdings)+ continue;+ if (item.kind == ItemKind::Position && !opts.include_positions)+ continue;++ PlannedOrder po;+ po.kind = item.kind;+ po.src_symbol = item.src_symbol;+ po.exchange = item.exchange.isEmpty() ? QStringLiteral("NSE") : item.exchange;+ po.quantity = std::floor(item.quantity); // whole shares+ po.est_price = item.ltp > 0 ? item.ltp : item.avg_price;+ po.est_value = po.quantity * po.est_price;++ if (item.kind == ItemKind::Holding) {+ po.side = QStringLiteral("buy");+ po.product = QStringLiteral("CNC");+ } else {+ po.side = is_short_side(item.side) ? QStringLiteral("sell") : QStringLiteral("buy");+ po.product = item.product.isEmpty() ? QStringLiteral("MIS") : item.product;+ }++ ResolveResult r = resolve ? resolve(item.src_symbol, po.exchange) : ResolveResult{true, item.src_symbol};+ po.norm_symbol = r.norm_symbol.isEmpty() ? item.src_symbol : r.norm_symbol;+ po.mapped = r.tradable_on_target;++ if (!po.mapped) {+ po.warning = QStringLiteral("not tradable on target broker");+ po.included = false;+ } else if (po.quantity <= 0) {+ po.warning = QStringLiteral("zero quantity after rounding");+ po.included = false;+ } else if (po.est_price <= 0) {+ po.warning = QStringLiteral("no price available");+ po.included = false;+ } else {+ po.included = true;+ }++ if (po.included)+ plan.required_capital += po.est_value;+ plan.orders.push_back(po);+ }+ return plan;+}++SymbolResolver make_instrument_resolver(const QString& source_broker_id,+ const QString& target_broker_id) {+ return [source_broker_id, target_broker_id](const QString& src_symbol,+ const QString& exchange) -> ResolveResult {+ auto& svc = InstrumentService::instance();+ // 1) source brsymbol → canonical normalized symbol (fallback: as-is)+ QString norm = src_symbol;+ if (auto n = svc.from_brsymbol(src_symbol, exchange, source_broker_id))+ norm = *n;+ // 2) tradable on the target broker? (also rules out cross-broker symbol gaps)+ bool tradable = svc.find(norm, exchange, target_broker_id).has_value();+ return ResolveResult{tradable, norm};+ };+}++ReplicationResult execute_plan(const ReplicationPlan& plan) {+ ReplicationResult res;+ for (const auto& po : plan.orders) {+ if (!po.included) {+ ++res.skipped;+ res.rows.push_back({po.norm_symbol, false, po.warning.isEmpty() ? QStringLiteral("skipped") : po.warning});+ continue;+ }+ try {+ std::optional<double> price_opt;+ if (po.est_price > 0)+ price_opt = po.est_price; // market reference price for margin calc+ auto ord = pt_place_order(plan.target_paper_portfolio_id, po.norm_symbol, po.side,+ QStringLiteral("market"), po.quantity, price_opt, std::nullopt,+ /*reduce_only=*/false, po.exchange, po.product);+ pt_fill_order(ord.id, po.est_price);+ ++res.placed;+ res.rows.push_back({po.norm_symbol, true, QString()});+ } catch (const std::exception& e) {+ ++res.failed;+ res.rows.push_back({po.norm_symbol, false, QString::fromUtf8(e.what())});+ }+ }+ return res;+}++} // namespace fincept::trading::replicationdiff --git a/fincept-qt/src/trading/replication/PortfolioReplicationService.h b/fincept-qt/src/trading/replication/PortfolioReplicationService.hnew file mode 100644index 000000000..928aee59b--- /dev/null+++ b/fincept-qt/src/trading/replication/PortfolioReplicationService.h@@ -0,0 +1,104 @@+#pragma once+// Portfolio Replication — copy a source account's holdings/positions into a+// PAPER account as exact 1:1 orders. Core is UI-independent and testable:+// build_plan() is pure (no network/DB/GUI) via an injected SymbolResolver.++#include "trading/BrokerAccount.h"+#include "trading/TradingTypes.h"++#include <QString>+#include <QVector>++#include <functional>+#include <optional>++namespace fincept::trading::replication {++enum class ItemKind { Holding, Position };++// A normalized view of one source holding or position.+struct SourceItem {+ ItemKind kind = ItemKind::Holding;+ QString src_symbol; // broker-native symbol from get_holdings/get_positions+ QString exchange; // "NSE"/"BSE"/"NFO"... ("" → treated as NSE)+ QString product; // "" for holdings; "MIS"/"CNC"/"NRML" for positions+ QString side; // "" for holdings; "long"/"short"/"LONG"/"SHORT" for positions+ double quantity = 0;+ double avg_price = 0;+ double ltp = 0;+};++// One planned paper order. Strings (side/product) match pt_place_order directly.+struct PlannedOrder {+ ItemKind kind = ItemKind::Holding;+ QString src_symbol;+ QString norm_symbol; // canonical symbol used for the paper order+ QString exchange;+ QString side; // "buy" | "sell"+ QString product; // "CNC" (holdings) | source product (positions)+ double quantity = 0; // floored to whole shares+ double est_price = 0; // ltp ?: avg_price+ double est_value = 0; // quantity * est_price+ bool mapped = false; // resolvable + tradable on target broker+ bool included = true; // default-unchecked when !mapped or unusable+ QString warning; // human-readable reason when !included/!mapped+};++struct ReplicationOptions {+ bool include_holdings = true;+ bool include_positions = true;+};++struct ReplicationPlan {+ QString source_account_id;+ QString target_account_id;+ QString target_paper_portfolio_id;+ QVector<PlannedOrder> orders;+ double required_capital = 0; // Σ est_value of *included* rows+ double target_available = 0; // target paper balance at plan time+};++struct ReplicationResult {+ struct Row { QString symbol; bool ok = false; QString error; };+ int placed = 0;+ int failed = 0;+ int skipped = 0;+ QVector<Row> rows;+};++// Resolver result: whether the symbol is tradable on the target broker, and its+// canonical (normalized) symbol to place the paper order with.+struct ResolveResult {+ bool tradable_on_target = false;+ QString norm_symbol;+};+using SymbolResolver = std::function<ResolveResult(const QString& src_symbol, const QString& exchange)>;++// ── Source extraction ────────────────────────────────────────────────────────+// Pure converter: live broker holdings+positions → SourceItem list.+QVector<SourceItem> to_source_items(const QVector<BrokerHolding>& holdings,+ const QVector<BrokerPosition>& positions);+// Paper source: reads the paper engine and splits CNC/NRML-delivery → holdings,+// rest → positions (mirrors refresh_paper_panels). Reads DB on the calling thread.+QVector<SourceItem> paper_source_items(const QString& portfolio_id);++// ── Planning (PURE) ──────────────────────────────────────────────────────────+ReplicationPlan build_plan(const QVector<SourceItem>& items,+ const ReplicationOptions& opts,+ double target_available,+ const QString& source_account_id,+ const QString& target_account_id,+ const QString& target_paper_portfolio_id,+ const SymbolResolver& resolve);++// Production resolver backed by InstrumentService (requires both brokers'+// instruments loaded; callers should load_from_db first).+SymbolResolver make_instrument_resolver(const QString& source_broker_id,+ const QString& target_broker_id);++// ── Execution (GUI thread) ───────────────────────────────────────────────────+// Places each included row as a market order into the target paper portfolio.+// Paper engine throws on margin/validation failure → captured per row.+ReplicationResult execute_plan(const ReplicationPlan& plan);++} // namespace fincept::trading::replicationdiff --git a/fincept-qt/src/ui/navigation/ToolBar.cpp b/fincept-qt/src/ui/navigation/ToolBar.cppindex cd8a7c607..97e79c0ed 100644--- a/fincept-qt/src/ui/navigation/ToolBar.cpp+++ b/fincept-qt/src/ui/navigation/ToolBar.cpp@@ -329,6 +329,9 @@ QMenu* ToolBar::build_file_menu() {}});+ m->addAction(tr("Close Window"), this, [this]() { emit action_triggered("close_window"); });+ m->addAction(tr("Close All Windows"), this, [this]() { emit action_triggered("close_all_windows"); });+m->addSeparator();m->addAction(tr("New Layout"), this, [this]() { emit action_triggered("layout_new"); });m->addAction(tr("Open Layout…"), this, [this]() { emit action_triggered("layout_open"); });diff --git a/fincept-qt/src/ui/widgets/algo/FnoLegRuleEditor.cpp b/fincept-qt/src/ui/widgets/algo/FnoLegRuleEditor.cppnew file mode 100644index 000000000..b81e37c83--- /dev/null+++ b/fincept-qt/src/ui/widgets/algo/FnoLegRuleEditor.cpp@@ -0,0 +1,255 @@+// src/ui/widgets/algo/FnoLegRuleEditor.cpp+#include "ui/widgets/algo/FnoLegRuleEditor.h"++#include <QComboBox>+#include <QDoubleSpinBox>+#include <QHBoxLayout>+#include <QPushButton>+#include <QSpinBox>+#include <QStringLiteral>+#include <QTableWidget>+#include <QVBoxLayout>++namespace fincept::ui::algo {++namespace {++// Column indices+constexpr int kColSide = 0;+constexpr int kColType = 1;+constexpr int kColStrike = 2;+constexpr int kColValue = 3;+constexpr int kColLots = 4;+constexpr int kColDelete = 5;+constexpr int kNumCols = 6;++const char* kStyle = R"(+QWidget#fnoLegRuleEditor {+ background: #1a1a2e;+ color: #e0e0e0;+}+QTableWidget {+ background: #12121f;+ color: #e0e0e0;+ gridline-color: #2a2a4a;+ border: 1px solid #2a2a4a;+ selection-background-color: #2a2a6a;+ selection-color: #ffffff;+ font-size: 12px;+}+QTableWidget::item {+ padding: 2px 4px;+}+QHeaderView::section {+ background: #1a1a3a;+ color: #a0a0c0;+ border: none;+ border-bottom: 1px solid #2a2a4a;+ padding: 3px 6px;+ font-size: 11px;+ font-weight: bold;+}+QComboBox {+ background: #1e1e38;+ color: #e0e0e0;+ border: 1px solid #3a3a5a;+ border-radius: 3px;+ padding: 1px 4px;+ font-size: 12px;+}+QComboBox QAbstractItemView {+ background: #1a1a30;+ color: #e0e0e0;+ selection-background-color: #3a3a7a;+}+QDoubleSpinBox, QSpinBox {+ background: #1e1e38;+ color: #e0e0e0;+ border: 1px solid #3a3a5a;+ border-radius: 3px;+ padding: 1px 4px;+ font-size: 12px;+}+QPushButton#addLegBtn {+ background: #1e3a5a;+ color: #a0d0ff;+ border: 1px solid #2a5a8a;+ border-radius: 4px;+ padding: 4px 12px;+ font-size: 12px;+}+QPushButton#addLegBtn:hover {+ background: #2a4a7a;+}+QPushButton#deleteLegBtn {+ background: #3a1a1a;+ color: #ff8080;+ border: 1px solid #6a2a2a;+ border-radius: 3px;+ padding: 1px 6px;+ font-size: 11px;+}+QPushButton#deleteLegBtn:hover {+ background: #5a2a2a;+}+)";++} // namespace++FnoLegRuleEditor::FnoLegRuleEditor(QWidget* parent)+ : QWidget(parent) {+ setObjectName(QStringLiteral("fnoLegRuleEditor"));+ setStyleSheet(QString::fromLatin1(kStyle));++ auto* layout = new QVBoxLayout(this);+ layout->setContentsMargins(0, 0, 0, 0);+ layout->setSpacing(4);++ // ── Table ────────────────────────────────────────────────────────────────+ table_ = new QTableWidget(0, kNumCols, this);+ table_->setObjectName(QStringLiteral("fnoLegTable"));+ table_->setHorizontalHeaderLabels(+ {tr("B/S"), tr("Type"), tr("Strike"), tr("Value"), tr("Lots"), tr("")});+ table_->horizontalHeader()->setStretchLastSection(false);+ table_->horizontalHeader()->setDefaultSectionSize(90);+ table_->setColumnWidth(kColSide, 70);+ table_->setColumnWidth(kColType, 60);+ table_->setColumnWidth(kColStrike, 100);+ table_->setColumnWidth(kColValue, 90);+ table_->setColumnWidth(kColLots, 70);+ table_->setColumnWidth(kColDelete, 32);+ table_->verticalHeader()->setVisible(false);+ table_->setSelectionBehavior(QAbstractItemView::SelectRows);+ table_->setEditTriggers(QAbstractItemView::NoEditTriggers);+ table_->setAlternatingRowColors(false);+ table_->setShowGrid(true);+ layout->addWidget(table_);++ // ── Add Leg button ───────────────────────────────────────────────────────+ auto* btn_row = new QHBoxLayout();+ btn_row->setContentsMargins(0, 2, 0, 0);+ auto* add_btn = new QPushButton(tr("Add Leg"), this);+ add_btn->setObjectName(QStringLiteral("addLegBtn"));+ add_btn->setFixedHeight(26);+ btn_row->addWidget(add_btn);+ btn_row->addStretch();+ layout->addLayout(btn_row);++ connect(add_btn, &QPushButton::clicked, this, [this]() {+ fincept::algo::fno::AlgoFnoLeg def;+ def.kind = QStringLiteral("CE");+ def.side = QStringLiteral("BUY");+ def.lots = 1;+ def.strike_mode = QStringLiteral("ATM");+ def.strike_value = 0;+ add_row(def);+ emit legs_changed();+ });+}++void FnoLegRuleEditor::add_row(const fincept::algo::fno::AlgoFnoLeg& leg) {+ const int row = table_->rowCount();+ table_->insertRow(row);+ table_->setRowHeight(row, 28);++ // B/S combo+ auto* side_cb = new QComboBox(this);+ side_cb->addItems({QStringLiteral("BUY"), QStringLiteral("SELL")});+ side_cb->setCurrentText(leg.side.isEmpty() ? QStringLiteral("BUY") : leg.side);+ table_->setCellWidget(row, kColSide, side_cb);++ // Type combo+ auto* type_cb = new QComboBox(this);+ type_cb->addItems({QStringLiteral("CE"), QStringLiteral("PE"), QStringLiteral("FUT")});+ type_cb->setCurrentText(leg.kind.isEmpty() ? QStringLiteral("CE") : leg.kind);+ table_->setCellWidget(row, kColType, type_cb);++ // Strike mode combo+ auto* strike_cb = new QComboBox(this);+ strike_cb->addItems({QStringLiteral("ATM"), QStringLiteral("ATM_OFFSET"),+ QStringLiteral("DELTA"), QStringLiteral("ABSOLUTE")});+ strike_cb->setCurrentText(leg.strike_mode.isEmpty() ? QStringLiteral("ATM") : leg.strike_mode);+ table_->setCellWidget(row, kColStrike, strike_cb);++ // Strike value double-spin+ auto* val_spin = new QDoubleSpinBox(this);+ val_spin->setRange(-1e6, 1e6);+ val_spin->setDecimals(2);+ val_spin->setSingleStep(1.0);+ val_spin->setValue(leg.strike_value);+ table_->setCellWidget(row, kColValue, val_spin);++ // Lots spin+ auto* lots_spin = new QSpinBox(this);+ lots_spin->setRange(1, 10000);+ lots_spin->setValue(leg.lots < 1 ? 1 : leg.lots);+ table_->setCellWidget(row, kColLots, lots_spin);++ // Delete button+ auto* del_btn = new QPushButton(QStringLiteral("✕"), this);+ del_btn->setObjectName(QStringLiteral("deleteLegBtn"));+ del_btn->setFixedSize(26, 22);+ table_->setCellWidget(row, kColDelete, del_btn);++ // Connect change signals — use this->table_ capture to scan for current row+ // at click time (avoids stale index after row removal).+ connect(side_cb, QOverload<int>::of(&QComboBox::currentIndexChanged),+ this, [this](int) { emit legs_changed(); });+ connect(type_cb, QOverload<int>::of(&QComboBox::currentIndexChanged),+ this, [this](int) { emit legs_changed(); });+ connect(strike_cb, QOverload<int>::of(&QComboBox::currentIndexChanged),+ this, [this](int) { emit legs_changed(); });+ connect(val_spin, QOverload<double>::of(&QDoubleSpinBox::valueChanged),+ this, [this](double) { emit legs_changed(); });+ connect(lots_spin, QOverload<int>::of(&QSpinBox::valueChanged),+ this, [this](int) { emit legs_changed(); });++ // Delete: find the row by scanning cellWidget at click time+ connect(del_btn, &QPushButton::clicked, this, [this, del_btn]() {+ for (int r = 0; r < table_->rowCount(); ++r) {+ if (table_->cellWidget(r, kColDelete) == del_btn) {+ table_->removeRow(r);+ emit legs_changed();+ return;+ }+ }+ });+}++fincept::algo::fno::AlgoFnoLeg FnoLegRuleEditor::row_to_leg(int row) const {+ fincept::algo::fno::AlgoFnoLeg leg;++ if (auto* w = qobject_cast<QComboBox*>(table_->cellWidget(row, kColSide)))+ leg.side = w->currentText();+ if (auto* w = qobject_cast<QComboBox*>(table_->cellWidget(row, kColType)))+ leg.kind = w->currentText();+ if (auto* w = qobject_cast<QComboBox*>(table_->cellWidget(row, kColStrike)))+ leg.strike_mode = w->currentText();+ if (auto* w = qobject_cast<QDoubleSpinBox*>(table_->cellWidget(row, kColValue)))+ leg.strike_value = w->value();+ if (auto* w = qobject_cast<QSpinBox*>(table_->cellWidget(row, kColLots)))+ leg.lots = w->value();++ return leg;+}++QVector<fincept::algo::fno::AlgoFnoLeg> FnoLegRuleEditor::legs() const {+ QVector<fincept::algo::fno::AlgoFnoLeg> result;+ result.reserve(table_->rowCount());+ for (int r = 0; r < table_->rowCount(); ++r)+ result.append(row_to_leg(r));+ return result;+}++void FnoLegRuleEditor::set_legs(const QVector<fincept::algo::fno::AlgoFnoLeg>& legs) {+ table_->setRowCount(0); // clears all rows and their cell widgets+ for (const auto& leg : legs)+ add_row(leg);+ // Intentionally NOT emitting legs_changed() — programmatic load.+}++void FnoLegRuleEditor::clear_legs() {+ table_->setRowCount(0);+}++} // namespace fincept::ui::algodiff --git a/fincept-qt/src/ui/widgets/algo/FnoLegRuleEditor.h b/fincept-qt/src/ui/widgets/algo/FnoLegRuleEditor.hnew file mode 100644index 000000000..8e81d3ccb--- /dev/null+++ b/fincept-qt/src/ui/widgets/algo/FnoLegRuleEditor.h@@ -0,0 +1,34 @@+#pragma once++#include "algo_engine/fno/FnoAlgoTypes.h"++#include <QVector>+#include <QWidget>++class QTableWidget;++namespace fincept::ui::algo {++// Rule-based F&O leg editor. Source of truth for the strategy's AlgoFnoLeg rules+// (kind/side/lots + strike rule). No live-chain dependency — strikes are rules,+// resolved later at entry/preview time.+class FnoLegRuleEditor : public QWidget {+ Q_OBJECT+ public:+ explicit FnoLegRuleEditor(QWidget* parent = nullptr);++ QVector<fincept::algo::fno::AlgoFnoLeg> legs() const;+ void set_legs(const QVector<fincept::algo::fno::AlgoFnoLeg>& legs);+ void clear_legs();++ signals:+ void legs_changed();++ private:+ void add_row(const fincept::algo::fno::AlgoFnoLeg& leg);+ fincept::algo::fno::AlgoFnoLeg row_to_leg(int row) const;++ QTableWidget* table_ = nullptr;+};++} // namespace fincept::ui::algo