Skip to content

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

checkpoint: WIP before algo/equity market-data refactor

tilakpatel22151f1765949a
diff --git a/fincept-qt/CMakeLists.txt b/fincept-qt/CMakeLists.txt
index 3c511fefb..a2a8932b0 100644
--- a/fincept-qt/CMakeLists.txt
+++ b/fincept-qt/CMakeLists.txt
@@ -851,6 +851,7 @@ set(STORAGE_SOURCES
src/storage/sqlite/migrations/v036_instrument_broker_token.cpp
src/storage/sqlite/migrations/v037_cloud_sync.cpp
src/storage/sqlite/migrations/v038_notebooks.cpp
+ src/storage/sqlite/migrations/v039_algo_schema_fix.cpp
# Historical OHLCV data store (Historify, Phase 3 §13)
src/storage/HistoricalDataStore.cpp
@@ -2294,6 +2295,7 @@ set_source_files_properties(
src/storage/sqlite/migrations/v036_instrument_broker_token.cpp
src/storage/sqlite/migrations/v037_cloud_sync.cpp
src/storage/sqlite/migrations/v038_notebooks.cpp
+ src/storage/sqlite/migrations/v039_algo_schema_fix.cpp
# Polymarket screen files — each defines static fmt_* helpers in same namespace
src/screens/polymarket/PolymarketScreen.cpp
src/screens/polymarket/PolymarketCommandBar.cpp
diff --git a/fincept-qt/resources/charts/klinechart.html b/fincept-qt/resources/charts/klinechart.html
index 383332673..f4c860d9a 100644
--- a/fincept-qt/resources/charts/klinechart.html
+++ b/fincept-qt/resources/charts/klinechart.html
@@ -282,6 +282,21 @@
try { chart.setStyles({ yAxis: { type: type } }); } catch (e) { log('scale err: ' + e.message); }
};
+ // Price under a vertical viewport coordinate (used by chart right-click
+ // trading). `clientY` is relative to the web view's top-left; we subtract the
+ // chart container's offset (toolbar height) before asking KLineChart to map
+ // the pixel to a y-axis value on the candle pane.
+ window.priceAtY = function(clientY) {
+ try {
+ var el = document.getElementById('chart');
+ var rect = el.getBoundingClientRect();
+ var y = clientY - rect.top;
+ var r = chart.convertFromPixel({ x: 0, y: y }, { paneId: 'candle_pane' });
+ var v = Array.isArray(r) ? (r[0] && r[0].value) : (r && r.value);
+ return (typeof v === 'number' && isFinite(v)) ? v : null;
+ } catch (e) { return null; }
+ };
+
// Edit an active indicator's calc params (e.g. MA periods "5,10,20,60").
window.editIndicatorParams = function(name) {
var paneId = activeIndicators[name];
diff --git a/fincept-qt/src/algo_engine/AlgoEngine.cpp b/fincept-qt/src/algo_engine/AlgoEngine.cpp
index 5142e254e..05ea9c98b 100644
--- a/fincept-qt/src/algo_engine/AlgoEngine.cpp
+++ b/fincept-qt/src/algo_engine/AlgoEngine.cpp
@@ -6,9 +6,13 @@
#include "trading/UnifiedTrading.h"
#include <QDateTime>
+#include <QJsonArray>
+#include <QJsonDocument>
#include <QMetaObject>
#include <QPointer>
+#include <QSqlError>
#include <QSqlQuery>
+#include <QUuid>
#include <QtConcurrent>
namespace fincept::algo {
@@ -19,6 +23,11 @@ AlgoEngine& AlgoEngine::instance() {
}
AlgoEngine::AlgoEngine() {
+ // Register types crossing the engine-thread → UI-thread queued signals.
+ qRegisterMetaType<fincept::algo::AlgoLiveSnapshot>("fincept::algo::AlgoLiveSnapshot");
+ qRegisterMetaType<fincept::algo::AlgoMetrics>("fincept::algo::AlgoMetrics");
+ qRegisterMetaType<fincept::algo::AlgoTradeRecord>("fincept::algo::AlgoTradeRecord");
+
engine_thread_.setObjectName(QStringLiteral("AlgoEngineThread"));
engine_thread_.start();
moveToThread(&engine_thread_);
@@ -44,6 +53,7 @@ void AlgoEngine::start_deployment(const services::algo::AlgoDeployment& deployme
connect(runner, &DeploymentRunner::trade_executed, this, &AlgoEngine::trade_executed);
connect(runner, &DeploymentRunner::metrics_updated, this, &AlgoEngine::metrics_updated);
connect(runner, &DeploymentRunner::error_occurred, this, &AlgoEngine::error_occurred);
+ connect(runner, &DeploymentRunner::live_update, this, &AlgoEngine::live_update);
connect(runner, &DeploymentRunner::order_requested, this, &AlgoEngine::on_order_requested);
connect(runner, &DeploymentRunner::status_changed, this, [this](const QString& id, const QString& status) {
if (status == "stopped" || status == "error") {
@@ -73,6 +83,10 @@ void AlgoEngine::start_deployment(const services::algo::AlgoDeployment& deployme
runners_.insert(deployment.id, runner);
lock.unlock();
+ // Persist the row BEFORE the runner's queued start() (which UPDATEs status) and
+ // before the UI refreshes the Dashboard — both read/expect this row to exist.
+ persist_deployment(deployment);
+
QMetaObject::invokeMethod(runner, &DeploymentRunner::start, Qt::QueuedConnection);
emit deployment_started(deployment.id);
LOG_INFO("AlgoEngine", QString("Started deployment %1 for strategy '%2' on %3")
@@ -140,6 +154,27 @@ void AlgoEngine::on_order_requested(const AlgoOrderSignal& signal) {
void AlgoEngine::execute_order(const AlgoOrderSignal& signal) {
QPointer<AlgoEngine> self = this;
QString dep_id = signal.deployment_id;
+ const double submitted_price = signal.price;
+ const double qty = signal.quantity;
+
+ // ── Paper: never touch a real broker ────────────────────────────────────────
+ // Simulate an immediate fill at the signal's reference price. This is the hard
+ // safety gate: even though a paper deployment carries a real broker account (its
+ // data source), its orders are never sent to that broker.
+ if (signal.mode != QStringLiteral("live")) {
+ const QString sim_id = QStringLiteral("paper-") + QUuid::createUuid().toString(QUuid::WithoutBraces);
+ QMetaObject::invokeMethod(this, [self, dep_id, sim_id, submitted_price, qty]() {
+ if (!self) return;
+ QMutexLocker lock(&self->mutex_);
+ auto* runner = self->runners_.value(dep_id, nullptr);
+ if (!runner) return;
+ lock.unlock();
+ runner->on_order_filled(sim_id, submitted_price, qty);
+ }, Qt::QueuedConnection);
+ LOG_INFO("AlgoEngine", QString("Deployment %1: PAPER simulated fill %2 %3 @ %4")
+ .arg(dep_id, signal.side).arg(qty).arg(submitted_price));
+ return;
+ }
fincept::trading::UnifiedOrder order;
order.symbol = signal.symbol;
@@ -154,15 +189,14 @@ void AlgoEngine::execute_order(const AlgoOrderSignal& signal) {
else
order.product_type = trading::ProductType::Intraday;
- QString account_id = signal.account_id;
- double submitted_price = signal.price;
+ const QString account_id = signal.account_id;
QtConcurrent::run([self, dep_id, account_id, order, submitted_price]() {
auto response = fincept::trading::UnifiedTrading::instance()
.place_order(account_id, order);
if (!self) return;
- QMetaObject::invokeMethod(self, [self, dep_id, response, order]() {
+ QMetaObject::invokeMethod(self, [self, dep_id, response, order, submitted_price]() {
if (!self) return;
QMutexLocker lock(&self->mutex_);
auto* runner = self->runners_.value(dep_id, nullptr);
@@ -170,7 +204,9 @@ void AlgoEngine::execute_order(const AlgoOrderSignal& signal) {
lock.unlock();
if (response.success) {
- runner->on_order_filled(response.order_id, order.quantity > 0 ? order.price : 0, order.quantity);
+ // Use the signal's reference price as the fill price (market orders
+ // carry no price; the broker's avg-fill isn't returned synchronously).
+ runner->on_order_filled(response.order_id, submitted_price, order.quantity);
} else {
runner->on_order_rejected(response.order_id, response.message);
}
@@ -178,6 +214,41 @@ void AlgoEngine::execute_order(const AlgoOrderSignal& signal) {
});
}
+void AlgoEngine::persist_deployment(const services::algo::AlgoDeployment& d) {
+ auto db = fincept::Database::instance().connection();
+ QSqlQuery q(db);
+ q.prepare(QStringLiteral(
+ "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'))"));
+ q.addBindValue(d.id);
+ q.addBindValue(d.strategy_id);
+ q.addBindValue(d.strategy_name);
+ q.addBindValue(d.strategy_kind);
+ q.addBindValue(d.symbol);
+ q.addBindValue(d.exchange);
+ q.addBindValue(d.product_type);
+ q.addBindValue(d.mode);
+ q.addBindValue(d.entry_side);
+ q.addBindValue(d.backend);
+ q.addBindValue(d.broker_id);
+ q.addBindValue(d.broker_account_id);
+ q.addBindValue(d.paper_portfolio_id);
+ q.addBindValue(d.timeframe);
+ q.addBindValue(d.quantity);
+ q.addBindValue(d.max_order_value);
+ q.addBindValue(d.max_daily_loss);
+ q.addBindValue(QStringLiteral("starting"));
+ if (!q.exec())
+ LOG_ERROR("AlgoEngine",
+ QString("Failed to persist deployment %1: %2").arg(d.id, q.lastError().text()));
+ else
+ LOG_INFO("AlgoEngine", QString("Persisted deployment row %1 (%2/%3 on %4)")
+ .arg(d.id, d.mode, d.backend, d.symbol));
+}
+
void AlgoEngine::list_deployments() {
QPointer<AlgoEngine> self = this;
QtConcurrent::run([self]() {
@@ -200,6 +271,7 @@ void AlgoEngine::list_deployments() {
d.broker_id = q.value("broker_id").toString();
d.broker_account_id = q.value("broker_account_id").toString();
d.status = q.value("status").toString();
+ d.error_message = q.value("error_message").toString();
d.timeframe = q.value("timeframe").toString();
d.quantity = q.value("quantity").toDouble();
d.max_order_value = q.value("max_order_value").toDouble();
@@ -221,6 +293,10 @@ void AlgoEngine::list_deployments() {
deployments[i].total_trades = mq.value("total_trades").toInt();
deployments[i].win_rate = mq.value("win_rate").toDouble();
deployments[i].max_drawdown = mq.value("max_drawdown").toDouble();
+ deployments[i].current_price = mq.value("current_price").toDouble();
+ deployments[i].position_qty = mq.value("current_position_qty").toDouble();
+ deployments[i].position_side = mq.value("current_position_side").toString();
+ deployments[i].position_entry = mq.value("current_position_entry").toDouble();
break;
}
}
@@ -235,24 +311,124 @@ void AlgoEngine::list_deployments() {
}
void AlgoEngine::recover_orphaned() {
+ // On restart, deployments that were active (or stuck in error from the prior
+ // no-data bug) should resume rather than silently die — that's what users
+ // expect of a deployed algo. Reload each one + its strategy and restart it.
auto db = fincept::Database::instance().connection();
QSqlQuery q(db);
q.exec(QStringLiteral(
- "SELECT id FROM algo_deployments WHERE status IN ('running', 'starting')"));
+ "SELECT * FROM algo_deployments WHERE status IN ('running','starting','error','crashed')"));
+
+ QVector<services::algo::AlgoDeployment> to_resume;
while (q.next()) {
- QString id = q.value(0).toString();
- QSqlQuery u(db);
- u.prepare(QStringLiteral(
- "UPDATE algo_deployments SET status = 'crashed', "
- "error_message = 'Application restarted' WHERE id = ?"));
- u.addBindValue(id);
- u.exec();
-
- datahub::DataHub::instance().publish(
- QStringLiteral("algo:state:") + id, QVariant::fromValue(QStringLiteral("crashed")));
- emit deployment_crashed(id, QStringLiteral("Application restarted unexpectedly"));
- LOG_WARN("AlgoEngine", QString("Marked orphaned deployment %1 as crashed").arg(id));
+ services::algo::AlgoDeployment d;
+ d.id = q.value("id").toString();
+ d.strategy_id = q.value("strategy_id").toString();
+ d.strategy_name = q.value("strategy_name").toString();
+ d.strategy_kind = q.value("strategy_kind").toString();
+ d.symbol = q.value("symbol").toString();
+ d.exchange = q.value("exchange").toString();
+ d.product_type = q.value("product_type").toString();
+ d.mode = q.value("mode").toString();
+ d.entry_side = q.value("entry_side").toString();
+ 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.paper_portfolio_id = q.value("paper_portfolio_id").toString();
+ d.timeframe = q.value("timeframe").toString();
+ 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();
+ to_resume.append(d);
+ }
+
+ for (const auto& d : to_resume) {
+ auto strat = load_strategy(d.strategy_id);
+ if (strat.id.isEmpty()) {
+ QSqlQuery u(db);
+ u.prepare(QStringLiteral("UPDATE algo_deployments SET status='stopped', "
+ "error_message='Strategy not found on resume' WHERE id=?"));
+ u.addBindValue(d.id);
+ u.exec();
+ LOG_WARN("AlgoEngine",
+ QString("Cannot resume deployment %1: strategy %2 missing").arg(d.id, d.strategy_id));
+ continue;
+ }
+ LOG_INFO("AlgoEngine", QString("Resuming deployment %1 ('%2' on %3) after restart")
+ .arg(d.id, strat.name, d.symbol));
+ start_deployment(d, strat);
}
}
+bool AlgoEngine::has_active_duplicate(const QString& strategy_id, const QString& symbol,
+ const QString& mode, const QString& entry_side) const {
+ auto db = fincept::Database::instance().connection();
+ QSqlQuery q(db);
+ q.prepare(QStringLiteral(
+ "SELECT COUNT(*) FROM algo_deployments WHERE strategy_id=? AND symbol=? AND mode=? "
+ "AND entry_side=? AND status IN ('running','starting')"));
+ q.addBindValue(strategy_id);
+ q.addBindValue(symbol);
+ q.addBindValue(mode);
+ q.addBindValue(entry_side);
+ if (q.exec() && q.next())
+ return q.value(0).toInt() > 0;
+ return false;
+}
+
+void AlgoEngine::remove_deployment(const QString& deployment_id) {
+ // Stop the runner first if it happens to be live (REMOVE is normally only shown
+ // for already-stopped rows, but guard anyway).
+ {
+ QMutexLocker lock(&mutex_);
+ if (auto* r = runners_.value(deployment_id, nullptr)) {
+ lock.unlock();
+ QMetaObject::invokeMethod(r, &DeploymentRunner::stop, Qt::QueuedConnection);
+ }
+ }
+
+ auto db = fincept::Database::instance().connection();
+ const char* const stmts[] = {
+ "DELETE FROM algo_deployments WHERE id = ?",
+ "DELETE FROM algo_metrics WHERE deployment_id = ?",
+ "DELETE FROM algo_deployment_heartbeat WHERE deployment_id = ?",
+ "DELETE FROM algo_order_signals WHERE deployment_id = ?",
+ "DELETE FROM algo_trades WHERE deployment_id = ?",
+ };
+ for (const char* sql : stmts) {
+ QSqlQuery q(db);
+ q.prepare(QString::fromLatin1(sql));
+ q.addBindValue(deployment_id);
+ if (!q.exec())
+ LOG_ERROR("AlgoEngine",
+ QString("remove_deployment(%1): %2").arg(deployment_id, q.lastError().text()));
+ }
+ LOG_INFO("AlgoEngine", QString("Removed deployment %1").arg(deployment_id));
+ list_deployments(); // refresh the Dashboard
+}
+
+services::algo::AlgoStrategy AlgoEngine::load_strategy(const QString& strategy_id) {
+ services::algo::AlgoStrategy s;
+ auto db = fincept::Database::instance().connection();
+ QSqlQuery q(db);
+ q.prepare(QStringLiteral("SELECT * FROM algo_strategies WHERE id = ?"));
+ q.addBindValue(strategy_id);
+ if (q.exec() && q.next()) {
+ s.id = q.value("id").toString();
+ s.name = q.value("name").toString();
+ s.description = q.value("description").toString();
+ s.timeframe = q.value("timeframe").toString();
+ s.entry_conditions =
+ QJsonDocument::fromJson(q.value("entry_conditions").toString().toUtf8()).array();
+ s.exit_conditions =
+ QJsonDocument::fromJson(q.value("exit_conditions").toString().toUtf8()).array();
+ s.entry_logic = q.value("entry_logic").toString();
+ s.exit_logic = q.value("exit_logic").toString();
+ s.stop_loss = q.value("stop_loss").toDouble();
+ s.take_profit = q.value("take_profit").toDouble();
+ s.trailing_stop = q.value("trailing_stop").toDouble();
+ }
+ return s;
+}
+
} // namespace fincept::algo
diff --git a/fincept-qt/src/algo_engine/AlgoEngine.h b/fincept-qt/src/algo_engine/AlgoEngine.h
index e60d220dd..c830e1c01 100644
--- a/fincept-qt/src/algo_engine/AlgoEngine.h
+++ b/fincept-qt/src/algo_engine/AlgoEngine.h
@@ -22,6 +22,10 @@ public:
void stop_deployment(const QString& deployment_id);
void pause_deployment(const QString& deployment_id);
void resume_deployment(const QString& deployment_id);
+ // Permanently delete a deployment and all its rows (deployments, metrics,
+ // heartbeat, order signals, trades), stopping the runner first if live. Then
+ // refreshes the deployment list. This is what the Dashboard's REMOVE invokes.
+ void remove_deployment(const QString& deployment_id);
void stop_all();
bool is_running(const QString& deployment_id) const;
@@ -31,6 +35,10 @@ public:
void list_deployments();
void recover_orphaned();
+ // True if a running/starting deployment with the same strategy+symbol+mode+side
+ // already exists — used to confirm before deploying an exact duplicate.
+ bool has_active_duplicate(const QString& strategy_id, const QString& symbol,
+ const QString& mode, const QString& entry_side) const;
signals:
void deployment_started(const QString& deployment_id);
@@ -40,6 +48,8 @@ signals:
void trade_executed(const fincept::algo::AlgoTradeRecord& trade);
void metrics_updated(const QString& deployment_id, const fincept::algo::AlgoMetrics& metrics);
void error_occurred(const QString& deployment_id, const QString& error);
+ // Real-time per-tick snapshot relayed from each runner to the Dashboard.
+ void live_update(const QString& deployment_id, const fincept::algo::AlgoLiveSnapshot& snap);
private slots:
void on_order_requested(const fincept::algo::AlgoOrderSignal& signal);
@@ -50,6 +60,13 @@ private:
Q_DISABLE_COPY(AlgoEngine)
void execute_order(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.
+ void persist_deployment(const fincept::services::algo::AlgoDeployment& deployment);
+ // Loads a full AlgoStrategy (incl. parsed entry/exit conditions) from the
+ // algo_strategies table — used to resume deployments after an app restart.
+ fincept::services::algo::AlgoStrategy load_strategy(const QString& strategy_id);
QThread engine_thread_;
mutable QMutex mutex_;
diff --git a/fincept-qt/src/algo_engine/AlgoEngineTypes.h b/fincept-qt/src/algo_engine/AlgoEngineTypes.h
index d6b5c0680..50a8b3c15 100644
--- a/fincept-qt/src/algo_engine/AlgoEngineTypes.h
+++ b/fincept-qt/src/algo_engine/AlgoEngineTypes.h
@@ -174,6 +174,31 @@ struct AlgoOrderSignal {
double price = 0;
double trigger_price = 0;
QString reason;
+ QString mode = "paper"; // paper | live — paper simulates the fill, live routes to the broker
+};
+
+// ── Live dashboard snapshot ───────────────────────────────────────────────────
+// Pushed from the runner to the Dashboard on every tick (throttled) so the UI can
+// show real-time price, P&L, position, and per-condition status without re-reading
+// the DB. Each AlgoConditionStatus is one entry/exit leaf with its live computed
+// value vs its target, so the user can see exactly why a rule is or isn't firing.
+
+struct AlgoConditionStatus {
+ QString label; // human label, e.g. "CLOSE crosses above 1205"
+ QString op; // raw operator (>, crosses_above, …) — UI derives hints from it
+ QString section; // "entry" | "exit"
+ double computed = 0; // current value of the LHS operand
+ double target = 0; // the threshold / RHS value
+ bool met = false; // did this leaf evaluate true this tick
+};
+
+struct AlgoLiveSnapshot {
+ QString deployment_id;
+ double current_price = 0;
+ int64_t last_update_ms = 0;
+ AlgoMetrics metrics;
+ QVector<AlgoConditionStatus> conditions; // entry rows then exit rows
+ QString note; // short activity line, e.g. "entry not met"
};
} // namespace fincept::algo
@@ -181,3 +206,5 @@ struct AlgoOrderSignal {
Q_DECLARE_METATYPE(fincept::algo::AlgoMetrics)
Q_DECLARE_METATYPE(fincept::algo::AlgoTradeRecord)
Q_DECLARE_METATYPE(fincept::algo::OhlcvCandle)
+Q_DECLARE_METATYPE(fincept::algo::AlgoConditionStatus)
+Q_DECLARE_METATYPE(fincept::algo::AlgoLiveSnapshot)
diff --git a/fincept-qt/src/algo_engine/ConditionEvaluator.cpp b/fincept-qt/src/algo_engine/ConditionEvaluator.cpp
index e04a511be..06fe40e9c 100644
--- a/fincept-qt/src/algo_engine/ConditionEvaluator.cpp
+++ b/fincept-qt/src/algo_engine/ConditionEvaluator.cpp
@@ -15,7 +15,10 @@ constexpr double kNaN = std::numeric_limits<double>::quiet_NaN();
bool op_needs_prev(const QString& op) {
return op == "crosses_above" || op == "crosses_below" ||
- op == "rising" || op == "falling";
+ op == "rising" || op == "falling" ||
+ // "==" is a level *touch*: it needs the previous sample to detect the
+ // price passing through the target between two (polled) ticks.
+ op == "==";
}
} // namespace
@@ -136,6 +139,24 @@ ConditionResult ConditionEvaluator::evaluate_single(
} else if (condition.op == "between") {
result.met = !std::isnan(lhs_curr) && lhs_curr >= condition.value && lhs_curr <= condition.value2;
result.target_value = condition.value2;
+ } else if (condition.op == "==") {
+ // Level touch / equality cross. A live price polled every few seconds skips
+ // the exact value (280.35 → 280.45 never equals 280.40), so plain float ==
+ // never fires. Instead, trigger when the operands meet OR cross between the
+ // previous and current sample — i.e. lhs−rhs is ~0 now, or changed sign
+ // since the last sample (passed through equality, from either direction).
+ double tol = std::abs(rhs_curr) * 1e-7;
+ if (tol < 1e-9) tol = 1e-9;
+ const double curr_diff = lhs_curr - rhs_curr;
+ const double prev_diff = lhs_prev - rhs_prev; // NaN on the first sample
+ if (std::isnan(lhs_curr) || std::isnan(rhs_curr))
+ result.met = false;
+ else if (std::abs(curr_diff) <= tol)
+ result.met = true; // sitting on the level (within float tolerance)
+ else if (!std::isnan(prev_diff) && ((prev_diff < 0) != (curr_diff < 0)))
+ result.met = true; // crossed through the level since the last sample
+ else
+ result.met = false;
} else {
result.met = apply_comparison(lhs_curr, condition.op, rhs_curr);
}
diff --git a/fincept-qt/src/algo_engine/DeploymentRunner.cpp b/fincept-qt/src/algo_engine/DeploymentRunner.cpp
index 974a390d7..821b45ded 100644
--- a/fincept-qt/src/algo_engine/DeploymentRunner.cpp
+++ b/fincept-qt/src/algo_engine/DeploymentRunner.cpp
@@ -7,6 +7,9 @@
#include "storage/sqlite/Database.h"
using fincept::Database;
+#include "trading/AccountManager.h"
+#include "trading/BrokerInterface.h"
+#include "trading/BrokerRegistry.h"
#include "trading/BrokerTopic.h"
#include "trading/TradingTypes.h"
@@ -15,6 +18,7 @@ using fincept::Database;
#include <QSqlQuery>
#include <QUuid>
#include <QVariant>
+#include <QtConcurrent>
namespace fincept::algo {
@@ -26,6 +30,11 @@ DeploymentRunner::DeploymentRunner(const services::algo::AlgoDeployment& deploym
, strategy_(strategy)
, timeframe_(timeframe_from_string(deployment.timeframe.isEmpty() ? strategy.timeframe : deployment.timeframe)) {
+ // "live" timeframe → evaluate entry/exit on every quote (tick), not on candle
+ // close. (timeframe_ itself falls back to M5 for aggregation/warm-up history.)
+ const QString tf_str = deployment.timeframe.isEmpty() ? strategy.timeframe : deployment.timeframe;
+ live_mode_ = (tf_str.compare(QStringLiteral("live"), Qt::CaseInsensitive) == 0);
+
// Capacity 500 so long indicators (SMA200) + a crossover lookback fit.
aggregator_ = std::make_unique<CandleAggregator>(deployment.symbol, timeframe_, 500, this);
connect(aggregator_.get(), &CandleAggregator::candle_closed,
@@ -39,6 +48,12 @@ DeploymentRunner::DeploymentRunner(const services::algo::AlgoDeployment& deploym
heartbeat_timer_ = new QTimer(this);
heartbeat_timer_->setInterval(5000);
connect(heartbeat_timer_, &QTimer::timeout, this, &DeploymentRunner::on_heartbeat);
+
+ // Poll the broker for a fresh quote every 3s while running. Lives on the engine
+ // thread (the runner is moved there before start()), so the timer fires there.
+ quote_timer_ = new QTimer(this);
+ quote_timer_->setInterval(3000);
+ connect(quote_timer_, &QTimer::timeout, this, &DeploymentRunner::poll_quote);
}
DeploymentRunner::~DeploymentRunner() {
@@ -53,6 +68,9 @@ void DeploymentRunner::start() {
paused_ = false;
last_heartbeat_ms_ = QDateTime::currentMSecsSinceEpoch();
+ // Resume any open position + cumulative metrics persisted before a restart.
+ restore_state_from_db();
+
// Warm the aggregator with historical candles before going live, so indicators
// are valid immediately. Without this the buffer starts empty and the strategy
// can't trigger until hundreds of live bars accumulate. Live ticks are
@@ -76,7 +94,7 @@ void DeploymentRunner::start() {
QString("Deployment %1 backfill failed (%2) — warming from live ticks only")
.arg(self->deployment_.id, err));
}
- self->subscribe_tick_topic();
+ self->start_market_data();
});
heartbeat_timer_->start();
@@ -105,29 +123,63 @@ void DeploymentRunner::stop() {
running_ = false;
paused_ = false;
heartbeat_timer_->stop();
- unsubscribe_tick_topic();
+ stop_market_data();
persist_metrics();
update_deployment_status(QStringLiteral("stopped"));
emit status_changed(deployment_.id, QStringLiteral("stopped"));
LOG_INFO("AlgoEngine", QString("Deployment %1 stopped").arg(deployment_.id));
}
-void DeploymentRunner::subscribe_tick_topic() {
- const QString topic = fincept::trading::broker_topic(
- deployment_.broker_id, deployment_.broker_account_id,
- QStringLiteral("ticks"), deployment_.symbol);
+void DeploymentRunner::start_market_data() {
+ if (deployment_.broker_id.isEmpty() || deployment_.broker_account_id.isEmpty()) {
+ LOG_WARN("AlgoEngine",
+ QString("Deployment %1: no broker account attached — cannot source live "
+ "market data (deploy again and pick a connected broker).")
+ .arg(deployment_.id));
+ return;
+ }
+ LOG_INFO("AlgoEngine", QString("Deployment %1: polling %2 quotes from broker '%3' every 3s")
+ .arg(deployment_.id, deployment_.symbol, deployment_.broker_id));
+ quote_timer_->start();
+ poll_quote(); // fire the first one immediately rather than waiting 3s
+}
- auto& hub = fincept::datahub::DataHub::instance();
- tick_connection_ = hub.subscribe(this, topic,
- [this](const QVariant& v) { on_tick_data(v); });
+void DeploymentRunner::stop_market_data() {
+ if (quote_timer_)
+ quote_timer_->stop();
}
-void DeploymentRunner::unsubscribe_tick_topic() {
- if (tick_connection_) {
- QObject::disconnect(tick_connection_);
- tick_connection_ = {};
- }
- fincept::datahub::DataHub::instance().unsubscribe(this);
+void DeploymentRunner::poll_quote() {
+ if (!running_.load() || paused_.load())
+ return;
+ const QString broker_id = deployment_.broker_id;
+ const QString account_id = deployment_.broker_account_id;
+ const QString symbol = deployment_.symbol;
+ if (broker_id.isEmpty() || account_id.isEmpty())
+ return;
+
+ // Hit the broker's quote REST endpoint off-thread; deliver the result back on
+ // the engine thread via on_tick_data (same entry point a WS tick would use).
+ QPointer<DeploymentRunner> self = this;
+ QtConcurrent::run([self, broker_id, account_id, symbol]() {
+ auto* broker = trading::BrokerRegistry::instance().get(broker_id);
+ if (!broker)
+ return;
+ auto creds = trading::AccountManager::instance().load_credentials(account_id);
+ auto resp = broker->get_quotes(creds, {symbol});
+ if (!resp.success || !resp.data.has_value() || resp.data->isEmpty())
+ return;
+ const trading::BrokerQuote quote = resp.data->first();
+ if (!self)
+ return;
+ QMetaObject::invokeMethod(
+ self,
+ [self, quote]() {
+ if (self && self->running_.load())
+ self->on_tick_data(QVariant::fromValue(quote));
+ },
+ Qt::QueuedConnection);
+ });
}
void DeploymentRunner::on_tick_data(const QVariant& data) {
@@ -154,6 +206,14 @@ void DeploymentRunner::on_tick_data(const QVariant& data) {
if (price <= 0) return;
+ if (!first_tick_logged_) {
+ first_tick_logged_ = true;
+ LOG_INFO("AlgoEngine", QString("Deployment %1: receiving live quotes (%2 = %3) from '%4'")
+ .arg(deployment_.id, deployment_.symbol)
+ .arg(price)
+ .arg(deployment_.broker_id));
+ }
+
position_mgr_->update_price(price);
auto risk_signal = position_mgr_->check_risk(price);
@@ -162,15 +222,113 @@ void DeploymentRunner::on_tick_data(const QVariant& data) {
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);
+
+ // Live timeframe: evaluate entry/exit on every tick against the live price.
+ if (live_mode_)
+ evaluate_live(price);
+
+ // Always push a real-time snapshot to the Dashboard (throttled inside).
+ emit_live_snapshot(price, QString());
+ last_tick_price_ = price;
+}
+
+QVector<OhlcvCandle> DeploymentRunner::live_eval_window(double price) const {
+ QVector<OhlcvCandle> candles = aggregator_->closed_candles();
+ const int64_t now = QDateTime::currentMSecsSinceEpoch();
+ // Append previous + current tick as the last two bars so a crossover is detected
+ // tick-to-tick against the live price (prev < target ≤ current).
+ if (last_tick_price_ > 0) {
+ OhlcvCandle prev;
+ prev.open = prev.high = prev.low = prev.close = last_tick_price_;
+ prev.open_time = prev.close_time = now - 1;
+ prev.volume = 0;
+ prev.is_closed = true;
+ candles.append(prev);
+ }
+ OhlcvCandle cur;
+ cur.open = cur.high = cur.low = cur.close = price;
+ cur.open_time = cur.close_time = now;
+ cur.volume = 0;
+ cur.is_closed = true;
+ candles.append(cur);
+ return candles;
+}
+
+void DeploymentRunner::evaluate_live(double price) {
+ if (position_mgr_->is_paused())
+ return;
+ auto candles = live_eval_window(price);
+ if (candles.size() < 2)
+ return;
+ if (position_mgr_->has_position())
+ evaluate_exit(candles);
+ else
+ evaluate_entry(candles);
+}
+
+namespace {
+QString pretty_op(const QString& op) {
+ if (op == "crosses_above") return QStringLiteral("crosses above");
+ if (op == "crosses_below") return QStringLiteral("crosses below");
+ if (op == "rising") return QStringLiteral("rising");
+ if (op == "falling") return QStringLiteral("falling");
+ if (op == "between") return QStringLiteral("between");
+ return op; // >, <, >=, <=, ==
+}
+} // namespace
+
+void DeploymentRunner::emit_live_snapshot(double price, const QString& note) {
+ const int64_t now = QDateTime::currentMSecsSinceEpoch();
+ // Throttle the periodic stream to ~1/s; event notes (fills, signals) bypass it.
+ if (note.isEmpty() && now - last_emit_ms_ < 1000)
+ return;
+ last_emit_ms_ = now;
+
+ const auto candles = live_eval_window(price);
+
+ AlgoLiveSnapshot snap;
+ snap.deployment_id = deployment_.id;
+ snap.current_price = price;
+ snap.last_update_ms = now;
+ auto m = position_mgr_->metrics();
+ m.current_price = price;
+ snap.metrics = m;
+ snap.note = note;
+
+ auto add_rows = [&](const QJsonArray& conds, const QString& logic, const QString& section) {
+ if (conds.isEmpty())
+ return;
+ const auto res = ConditionEvaluator::evaluate_group(conds, logic, candles);
+ for (const auto& d : res.details) {
+ AlgoConditionStatus cs;
+ cs.section = section;
+ cs.op = d.op;
+ cs.computed = d.computed_value;
+ cs.target = d.target_value;
+ cs.met = d.met;
+ const QString fld = (d.field.isEmpty() || d.field == "value") ? QString()
+ : (QStringLiteral(".") + d.field);
+ cs.label = QStringLiteral("%1%2 %3 %4")
+ .arg(d.indicator, fld, pretty_op(d.op))
+ .arg(d.target_value, 0, 'f', 2);
+ snap.conditions.append(cs);
+ }
+ };
+ add_rows(strategy_.entry_conditions, strategy_.entry_logic, QStringLiteral("entry"));
+ add_rows(strategy_.exit_conditions, strategy_.exit_logic, QStringLiteral("exit"));
+
+ emit live_update(deployment_.id, snap);
}
void DeploymentRunner::on_candle_closed(const OhlcvCandle& /*candle*/) {
if (!running_.load() || paused_.load()) return;
if (position_mgr_->is_paused()) return;
+ if (live_mode_) return; // live mode evaluates per tick in on_tick_data
auto candles = aggregator_->closed_candles();
if (candles.size() < 20) return;
@@ -201,6 +359,7 @@ void DeploymentRunner::evaluate_entry(const QVector<OhlcvCandle>& candles) {
signal.side = deployment_.entry_side;
signal.quantity = deployment_.quantity;
signal.order_type = "MARKET";
+ signal.price = candles.last().close; // fill reference for paper sim / P&L
signal.reason = "entry_signal";
if (!position_mgr_->validate_order_value(signal.quantity, candles.last().close)) {
@@ -228,24 +387,37 @@ void DeploymentRunner::evaluate_exit(const QVector<OhlcvCandle>& candles) {
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.reason = "exit_signal";
emit_order_signal(signal);
}
-void DeploymentRunner::emit_order_signal(const AlgoOrderSignal& signal) {
+void DeploymentRunner::emit_order_signal(const AlgoOrderSignal& signal_in) {
// Only one order in flight at a time. Position/risk state updates only when a
// fill arrives, so without this guard a stop-loss re-fires on every tick (and
// entry/exit on every candle) until the fill lands — flooding duplicate orders.
if (!pending_orders_.isEmpty())
return;
+ // Stamp the deployment's mode so the engine routes paper→simulated-fill and
+ // live→broker. This is the single safety gate that stops a PAPER deployment
+ // from ever hitting a real broker, even though it carries a real account id
+ // (the account is its data source).
+ AlgoOrderSignal signal = signal_in;
+ signal.mode = deployment_.mode;
+ if (signal.price <= 0)
+ signal.price = position_mgr_->metrics().current_price;
+
PendingOrder pending;
pending.signal = signal;
pending.submitted_ms = QDateTime::currentMSecsSinceEpoch();
pending_orders_.append(pending);
emit order_requested(signal);
+ emit_live_snapshot(signal.price, QStringLiteral("%1: %2 %3 @ MARKET")
+ .arg(signal.reason, signal.side)
+ .arg(signal.quantity, 0, 'f', 0));
LOG_INFO("AlgoEngine", QString("Deployment %1: %2 %3 %4 @ MARKET (%5)")
.arg(deployment_.id, signal.side,
QString::number(signal.quantity), signal.symbol, signal.reason));
@@ -292,6 +464,10 @@ void DeploymentRunner::on_order_filled(const QString& broker_order_id,
persist_trade(trade);
emit trade_executed(trade);
emit metrics_updated(deployment_.id, position_mgr_->metrics());
+ emit_live_snapshot(fill_price, QStringLiteral("%1 FILLED %2 @ %3")
+ .arg(is_entry ? QStringLiteral("ENTRY") : QStringLiteral("EXIT"))
+ .arg(fill_qty, 0, 'f', 0)
+ .arg(fill_price, 0, 'f', 2));
}
void DeploymentRunner::on_order_rejected(const QString& /*broker_order_id*/,
@@ -306,6 +482,10 @@ void DeploymentRunner::on_heartbeat() {
if (!running_.load()) return;
int64_t now = QDateTime::currentMSecsSinceEpoch();
+ // Keep the DB metrics row fresh (~5s) so the summary cards and any structural
+ // rebuild show current values instead of stale zeros.
+ persist_metrics();
+
// Purge orders that never reported a fill/rejection so a lost ack doesn't
// permanently block new signals (the in-flight guard in emit_order_signal).
for (int i = pending_orders_.size() - 1; i >= 0; --i) {
@@ -318,11 +498,24 @@ void DeploymentRunner::on_heartbeat() {
}
if (now - last_heartbeat_ms_ > 30000) {
- LOG_ERROR("AlgoEngine", QString("Deployment %1: no tick data for 30s, marking error")
- .arg(deployment_.id));
- update_deployment_status(QStringLiteral("error"));
+ const QString msg =
+ deployment_.broker_id.isEmpty()
+ ? QStringLiteral("No market data in 30s — no broker is attached to this deployment.")
+ : QString("No market data from broker '%1' in 30s — check the broker is connected "
+ "and the market is open.")
+ .arg(deployment_.broker_id);
+ LOG_ERROR("AlgoEngine", QString("Deployment %1: %2").arg(deployment_.id, msg));
+
+ auto db = Database::instance().connection();
+ QSqlQuery q(db);
+ q.prepare(QStringLiteral("UPDATE algo_deployments SET status='error', error_message=?, "
+ "updated_at=datetime('now') WHERE id=?"));
+ q.addBindValue(msg);
+ q.addBindValue(deployment_.id);
+ q.exec();
+
emit status_changed(deployment_.id, QStringLiteral("error"));
- emit error_occurred(deployment_.id, QStringLiteral("No tick data received for 30 seconds"));
+ emit error_occurred(deployment_.id, msg);
}
}
@@ -370,6 +563,34 @@ void DeploymentRunner::persist_metrics() {
LOG_ERROR("AlgoEngine", QString("Failed to persist metrics: %1").arg(q.lastError().text()));
}
+void DeploymentRunner::restore_state_from_db() {
+ auto db = Database::instance().connection();
+ QSqlQuery q(db);
+ q.prepare(QStringLiteral(
+ "SELECT total_pnl, total_trades, win_rate, max_drawdown, current_position_qty, "
+ "current_position_side, current_position_entry FROM algo_metrics WHERE deployment_id = ?"));
+ q.addBindValue(deployment_.id);
+ if (!q.exec() || !q.next())
+ return; // fresh deploy — no prior state
+
+ const QString side_s = q.value("current_position_side").toString();
+ const PositionSide side = (side_s == "LONG") ? PositionSide::Long
+ : (side_s == "SHORT") ? PositionSide::Short
+ : PositionSide::None;
+ const double qty = q.value("current_position_qty").toDouble();
+ const double entry = q.value("current_position_entry").toDouble();
+
+ position_mgr_->restore_state(side, qty, entry, q.value("total_pnl").toDouble(),
+ q.value("total_trades").toInt(), q.value("win_rate").toDouble(),
+ q.value("max_drawdown").toDouble());
+
+ if (side != PositionSide::None)
+ LOG_INFO("AlgoEngine", QString("Deployment %1: restored open %2 %3 @ %4 across restart")
+ .arg(deployment_.id, side_s)
+ .arg(qty, 0, 'f', 0)
+ .arg(entry, 0, 'f', 2));
+}
+
void DeploymentRunner::update_deployment_status(const QString& status) {
auto db = Database::instance().connection();
QSqlQuery q(db);
diff --git a/fincept-qt/src/algo_engine/DeploymentRunner.h b/fincept-qt/src/algo_engine/DeploymentRunner.h
index c326ccb49..2c2e91057 100644
--- a/fincept-qt/src/algo_engine/DeploymentRunner.h
+++ b/fincept-qt/src/algo_engine/DeploymentRunner.h
@@ -38,6 +38,8 @@ signals:
void status_changed(const QString& deployment_id, const QString& status);
void order_requested(const fincept::algo::AlgoOrderSignal& signal);
void error_occurred(const QString& deployment_id, const QString& error);
+ // Real-time snapshot for the Dashboard (LTP, P&L, position, per-condition status).
+ void live_update(const QString& deployment_id, const fincept::algo::AlgoLiveSnapshot& snap);
public slots:
void on_order_filled(const QString& broker_order_id, double fill_price, double fill_qty);
@@ -49,13 +51,30 @@ private slots:
void on_heartbeat();
private:
- void subscribe_tick_topic();
- void unsubscribe_tick_topic();
+ // Live market data: poll the connected broker's quote REST endpoint on a timer
+ // and feed each BrokerQuote into on_tick_data(). Self-contained — does NOT touch
+ // the shared AccountDataStream/WebSocket (whose single-symbol subscription is
+ // owned by the Equity screen), so it can't clobber other consumers.
+ void start_market_data();
+ void stop_market_data();
+ void poll_quote();
+ // Builds the candle window used for live (per-tick) evaluation: the closed
+ // history plus the previous and current tick as the last two bars, so a
+ // crossover is detected tick-to-tick against the live price.
+ QVector<OhlcvCandle> live_eval_window(double price) const;
+ // Evaluates entry/exit each tick (live timeframe only) and emits a snapshot.
+ void evaluate_live(double price);
+ // Pushes the real-time snapshot (LTP, P&L, position, per-condition status) to
+ // the Dashboard, throttled. `note` is a short activity line.
+ void emit_live_snapshot(double price, const QString& note);
void evaluate_entry(const QVector<OhlcvCandle>& candles);
void evaluate_exit(const QVector<OhlcvCandle>& candles);
void emit_order_signal(const AlgoOrderSignal& signal);
void persist_trade(const AlgoTradeRecord& trade);
void persist_metrics();
+ // 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();
void update_deployment_status(const QString& status);
fincept::services::algo::AlgoDeployment deployment_;
@@ -67,9 +86,13 @@ private:
std::atomic<bool> running_{false};
std::atomic<bool> paused_{false};
- QMetaObject::Connection tick_connection_;
QTimer* heartbeat_timer_ = nullptr;
+ QTimer* quote_timer_ = nullptr; // drives poll_quote()
int64_t last_heartbeat_ms_ = 0;
+ bool first_tick_logged_ = false; // log the first live quote once, for trackability
+ bool live_mode_ = false; // timeframe == "live" → evaluate per tick
+ int64_t last_emit_ms_ = 0; // throttle for live_update emission
+ double last_tick_price_ = 0; // previous tick price → tick-to-tick crossovers
struct PendingOrder {
QString broker_order_id;
diff --git a/fincept-qt/src/algo_engine/PositionManager.cpp b/fincept-qt/src/algo_engine/PositionManager.cpp
index fb43131f8..751ac8fef 100644
--- a/fincept-qt/src/algo_engine/PositionManager.cpp
+++ b/fincept-qt/src/algo_engine/PositionManager.cpp
@@ -137,6 +137,32 @@ double PositionManager::record_exit(double qty, double price, int64_t time_ms) {
return pnl;
}
+void PositionManager::restore_state(PositionSide side, double qty, double entry_price,
+ double total_pnl, int total_trades, double win_rate,
+ double max_drawdown) {
+ QMutexLocker lock(&mutex_);
+ position_.side = side;
+ position_.quantity = qty;
+ position_.entry_price = entry_price;
+ position_.highest_since_entry = entry_price; // trailing-stop baseline resets on resume
+ position_.lowest_since_entry = entry_price;
+
+ metrics_.total_pnl = total_pnl;
+ metrics_.total_trades = total_trades;
+ metrics_.win_rate = win_rate;
+ metrics_.winning_trades = static_cast<int>(std::lround(win_rate * total_trades / 100.0));
+ metrics_.losing_trades = total_trades - metrics_.winning_trades;
+ if (metrics_.losing_trades < 0)
+ metrics_.losing_trades = 0;
+ metrics_.max_drawdown = max_drawdown;
+ metrics_.current_position_qty = qty;
+ metrics_.current_position_side = position_side_to_string(side);
+ metrics_.current_position_entry = entry_price;
+
+ risk_.max_drawdown = max_drawdown;
+ risk_.peak_equity = total_pnl > 0 ? total_pnl : 0;
+}
+
void PositionManager::update_price(double price) {
QMutexLocker lock(&mutex_);
metrics_.current_price = price;
diff --git a/fincept-qt/src/algo_engine/PositionManager.h b/fincept-qt/src/algo_engine/PositionManager.h
index 5d08f8160..676007dca 100644
--- a/fincept-qt/src/algo_engine/PositionManager.h
+++ b/fincept-qt/src/algo_engine/PositionManager.h
@@ -20,6 +20,11 @@ public:
void record_entry(PositionSide side, double qty, double price, int64_t time_ms);
double record_exit(double qty, double price, int64_t time_ms);
+ // Re-seed position + cumulative metrics after an app restart so a resumed
+ // deployment continues its open position instead of starting flat.
+ void restore_state(PositionSide side, double qty, double entry_price,
+ double total_pnl, int total_trades, double win_rate, double max_drawdown);
+
bool has_position() const;
bool is_paused() const;
bool validate_order_value(double qty, double price) const;
diff --git a/fincept-qt/src/app/main.cpp b/fincept-qt/src/app/main.cpp
index 2d100b7b9..eef49eeeb 100644
--- a/fincept-qt/src/app/main.cpp
+++ b/fincept-qt/src/app/main.cpp
@@ -699,6 +699,7 @@ int main(int argc, char* argv[]) {
fincept::register_migration_v036();
fincept::register_migration_v037();
fincept::register_migration_v038();
+ fincept::register_migration_v039();
// Open main database
QString db_path = fincept::AppPaths::data() + "/fincept.db";
@@ -708,6 +709,14 @@ int main(int argc, char* argv[]) {
// DB unavailable — apply theme with built-in defaults so the UI is at least styled
fincept::ui::apply_global_stylesheet();
} else {
+ // Load broker accounts now that the DB is open. The AccountManager
+ // singleton loads eagerly in its constructor on first access; if anything
+ // touched it before this point (before open()), it found an unusable DB
+ // and loaded nothing. This explicit main-thread reload guarantees the
+ // account map is populated from the now-open DB, so configured brokers
+ // survive restarts instead of vanishing.
+ fincept::trading::AccountManager::instance().reload_from_db();
+
// Prune news articles older than 30 days — deferred to run after the event loop
// starts so the startup critical path is not blocked.
// NewsArticleRepository uses the main-thread DB connection (not thread-safe),
diff --git a/fincept-qt/src/screens/about/AboutScreen.cpp b/fincept-qt/src/screens/about/AboutScreen.cpp
index 877dedc55..a9f2c0c47 100644
--- a/fincept-qt/src/screens/about/AboutScreen.cpp
+++ b/fincept-qt/src/screens/about/AboutScreen.cpp
@@ -68,7 +68,7 @@ static QWidget* makePanel() {
}
static QLabel* makePanelHeader(const QString& icon, const QString& title, const QString& iconColor) {
- auto* lbl = new QLabel(QString("%1 %2").arg(icon, title));
+ auto* lbl = new QLabel(icon.isEmpty() ? title : QString("%1 %2").arg(icon, title));
lbl->setStyleSheet(QString("color: %1; font-size: 11px; font-weight: bold; letter-spacing: 0.5px; "
"background: %2; padding: 10px 14px; border-bottom: 1px solid %3; "
"font-family: 'Consolas','Courier New',monospace;")
@@ -87,7 +87,7 @@ static QLabel* makeBullet(const QString& text) {
// Re-apply icon + title to a panel header (mirrors makePanelHeader's text format).
static void setPanelHeaderText(QLabel* lbl, const QString& icon, const QString& title) {
- if (lbl) lbl->setText(QString("%1 %2").arg(icon, title));
+ if (lbl) lbl->setText(icon.isEmpty() ? title : QString("%1 %2").arg(icon, title));
}
// Re-apply bullet text (mirrors makeBullet's "■ %1" format).
@@ -205,7 +205,7 @@ AboutScreen::AboutScreen(QWidget* parent) : QWidget(parent) {
auto* pvl = new QVBoxLayout(panel);
pvl->setContentsMargins(0, 0, 0, 0);
pvl->setSpacing(0);
- oss_header_ = makePanelHeader("📄", tr("OPEN SOURCE LICENSE"), ui::colors::POSITIVE);
+ oss_header_ = makePanelHeader("", tr("OPEN SOURCE LICENSE"), ui::colors::POSITIVE);
pvl->addWidget(oss_header_);
auto* body = new QWidget(this);
@@ -320,7 +320,7 @@ AboutScreen::AboutScreen(QWidget* parent) : QWidget(parent) {
auto* pvl = new QVBoxLayout(panel);
pvl->setContentsMargins(0, 0, 0, 0);
pvl->setSpacing(0);
- trademarks_header_ = makePanelHeader("🛡", tr("TRADEMARKS"), ui::colors::AMBER);
+ trademarks_header_ = makePanelHeader("", tr("TRADEMARKS"), ui::colors::AMBER);
pvl->addWidget(trademarks_header_);
auto* body = new QWidget(this);
@@ -352,7 +352,7 @@ AboutScreen::AboutScreen(QWidget* parent) : QWidget(parent) {
auto* pvl = new QVBoxLayout(panel);
pvl->setContentsMargins(0, 0, 0, 0);
pvl->setSpacing(0);
- resources_header_ = makePanelHeader("🌐", tr("RESOURCES"), ui::colors::AMBER);
+ resources_header_ = makePanelHeader("", tr("RESOURCES"), ui::colors::AMBER);
pvl->addWidget(resources_header_);
auto* body = new QWidget(this);
@@ -458,7 +458,7 @@ void AboutScreen::retranslateUi() {
if (copyright_) copyright_->setText(tr("© 2024-2026 Fincept Corporation. All rights reserved."));
// Open source license — bullet 0 is the SPDX identifier (untranslated).
- setPanelHeaderText(oss_header_, "📄", tr("OPEN SOURCE LICENSE"));
+ setPanelHeaderText(oss_header_, "", tr("OPEN SOURCE LICENSE"));
if (oss_bullets_.size() == 4) {
setBulletText(oss_bullets_[1], tr("Free for personal & educational use"));
setBulletText(oss_bullets_[2], tr("Share modifications under same license"));
@@ -480,7 +480,7 @@ void AboutScreen::retranslateUi() {
if (open_folder_btn_) open_folder_btn_->setText(tr("Open Folder"));
// Trademarks
- setPanelHeaderText(trademarks_header_, "🛡", tr("TRADEMARKS"));
+ setPanelHeaderText(trademarks_header_, "", tr("TRADEMARKS"));
if (trademarks_desc_)
trademarks_desc_->setText(tr("\"Fincept\", \"Fincept Terminal\", and associated logos are trademarks of "
"Fincept Corporation. Use of these marks requires explicit written permission."));
@@ -489,7 +489,7 @@ void AboutScreen::retranslateUi() {
"affiliation with or endorsement by Fincept Corporation without prior written consent."));
// Resources
- setPanelHeaderText(resources_header_, "🌐", tr("RESOURCES"));
+ setPanelHeaderText(resources_header_, "", tr("RESOURCES"));
if (resource_btns_.size() == 6) {
resource_btns_[0]->setText(tr("GitHub Repository"));
resource_btns_[1]->setText(tr("License (AGPL-3.0)"));
diff --git a/fincept-qt/src/screens/ai_chat/AiChatBubble.cpp b/fincept-qt/src/screens/ai_chat/AiChatBubble.cpp
index 7ec8715e6..501275ea0 100644
--- a/fincept-qt/src/screens/ai_chat/AiChatBubble.cpp
+++ b/fincept-qt/src/screens/ai_chat/AiChatBubble.cpp
@@ -8,7 +8,7 @@
// ┌─ Header (title + subtitle "not saved" + voice / clear / close) ─┐
// │ ...messages, scrollable │
// │ ────────────────────────────────────────────────────────────── │
-// │ [ input box .................. ] 🎤 [Send] │
+// │ [ input box .................. ] [MIC] [Send] │
// │ status strip (one line, hidden when idle) │
// └──────────────────────────────────────────────────────────────────┘
@@ -321,13 +321,13 @@ QWidget* AiChatBubble::build_input_row() {
input_box_->installEventFilter(this);
hl->addWidget(input_box_, 1);
- mic_btn_ = new QPushButton("🎤");
+ mic_btn_ = new QPushButton("MIC");
mic_btn_->setFixedSize(38, 38);
mic_btn_->setCursor(Qt::PointingHandCursor);
mic_btn_->setToolTip(tr("Push-to-talk: click to dictate one message"));
// No setCheckable — listening state is rendered via property + opacity.
mic_btn_->setStyleSheet(QString("QPushButton{background:transparent;color:%1;border:1px solid %2;"
- "border-radius:0px;font-size:18px;}"
+ "border-radius:0px;font-size:11px;font-weight:700;letter-spacing:0.5px;}"
"QPushButton:hover{border-color:%3;}"
"QPushButton[listening=\"true\"]{background:%4;border-color:%3;color:%5;}")
.arg(col::TEXT_PRIMARY(), col::BORDER_MED(), col::AMBER(),
diff --git a/fincept-qt/src/screens/algo_trading/AlgoDeployDialog.cpp b/fincept-qt/src/screens/algo_trading/AlgoDeployDialog.cpp
index cae1cd1f1..8000f6939 100644
--- a/fincept-qt/src/screens/algo_trading/AlgoDeployDialog.cpp
+++ b/fincept-qt/src/screens/algo_trading/AlgoDeployDialog.cpp
@@ -8,6 +8,7 @@
#include <QDialogButtonBox>
#include <QFormLayout>
#include <QMessageBox>
+#include <QUuid>
#include <QVBoxLayout>
namespace fincept::screens {
@@ -35,6 +36,15 @@ AlgoDeployDialog::AlgoDeployDialog(const AlgoStrategy& strategy, QWidget* parent
result_.strategy_id = strategy.id;
result_.strategy_name = strategy.name;
result_.timeframe = strategy.timeframe;
+ // Match the dialog's timeframe to the strategy so the deployment evaluates on
+ // the same bars the strategy was designed/backtested on (build_ui already ran).
+ if (timeframe_combo_ && !strategy.timeframe.isEmpty())
+ timeframe_combo_->setCurrentText(strategy.timeframe);
+}
+
+void AlgoDeployDialog::set_symbol(const QString& symbol) {
+ if (symbol_edit_)
+ symbol_edit_->setText(symbol.trimmed().toUpper());
}
void AlgoDeployDialog::build_ui() {
@@ -138,13 +148,20 @@ void AlgoDeployDialog::build_ui() {
}
void AlgoDeployDialog::on_mode_changed(int index) {
- bool is_live = (mode_combo_->itemData(index).toString() == "live");
- account_label_->setVisible(is_live);
- account_combo_->setVisible(is_live);
- exchange_label_->setVisible(is_live);
- exchange_combo_->setVisible(is_live);
- product_type_label_->setVisible(is_live);
- product_type_combo_->setVisible(is_live);
+ // The broker/account is shown in BOTH modes: it is the real market-data source
+ // for the deployment (warm-up history + live quotes). Live additionally routes
+ // real orders through it; paper simulates fills against the same data. Hiding it
+ // for paper is what made users ask "which broker is it even using?".
+ Q_UNUSED(index);
+ account_label_->setVisible(true);
+ account_combo_->setVisible(true);
+ exchange_label_->setVisible(true);
+ exchange_combo_->setVisible(true);
+ product_type_label_->setVisible(true);
+ product_type_combo_->setVisible(true);
+
+ const bool is_live = (mode_combo_->currentData().toString() == "live");
+ account_label_->setText(is_live ? tr("Broker (orders + data):") : tr("Broker (data source):"));
}
void AlgoDeployDialog::populate_accounts() {
@@ -208,6 +225,10 @@ void AlgoDeployDialog::on_ok() {
}
}
+ // Mint a stable id for this deployment — used as the runner key, the
+ // algo_deployments primary key, and the WHERE of every status UPDATE.
+ if (result_.id.isEmpty())
+ result_.id = QUuid::createUuid().toString(QUuid::WithoutBraces);
result_.strategy_id = strategy_id_;
result_.strategy_name = strategy_name_;
result_.strategy_kind = kind_to_string(kind_from_id(strategy_id_));
@@ -219,18 +240,20 @@ void AlgoDeployDialog::on_ok() {
result_.max_order_value = max_order_spin_->value();
result_.max_daily_loss = max_loss_spin_->value();
- if (mode == "live") {
- auto account_id = account_combo_->currentData().toString();
+ // Attach the chosen connected account in BOTH modes — it's the market-data
+ // source. Live additionally routes real orders through it (backend=equity_broker);
+ // paper simulates fills (backend=paper) but still sources real data from it.
+ const QString account_id = account_combo_->currentData().toString();
+ if (!account_id.isEmpty()) {
auto account = AccountManager::instance().get_account(account_id);
- result_.backend = backend_to_string(TradingBackend::EquityBroker);
result_.broker_id = account.broker_id;
result_.broker_account_id = account_id;
result_.exchange = exchange_combo_->currentText();
int pt_index = product_type_combo_->currentData().toInt();
result_.product_type = product_type_str(static_cast<trading::ProductType>(pt_index));
- } else {
- result_.backend = backend_to_string(TradingBackend::Paper);
}
+ result_.backend = backend_to_string(mode == "live" ? TradingBackend::EquityBroker
+ : TradingBackend::Paper);
accept();
}
diff --git a/fincept-qt/src/screens/algo_trading/AlgoDeployDialog.h b/fincept-qt/src/screens/algo_trading/AlgoDeployDialog.h
index d0e761b0f..4f1281ded 100644
--- a/fincept-qt/src/screens/algo_trading/AlgoDeployDialog.h
+++ b/fincept-qt/src/screens/algo_trading/AlgoDeployDialog.h
@@ -21,6 +21,10 @@ class AlgoDeployDialog : public QDialog {
fincept::services::algo::AlgoDeployment result() const;
fincept::services::algo::AlgoDeployment deployment() const { return result_; }
+ // Prefill the symbol field (the builder's selected symbol isn't part of
+ // AlgoStrategy, so it's pushed in after construction).
+ void set_symbol(const QString& symbol);
+
protected:
void changeEvent(QEvent* event) override;
diff --git a/fincept-qt/src/screens/algo_trading/AlgoTradingScreen.cpp b/fincept-qt/src/screens/algo_trading/AlgoTradingScreen.cpp
index daa7ff643..c7e44f30a 100644
--- a/fincept-qt/src/screens/algo_trading/AlgoTradingScreen.cpp
+++ b/fincept-qt/src/screens/algo_trading/AlgoTradingScreen.cpp
@@ -89,6 +89,10 @@ void AlgoTradingScreen::build_ui() {
builder_->load_and_backtest(s, symbol, start, end);
});
+ // Deploying from the Builder jumps to the Dashboard (tab 3); on_tab_changed(3)
+ // refreshes list_deployments() so the just-persisted row shows immediately.
+ connect(builder_, &StrategyBuilderPanel::deployed, this, [this]() { on_tab_changed(3); });
+
root->addWidget(build_status_bar());
setStyleSheet(QString("background:%1;").arg(ui::colors::BG_BASE()));
}
diff --git a/fincept-qt/src/screens/algo_trading/DeploymentDashboard.cpp b/fincept-qt/src/screens/algo_trading/DeploymentDashboard.cpp
index ccc37fdea..14e741ff8 100644
--- a/fincept-qt/src/screens/algo_trading/DeploymentDashboard.cpp
+++ b/fincept-qt/src/screens/algo_trading/DeploymentDashboard.cpp
@@ -5,14 +5,17 @@
#include "core/currency/Currency.h"
#include "core/logging/Logger.h"
#include "services/algo_trading/AlgoTradingService.h"
+#include "trading/AccountManager.h"
#include "trading/BrokerRegistry.h"
#include "ui/theme/Theme.h"
+#include <QDateTime>
#include <QFrame>
#include <QHBoxLayout>
#include <QProgressBar>
#include <QPushButton>
#include <QScrollArea>
+#include <QTime>
#include <cmath>
@@ -64,6 +67,11 @@ DeploymentDashboard::DeploymentDashboard(QWidget* parent) : QWidget(parent) {
void DeploymentDashboard::connect_service() {
auto& engine = algo_ns::AlgoEngine::instance();
connect(&engine, &algo_ns::AlgoEngine::deployments_loaded, this, &DeploymentDashboard::on_deployments_loaded);
+ // Real-time per-tick updates — the card refreshes in place from these, not the
+ // 5s DB poll (which only fixes the deployment list structure).
+ connect(&engine, &algo_ns::AlgoEngine::live_update, this, &DeploymentDashboard::on_live_update);
+ connect(&engine, &algo_ns::AlgoEngine::deployment_started, this,
+ [](const QString&) { algo_ns::AlgoEngine::instance().list_deployments(); });
connect(&engine, &algo_ns::AlgoEngine::deployment_stopped, this, [](const QString& id) {
LOG_INFO("AlgoTrading", QString("Deployment stopped: %1").arg(id));
algo_ns::AlgoEngine::instance().list_deployments();
@@ -73,6 +81,12 @@ void DeploymentDashboard::connect_service() {
// Also connect to legacy service for QC deployments
auto& svc = AlgoTradingService::instance();
connect(&svc, &AlgoTradingService::error_occurred, this, &DeploymentDashboard::on_error);
+
+ // Ticks the "updated Ns ago" labels once a second.
+ age_timer_ = new QTimer(this);
+ age_timer_->setInterval(1000);
+ connect(age_timer_, &QTimer::timeout, this, &DeploymentDashboard::refresh_ages);
+ age_timer_->start();
}
// ── Build summary stat card ─────────────────────────────────────────────────
@@ -162,6 +176,28 @@ QWidget* DeploymentDashboard::build_deployment_card(const AlgoDeployment& d, QWi
.arg(is_paper ? "22,163,74" : "217,119,6"));
top->addWidget(mode_badge);
+ // Broker + connection badge — so users can see WHICH broker is wired and whether
+ // it's currently connected (the data source for this deployment).
+ if (!d.broker_id.isEmpty()) {
+ const auto cstate = fincept::trading::AccountManager::instance().connection_state(d.broker_account_id);
+ const bool connected = (cstate == fincept::trading::ConnectionState::Connected);
+ auto* broker_badge = new QLabel(
+ d.broker_id.toUpper() + (connected ? QStringLiteral(" ● ") : QStringLiteral(" ○ ")) +
+ (connected ? tr("CONNECTED") : tr("OFFLINE")),
+ card);
+ const QString clr = connected ? fincept::ui::colors::POSITIVE() : fincept::ui::colors::NEGATIVE();
+ broker_badge->setStyleSheet(QString("color: %1; font-size: %2px; font-weight: 700; %3"
+ " padding: 2px 6px; background: transparent;"
+ " border: 1px solid %1;")
+ .arg(clr)
+ .arg(fincept::ui::fonts::TINY)
+ .arg(kMonoFont()));
+ broker_badge->setToolTip(connected
+ ? tr("Broker connected — sourcing live quotes")
+ : tr("Broker not connected — connect it in Equity Trading to get live data"));
+ top->addWidget(broker_badge);
+ }
+
// Entry side badge
bool is_sell = (d.entry_side == "SELL");
auto* side_badge = new QLabel(d.entry_side.isEmpty() ? "BUY" : d.entry_side, card);
@@ -195,12 +231,25 @@ QWidget* DeploymentDashboard::build_deployment_card(const AlgoDeployment& d, QWi
vl->addLayout(top);
+ // Live handles for this card — updated in place by on_live_update().
+ CardHandles h;
+ h.broker_id = d.broker_id;
+ h.mode = d.mode;
+
+ // "updated …" line (ticks via refresh_ages()).
+ h.updated = new QLabel(tr("waiting for data…"), card);
+ h.updated->setStyleSheet(QString("color: %1; font-size: %2px; %3 background: transparent; border: none;")
+ .arg(fincept::ui::colors::TEXT_TERTIARY())
+ .arg(fincept::ui::fonts::TINY)
+ .arg(kMonoFont()));
+ vl->addWidget(h.updated);
+
// ── Metrics row ─────────────────────────────────────────────────────────
auto* metrics = new QHBoxLayout;
metrics->setSpacing(16);
auto add_metric = [&](const QString& label, const QString& value, const QString& color,
- int font_size = fincept::ui::fonts::SMALL) {
+ int font_size, QLabel** out) {
auto* w = new QWidget(card);
auto* ml = new QVBoxLayout(w);
ml->setContentsMargins(0, 0, 0, 0);
@@ -219,46 +268,52 @@ QWidget* DeploymentDashboard::build_deployment_card(const AlgoDeployment& d, QWi
ml->addWidget(lbl);
ml->addWidget(val);
metrics->addWidget(w);
+ if (out)
+ *out = val;
};
- // P&L — larger font to match Quant Lab KPI style
- double total_pnl = d.total_pnl + d.unrealized_pnl;
const auto cs = currency_symbol(d.broker_id);
+ const double total_pnl = d.total_pnl + d.unrealized_pnl;
+
+ add_metric(tr("LTP"),
+ d.current_price > 0 ? QString("%1%2").arg(cs).arg(d.current_price, 0, 'f', 2)
+ : QStringLiteral("—"),
+ fincept::ui::colors::CYAN, fincept::ui::fonts::TITLE, &h.ltp);
add_metric(tr("P&L"), QString("%1%2%3").arg(total_pnl >= 0 ? "+" : "-", cs).arg(std::abs(total_pnl), 0, 'f', 2),
total_pnl >= 0 ? fincept::ui::colors::POSITIVE : fincept::ui::colors::NEGATIVE,
- fincept::ui::fonts::TITLE);
-
- // Current price
- if (d.current_price > 0) {
- add_metric(tr("LTP"), QString("%1%2").arg(cs).arg(d.current_price, 0, 'f', 2),
- fincept::ui::colors::CYAN);
- }
-
- // Win Rate
- add_metric(tr("WIN RATE"), QString("%1%").arg(d.win_rate, 0, 'f', 1), fincept::ui::colors::TEXT_PRIMARY);
-
- // Position
- if (d.position_qty != 0) {
- add_metric(tr("POSITION"),
- QString("%1 %2 @ %3")
- .arg(d.position_qty, 0, 'f', 2)
- .arg(d.position_side.toUpper())
- .arg(d.position_entry, 0, 'f', 2),
- fincept::ui::colors::TEXT_PRIMARY);
- } else {
- add_metric(tr("POSITION"), tr("FLAT"), fincept::ui::colors::TEXT_TERTIARY);
- }
-
- // Trades
- add_metric(tr("TRADES"), QString::number(d.total_trades), fincept::ui::colors::TEXT_PRIMARY);
-
- // Max Drawdown
- add_metric(tr("MAX DD"), QString("-%1%").arg(std::abs(d.max_drawdown), 0, 'f', 2), fincept::ui::colors::NEGATIVE);
+ fincept::ui::fonts::TITLE, &h.pnl);
+ add_metric(tr("WIN RATE"), QString("%1%").arg(d.win_rate, 0, 'f', 1), fincept::ui::colors::TEXT_PRIMARY,
+ fincept::ui::fonts::SMALL, nullptr);
+ add_metric(tr("POSITION"), tr("FLAT"), fincept::ui::colors::TEXT_TERTIARY, fincept::ui::fonts::SMALL, &h.position);
+ add_metric(tr("TRADES"), QString::number(d.total_trades), fincept::ui::colors::TEXT_PRIMARY,
+ fincept::ui::fonts::SMALL, &h.trades);
+ add_metric(tr("MAX DD"), QString("-%1%").arg(std::abs(d.max_drawdown), 0, 'f', 2), fincept::ui::colors::NEGATIVE,
+ fincept::ui::fonts::SMALL, nullptr);
metrics->addStretch();
-
vl->addLayout(metrics);
+ // ── Condition status (filled live by on_live_update) ─────────────────────
+ auto* cond_title = new QLabel(tr("CONDITIONS"), card);
+ cond_title->setStyleSheet(kSectionLabel());
+ vl->addWidget(cond_title);
+ auto* cond_box = new QWidget(card);
+ h.conditions = new QVBoxLayout(cond_box);
+ h.conditions->setContentsMargins(0, 0, 0, 0);
+ h.conditions->setSpacing(2);
+ vl->addWidget(cond_box);
+
+ // ── Activity log (last few events) ───────────────────────────────────────
+ h.activity = new QLabel(card);
+ h.activity->setWordWrap(true);
+ h.activity->setStyleSheet(QString("color: %1; font-size: %2px; %3 background: transparent; border: none;")
+ .arg(fincept::ui::colors::TEXT_TERTIARY())
+ .arg(fincept::ui::fonts::TINY)
+ .arg(kMonoFont()));
+ vl->addWidget(h.activity);
+
+ cards_.insert(d.id, h);
+
// ── Win rate progress bar ────────────────────────────────────────────────
auto* win_bar = new QProgressBar(card);
win_bar->setFixedHeight(4);
@@ -313,7 +368,8 @@ QWidget* DeploymentDashboard::build_deployment_card(const AlgoDeployment& d, QWi
.arg(fincept::ui::fonts::TINY)
.arg(kMonoFont()));
connect(remove_btn, &QPushButton::clicked, card, [dep_id = d.id]() {
- algo_ns::AlgoEngine::instance().stop_deployment(dep_id);
+ algo_ns::AlgoEngine::instance().remove_deployment(dep_id);
+ LOG_INFO("AlgoTrading", QString("Remove requested: %1").arg(dep_id));
});
btn_row->addWidget(remove_btn);
}
@@ -505,14 +561,10 @@ void DeploymentDashboard::build_ui() {
// ── Slots ───────────────────────────────────────────────────────────────────
void DeploymentDashboard::on_deployments_loaded(QVector<AlgoDeployment> deployments) {
- // Clear existing cards
- while (deployments_layout_->count() > 0) {
- auto* item = deployments_layout_->takeAt(0);
- if (item->widget())
- item->widget()->deleteLater();
- delete item;
- }
-
+ // This is the STRUCTURAL refresh (5s DB poll). Live values come from
+ // on_live_update(); we must NOT tear down/rebuild cards here when the set of
+ // deployments is unchanged — doing so blanked every card to its (stale, zero)
+ // DB values for a moment between live snapshots, which read as a 1s blink.
update_summary(deployments);
deployment_count_ = deployments.size();
@@ -527,11 +579,150 @@ void DeploymentDashboard::on_deployments_loaded(QVector<AlgoDeployment> deployme
.arg(kMonoFont()));
}
+ // Signature includes status so a running→stopped transition (e.g. after STOP)
+ // forces a rebuild — the card then swaps RUNNING/STOP → STOPPED/REMOVE. Without
+ // status here, stopping a deployment left the card frozen on STOP (looked broken).
+ QStringList new_sig;
+ new_sig.reserve(deployments.size());
+ for (const auto& d : deployments)
+ new_sig << (d.id + QLatin1Char('|') + d.status);
+
+ // Same deployments AND same statuses → keep the live-updated cards untouched.
+ if (new_sig == card_order_ && new_sig.size() == cards_.size())
+ return;
+
+ // Structure changed (deploy/remove) → rebuild the card list. Old widgets are
+ // deleted, so drop their handles first.
+ cards_.clear();
+ card_order_.clear();
+ while (deployments_layout_->count() > 0) {
+ auto* item = deployments_layout_->takeAt(0);
+ if (item->widget())
+ item->widget()->deleteLater();
+ delete item;
+ }
for (const auto& d : deployments) {
deployments_layout_->addWidget(build_deployment_card(d, nullptr));
+ card_order_.append(d.id + QLatin1Char('|') + d.status);
+ }
+
+ LOG_INFO("AlgoTrading", QString("Dashboard rebuilt: %1 deployments").arg(deployments.size()));
+}
+
+void DeploymentDashboard::on_live_update(const QString& deployment_id,
+ const fincept::algo::AlgoLiveSnapshot& snap) {
+ auto it = cards_.find(deployment_id);
+ if (it == cards_.end())
+ return; // structure not built yet — next list_deployments() will add it
+ CardHandles& h = it.value();
+ h.last_update_ms = snap.last_update_ms;
+
+ const QString cs = currency_symbol(h.broker_id);
+ const auto& m = snap.metrics;
+
+ if (h.ltp)
+ h.ltp->setText(QString("%1%2").arg(cs).arg(snap.current_price, 0, 'f', 2));
+
+ if (h.pnl) {
+ const double total = m.total_pnl + m.unrealized_pnl;
+ h.pnl->setText(QString("%1%2%3").arg(total >= 0 ? "+" : "-", cs).arg(std::abs(total), 0, 'f', 2));
+ h.pnl->setStyleSheet(QString("color: %1; font-size: %2px; font-weight: 700; %3"
+ " background: transparent; border: none;")
+ .arg(total >= 0 ? fincept::ui::colors::POSITIVE() : fincept::ui::colors::NEGATIVE())
+ .arg(fincept::ui::fonts::TITLE)
+ .arg(kMonoFont()));
}
- LOG_INFO("AlgoTrading", QString("Dashboard updated: %1 deployments").arg(deployments.size()));
+ if (h.position) {
+ if (m.current_position_qty != 0)
+ h.position->setText(QString("%1 %2 @ %3")
+ .arg(m.current_position_qty, 0, 'f', 0)
+ .arg(m.current_position_side.toUpper())
+ .arg(m.current_position_entry, 0, 'f', 2));
+ else
+ h.position->setText(tr("FLAT"));
+ }
+ if (h.trades)
+ h.trades->setText(QString::number(m.total_trades));
+
+ // Update the per-condition status rows IN PLACE (only rebuild if the count
+ // changed) so they don't flicker every tick.
+ if (h.conditions) {
+ const int n = static_cast<int>(snap.conditions.size());
+ const bool same_count = (h.conditions->count() == n);
+ if (!same_count) {
+ while (h.conditions->count() > 0) {
+ auto* item = h.conditions->takeAt(0);
+ if (item->widget())
+ item->widget()->deleteLater();
+ delete item;
+ }
+ }
+ const bool in_position = (m.current_position_qty != 0);
+ for (int i = 0; i < n; ++i) {
+ const auto& c = snap.conditions[i];
+ // GREEN = currently met OR already executed. Entry rows stay green once a
+ // position is open (they matched & fired) even if the live price has since
+ // moved off the level — showing them grey there confused users.
+ const bool executed = (c.section == QLatin1String("entry") && in_position);
+ const bool green = c.met || executed;
+
+ QString hint;
+ if (!green) {
+ if (c.op == "crosses_above" && c.computed >= c.target)
+ hint = tr(" ⚠ already above — can't cross up");
+ else if (c.op == "crosses_below" && c.computed <= c.target)
+ hint = tr(" ⚠ already below — can't cross down");
+ }
+ const QString suffix = (executed && !c.met) ? tr(" · executed") : QString();
+
+ const QString tick = green ? QStringLiteral("✓") : QStringLiteral("✗");
+ const QString clr = green ? fincept::ui::colors::POSITIVE()
+ : (hint.isEmpty() ? fincept::ui::colors::TEXT_SECONDARY()
+ : fincept::ui::colors::WARNING());
+ const QString text = QString("%1 %2 now %3%4%5")
+ .arg(tick, c.label).arg(c.computed, 0, 'f', 2).arg(hint, suffix);
+ const QString ss = QString("color: %1; font-size: %2px; %3 background: transparent; border: none;")
+ .arg(clr)
+ .arg(fincept::ui::fonts::TINY)
+ .arg(kMonoFont());
+ QLabel* row = same_count ? qobject_cast<QLabel*>(h.conditions->itemAt(i)->widget()) : nullptr;
+ if (row) {
+ row->setText(text);
+ row->setStyleSheet(ss);
+ } else {
+ row = new QLabel(text, nullptr);
+ row->setStyleSheet(ss);
+ h.conditions->addWidget(row);
+ }
+ }
+ }
+
+ // Append activity note (keep last 4).
+ if (h.activity && !snap.note.isEmpty()) {
+ const QString ts = QTime::currentTime().toString("HH:mm:ss");
+ h.activity_lines.prepend(QString("%1 %2").arg(ts, snap.note));
+ while (h.activity_lines.size() > 4)
+ h.activity_lines.removeLast();
+ h.activity->setText(h.activity_lines.join("\n"));
+ }
+
+ refresh_ages();
+}
+
+void DeploymentDashboard::refresh_ages() {
+ const int64_t now = QDateTime::currentMSecsSinceEpoch();
+ for (auto it = cards_.begin(); it != cards_.end(); ++it) {
+ CardHandles& h = it.value();
+ if (!h.updated)
+ continue;
+ if (h.last_update_ms <= 0) {
+ h.updated->setText(tr("waiting for data…"));
+ continue;
+ }
+ const int secs = static_cast<int>((now - h.last_update_ms) / 1000);
+ h.updated->setText(secs <= 1 ? tr("updated just now") : tr("updated %1s ago").arg(secs));
+ }
}
void DeploymentDashboard::on_error(const QString& context, const QString& msg) {
diff --git a/fincept-qt/src/screens/algo_trading/DeploymentDashboard.h b/fincept-qt/src/screens/algo_trading/DeploymentDashboard.h
index 9ef90fbda..6ac644ce5 100644
--- a/fincept-qt/src/screens/algo_trading/DeploymentDashboard.h
+++ b/fincept-qt/src/screens/algo_trading/DeploymentDashboard.h
@@ -1,12 +1,16 @@
// src/screens/algo_trading/DeploymentDashboard.h
#pragma once
+#include "algo_engine/AlgoEngineTypes.h"
#include "services/algo_trading/AlgoTradingTypes.h"
#include <QEvent>
#include <QFrame>
+#include <QHash>
#include <QLabel>
#include <QProgressBar>
#include <QPushButton>
+#include <QStringList>
+#include <QTimer>
#include <QVBoxLayout>
#include <QWidget>
@@ -23,6 +27,7 @@ class DeploymentDashboard : public QWidget {
private slots:
void on_deployments_loaded(QVector<fincept::services::algo::AlgoDeployment> deployments);
+ void on_live_update(const QString& deployment_id, const fincept::algo::AlgoLiveSnapshot& snap);
void on_error(const QString& context, const QString& msg);
private:
@@ -30,8 +35,28 @@ class DeploymentDashboard : public QWidget {
void connect_service();
QWidget* build_deployment_card(const fincept::services::algo::AlgoDeployment& d, QWidget* parent);
void update_summary(const QVector<fincept::services::algo::AlgoDeployment>& deployments);
+ void refresh_ages();
void retranslateUi();
+ // Live-updated widgets per deployment, so the card updates in place (no flicker)
+ // on each snapshot instead of rebuilding the whole list.
+ struct CardHandles {
+ QLabel* ltp = nullptr;
+ QLabel* updated = nullptr;
+ QLabel* pnl = nullptr;
+ QLabel* position = nullptr;
+ QLabel* trades = nullptr;
+ QVBoxLayout* conditions = nullptr; // condition-status rows (rebuilt per update)
+ QLabel* activity = nullptr;
+ QString broker_id;
+ QString mode;
+ int64_t last_update_ms = 0;
+ QStringList activity_lines;
+ };
+ QHash<QString, CardHandles> cards_;
+ QStringList card_order_; // deployment ids currently shown, to detect structure changes
+ QTimer* age_timer_ = nullptr;
+
// Summary stats (value labels captured by build_stat_card; captions cached for retranslate)
QLabel* active_count_ = nullptr;
QLabel* active_caption_ = nullptr;
diff --git a/fincept-qt/src/screens/algo_trading/StrategyBuilderPanel.cpp b/fincept-qt/src/screens/algo_trading/StrategyBuilderPanel.cpp
index d53326dff..5fa5f67a3 100644
--- a/fincept-qt/src/screens/algo_trading/StrategyBuilderPanel.cpp
+++ b/fincept-qt/src/screens/algo_trading/StrategyBuilderPanel.cpp
@@ -7,18 +7,31 @@
#include "core/logging/Logger.h"
#include "screens/algo_trading/AlgoDeployDialog.h"
#include "services/algo_trading/AlgoTradingService.h"
+#include "trading/AccountManager.h"
+#include "trading/BrokerInterface.h"
+#include "trading/BrokerRegistry.h"
#include "ui/theme/Theme.h"
#include <QDate>
#include <QDateEdit>
+#include <QEventLoop>
#include <QFrame>
+#include <QFutureWatcher>
#include <QGridLayout>
#include <QHBoxLayout>
+#include <QJsonArray>
#include <QJsonDocument>
+#include <QJsonObject>
+#include <QMessageBox>
#include <QScrollArea>
+#include <QSet>
#include <QSplitter>
+#include <QTimer>
#include <QUuid>
#include <QVBoxLayout>
+#include <QtConcurrent>
+
+#include <cmath>
namespace fincept::screens {
namespace algo_ns = fincept::algo;
@@ -126,6 +139,64 @@ QString status_style() {
.arg(ui::fonts::DATA_FAMILY());
}
+// Bounded fetch of the current LTP from the connected broker for deploy-time sanity
+// checks. Runs off-thread with a short timeout so the deploy click never hangs.
+double fetch_quote_ltp(const QString& broker_id, const QString& account_id, const QString& symbol,
+ int timeout_ms) {
+ if (broker_id.isEmpty() || account_id.isEmpty() || symbol.isEmpty())
+ return 0.0;
+ auto fut = QtConcurrent::run([broker_id, account_id, symbol]() -> double {
+ auto* broker = trading::BrokerRegistry::instance().get(broker_id);
+ if (!broker)
+ return 0.0;
+ auto creds = trading::AccountManager::instance().load_credentials(account_id);
+ auto resp = broker->get_quotes(creds, {symbol});
+ if (resp.success && resp.data.has_value() && !resp.data->isEmpty())
+ return resp.data->first().ltp;
+ return 0.0;
+ });
+ QFutureWatcher<double> watcher;
+ QEventLoop loop;
+ QObject::connect(&watcher, &QFutureWatcher<double>::finished, &loop, &QEventLoop::quit);
+ watcher.setFuture(fut);
+ QTimer::singleShot(timeout_ms, &loop, &QEventLoop::quit);
+ loop.exec();
+ return watcher.isFinished() ? watcher.result() : 0.0;
+}
+
+// Collects human-readable warnings for price-based leaves that can't fire at `price`
+// (crossover already on the wrong side, or threshold wildly far from price). Only
+// price-scale indicators are checked — RSI<30 etc. are left alone.
+void scan_unreachable(const QJsonArray& conds, const QString& section, double price, QStringList& out) {
+ static const QSet<QString> price_inds = {"CLOSE", "OPEN", "HIGH", "LOW", "VWAP"};
+ for (const auto& v : conds) {
+ const QJsonObject o = v.toObject();
+ if (o.contains("children")) {
+ scan_unreachable(o.value("children").toArray(), section, price, out);
+ continue;
+ }
+ if (o.value("compare_mode").toString("value") != "value")
+ continue;
+ const QString ind = o.value("indicator").toString();
+ if (!price_inds.contains(ind))
+ continue;
+ const QString op = o.value("operator").toString();
+ const double val = o.value("value").toDouble();
+ if (val <= 0)
+ continue;
+ if (op == "crosses_above" && price > val)
+ out << QString("• %1 '%2 crosses above %3' — price %4 is already above; it can never cross up.")
+ .arg(section, ind).arg(val, 0, 'f', 2).arg(price, 0, 'f', 2);
+ else if (op == "crosses_below" && price < val)
+ out << QString("• %1 '%2 crosses below %3' — price %4 is already below; it can never cross down.")
+ .arg(section, ind).arg(val, 0, 'f', 2).arg(price, 0, 'f', 2);
+ else if (std::abs(price - val) / price > 0.25)
+ out << QString("• %1 '%2 %3 %4' — threshold is %5% away from price %6.")
+ .arg(section, ind, op).arg(val, 0, 'f', 2)
+ .arg(std::abs(price - val) / price * 100.0, 0, 'f', 0).arg(price, 0, 'f', 2);
+ }
+}
+
} // namespace
StrategyBuilderPanel::StrategyBuilderPanel(QWidget* parent)
@@ -467,8 +538,13 @@ void StrategyBuilderPanel::on_backtest() {
}
void StrategyBuilderPanel::on_deploy() {
+ // Guards use a visible dialog/banner: the status label lives in the right-hand
+ // backtest card, far from the Deploy button, so a silent setText() there reads
+ // as "Deploy did nothing".
if (name_edit_->text().trimmed().isEmpty()) {
- status_label_->setText(tr("Save strategy first."));
+ QMessageBox::warning(this, tr("Deploy"),
+ tr("Enter a strategy name before deploying."));
+ name_edit_->setFocus();
return;
}
if (const QString err = validate(); !err.isEmpty()) {
@@ -482,19 +558,66 @@ void StrategyBuilderPanel::on_deploy() {
auto strat = build_strategy();
auto* dialog = new AlgoDeployDialog(strat, this);
+ dialog->set_symbol(symbol_combo_->currentText()); // carry the builder's symbol in
if (dialog->exec() == QDialog::Accepted) {
auto deployment = dialog->deployment();
deployment.quantity = risk_panel_->quantity();
deployment.max_order_value = risk_panel_->max_order_value();
+ // Sanity check (non-blocking, bounded): warn if a rule can't fire at the
+ // current price — e.g. 'crosses_above 280.45' on a stock trading at 1204.
+ const double cur_price = fetch_quote_ltp(deployment.broker_id, deployment.broker_account_id,
+ deployment.symbol, 2500);
+ if (cur_price > 0) {
+ QStringList warns;
+ scan_unreachable(strat.entry_conditions, tr("Entry"), cur_price, warns);
+ scan_unreachable(strat.exit_conditions, tr("Exit"), cur_price, warns);
+ if (!warns.isEmpty()) {
+ const auto btn = QMessageBox::warning(
+ this, tr("Deploy — check conditions"),
+ tr("%1 is at %2, but some rules may never trigger:\n\n%3\n\nDeploy anyway?")
+ .arg(deployment.symbol).arg(cur_price, 0, 'f', 2).arg(warns.join("\n\n")),
+ QMessageBox::Yes | QMessageBox::Cancel, QMessageBox::Cancel);
+ if (btn != QMessageBox::Yes) {
+ dialog->deleteLater();
+ return;
+ }
+ }
+ }
+
+ // Confirm before deploying an exact duplicate of an already-running setup.
+ if (algo_ns::AlgoEngine::instance().has_active_duplicate(
+ deployment.strategy_id, deployment.symbol, deployment.mode, deployment.entry_side)) {
+ const auto btn = QMessageBox::question(
+ this, tr("Already deployed"),
+ tr("An identical deployment is already running:\n\n%1 · %2 · %3 · %4\n\n"
+ "Deploy another copy anyway?")
+ .arg(deployment.strategy_name, deployment.symbol, deployment.mode.toUpper(),
+ deployment.entry_side),
+ QMessageBox::Yes | QMessageBox::Cancel, QMessageBox::Cancel);
+ if (btn != QMessageBox::Yes) {
+ dialog->deleteLater();
+ return;
+ }
+ }
+
// Save strategy first
services::algo::AlgoTradingService::instance().save_strategy(strat);
- // Deploy via C++ engine
+ LOG_INFO("AlgoTrading",
+ QString("Deploy requested: id=%1 strategy='%2' symbol=%3 mode=%4 backend=%5 "
+ "broker=%6 acct=%7 qty=%8")
+ .arg(deployment.id, strat.name, deployment.symbol, deployment.mode,
+ deployment.backend, deployment.broker_id, deployment.broker_account_id)
+ .arg(deployment.quantity));
+
+ // Deploy via C++ engine (persists the row, then starts the runner). Feedback
+ // is the jump to the Dashboard below — NOT a label on the backtest card, which
+ // is unrelated to deployment and read as "stuck on Deploying…".
algo_ns::AlgoEngine::instance().start_deployment(deployment, strat);
- status_label_->setText(tr("Deploying strategy..."));
- // Switch to deployments tab handled by AlgoTradingScreen
+ // Tell the parent screen to switch to the Dashboard and refresh.
+ emit deployed();
}
dialog->deleteLater();
}
diff --git a/fincept-qt/src/screens/algo_trading/StrategyBuilderPanel.h b/fincept-qt/src/screens/algo_trading/StrategyBuilderPanel.h
index 5cdc5a639..a6ecafb33 100644
--- a/fincept-qt/src/screens/algo_trading/StrategyBuilderPanel.h
+++ b/fincept-qt/src/screens/algo_trading/StrategyBuilderPanel.h
@@ -33,6 +33,11 @@ public:
void load_and_backtest(const services::algo::AlgoStrategy& strategy, const QString& symbol,
const QString& start_date, const QString& end_date);
+signals:
+ // Emitted after a strategy is successfully deployed, so the parent screen can
+ // switch to the Dashboard tab and refresh the deployment list.
+ void deployed();
+
protected:
void changeEvent(QEvent* event) override;
diff --git a/fincept-qt/src/screens/auth/PricingScreen.cpp b/fincept-qt/src/screens/auth/PricingScreen.cpp
index 933275959..c74d51b07 100644
--- a/fincept-qt/src/screens/auth/PricingScreen.cpp
+++ b/fincept-qt/src/screens/auth/PricingScreen.cpp
@@ -371,9 +371,10 @@ QWidget* PricingScreen::create_plan_card(const auth::SubscriptionPlan& plan, int
.arg(MF));
vl->addWidget(price);
} else {
- // Symbol-only (values are stored USD; not FX-converted). Preserve the
+ // Plan prices are intrinsically USD (not FX-converted), so pin the symbol
+ // to USD rather than following the global currency preference. Preserve the
// whole-number format used for plan prices.
- auto* price = new QLabel(cur::symbol() + QString::number(plan.price_usd, 'f', 0));
+ auto* price = new QLabel(cur::symbol_for("USD") + QString::number(plan.price_usd, 'f', 0));
price->setAlignment(Qt::AlignCenter);
price->setStyleSheet(QString("color: %1; font-size: 28px; font-weight: 700; "
"background: transparent; %2")
diff --git a/fincept-qt/src/screens/crypto_trading/CryptoTradingScreen.cpp b/fincept-qt/src/screens/crypto_trading/CryptoTradingScreen.cpp
index d7cada000..cc0b2172c 100644
--- a/fincept-qt/src/screens/crypto_trading/CryptoTradingScreen.cpp
+++ b/fincept-qt/src/screens/crypto_trading/CryptoTradingScreen.cpp
@@ -28,6 +28,7 @@
#include "ui/theme/StyleSheets.h"
#include "ui/theme/Theme.h"
+#include <QAbstractItemView>
#include <QCompleter>
#include <QDateTime>
#include <QHBoxLayout>
@@ -176,6 +177,25 @@ void CryptoTradingScreen::setup_ui() {
completer->setCaseSensitivity(Qt::CaseInsensitive);
completer->setFilterMode(Qt::MatchContains);
symbol_input_->setCompleter(completer);
+
+ // The completer popup is an unstyled top-level QListView — give it a solid
+ // background (it would otherwise render transparent over the screen) and wire
+ // activated() so a mouse click / Enter / Arrow+Enter on a suggestion selects
+ // the symbol, not merely pastes it into the box.
+ if (auto* popup = completer->popup()) {
+ popup->setObjectName("cryptoSymbolCompleterPopup");
+ popup->setStyleSheet(
+ QString("QListView { background:%1; color:%2; border:1px solid %3; outline:none;"
+ " font-family:%4; font-size:%5px; }"
+ "QListView::item { padding:4px 8px; border:none; }"
+ "QListView::item:selected { background:%6; color:%2; }")
+ .arg(fincept::ui::colors::BG_SURFACE(), fincept::ui::colors::TEXT_PRIMARY(),
+ fincept::ui::colors::BORDER_MED(), fincept::ui::fonts::DATA_FAMILY())
+ .arg(fincept::ui::fonts::SMALL)
+ .arg(fincept::ui::colors::BG_HOVER()));
+ }
+ connect(completer, QOverload<const QString&>::of(&QCompleter::activated), this,
+ [this](const QString& choice) { on_symbol_selected(choice.trimmed().toUpper()); });
connect(symbol_input_, &QLineEdit::returnPressed, this,
[this]() { on_symbol_selected(symbol_input_->text().trimmed().toUpper()); });
cmd_layout->addWidget(symbol_input_);
diff --git a/fincept-qt/src/screens/equity_trading/EquityChart.cpp b/fincept-qt/src/screens/equity_trading/EquityChart.cpp
index 68d3d0a8a..6c1ff703b 100644
--- a/fincept-qt/src/screens/equity_trading/EquityChart.cpp
+++ b/fincept-qt/src/screens/equity_trading/EquityChart.cpp
@@ -34,6 +34,7 @@
#include <QCandlestickSet>
#include <QChart>
#include <QChartView>
+#include <QContextMenuEvent>
#include <QDateTime>
#include <QDateTimeAxis>
#include <QEnterEvent>
@@ -47,6 +48,7 @@
#include <QHBoxLayout>
#include <QLabel>
#include <QLineSeries>
+#include <QMenu>
#include <QMouseEvent>
#include <QPainter>
#include <QPen>
@@ -146,6 +148,15 @@ class HoverEquityChartView : public QChartView {
}
e->accept();
}
+ void contextMenuEvent(QContextMenuEvent* e) override {
+ if (host_ && chart()) {
+ const QPointF v = chart()->mapToValue(e->pos());
+ host_->show_trade_menu(v.y(), e->globalPos());
+ e->accept();
+ return;
+ }
+ QChartView::contextMenuEvent(e);
+ }
private:
EquityChart* host_ = nullptr;
@@ -727,4 +738,21 @@ void EquityChart::on_hover_leave() {
update_last_price_marker();
}
+void EquityChart::show_trade_menu(double price, const QPoint& global_pos) {
+ const QString pstr = price > 0 ? QString::number(price, 'f', 2) : QString();
+ QMenu menu(this);
+ QAction* buy_act = menu.addAction(price > 0 ? tr("Buy @ %1").arg(pstr) : tr("Buy"));
+ QAction* sell_act = menu.addAction(price > 0 ? tr("Sell @ %1").arg(pstr) : tr("Sell"));
+ menu.addSeparator();
+ QAction* wl_act = menu.addAction(tr("Add to watchlist"));
+
+ QAction* chosen = menu.exec(global_pos);
+ if (chosen == buy_act)
+ emit buy_requested(price);
+ else if (chosen == sell_act)
+ emit sell_requested(price);
+ else if (chosen == wl_act)
+ emit add_to_watchlist_requested();
+}
+
} // namespace fincept::screens::equity
diff --git a/fincept-qt/src/screens/equity_trading/EquityChart.h b/fincept-qt/src/screens/equity_trading/EquityChart.h
index 8a626d534..941c0d702 100644
--- a/fincept-qt/src/screens/equity_trading/EquityChart.h
+++ b/fincept-qt/src/screens/equity_trading/EquityChart.h
@@ -7,6 +7,7 @@
#include <QColor>
#include <QEvent>
+#include <QPoint>
#include <QPushButton>
#include <QVector>
#include <QWidget>
@@ -46,12 +47,18 @@ public:
signals:
void timeframe_changed(const QString& tf);
+ void buy_requested(double price);
+ void sell_requested(double price);
+ void add_to_watchlist_requested();
protected:
void changeEvent(QEvent* event) override;
private:
void retranslateUi();
+ // Pop the right-click trading menu (Buy/Sell @ price + watchlist) at the
+ // given screen position; `price` is the y-axis value under the cursor.
+ void show_trade_menu(double price, const QPoint& global_pos);
void rebuild_chart();
void update_axes(double min_price, double max_price, qint64 min_time, qint64 max_time);
void set_active_tf(int idx);
diff --git a/fincept-qt/src/screens/equity_trading/EquityChartPanel.cpp b/fincept-qt/src/screens/equity_trading/EquityChartPanel.cpp
index 8065565c4..16024fe0c 100644
--- a/fincept-qt/src/screens/equity_trading/EquityChartPanel.cpp
+++ b/fincept-qt/src/screens/equity_trading/EquityChartPanel.cpp
@@ -38,6 +38,14 @@ EquityChartPanel::EquityChartPanel(QWidget* parent) : QWidget(parent) {
kline_ = new fincept::ui::KLineChartWidget(this);
if (kline_->is_available()) {
build_kline_ui();
+ // Right-click chart trading — enable the menu and forward its actions up.
+ kline_->set_trading_menu_enabled(true);
+ connect(kline_, &fincept::ui::KLineChartWidget::buy_requested, this,
+ &EquityChartPanel::buy_requested);
+ connect(kline_, &fincept::ui::KLineChartWidget::sell_requested, this,
+ &EquityChartPanel::sell_requested);
+ connect(kline_, &fincept::ui::KLineChartWidget::add_to_watchlist_requested, this,
+ &EquityChartPanel::add_to_watchlist_requested);
} else {
// No WebEngine — drop KLineChart, use the Qt-Charts chart (which carries
// its own timeframe buttons + overlays). Forward its timeframe signal.
@@ -46,6 +54,10 @@ EquityChartPanel::EquityChartPanel(QWidget* parent) : QWidget(parent) {
fallback_ = new EquityChart(this);
connect(fallback_, &EquityChart::timeframe_changed, this,
&EquityChartPanel::timeframe_changed);
+ connect(fallback_, &EquityChart::buy_requested, this, &EquityChartPanel::buy_requested);
+ connect(fallback_, &EquityChart::sell_requested, this, &EquityChartPanel::sell_requested);
+ connect(fallback_, &EquityChart::add_to_watchlist_requested, this,
+ &EquityChartPanel::add_to_watchlist_requested);
root->addWidget(fallback_);
}
@@ -308,6 +320,26 @@ void EquityChartPanel::set_position(const QString& symbol, const QString& side,
clear_position();
return;
}
+
+ // Title (LONG/SHORT qty @ entry) changes only when the position changes, so
+ // render it here — NOT on every per-tick P&L refresh, where setStyleSheet()
+ // would force a needless style re-parse + re-polish each tick.
+ {
+ namespace c = fincept::ui::colors;
+ const bool is_long = (pos_side_ != QLatin1String("short"));
+ const QString qty_str = QString::number(pos_qty_, 'f', pos_qty_ == qRound64(pos_qty_) ? 0 : 2);
+ pos_title_lbl_->setText(QStringLiteral("%1 %2 @ %3")
+ .arg(is_long ? tr("LONG") : tr("SHORT"))
+ .arg(qty_str)
+ .arg(QString::number(pos_entry_, 'f', 2)));
+ pos_title_lbl_->setStyleSheet(QString("background:transparent;border:none;font-weight:700;"
+ "font-size:%1px;font-family:%2;color:%3;")
+ .arg(fincept::ui::fonts::TINY)
+ .arg(fincept::ui::fonts::DATA_FAMILY())
+ .arg(is_long ? c::POSITIVE() : c::NEGATIVE()));
+ }
+ pos_pnl_sign_ = 0; // force the P&L color to be re-applied for the new position
+
refresh_position_card();
draw_position_line();
if (pos_card_) {
@@ -332,8 +364,9 @@ void EquityChartPanel::update_pnl(double ltp) {
pos_ltp_ = ltp;
if (!has_position_)
return;
+ // P&L text only. refresh_position_card() already adjustSize()s the card; the
+ // full layout (reposition + raise) runs on set_position()/resize, not per tick.
refresh_position_card();
- layout_position_card();
}
void EquityChartPanel::refresh_position_card() {
@@ -341,18 +374,9 @@ void EquityChartPanel::refresh_position_card() {
return;
namespace c = fincept::ui::colors;
+ // Per-tick path: only the live P&L changes here. The title (LONG/SHORT qty @
+ // entry) is rendered once in set_position(), not on every tick.
const bool is_long = (pos_side_ != QLatin1String("short"));
- const QString qty_str = QString::number(pos_qty_, 'f', pos_qty_ == qRound64(pos_qty_) ? 0 : 2);
- pos_title_lbl_->setText(QStringLiteral("%1 %2 @ %3")
- .arg(is_long ? tr("LONG") : tr("SHORT"))
- .arg(qty_str)
- .arg(QString::number(pos_entry_, 'f', 2)));
- pos_title_lbl_->setStyleSheet(QString("background:transparent;border:none;font-weight:700;"
- "font-size:%1px;font-family:%2;color:%3;")
- .arg(fincept::ui::fonts::TINY)
- .arg(fincept::ui::fonts::DATA_FAMILY())
- .arg(is_long ? c::POSITIVE() : c::NEGATIVE()));
-
const double ltp = pos_ltp_ > 0.0 ? pos_ltp_ : pos_entry_;
const double pnl = is_long ? (ltp - pos_entry_) * pos_qty_ : (pos_entry_ - ltp) * pos_qty_;
const double basis = pos_entry_ * pos_qty_;
@@ -362,11 +386,18 @@ void EquityChartPanel::refresh_position_card() {
(pnl >= 0 ? QStringLiteral("+") : QString()) + cur::money(pnl, false, pos_currency_);
const QString pct_txt = QStringLiteral("%1%2%").arg(pct >= 0 ? "+" : "").arg(pct, 0, 'f', 2);
pos_pnl_lbl_->setText(pnl_txt + QStringLiteral(" ") + pct_txt);
- pos_pnl_lbl_->setStyleSheet(QString("background:transparent;border:none;font-weight:700;"
- "font-size:%1px;font-family:%2;color:%3;")
- .arg(fincept::ui::fonts::DATA)
- .arg(fincept::ui::fonts::DATA_FAMILY())
- .arg(pnl >= 0 ? c::POSITIVE() : c::NEGATIVE()));
+
+ // setStyleSheet() forces a full style re-parse + re-polish; only do it when
+ // the P&L sign — and therefore the color — actually flips.
+ const int sign = pnl >= 0 ? 1 : -1;
+ if (sign != pos_pnl_sign_) {
+ pos_pnl_sign_ = sign;
+ pos_pnl_lbl_->setStyleSheet(QString("background:transparent;border:none;font-weight:700;"
+ "font-size:%1px;font-family:%2;color:%3;")
+ .arg(fincept::ui::fonts::DATA)
+ .arg(fincept::ui::fonts::DATA_FAMILY())
+ .arg(pnl >= 0 ? c::POSITIVE() : c::NEGATIVE()));
+ }
pos_card_->adjustSize();
}
diff --git a/fincept-qt/src/screens/equity_trading/EquityChartPanel.h b/fincept-qt/src/screens/equity_trading/EquityChartPanel.h
index 778865627..86f6e7fe8 100644
--- a/fincept-qt/src/screens/equity_trading/EquityChartPanel.h
+++ b/fincept-qt/src/screens/equity_trading/EquityChartPanel.h
@@ -56,6 +56,11 @@ class EquityChartPanel : public QWidget {
signals:
void timeframe_changed(const QString& tf);
+ // Right-click chart trading: forwarded from the active backend (KLineChart or
+ // the Qt-Charts fallback). `price` is the y-axis value under the cursor.
+ void buy_requested(double price);
+ void sell_requested(double price);
+ void add_to_watchlist_requested();
// Emitted when the user clicks EXIT on the position card. The screen confirms
// and routes the square-off (it owns the active account).
void exit_position_requested(const QString& symbol, const QString& exchange,
@@ -107,6 +112,10 @@ class EquityChartPanel : public QWidget {
double pos_qty_ = 0.0;
double pos_entry_ = 0.0;
double pos_ltp_ = 0.0;
+ // Last applied P&L sign (+1 / -1 / 0=unset). setStyleSheet() forces a full
+ // style re-parse + re-polish, so on the per-tick refresh we only touch the
+ // P&L label's stylesheet when the sign (hence color) actually flips.
+ int pos_pnl_sign_ = 0;
// Drag state — once the user moves the card it stays where they put it.
QPoint pos_drag_offset_;
bool pos_dragging_ = false;
diff --git a/fincept-qt/src/screens/equity_trading/EquityOrderEntry.cpp b/fincept-qt/src/screens/equity_trading/EquityOrderEntry.cpp
index 9485f70b0..a1062063b 100644
--- a/fincept-qt/src/screens/equity_trading/EquityOrderEntry.cpp
+++ b/fincept-qt/src/screens/equity_trading/EquityOrderEntry.cpp
@@ -7,9 +7,12 @@
#include "trading/OptionsStrategyBuilder.h"
#include "ui/theme/Theme.h"
+#include <QFrame>
+#include <QGridLayout>
#include <QHBoxLayout>
#include <QMetaObject>
#include <QPointer>
+#include <QScrollArea>
#include <QStyle>
#include <QTimer>
#include <QVBoxLayout>
@@ -28,12 +31,12 @@ EquityOrderEntry::EquityOrderEntry(QWidget* parent) : QWidget(parent) {
layout->setContentsMargins(0, 0, 0, 0);
layout->setSpacing(0);
- // Header
+ // ── Header ─────────────────────────────────────────────────────────────────
auto* header = new QWidget(this);
header->setObjectName("eqOeHeader");
- header->setFixedHeight(30);
+ header->setFixedHeight(32);
auto* h_layout = new QHBoxLayout(header);
- h_layout->setContentsMargins(8, 0, 8, 0);
+ h_layout->setContentsMargins(10, 0, 10, 0);
title_label_ = new QLabel(tr("ORDER ENTRY"));
title_label_->setObjectName("eqOeTitle");
@@ -47,11 +50,29 @@ EquityOrderEntry::EquityOrderEntry(QWidget* parent) : QWidget(parent) {
layout->addWidget(header);
- // Content
- auto* content = new QWidget(this);
+ // ── Scrollable content — a tall ticket never clips in the narrow column ──────
+ auto* scroll = new QScrollArea(this);
+ scroll->setObjectName("eqOeScroll");
+ scroll->setWidgetResizable(true);
+ scroll->setFrameShape(QFrame::NoFrame);
+ scroll->setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
+ layout->addWidget(scroll, 1);
+
+ auto* content = new QWidget;
+ content->setObjectName("eqOeContent");
+ scroll->setWidget(content);
auto* form = new QVBoxLayout(content);
- form->setContentsMargins(8, 6, 8, 6);
- form->setSpacing(4);
+ form->setContentsMargins(10, 10, 10, 10);
+ form->setSpacing(8);
+
+ // Thin section separator — groups the ticket into scannable blocks.
+ auto make_sep = [content]() {
+ auto* line = new QFrame(content);
+ line->setObjectName("eqOeSep");
+ line->setFrameShape(QFrame::HLine);
+ line->setFixedHeight(1);
+ return line;
+ };
// BUY / SELL tabs
auto* side_row = new QHBoxLayout;
@@ -61,7 +82,7 @@ EquityOrderEntry::EquityOrderEntry(QWidget* parent) : QWidget(parent) {
buy_tab_->setObjectName("eqBuyTab");
buy_tab_->setProperty("active", true);
buy_tab_->setCursor(Qt::PointingHandCursor);
- buy_tab_->setFixedHeight(28);
+ buy_tab_->setFixedHeight(36);
connect(buy_tab_, &QPushButton::clicked, this, [this]() { set_buy_side(true); });
side_row->addWidget(buy_tab_, 1);
@@ -69,19 +90,19 @@ EquityOrderEntry::EquityOrderEntry(QWidget* parent) : QWidget(parent) {
sell_tab_->setObjectName("eqSellTab");
sell_tab_->setProperty("active", false);
sell_tab_->setCursor(Qt::PointingHandCursor);
- sell_tab_->setFixedHeight(28);
+ sell_tab_->setFixedHeight(36);
connect(sell_tab_, &QPushButton::clicked, this, [this]() { set_buy_side(false); });
side_row->addWidget(sell_tab_, 1);
form->addLayout(side_row);
// Order type toggle buttons
auto* type_row = new QHBoxLayout;
- type_row->setSpacing(2);
+ type_row->setSpacing(4);
const QString type_labels[] = {tr("MKT"), tr("LMT"), tr("SL"), tr("SL-L")};
for (int i = 0; i < 4; ++i) {
type_btns_[i] = new QPushButton(type_labels[i]);
type_btns_[i]->setObjectName("eqOeTypeBtn");
- type_btns_[i]->setFixedHeight(20);
+ type_btns_[i]->setFixedHeight(26);
type_btns_[i]->setCursor(Qt::PointingHandCursor);
if (i == 0)
type_btns_[i]->setProperty("active", true);
@@ -90,89 +111,117 @@ EquityOrderEntry::EquityOrderEntry(QWidget* parent) : QWidget(parent) {
}
form->addLayout(type_row);
- // Product type
+ // ── Symbol context ──────────────────────────────────────────────────────────
+ symbol_label_ = new QLabel(QStringLiteral("%1 · %2").arg(current_symbol_, current_exchange_));
+ symbol_label_->setObjectName("eqOeSymbol");
+ symbol_label_->setAlignment(Qt::AlignCenter);
+ form->addWidget(symbol_label_);
+
+ // ── Live info: LTP (left) · Balance (right) ─────────────────────────────────
+ auto* info_box = new QWidget(content);
+ info_box->setObjectName("eqOeInfo");
+ auto* info_row = new QHBoxLayout(info_box);
+ info_row->setContentsMargins(8, 5, 8, 5);
+ info_row->setSpacing(6);
+
+ market_price_label_ = new QLabel(tr("LTP --"));
+ market_price_label_->setObjectName("eqOeMarketPrice");
+ info_row->addWidget(market_price_label_);
+ info_row->addStretch();
+
+ balance_label_ = new QLabel(tr("Bal --"));
+ balance_label_->setObjectName("eqOeBalance");
+ balance_label_->setAlignment(Qt::AlignRight | Qt::AlignVCenter);
+ info_row->addWidget(balance_label_);
+ form->addWidget(info_box);
+
+ form->addWidget(make_sep());
+
+ // ── Order parameters — aligned label + field rows ───────────────────────────
+ auto* params = new QGridLayout;
+ params->setHorizontalSpacing(8);
+ params->setVerticalSpacing(6);
+ params->setColumnStretch(0, 0);
+ params->setColumnStretch(1, 1);
+ int prow = 0;
+
product_title_ = new QLabel(tr("PRODUCT"));
product_title_->setObjectName("eqOeLabel");
- form->addWidget(product_title_);
-
product_combo_ = new QComboBox;
product_combo_->setObjectName("eqOeCombo");
product_combo_->addItems({tr("Intraday (MIS)"), tr("Delivery (CNC)"), tr("Margin (NRML)")});
- product_combo_->setFixedHeight(26);
- form->addWidget(product_combo_);
+ product_combo_->setFixedHeight(28);
+ params->addWidget(product_title_, prow, 0);
+ params->addWidget(product_combo_, prow, 1);
+ ++prow;
- // Exchange
exchange_title_ = new QLabel(tr("EXCHANGE"));
exchange_title_->setObjectName("eqOeLabel");
- form->addWidget(exchange_title_);
-
exchange_combo_ = new QComboBox;
exchange_combo_->setObjectName("eqOeCombo");
// Exchange codes (NSE/BSE/…) are market identifiers — data, not translated.
exchange_combo_->addItems({"NSE", "BSE", "NYSE", "NASDAQ"});
- exchange_combo_->setFixedHeight(26);
- form->addWidget(exchange_combo_);
-
- // Brokerage info
- brokerage_label_ = new QLabel("");
- brokerage_label_->setObjectName("eqOeBrokerage");
- brokerage_label_->setStyleSheet(QString("color: %1; font-size: 10px;").arg(colors::TEXT_TERTIARY()));
- form->addWidget(brokerage_label_);
-
- form->addSpacing(2);
-
- // Balance
- balance_label_ = new QLabel("--");
- balance_label_->setObjectName("eqOeBalance");
- form->addWidget(balance_label_);
-
- // Market price
- market_price_label_ = new QLabel(tr("MKT: --"));
- market_price_label_->setObjectName("eqOeMarketPrice");
- form->addWidget(market_price_label_);
+ exchange_combo_->setFixedHeight(28);
+ connect(exchange_combo_, &QComboBox::currentTextChanged, this, [this](const QString& ex) {
+ current_exchange_ = ex;
+ if (symbol_label_)
+ symbol_label_->setText(QStringLiteral("%1 · %2").arg(current_symbol_, ex));
+ });
+ params->addWidget(exchange_title_, prow, 0);
+ params->addWidget(exchange_combo_, prow, 1);
+ ++prow;
- // Quantity
qty_title_ = new QLabel(tr("QTY"));
qty_title_->setObjectName("eqOeLabel");
- form->addWidget(qty_title_);
-
qty_edit_ = new QLineEdit;
qty_edit_->setObjectName("eqOeInput");
qty_edit_->setPlaceholderText("0");
- qty_edit_->setFixedHeight(26);
+ qty_edit_->setFixedHeight(28);
+ qty_edit_->setAlignment(Qt::AlignRight);
connect(qty_edit_, &QLineEdit::textChanged, this, [this]() { update_cost_preview(); });
- form->addWidget(qty_edit_);
+ params->addWidget(qty_title_, prow, 0);
+ params->addWidget(qty_edit_, prow, 1);
+ ++prow;
- // Price
price_title_ = new QLabel(tr("PRICE"));
price_title_->setObjectName("eqOeLabel");
- form->addWidget(price_title_);
-
price_edit_ = new QLineEdit;
price_edit_->setObjectName("eqOeInput");
price_edit_->setPlaceholderText(tr("Limit price"));
price_edit_->setEnabled(false);
- price_edit_->setFixedHeight(26);
+ price_edit_->setFixedHeight(28);
+ price_edit_->setAlignment(Qt::AlignRight);
connect(price_edit_, &QLineEdit::textChanged, this, [this]() { update_cost_preview(); });
- form->addWidget(price_edit_);
+ params->addWidget(price_title_, prow, 0);
+ params->addWidget(price_edit_, prow, 1);
+ ++prow;
- // Trigger/Stop price
trigger_title_ = new QLabel(tr("TRIGGER"));
trigger_title_->setObjectName("eqOeLabel");
- form->addWidget(trigger_title_);
-
stop_price_edit_ = new QLineEdit;
stop_price_edit_->setObjectName("eqOeInput");
stop_price_edit_->setPlaceholderText(tr("Trigger price"));
stop_price_edit_->setEnabled(false);
- stop_price_edit_->setFixedHeight(26);
- form->addWidget(stop_price_edit_);
+ stop_price_edit_->setFixedHeight(28);
+ stop_price_edit_->setAlignment(Qt::AlignRight);
+ params->addWidget(trigger_title_, prow, 0);
+ params->addWidget(stop_price_edit_, prow, 1);
+ ++prow;
+
+ form->addLayout(params);
+
+ // Brokerage / fee note
+ brokerage_label_ = new QLabel("");
+ brokerage_label_->setObjectName("eqOeBrokerage");
+ brokerage_label_->setWordWrap(true);
+ form->addWidget(brokerage_label_);
// Advanced toggle
+ form->addWidget(make_sep());
advanced_toggle_ = new QPushButton(tr("+ ADVANCED"));
advanced_toggle_->setObjectName("eqAdvToggle");
advanced_toggle_->setCursor(Qt::PointingHandCursor);
- advanced_toggle_->setFixedHeight(18);
+ advanced_toggle_->setFixedHeight(22);
form->addWidget(advanced_toggle_);
// SL/TP section
@@ -212,7 +261,7 @@ EquityOrderEntry::EquityOrderEntry(QWidget* parent) : QWidget(parent) {
strategy_toggle_ = new QPushButton(tr("+ OPTIONS STRATEGY"));
strategy_toggle_->setObjectName("eqAdvToggle");
strategy_toggle_->setCursor(Qt::PointingHandCursor);
- strategy_toggle_->setFixedHeight(18);
+ strategy_toggle_->setFixedHeight(22);
form->addWidget(strategy_toggle_);
strategy_section_ = new QWidget(this);
@@ -275,7 +324,7 @@ EquityOrderEntry::EquityOrderEntry(QWidget* parent) : QWidget(parent) {
strategy_preview_ = new QLabel(tr("Select a strategy"));
strategy_preview_->setObjectName("eqOeBrokerage");
- strategy_preview_->setStyleSheet(QString("color: %1; font-size: 10px;").arg(colors::TEXT_TERTIARY()));
+ strategy_preview_->setStyleSheet(QString("color: %1; font-size: 11px;").arg(colors::TEXT_SECONDARY()));
strategy_preview_->setWordWrap(true);
strategy_preview_->setTextInteractionFlags(Qt::TextSelectableByMouse);
strat_layout->addWidget(strategy_preview_);
@@ -303,16 +352,26 @@ EquityOrderEntry::EquityOrderEntry(QWidget* parent) : QWidget(parent) {
connect(strat_lot_edit_, &QLineEdit::textChanged, this, [this]() { refresh_strategy_preview(); });
connect(strat_width_edit_, &QLineEdit::textChanged, this, [this]() { refresh_strategy_preview(); });
- // Cost preview
+ // ── Cost / margin summary ───────────────────────────────────────────────────
+ form->addWidget(make_sep());
+
+ auto* summary = new QWidget(content);
+ summary->setObjectName("eqOeSummary");
+ auto* sum_layout = new QVBoxLayout(summary);
+ sum_layout->setContentsMargins(8, 6, 8, 6);
+ sum_layout->setSpacing(3);
+
cost_label_ = new QLabel(tr("Est: --"));
cost_label_->setObjectName("eqOeCost");
- form->addWidget(cost_label_);
+ sum_layout->addWidget(cost_label_);
// Required margin (live broker only)
margin_label_ = new QLabel("");
margin_label_->setObjectName("eqOeMargin");
margin_label_->hide();
- form->addWidget(margin_label_);
+ sum_layout->addWidget(margin_label_);
+
+ form->addWidget(summary);
// Submit row: main submit + broadcast
auto* submit_row = new QHBoxLayout;
@@ -320,19 +379,20 @@ EquityOrderEntry::EquityOrderEntry(QWidget* parent) : QWidget(parent) {
submit_btn_ = new QPushButton(tr("BUY %1").arg(current_symbol_));
submit_btn_->setObjectName("eqBuySubmit");
- submit_btn_->setFixedHeight(34);
+ submit_btn_->setFixedHeight(40);
submit_btn_->setCursor(Qt::PointingHandCursor);
connect(submit_btn_, &QPushButton::clicked, this, &EquityOrderEntry::on_submit);
submit_row->addWidget(submit_btn_, 3);
broadcast_btn_ = new QPushButton(tr("ALL"));
broadcast_btn_->setObjectName("eqBroadcastBtn");
- broadcast_btn_->setFixedHeight(34);
+ broadcast_btn_->setFixedHeight(40);
broadcast_btn_->setCursor(Qt::PointingHandCursor);
broadcast_btn_->setToolTip(tr("Broadcast this order to multiple accounts"));
broadcast_btn_->setStyleSheet(
- QString("QPushButton { background: %1; color: %2; font-weight: 700; font-size: 11px; border-radius: 2px; }"
- "QPushButton:hover { background: %3; }")
+ QString("QPushButton { background: %1; color: %2; font-weight: 700; font-size: 12px; "
+ " border: 1px solid %3; border-radius: 4px; }"
+ "QPushButton:hover { background: %3; color: %2; }")
.arg(colors::BG_RAISED(), colors::AMBER(), colors::BORDER_MED()));
connect(broadcast_btn_, &QPushButton::clicked, this, [this]() {
const double qty = qty_edit_->text().toDouble();
@@ -370,7 +430,6 @@ EquityOrderEntry::EquityOrderEntry(QWidget* parent) : QWidget(parent) {
form->addWidget(status_label_);
form->addStretch();
- layout->addWidget(content, 1);
// Debounce timer: fetch margin 600ms after last qty/price change (live broker only)
margin_timer_ = new QTimer(this);
@@ -450,13 +509,13 @@ void EquityOrderEntry::set_order_type(int idx) {
void EquityOrderEntry::set_balance(double balance) {
balance_ = balance;
- balance_label_->setText(QString("%1%2").arg(currency_symbol(current_currency_)).arg(balance, 0, 'f', 2));
+ balance_label_->setText(tr("Bal %1%2").arg(currency_symbol(current_currency_)).arg(balance, 0, 'f', 2));
update_cost_preview();
}
void EquityOrderEntry::set_current_price(double price) {
current_price_ = price;
- market_price_label_->setText(tr("MKT: %1%2").arg(currency_symbol(current_currency_)).arg(price, 0, 'f', 2));
+ market_price_label_->setText(tr("LTP %1%2").arg(currency_symbol(current_currency_)).arg(price, 0, 'f', 2));
update_cost_preview();
}
@@ -471,10 +530,14 @@ void EquityOrderEntry::set_mode(bool is_paper) {
void EquityOrderEntry::set_symbol(const QString& symbol) {
current_symbol_ = symbol;
submit_btn_->setText(is_buy_side_ ? tr("BUY %1").arg(symbol) : tr("SELL %1").arg(symbol));
+ if (symbol_label_)
+ symbol_label_->setText(QStringLiteral("%1 · %2").arg(symbol, current_exchange_));
}
void EquityOrderEntry::set_exchange(const QString& exchange) {
current_exchange_ = exchange;
+ if (symbol_label_)
+ symbol_label_->setText(QStringLiteral("%1 · %2").arg(current_symbol_, exchange));
for (int i = 0; i < exchange_combo_->count(); ++i) {
if (exchange_combo_->itemText(i) == exchange) {
exchange_combo_->setCurrentIndex(i);
diff --git a/fincept-qt/src/screens/equity_trading/EquityOrderEntry.h b/fincept-qt/src/screens/equity_trading/EquityOrderEntry.h
index a14762ae8..43fa57a33 100644
--- a/fincept-qt/src/screens/equity_trading/EquityOrderEntry.h
+++ b/fincept-qt/src/screens/equity_trading/EquityOrderEntry.h
@@ -95,6 +95,7 @@ class EquityOrderEntry : public QWidget {
QPushButton* place_strategy_btn_ = nullptr;
// Labels
+ QLabel* symbol_label_ = nullptr; // "SYMBOL · EXCHANGE" context line
QLabel* balance_label_ = nullptr;
QLabel* market_price_label_ = nullptr;
QLabel* cost_label_ = nullptr;
diff --git a/fincept-qt/src/screens/equity_trading/EquityTradingScreen.cpp b/fincept-qt/src/screens/equity_trading/EquityTradingScreen.cpp
index 9f78530d3..6028ab909 100644
--- a/fincept-qt/src/screens/equity_trading/EquityTradingScreen.cpp
+++ b/fincept-qt/src/screens/equity_trading/EquityTradingScreen.cpp
@@ -128,6 +128,15 @@ void EquityTradingScreen::showEvent(QShowEvent* event) {
if (sym != selected_symbol_)
on_symbol_selected(sym);
}
+ // Fallback: if no valid account was restored (empty/stale persisted state,
+ // a deleted account, or first run), default to the first active broker so
+ // the screen loads ready-to-trade instead of stranding the user on
+ // "NO ACCOUNT" while configured brokers exist in the DB.
+ if (focused_account_id_.isEmpty()) {
+ const auto accts = AccountManager::instance().active_accounts();
+ if (!accts.isEmpty())
+ on_account_changed(accts.first().account_id);
+ }
}
// Start all active account data streams
@@ -366,6 +375,10 @@ void EquityTradingScreen::setup_ui() {
if (stream)
stream->fetch_candles(selected_symbol_, tf);
});
+ connect(chart_, &EquityChartPanel::buy_requested, this, &EquityTradingScreen::on_chart_buy_requested);
+ connect(chart_, &EquityChartPanel::sell_requested, this, &EquityTradingScreen::on_chart_sell_requested);
+ connect(chart_, &EquityChartPanel::add_to_watchlist_requested, this,
+ &EquityTradingScreen::on_chart_add_to_watchlist);
connect(chart_, &EquityChartPanel::exit_position_requested, this,
&EquityTradingScreen::on_chart_exit_position);
}
diff --git a/fincept-qt/src/screens/equity_trading/EquityTradingScreen.h b/fincept-qt/src/screens/equity_trading/EquityTradingScreen.h
index 820aeb2d2..bf5ca3781 100644
--- a/fincept-qt/src/screens/equity_trading/EquityTradingScreen.h
+++ b/fincept-qt/src/screens/equity_trading/EquityTradingScreen.h
@@ -122,9 +122,18 @@ class EquityTradingScreen : public QWidget, public IGroupLinked, public IStatefu
void update_account_menu();
void update_connection_status();
void async_modify_order(const QString& order_id, double qty, double price);
+
+ // Chart right-click trading: pop a confirm ticket (qty + limit price) at the
+ // clicked price, then route through on_order_submitted(). Watchlist-add reuses
+ // the existing on_watchlist_symbol_added() slot for the charted symbol.
+ void on_chart_buy_requested(double price);
+ void on_chart_sell_requested(double price);
+ void on_chart_add_to_watchlist();
+ void open_chart_order_ticket(bool is_buy, double price);
// Re-reads the focused account's paper portfolio into the panels. No-op for
// live accounts (their data flows from AccountDataStream via the hub).
void refresh_paper_panels();
+ void flush_paper_prices(); // persist buffered paper position prices to SQLite
// DataHub subscription helpers (D4 migration)
void hub_subscribe_streaming();
@@ -184,6 +193,17 @@ class EquityTradingScreen : public QWidget, public IGroupLinked, public IStatefu
// Paper trading (derived from focused account)
int fill_cb_id_ = -1; // OrderMatcher fill callback
+ // Cached focused-account trading context. Refreshed on every focus / symbol /
+ // mode change (hub_subscribe_streaming) and on every paper refresh, so the
+ // per-tick quote handler avoids a mutex-locked BrokerAccount copy per tick.
+ bool focused_is_paper_ = false;
+ QString focused_paper_portfolio_id_;
+ // Paper engine price persistence is coalesced off the per-tick GUI hot path:
+ // the latest LTP per symbol is buffered here and flushed to SQLite on a timer
+ // (and synchronously before refresh_paper_panels reads), instead of one DB
+ // UPDATE per tick. SL/TP + limit matching still run every tick (in-memory).
+ QHash<QString, double> pending_paper_prices_;
+ bool paper_flush_armed_ = false;
// Async guards
std::atomic<bool> token_expired_shown_{false};
@@ -196,7 +216,6 @@ class EquityTradingScreen : public QWidget, public IGroupLinked, public IStatefu
bool initialized_ = false;
bool hub_active_ = false;
- QHash<QString, trading::BrokerQuote> watchlist_quote_cache_;
// Symbol group link — SymbolGroup::None when unlinked.
SymbolGroup link_group_ = SymbolGroup::None;
diff --git a/fincept-qt/src/screens/equity_trading/EquityTradingScreen_Handlers.cpp b/fincept-qt/src/screens/equity_trading/EquityTradingScreen_Handlers.cpp
index 96bf777a9..53aa5ff33 100644
--- a/fincept-qt/src/screens/equity_trading/EquityTradingScreen_Handlers.cpp
+++ b/fincept-qt/src/screens/equity_trading/EquityTradingScreen_Handlers.cpp
@@ -41,6 +41,7 @@
#include <QDateTime>
#include <QDialog>
#include <QDialogButtonBox>
+#include <QDoubleSpinBox>
#include <QFormLayout>
#include <QHBoxLayout>
#include <QHash>
@@ -48,11 +49,13 @@
#include <QJsonArray>
#include <QJsonDocument>
#include <QJsonObject>
+#include <QLabel>
#include <QLineEdit>
#include <QMessageBox>
#include <QMouseEvent>
#include <QPointer>
#include <QPushButton>
+#include <QSpinBox>
#include <QRadioButton>
#include <QScrollBar>
#include <QSplitter>
@@ -476,6 +479,87 @@ void EquityTradingScreen::on_order_submitted(const UnifiedOrder& order) {
}
}
+void EquityTradingScreen::on_chart_buy_requested(double price) {
+ open_chart_order_ticket(true, price);
+}
+
+void EquityTradingScreen::on_chart_sell_requested(double price) {
+ open_chart_order_ticket(false, price);
+}
+
+void EquityTradingScreen::on_chart_add_to_watchlist() {
+ if (!selected_symbol_.isEmpty())
+ on_watchlist_symbol_added(selected_symbol_);
+}
+
+// Kite-style chart trading: a compact confirm ticket (qty + limit price,
+// prefilled at the clicked level), then route through the normal placement path
+// so paper/live handling, balances and status all behave exactly like the order
+// panel. For live accounts on_order_submitted() still applies its own pre-send
+// gate; for paper this ticket is the single confirmation.
+void EquityTradingScreen::open_chart_order_ticket(bool is_buy, double price) {
+ if (focused_account_id_.isEmpty()) {
+ order_entry_->show_order_status(tr("No account selected — add one via ACCOUNTS"), false);
+ return;
+ }
+ if (price <= 0)
+ price = current_price_; // cursor price unavailable — fall back to last traded
+
+ QDialog dlg(this);
+ dlg.setWindowTitle(is_buy ? tr("Buy %1").arg(selected_symbol_) : tr("Sell %1").arg(selected_symbol_));
+ auto* form = new QFormLayout(&dlg);
+
+ auto* hdr = new QLabel(
+ QStringLiteral("%1 %2 · %3").arg(is_buy ? tr("BUY") : tr("SELL"), selected_symbol_, selected_exchange_), &dlg);
+ hdr->setStyleSheet(QString("font-weight:700;font-size:13px;color:%1;")
+ .arg(is_buy ? fincept::ui::colors::POSITIVE() : fincept::ui::colors::NEGATIVE()));
+ form->addRow(hdr);
+
+ auto* type_combo = new QComboBox(&dlg);
+ type_combo->addItems({tr("Market"), tr("Limit")});
+ type_combo->setCurrentIndex(0); // default to Market
+ form->addRow(tr("Type"), type_combo);
+
+ auto* qty_spin = new QSpinBox(&dlg);
+ qty_spin->setRange(1, 10000000);
+ qty_spin->setValue(1);
+ form->addRow(tr("Qty"), qty_spin);
+
+ auto* px_spin = new QDoubleSpinBox(&dlg);
+ px_spin->setRange(0.01, 1.0e9);
+ px_spin->setDecimals(2);
+ px_spin->setValue(price > 0 ? price : 0.01);
+ form->addRow(tr("Limit price"), px_spin);
+
+ // A Market order needs no price (it fills at the LTP), so the limit-price
+ // row (label + field) is hidden entirely unless Limit is selected.
+ auto sync_type = [form, px_spin](int idx) { form->setRowVisible(px_spin, idx == 1); }; // 1 = Limit
+ connect(type_combo, qOverload<int>(&QComboBox::currentIndexChanged), &dlg, sync_type);
+ sync_type(type_combo->currentIndex());
+
+ auto* buttons = new QDialogButtonBox(QDialogButtonBox::Cancel, &dlg);
+ QPushButton* ok = buttons->addButton(is_buy ? tr("Buy") : tr("Sell"), QDialogButtonBox::AcceptRole);
+ ok->setDefault(true);
+ connect(buttons, &QDialogButtonBox::accepted, &dlg, &QDialog::accept);
+ connect(buttons, &QDialogButtonBox::rejected, &dlg, &QDialog::reject);
+ form->addRow(buttons);
+
+ if (dlg.exec() != QDialog::Accepted)
+ return;
+
+ UnifiedOrder order;
+ order.symbol = selected_symbol_;
+ order.exchange = selected_exchange_;
+ order.side = is_buy ? OrderSide::Buy : OrderSide::Sell;
+ const bool is_market = (type_combo->currentIndex() == 0);
+ order.order_type = is_market ? OrderType::Market : OrderType::Limit;
+ order.quantity = qty_spin->value();
+ order.price = is_market ? 0.0 : px_spin->value();
+ order.product_type = ProductType::Intraday;
+ order.validity = QStringLiteral("DAY");
+ on_order_submitted(order);
+}
+
void EquityTradingScreen::on_cancel_order(const QString& order_id) {
auto account = AccountManager::instance().get_account(focused_account_id_);
@@ -549,10 +633,30 @@ void EquityTradingScreen::async_modify_order(const QString& order_id, double qty
});
}
+void EquityTradingScreen::flush_paper_prices() {
+ paper_flush_armed_ = false;
+ if (pending_paper_prices_.isEmpty() || focused_paper_portfolio_id_.isEmpty()) {
+ pending_paper_prices_.clear();
+ return;
+ }
+ // Persist each symbol's latest buffered LTP. Coalesced off the per-tick hot
+ // path; recomputes the position's unrealized P&L in the same SQLite UPDATE.
+ for (auto it = pending_paper_prices_.cbegin(); it != pending_paper_prices_.cend(); ++it)
+ pt_update_position_price(focused_paper_portfolio_id_, it.key(), it.value());
+ pending_paper_prices_.clear();
+}
+
void EquityTradingScreen::refresh_paper_panels() {
auto account = AccountManager::instance().get_account(focused_account_id_);
+ // Keep the per-tick quote handler's cached context fresh — this also fires on
+ // paper order events, where the portfolio id may have just been assigned.
+ focused_is_paper_ = account.trading_mode == "paper";
+ focused_paper_portfolio_id_ = focused_is_paper_ ? account.paper_portfolio_id : QString();
if (account.trading_mode != "paper" || account.paper_portfolio_id.isEmpty())
return; // live data flows from AccountDataStream via the hub
+ // Persist any buffered tick prices first so the positions/funds snapshot below
+ // reflects the latest LTP at this refresh/order moment, not a coalesce window ago.
+ flush_paper_prices();
try {
auto portfolio = pt_get_portfolio(account.paper_portfolio_id);
auto positions = pt_get_positions(account.paper_portfolio_id);
diff --git a/fincept-qt/src/screens/equity_trading/EquityTradingScreen_Streams.cpp b/fincept-qt/src/screens/equity_trading/EquityTradingScreen_Streams.cpp
index 8d43d39f6..3ba54868c 100644
--- a/fincept-qt/src/screens/equity_trading/EquityTradingScreen_Streams.cpp
+++ b/fincept-qt/src/screens/equity_trading/EquityTradingScreen_Streams.cpp
@@ -27,6 +27,8 @@
#include "trading/OrderMatcher.h"
#include "trading/PaperTrading.h"
+#include <QTimer>
+
namespace fincept::screens {
using namespace fincept::trading;
@@ -34,6 +36,11 @@ using namespace fincept::screens::equity;
static const QString TAG = "EquityTrading";
+// Paper position prices are persisted to SQLite at most once per this window per
+// burst of ticks (coalesced), instead of one UPDATE per tick. The in-memory table
+// and chart card still update on every tick; only the DB write is throttled.
+static constexpr int kPaperPriceFlushMs = 1000;
+
// ============================================================================
// DataHub subscription helpers (D4)
// ============================================================================
@@ -48,7 +55,6 @@ void EquityTradingScreen::hub_subscribe_streaming() {
auto& hub = datahub::DataHub::instance();
hub.unsubscribe(this);
hub_active_ = false;
- watchlist_quote_cache_.clear();
const QString bid = broker_id_for_focused();
if (bid.isEmpty() || focused_account_id_.isEmpty())
@@ -59,8 +65,18 @@ void EquityTradingScreen::hub_subscribe_streaming() {
// Paper accounts must NOT show live broker positions/holdings/orders/balance —
// that data comes from the paper engine (pt_* / OrderMatcher). Only live mode
// subscribes to the live broker portfolio topics. Quotes flow in both modes.
- const bool is_paper =
- AccountManager::instance().get_account(aid).trading_mode == QLatin1String("paper");
+ //
+ // Cache the trading mode + paper portfolio id once here. This runs on every
+ // focus / symbol / mode change, so the cache stays fresh, and it keeps the
+ // per-tick quote handler off AccountManager::get_account() — which locks a
+ // mutex and copies the whole BrokerAccount struct on every single tick.
+ const auto focused_account = AccountManager::instance().get_account(aid);
+ const bool is_paper = focused_account.trading_mode == QLatin1String("paper");
+ focused_is_paper_ = is_paper;
+ focused_paper_portfolio_id_ = is_paper ? focused_account.paper_portfolio_id : QString();
+ // Drop any prices buffered for a previous account/portfolio. An in-flight flush
+ // timer simply finds the map empty (or the new portfolio's prices) and no-ops.
+ pending_paper_prices_.clear();
if (!is_paper) {
// ── Positions ──
@@ -135,9 +151,6 @@ void EquityTradingScreen::hub_subscribe_quotes() {
return;
const auto quote = v.value<BrokerQuote>();
- // Cache for watchlist rebuild
- watchlist_quote_cache_[sym] = quote;
-
// Open-positions table (bottom sheet): patch LTP / P&L from the SAME
// quote that feeds the ticker bar, so the header and the position row
// never show different prices. Live & paper both handled inside.
@@ -154,24 +167,34 @@ void EquityTradingScreen::hub_subscribe_quotes() {
chart_->update_pnl(quote.ltp); // live P&L on the chart's position card
}
- // Rebuild watchlist from cache
- QVector<BrokerQuote> wl_quotes;
- wl_quotes.reserve(watchlist_quote_cache_.size());
- for (auto it = watchlist_quote_cache_.cbegin(); it != watchlist_quote_cache_.cend(); ++it)
- wl_quotes.append(it.value());
- watchlist_->update_quotes(wl_quotes);
-
- // Feed paper trading engine
- auto account = AccountManager::instance().get_account(focused_account_id_);
- if (account.trading_mode == "paper" && !account.paper_portfolio_id.isEmpty() && quote.ltp > 0) {
- pt_update_position_price(account.paper_portfolio_id, sym, quote.ltp);
+ // Repaint only this symbol's watchlist row (a no-op if it isn't in the
+ // active list). Rebuilding the entire watchlist from a cache on every
+ // tick was O(rows×entries) of GUI-thread work per tick — the dominant
+ // cost on an unthrottled quote feed.
+ watchlist_->update_quote(quote);
+
+ // Feed paper trading engine. Mode + portfolio id are cached at subscribe
+ // time (hub_subscribe_streaming) so this hot path never copies a
+ // BrokerAccount under AccountManager's mutex on every tick.
+ if (focused_is_paper_ && !focused_paper_portfolio_id_.isEmpty() && quote.ltp > 0) {
+ // Buffer the latest price and coalesce the SQLite persist onto a
+ // timer — one UPDATE per symbol per window instead of per tick.
+ // flush_paper_prices() also runs synchronously before
+ // refresh_paper_panels reads, so order/funds snapshots stay exact.
+ pending_paper_prices_[sym] = quote.ltp;
+ if (!paper_flush_armed_) {
+ paper_flush_armed_ = true;
+ QTimer::singleShot(kPaperPriceFlushMs, this, [this]() { flush_paper_prices(); });
+ }
+ // SL/TP + limit matching must see EVERY tick — run on the live
+ // price against in-memory order/trigger tables (no DB per tick).
PriceData pd;
pd.last = quote.ltp;
pd.bid = quote.bid;
pd.ask = quote.ask;
pd.timestamp = quote.timestamp;
- OrderMatcher::instance().check_orders(sym, pd, account.paper_portfolio_id);
- OrderMatcher::instance().check_sl_tp_triggers(account.paper_portfolio_id, sym, quote.ltp);
+ OrderMatcher::instance().check_orders(sym, pd, focused_paper_portfolio_id_);
+ OrderMatcher::instance().check_sl_tp_triggers(focused_paper_portfolio_id_, sym, quote.ltp);
}
});
}
diff --git a/fincept-qt/src/screens/equity_trading/EquityTradingScreen_Watchlists.cpp b/fincept-qt/src/screens/equity_trading/EquityTradingScreen_Watchlists.cpp
index 14302d648..d9280ba17 100644
--- a/fincept-qt/src/screens/equity_trading/EquityTradingScreen_Watchlists.cpp
+++ b/fincept-qt/src/screens/equity_trading/EquityTradingScreen_Watchlists.cpp
@@ -84,12 +84,22 @@ void EquityTradingScreen::load_watchlists() {
nifty_id = cr.value().id;
for (const auto& s : equity::NIFTY50_WATCHLIST)
repo.add_stock(nifty_id, s, {}, selected_exchange_);
- active_watchlist_id_ = nifty_id; // newly created → default to it
auto r3 = repo.list_all();
if (r3.is_ok())
lists = r3.value();
}
}
+ // No user-selected watchlist yet → default Indian brokers to Nifty 50,
+ // even when other lists exist. A present active_watchlist_id_ means the
+ // user already picked a list, so leave their choice untouched.
+ bool indian_active_present = false;
+ for (const auto& w : lists)
+ if (w.id == active_watchlist_id_) {
+ indian_active_present = true;
+ break;
+ }
+ if (!indian_active_present && !nifty_id.isEmpty())
+ active_watchlist_id_ = nifty_id;
}
// Pick the active list: keep the current one if still present, else the
diff --git a/fincept-qt/src/screens/equity_trading/EquityTypes.h b/fincept-qt/src/screens/equity_trading/EquityTypes.h
index 7f184f5bc..2b927f771 100644
--- a/fincept-qt/src/screens/equity_trading/EquityTypes.h
+++ b/fincept-qt/src/screens/equity_trading/EquityTypes.h
@@ -40,7 +40,7 @@ inline const QStringList NIFTY50_WATCHLIST = {
"ITC", "JIOFIN", "JSWSTEEL", "KOTAKBANK", "LT",
"M&M", "MARUTI", "NESTLEIND", "NTPC", "ONGC",
"POWERGRID", "RELIANCE", "SBILIFE", "SBIN", "SHRIRAMFIN",
- "SUNPHARMA", "TATACONSUM", "TATAMOTORS", "TATASTEEL", "TCS",
+ "SUNPHARMA", "TATACONSUM", "TATASTEEL", "TCS",
"TECHM", "TITAN", "TRENT", "ULTRACEMCO", "WIPRO",
};
diff --git a/fincept-qt/src/screens/equity_trading/EquityWatchlist.cpp b/fincept-qt/src/screens/equity_trading/EquityWatchlist.cpp
index bab5ce069..c80a5d87b 100644
--- a/fincept-qt/src/screens/equity_trading/EquityWatchlist.cpp
+++ b/fincept-qt/src/screens/equity_trading/EquityWatchlist.cpp
@@ -7,6 +7,7 @@
#include "trading/instruments/InstrumentService.h"
#include "ui/theme/Theme.h"
+#include <QAbstractItemView>
#include <QAction>
#include <QHBoxLayout>
#include <QHeaderView>
@@ -128,6 +129,40 @@ EquityWatchlist::EquityWatchlist(QWidget* parent) : QWidget(parent) {
completer_->setMaxVisibleItems(8);
add_edit_->setCompleter(completer_);
+ // Style the completer's popup explicitly. It is a separate top-level QListView
+ // that no global stylesheet rule covers, so without this it renders with a
+ // transparent background and the watchlist behind it shows through. (The combo
+ // popups, e.g. #eqOeCombo QAbstractItemView, are styled the same way.)
+ if (auto* popup = completer_->popup()) {
+ popup->setObjectName("eqWatchlistCompleterPopup");
+ popup->setStyleSheet(
+ QString("QListView { background:%1; color:%2; border:1px solid %3; outline:none;"
+ " font-family:%4; font-size:%5px; }"
+ "QListView::item { padding:4px 8px; border:none; }"
+ "QListView::item:selected { background:%6; color:%2; }")
+ .arg(fincept::ui::colors::BG_SURFACE(), fincept::ui::colors::TEXT_PRIMARY(),
+ fincept::ui::colors::BORDER_MED(), fincept::ui::fonts::DATA_FAMILY())
+ .arg(fincept::ui::fonts::SMALL)
+ .arg(fincept::ui::colors::BG_HOVER()));
+ }
+
+ // Picking a suggestion (mouse click, Enter, or Arrow+Enter) must add the
+ // symbol — not merely paste "SYMBOL · EXCH · Broker" into the edit, which
+ // is all QCompleter does by default. Wire activated() to add + clear. This
+ // slot is connected after setCompleter(), so it runs after QCompleter's own
+ // text insertion; clearing here leaves the edit empty, so a trailing
+ // returnPressed becomes a harmless no-op (no double add).
+ connect(completer_, QOverload<const QString&>::of(&QCompleter::activated), this,
+ [this](const QString& choice) {
+ QString sym = choice.section(QStringLiteral(" · "), 0, 0).trimmed().toUpper();
+ if (sym.contains(':'))
+ sym = sym.section(':', 1);
+ if (sym.isEmpty())
+ return;
+ add_symbol(sym);
+ add_edit_->clear();
+ });
+
add_btn_ = new QPushButton("+");
add_btn_->setObjectName("eqWatchlistAddBtn");
add_btn_->setFixedSize(22, 22);
@@ -171,11 +206,13 @@ EquityWatchlist::EquityWatchlist(QWidget* parent) : QWidget(parent) {
// room from SYMBOL, which is what truncated the names.
table_->horizontalHeader()->setStretchLastSection(false);
table_->horizontalHeader()->setSectionResizeMode(0, QHeaderView::Stretch);
- table_->horizontalHeader()->setSectionResizeMode(1, QHeaderView::Fixed);
- table_->horizontalHeader()->setSectionResizeMode(2, QHeaderView::Fixed);
- table_->horizontalHeader()->setMinimumSectionSize(48);
- table_->setColumnWidth(1, 84); // LTP — fits up to "24500.50" without eliding
- table_->setColumnWidth(2, 64); // CHG% — fits "+12.34%"
+ // LTP/CHG auto-size to their widest value (+ header) so neither ever elides —
+ // a fixed 64px proved too tight once the data font resolved to Menlo, cutting
+ // "+12.34%" down to "+1.1…". ResizeToContents recomputes on each data change;
+ // SYMBOL (the Stretch column) still absorbs all leftover width.
+ table_->horizontalHeader()->setSectionResizeMode(1, QHeaderView::ResizeToContents);
+ table_->horizontalHeader()->setSectionResizeMode(2, QHeaderView::ResizeToContents);
+ table_->horizontalHeader()->setMinimumSectionSize(40);
table_->verticalHeader()->setDefaultSectionSize(24);
connect(table_, &QTableWidget::cellClicked, this, &EquityWatchlist::on_cell_clicked);
@@ -290,39 +327,40 @@ void EquityWatchlist::set_symbols(const QStringList& symbols) {
rebuild_table();
}
-void EquityWatchlist::update_quotes(const QVector<trading::BrokerQuote>& quotes) {
+void EquityWatchlist::update_quote(const trading::BrokerQuote& quote) {
QMutexLocker lock(&mutex_);
- for (const auto& q : quotes) {
- for (auto& e : entries_) {
- if (e.symbol == q.symbol) {
- e.ltp = q.ltp;
- e.change_pct = q.change_pct;
- e.volume = q.volume;
- e.has_data = true;
- break;
- }
+
+ // Update the cached entry for this symbol. Bail early if we don't track it —
+ // position symbols stream quotes too but may not be in the active watchlist.
+ WatchlistEntry* entry = nullptr;
+ for (auto& e : entries_) {
+ if (e.symbol == quote.symbol) {
+ entry = &e;
+ break;
}
}
- // Update visible rows without full rebuild
+ if (!entry)
+ return;
+ entry->ltp = quote.ltp;
+ entry->change_pct = quote.change_pct;
+ entry->volume = quote.volume;
+ entry->has_data = true;
+
+ // Repaint only this symbol's row. setText / setForeground are no-ops when the
+ // value is unchanged (Qt early-returns), so identical ticks cost nothing.
for (int row = 0; row < table_->rowCount(); ++row) {
auto* sym_item = table_->item(row, 0);
- if (!sym_item)
+ if (!sym_item || sym_item->data(Qt::UserRole).toString() != quote.symbol)
continue;
- const QString sym = sym_item->data(Qt::UserRole).toString();
- for (const auto& e : entries_) {
- if (e.symbol == sym && e.has_data) {
- auto* ltp_item = table_->item(row, 1);
- auto* chg_item = table_->item(row, 2);
- if (ltp_item)
- ltp_item->setText(QString::number(e.ltp, 'f', 2));
- if (chg_item) {
- chg_item->setText(QString("%1%2%").arg(e.change_pct >= 0 ? "+" : "").arg(e.change_pct, 0, 'f', 2));
- chg_item->setForeground(e.change_pct >= 0 ? QColor(fincept::ui::colors::POSITIVE())
- : QColor(fincept::ui::colors::NEGATIVE()));
- }
- break;
- }
+ if (auto* ltp_item = table_->item(row, 1))
+ ltp_item->setText(QString::number(entry->ltp, 'f', 2));
+ if (auto* chg_item = table_->item(row, 2)) {
+ chg_item->setText(
+ QString("%1%2%").arg(entry->change_pct >= 0 ? "+" : "").arg(entry->change_pct, 0, 'f', 2));
+ chg_item->setForeground(entry->change_pct >= 0 ? QColor(fincept::ui::colors::POSITIVE())
+ : QColor(fincept::ui::colors::NEGATIVE()));
}
+ break;
}
}
diff --git a/fincept-qt/src/screens/equity_trading/EquityWatchlist.h b/fincept-qt/src/screens/equity_trading/EquityWatchlist.h
index 50a41989a..11b59c966 100644
--- a/fincept-qt/src/screens/equity_trading/EquityWatchlist.h
+++ b/fincept-qt/src/screens/equity_trading/EquityWatchlist.h
@@ -33,7 +33,9 @@ class EquityWatchlist : public QWidget {
explicit EquityWatchlist(QWidget* parent = nullptr);
void set_symbols(const QStringList& symbols);
- void update_quotes(const QVector<trading::BrokerQuote>& quotes);
+ // Patch a single symbol's row in place. No-op if the symbol isn't tracked.
+ // Per-tick hot path — must stay O(entries + rows), never a full rebuild.
+ void update_quote(const trading::BrokerQuote& quote);
void set_active_symbol(const QString& symbol);
void set_broker_id(const QString& broker_id);
void add_symbol(const QString& symbol);
diff --git a/fincept-qt/src/screens/forum/ForumSidebarPanel.cpp b/fincept-qt/src/screens/forum/ForumSidebarPanel.cpp
index 6469c9875..02d9b33f3 100644
--- a/fincept-qt/src/screens/forum/ForumSidebarPanel.cpp
+++ b/fincept-qt/src/screens/forum/ForumSidebarPanel.cpp
@@ -451,7 +451,7 @@ void ForumSidebarPanel::rebuild_contributors() {
}
// Medal icons for top 3
- static const char* medals[] = {"🥇", "🥈", "🥉", " 4", " 5"};
+ static const char* medals[] = {" 1", " 2", " 3", " 4", " 5"};
const QString rank_colors[] = {ui::colors::AMBER(), ui::colors::TEXT_SECONDARY(), ui::colors::WARNING(),
ui::colors::TEXT_TERTIARY(), ui::colors::TEXT_TERTIARY()};
diff --git a/fincept-qt/src/screens/info/HelpScreen.cpp b/fincept-qt/src/screens/info/HelpScreen.cpp
index 3b777ab92..151b69a89 100644
--- a/fincept-qt/src/screens/info/HelpScreen.cpp
+++ b/fincept-qt/src/screens/info/HelpScreen.cpp
@@ -27,7 +27,8 @@ static QWidget* make_faq(const QString& question, const QString& answer, const Q
vl->setContentsMargins(0, 0, 0, 0);
vl->setSpacing(0);
- auto* q_btn = new QPushButton(QString(" %1 %2").arg(icon, question));
+ auto* q_btn = new QPushButton(icon.isEmpty() ? QString(" %1").arg(question)
+ : QString(" %1 %2").arg(icon, question));
q_btn->setCursor(Qt::PointingHandCursor);
q_btn->setStyleSheet(QString("QPushButton { color: %1; background: %2; border: 1px solid %3;"
" padding: 11px 14px; text-align: left;"
@@ -49,7 +50,8 @@ static QWidget* make_faq(const QString& question, const QString& answer, const Q
bool show = !a_lbl->isVisible();
a_lbl->setVisible(show);
QString arrow = show ? "▾" : "▸";
- q_btn->setText(QString(" %1 %2").arg(icon, question));
+ q_btn->setText(icon.isEmpty() ? QString(" %1").arg(question)
+ : QString(" %1 %2").arg(icon, question));
// tint open state
q_btn->setStyleSheet(
QString("QPushButton { color: %1; background: %2; border: 1px solid %3;"
@@ -165,13 +167,13 @@ QWidget* HelpScreen::build_page() {
auto make_chip = [](const QString& icon, const QString& text, const QString& color,
const QString& url = {}) -> QWidget* {
if (url.isEmpty()) {
- auto* chip = new QLabel(QString("%1 %2").arg(icon, text));
+ auto* chip = new QLabel(icon.isEmpty() ? text : QString("%1 %2").arg(icon, text));
chip->setStyleSheet(QString("color: %1; font-size: 11px; background: transparent;"
" font-family:'Consolas','Courier New',monospace;")
.arg(color));
return chip;
}
- auto* chip = new QPushButton(QString("%1 %2").arg(icon, text));
+ auto* chip = new QPushButton(icon.isEmpty() ? text : QString("%1 %2").arg(icon, text));
chip->setFlat(true);
chip->setCursor(Qt::PointingHandCursor);
chip->setStyleSheet(QString("QPushButton { color: %1; font-size: 11px; background: transparent;"
@@ -186,8 +188,8 @@ QWidget* HelpScreen::build_page() {
// Business-hours label IS translated.
chips_vl->addWidget(make_chip("✉", "[email protected]", colors::CYAN, "mailto:[email protected]"));
chips_vl->addWidget(
- make_chip("💬", "discord.gg/ae87a8ygbN", colors::POSITIVE, "https://discord.gg/ae87a8ygbN"));
- chips_vl->addWidget(make_chip("🕐", tr("Mon-Fri 9AM–6PM EST"), colors::TEXT_TERTIARY));
+ make_chip("", "discord.gg/ae87a8ygbN", colors::POSITIVE, "https://discord.gg/ae87a8ygbN"));
+ chips_vl->addWidget(make_chip("", tr("Mon-Fri 9AM–6PM EST"), colors::TEXT_TERTIARY));
hl->addLayout(chips_vl);
vl->addWidget(hero);
@@ -212,12 +214,12 @@ QWidget* HelpScreen::build_page() {
QString desc;
};
const Action actions[] = {
- {"👤", "create_account", tr("Create Account"), tr("Register for full access")},
- {"🔑", "reset_password", tr("Reset Password"), tr("Recover your account")},
- {"📖", "documentation", tr("Documentation"), tr("Guides, tutorials & API ref")},
- {"🐛", "report_bug", tr("Report a Bug"), tr("Open a bug report ticket")},
- {"💬", "join_discord", tr("Join Discord"), tr("Community & live support")},
- {"🎟", "support_tickets", tr("Support Tickets"), tr("View or open a support ticket")},
+ {"", "create_account", tr("Create Account"), tr("Register for full access")},
+ {"", "reset_password", tr("Reset Password"), tr("Recover your account")},
+ {"", "documentation", tr("Documentation"), tr("Guides, tutorials & API ref")},
+ {"", "report_bug", tr("Report a Bug"), tr("Open a bug report ticket")},
+ {"", "join_discord", tr("Join Discord"), tr("Community & live support")},
+ {"", "support_tickets", tr("Support Tickets"), tr("View or open a support ticket")},
};
int col = 0, row = 0;
@@ -237,13 +239,15 @@ QWidget* HelpScreen::build_page() {
auto* top = new QHBoxLayout;
top->setSpacing(7);
- auto* icon_lbl = new QLabel(QString::fromUtf8(a.icon));
- icon_lbl->setStyleSheet("background: transparent; font-size: 14px;");
+ if (a.icon[0]) {
+ auto* icon_lbl = new QLabel(QString::fromUtf8(a.icon));
+ icon_lbl->setStyleSheet("background: transparent; font-size: 14px;");
+ top->addWidget(icon_lbl);
+ }
auto* name_lbl = new QLabel(a.label);
name_lbl->setStyleSheet(QString("background: transparent; color: %1; font-size: 12px;"
" font-weight: bold; %2")
.arg(colors::TEXT_PRIMARY(), MF));
- top->addWidget(icon_lbl);
top->addWidget(name_lbl);
top->addStretch();
bl->addLayout(top);
@@ -284,41 +288,41 @@ QWidget* HelpScreen::build_page() {
QString a;
};
const FAQ faqs[] = {
- {"🔑", tr("How do I reset my password?"),
+ {"", tr("How do I reset my password?"),
tr("Click \"Forgot Password\" on the login screen. Enter your email address and we'll "
"send you a reset link. The link expires in 24 hours.")},
- {"👤", tr("What is Guest Access?"),
+ {"", tr("What is Guest Access?"),
tr("Guest access lets you explore the terminal without creating an account. "
"Features like trading, portfolio management, and AI analytics require a "
"registered account.")},
- {"💳", tr("What is a Credit?"),
+ {"", tr("What is a Credit?"),
tr("Credits are the in-app currency used for premium features such as AI analysis, "
"advanced data feeds, and quantitative analytics. Free accounts receive a limited "
"number of credits on signup. Additional credits can be purchased in Settings → Billing.")},
- {"📊", tr("How do I connect a broker?"),
+ {"", tr("How do I connect a broker?"),
tr("Navigate to Settings → Brokers, select your broker from the list, and enter your "
"API key and secret. Fincept supports 18+ brokers including Zerodha, Angel One, "
"Upstox, Interactive Brokers, and more.")},
- {"🐍", tr("Why does Python install at first launch?"),
+ {"", tr("Why does Python install at first launch?"),
tr("Fincept embeds Python for 1300+ analytics scripts covering equity, "
"portfolio, derivatives, and quant analysis. The one-time install is ~150 MB and "
"happens automatically in the background.")},
- {"💻", tr("What are the system requirements?"),
+ {"", tr("What are the system requirements?"),
tr("Windows 10+ (x64), macOS 12+, or Linux (glibc 2.31+). 8 GB RAM recommended. "
"Active internet required for data feeds. Python 3.11 is installed automatically "
"during first-time setup.")},
- {"🔒", tr("Is my data secure?"),
+ {"", tr("Is my data secure?"),
tr("Credentials are stored encrypted via SecureStorage (OS keychain on each platform). "
"API keys are never logged or sent to Fincept servers — they are used only for "
"direct broker connections from your machine.")},
- {"🐛", tr("How do I report a bug?"),
+ {"", tr("How do I report a bug?"),
tr("Open a support ticket with category \"bug report\" (Help → Support Tickets → "
"+ New Ticket). Include your OS, version, steps to reproduce, and any error "
"messages you see. Screenshots are helpful.")},
@@ -409,9 +413,9 @@ QWidget* HelpScreen::build_page() {
};
const Contact contacts[] = {
{"✉", tr("Email Support"), "[email protected]", "mailto:[email protected]"},
- {"💬", tr("Discord Server"), "discord.gg/ae87a8ygbN", "https://discord.gg/ae87a8ygbN"},
- {"🌐", tr("Website"), "fincept.in", "https://fincept.in"},
- {"📦", tr("GitHub"), "github.com/Fincept-Corporation/FinceptTerminal",
+ {"", tr("Discord Server"), "discord.gg/ae87a8ygbN", "https://discord.gg/ae87a8ygbN"},
+ {"", tr("Website"), "fincept.in", "https://fincept.in"},
+ {"", tr("GitHub"), "github.com/Fincept-Corporation/FinceptTerminal",
"https://github.com/Fincept-Corporation/FinceptTerminal"},
};
@@ -424,9 +428,11 @@ QWidget* HelpScreen::build_page() {
cl->setContentsMargins(14, 12, 14, 12);
cl->setSpacing(10);
- auto* ico = new QLabel(QString::fromUtf8(c.icon));
- ico->setStyleSheet("background: transparent; font-size: 18px;");
- cl->addWidget(ico);
+ if (c.icon[0]) {
+ auto* ico = new QLabel(QString::fromUtf8(c.icon));
+ ico->setStyleSheet("background: transparent; font-size: 18px;");
+ cl->addWidget(ico);
+ }
auto* tvl = new QVBoxLayout;
tvl->setSpacing(2);
diff --git a/fincept-qt/src/screens/polymarket/PolymarketCommandBar.h b/fincept-qt/src/screens/polymarket/PolymarketCommandBar.h
index 4aef4e9b5..d6371b8d2 100644
--- a/fincept-qt/src/screens/polymarket/PolymarketCommandBar.h
+++ b/fincept-qt/src/screens/polymarket/PolymarketCommandBar.h
@@ -45,7 +45,7 @@ class PolymarketCommandBar : public QWidget {
/// Update the account chip shown next to the exchange combo.
/// `connected == false` renders "⚪ No account" (clickable CTA);
- /// `connected == true` renders "🟢 <label>" in green.
+ /// `connected == true` renders "<label>" in green.
void set_account_status(bool connected, const QString& label);
signals:
diff --git a/fincept-qt/src/screens/polymarket/PolymarketDetailPanel.cpp b/fincept-qt/src/screens/polymarket/PolymarketDetailPanel.cpp
index 48265bc17..5227b8dfe 100644
--- a/fincept-qt/src/screens/polymarket/PolymarketDetailPanel.cpp
+++ b/fincept-qt/src/screens/polymarket/PolymarketDetailPanel.cpp
@@ -234,15 +234,11 @@ QWidget* PolymarketDetailPanel::create_trade_page() {
auto* nal = new QVBoxLayout(no_acct);
nal->setAlignment(Qt::AlignCenter);
nal->setSpacing(8);
- auto* icon_lbl = new QLabel("🔒");
- icon_lbl->setAlignment(Qt::AlignCenter);
- icon_lbl->setStyleSheet("font-size: 28px; background: transparent;");
no_acct_msg_lbl_ = new QLabel(tr("Connect an account\nto place orders"));
auto* msg_lbl = no_acct_msg_lbl_;
msg_lbl->setAlignment(Qt::AlignCenter);
msg_lbl->setStyleSheet(
QString("color: %1; font-size: 11px; background: transparent;").arg(colors::TEXT_DIM()));
- nal->addWidget(icon_lbl);
nal->addWidget(msg_lbl);
ticket_stack_->addWidget(no_acct); // index 0
diff --git a/fincept-qt/src/screens/portfolio/PortfolioDetailWrapper.cpp b/fincept-qt/src/screens/portfolio/PortfolioDetailWrapper.cpp
index 7297f891f..a6e56469b 100644
--- a/fincept-qt/src/screens/portfolio/PortfolioDetailWrapper.cpp
+++ b/fincept-qt/src/screens/portfolio/PortfolioDetailWrapper.cpp
@@ -240,7 +240,7 @@ void PortfolioDetailWrapper::changeEvent(QEvent* event) {
void PortfolioDetailWrapper::retranslateUi() {
if (back_btn_) back_btn_->setText(tr("← BACK"));
if (title_label_) title_label_->setText(view_title(current_view_));
- // portfolio_label_ holds "💼 NAME | CURRENCY" — pure portfolio data, no
+ // portfolio_label_ holds "NAME | CURRENCY" — pure portfolio data, no
// translation needed.
}
diff --git a/fincept-qt/src/screens/settings/AppearanceSection.cpp b/fincept-qt/src/screens/settings/AppearanceSection.cpp
index 28b9b56db..7e58cdf5a 100644
--- a/fincept-qt/src/screens/settings/AppearanceSection.cpp
+++ b/fincept-qt/src/screens/settings/AppearanceSection.cpp
@@ -93,8 +93,31 @@ void AppearanceSection::build_ui() {
vl->addWidget(font_size_row);
app_font_family_ = new QComboBox;
- app_font_family_->addItems(QFontDatabase::families());
- app_font_family_->setCurrentText(kDefaultFontFamily);
+ // QFontDatabase::families() on macOS includes hidden system families
+ // prefixed with '.' (".Apple Color Emoji UI", ".AppleSystemUIFont", …).
+ // Offering them is a trap: the emoji font carries ASCII digit glyphs
+ // (keycap-emoji bases) that render grossly letter-spaced, so picking it
+ // mangles every number in the UI. Exclude private and emoji families.
+ {
+ QStringList fams;
+ for (const QString& f : QFontDatabase::families())
+ if (!f.startsWith('.') && !f.contains("emoji", Qt::CaseInsensitive))
+ fams << f;
+ app_font_family_->addItems(fams);
+ }
+ // setCurrentText() is a no-op when the default isn't installed (Consolas is
+ // Windows-only), which previously left the combo on item 0 — and with the
+ // '.'-prefixed fonts sorted to the top, item 0 was the emoji font, so a save
+ // persisted it. Fall back to the first available monospace instead.
+ if (app_font_family_->findText(kDefaultFontFamily) >= 0) {
+ app_font_family_->setCurrentText(kDefaultFontFamily);
+ } else {
+ for (const char* mono : {"Menlo", "SF Mono", "Monaco", "Cascadia Mono",
+ "DejaVu Sans Mono", "Courier New"}) {
+ int idx = app_font_family_->findText(QString::fromLatin1(mono));
+ if (idx >= 0) { app_font_family_->setCurrentIndex(idx); break; }
+ }
+ }
app_font_family_->setStyleSheet(combo_ss());
auto* font_family_row = make_row(tr("Font Family"), app_font_family_);
capture_row_labels(font_family_row, &font_family_label_);
diff --git a/fincept-qt/src/screens/settings/NotificationsSection.cpp b/fincept-qt/src/screens/settings/NotificationsSection.cpp
index c106615d1..f656bce7d 100644
--- a/fincept-qt/src/screens/settings/NotificationsSection.cpp
+++ b/fincept-qt/src/screens/settings/NotificationsSection.cpp
@@ -55,50 +55,50 @@ const QVector<ProviderDef>& provider_defs() {
{"telegram", "Telegram", "✈",
{{"bot_token", "Bot Token", "Enter bot token from @BotFather", true},
{"chat_id", "Chat ID", "e.g. 123456789"}}},
- {"discord", "Discord", "🎮",
+ {"discord", "Discord", "",
{{"webhook_url", "Webhook URL", "https://discord.com/api/webhooks/..."}}},
- {"slack", "Slack", "💬",
+ {"slack", "Slack", "",
{{"webhook_url", "Webhook URL", "https://hooks.slack.com/services/..."},
{"channel", "Channel", "#alerts (optional)"}}},
- {"email", "Email", "📧",
+ {"email", "Email", "",
{{"smtp_host", "SMTP Host", "smtp.gmail.com"},
{"smtp_port", "Port", "587"},
{"smtp_user", "Username", "[email protected]"},
{"smtp_pass", "Password", "App password", true},
{"to_addr", "To Address","[email protected]"},
{"from_addr", "From Address","[email protected] (optional)"}}},
- {"whatsapp", "WhatsApp", "📱",
+ {"whatsapp", "WhatsApp", "",
{{"account_sid", "Account SID", "Twilio Account SID"},
{"auth_token", "Auth Token", "Twilio Auth Token", true},
{"from_number", "From Number", "+14155238886"},
{"to_number", "To Number", "+1XXXXXXXXXX"}}},
- {"pushover", "Pushover", "🔔",
+ {"pushover", "Pushover", "",
{{"api_token", "API Token", "Your Pushover app token", true},
{"user_key", "User Key", "Your Pushover user key", true}}},
- {"ntfy", "ntfy", "📢",
+ {"ntfy", "ntfy", "",
{{"server_url", "Server URL", "https://ntfy.sh (leave empty for default)"},
{"topic", "Topic", "your-topic-name"},
{"token", "Auth Token", "Optional auth token", true}}},
- {"pushbullet", "Pushbullet", "🔵",
+ {"pushbullet", "Pushbullet", "",
{{"api_key", "API Key", "Your Pushbullet API key", true},
{"channel_tag", "Channel Tag", "Optional channel tag"}}},
- {"gotify", "Gotify", "🔊",
+ {"gotify", "Gotify", "",
{{"server_url", "Server URL", "https://your-gotify-server.com"},
{"app_token", "App Token", "Application token", true}}},
- {"mattermost", "Mattermost", "🟦",
+ {"mattermost", "Mattermost", "",
{{"webhook_url", "Webhook URL", "https://your-mattermost.com/hooks/..."},
{"channel", "Channel", "#town-square (optional)"},
{"username", "Username", "Fincept (optional)"}}},
- {"teams", "MS Teams", "🟪",
+ {"teams", "MS Teams", "",
{{"webhook_url", "Webhook URL", "https://outlook.office.com/webhook/..."}}},
- {"webhook", "Webhook", "🌐",
+ {"webhook", "Webhook", "",
{{"url", "URL", "https://your-endpoint.com/notify"},
{"method", "Method", "POST"}}},
- {"pagerduty", "PagerDuty", "🚨",
+ {"pagerduty", "PagerDuty", "",
{{"routing_key", "Routing Key", "32-character integration key", true}}},
- {"opsgenie", "Opsgenie", "🔴",
+ {"opsgenie", "Opsgenie", "",
{{"api_key", "API Key", "Your Opsgenie API key", true}}},
- {"sms", "SMS (Twilio)", "💬",
+ {"sms", "SMS (Twilio)", "",
{{"account_sid", "Account SID", "Twilio Account SID"},
{"auth_token", "Auth Token", "Twilio Auth Token", true},
{"from_number", "From Number", "+15005550006"},
@@ -171,7 +171,8 @@ void NotificationsSection::build_ui() {
QString("color: %1; background: transparent;").arg(ui::colors::TEXT_SECONDARY()));
hl->addWidget(arrow_lbl);
- auto* icon_lbl = new QLabel(def.icon + " " + def.name.toUpper());
+ auto* icon_lbl = new QLabel(def.icon.isEmpty() ? def.name.toUpper()
+ : def.icon + " " + def.name.toUpper());
icon_lbl->setStyleSheet(
QString("color: %1; font-weight: bold; background: transparent;").arg(ui::colors::TEXT_PRIMARY()));
hl->addWidget(icon_lbl, 1);
diff --git a/fincept-qt/src/screens/support/SupportScreen.cpp b/fincept-qt/src/screens/support/SupportScreen.cpp
index 6c69fb224..0629c3e02 100644
--- a/fincept-qt/src/screens/support/SupportScreen.cpp
+++ b/fincept-qt/src/screens/support/SupportScreen.cpp
@@ -88,8 +88,6 @@ SupportScreen::SupportScreen(QWidget* parent) : QWidget(parent) {
bl->setSpacing(10);
// Title (text set in retranslateUi)
- auto* icon_lbl = lbl("🎟", ui::colors::AMBER(), 14);
- bl->addWidget(icon_lbl);
title_lbl_ = lbl(QString(), ui::colors::TEXT_PRIMARY(), 14, true);
bl->addWidget(title_lbl_);
@@ -231,7 +229,7 @@ void SupportScreen::retranslateUi() {
// ── Sidebar header ────────────────────────────────────────────────────────
if (new_ticket_btn_) new_ticket_btn_->setText(tr("+ New Ticket"));
- if (search_input_) search_input_->setPlaceholderText(tr("🔍 Search tickets…"));
+ if (search_input_) search_input_->setPlaceholderText(tr("Search tickets…"));
// Filter combo — preserve current row across the rebuild.
if (filter_combo_) {
diff --git a/fincept-qt/src/screens/support/SupportScreen_Layout.cpp b/fincept-qt/src/screens/support/SupportScreen_Layout.cpp
index d2ab6faa8..de93ca5f1 100644
--- a/fincept-qt/src/screens/support/SupportScreen_Layout.cpp
+++ b/fincept-qt/src/screens/support/SupportScreen_Layout.cpp
@@ -135,10 +135,6 @@ QWidget* SupportScreen::build_empty_state() {
vl->setAlignment(Qt::AlignCenter);
vl->setSpacing(12);
- auto* icon = lbl("🎟", ui::colors::TEXT_TERTIARY(), 40);
- icon->setAlignment(Qt::AlignCenter);
- vl->addWidget(icon);
-
auto* t = lbl(tr("Select a ticket to view details"), ui::colors::TEXT_SECONDARY(), 13, true);
t->setAlignment(Qt::AlignCenter);
vl->addWidget(t);
diff --git a/fincept-qt/src/services/notifications/providers/DiscordProvider.h b/fincept-qt/src/services/notifications/providers/DiscordProvider.h
index cc8ec8172..7397f71ad 100644
--- a/fincept-qt/src/services/notifications/providers/DiscordProvider.h
+++ b/fincept-qt/src/services/notifications/providers/DiscordProvider.h
@@ -7,7 +7,7 @@ class DiscordProvider final : public BaseProvider {
public:
QString provider_id() const override { return "discord"; }
QString display_name() const override { return "Discord"; }
- QString icon() const override { return "🎮"; }
+ QString icon() const override { return ""; }
bool is_configured() const override { return !webhook_url_.isEmpty(); }
void send(const NotificationRequest& req, std::function<void(bool, QString)> cb) override;
diff --git a/fincept-qt/src/services/notifications/providers/EmailProvider.h b/fincept-qt/src/services/notifications/providers/EmailProvider.h
index b9715319f..ef284d0f5 100644
--- a/fincept-qt/src/services/notifications/providers/EmailProvider.h
+++ b/fincept-qt/src/services/notifications/providers/EmailProvider.h
@@ -10,7 +10,7 @@ class EmailProvider final : public BaseProvider {
public:
QString provider_id() const override { return "email"; }
QString display_name() const override { return "Email"; }
- QString icon() const override { return "📧"; }
+ QString icon() const override { return ""; }
bool is_configured() const override { return !smtp_host_.isEmpty() && !to_addr_.isEmpty(); }
void send(const NotificationRequest& req, std::function<void(bool, QString)> cb) override;
diff --git a/fincept-qt/src/services/notifications/providers/GotifyProvider.h b/fincept-qt/src/services/notifications/providers/GotifyProvider.h
index 70bb68ff4..84daee92f 100644
--- a/fincept-qt/src/services/notifications/providers/GotifyProvider.h
+++ b/fincept-qt/src/services/notifications/providers/GotifyProvider.h
@@ -7,7 +7,7 @@ class GotifyProvider final : public BaseProvider {
public:
QString provider_id() const override { return "gotify"; }
QString display_name() const override { return "Gotify"; }
- QString icon() const override { return "🔊"; }
+ QString icon() const override { return ""; }
bool is_configured() const override { return !server_url_.isEmpty() && !app_token_.isEmpty(); }
void send(const NotificationRequest& req, std::function<void(bool, QString)> cb) override;
diff --git a/fincept-qt/src/services/notifications/providers/MattermostProvider.h b/fincept-qt/src/services/notifications/providers/MattermostProvider.h
index 106e31a36..958b8305d 100644
--- a/fincept-qt/src/services/notifications/providers/MattermostProvider.h
+++ b/fincept-qt/src/services/notifications/providers/MattermostProvider.h
@@ -7,7 +7,7 @@ class MattermostProvider final : public BaseProvider {
public:
QString provider_id() const override { return "mattermost"; }
QString display_name() const override { return "Mattermost"; }
- QString icon() const override { return "🟦"; }
+ QString icon() const override { return ""; }
bool is_configured() const override { return !webhook_url_.isEmpty(); }
void send(const NotificationRequest& req, std::function<void(bool, QString)> cb) override;
diff --git a/fincept-qt/src/services/notifications/providers/NtfyProvider.h b/fincept-qt/src/services/notifications/providers/NtfyProvider.h
index f272d0707..5ab7932df 100644
--- a/fincept-qt/src/services/notifications/providers/NtfyProvider.h
+++ b/fincept-qt/src/services/notifications/providers/NtfyProvider.h
@@ -8,7 +8,7 @@ class NtfyProvider final : public BaseProvider {
public:
QString provider_id() const override { return "ntfy"; }
QString display_name() const override { return "ntfy"; }
- QString icon() const override { return "📢"; }
+ QString icon() const override { return ""; }
bool is_configured() const override { return !topic_.isEmpty(); }
void send(const NotificationRequest& req, std::function<void(bool, QString)> cb) override;
diff --git a/fincept-qt/src/services/notifications/providers/OpsgenieProvider.h b/fincept-qt/src/services/notifications/providers/OpsgenieProvider.h
index 78c26c72b..0f6b41308 100644
--- a/fincept-qt/src/services/notifications/providers/OpsgenieProvider.h
+++ b/fincept-qt/src/services/notifications/providers/OpsgenieProvider.h
@@ -7,7 +7,7 @@ class OpsgenieProvider final : public BaseProvider {
public:
QString provider_id() const override { return "opsgenie"; }
QString display_name() const override { return "Opsgenie"; }
- QString icon() const override { return "🔴"; }
+ QString icon() const override { return ""; }
bool is_configured() const override { return !api_key_.isEmpty(); }
void send(const NotificationRequest& req, std::function<void(bool, QString)> cb) override;
diff --git a/fincept-qt/src/services/notifications/providers/PagerDutyProvider.h b/fincept-qt/src/services/notifications/providers/PagerDutyProvider.h
index 2a5615cf5..763291e39 100644
--- a/fincept-qt/src/services/notifications/providers/PagerDutyProvider.h
+++ b/fincept-qt/src/services/notifications/providers/PagerDutyProvider.h
@@ -7,7 +7,7 @@ class PagerDutyProvider final : public BaseProvider {
public:
QString provider_id() const override { return "pagerduty"; }
QString display_name() const override { return "PagerDuty"; }
- QString icon() const override { return "🚨"; }
+ QString icon() const override { return ""; }
bool is_configured() const override { return !routing_key_.isEmpty(); }
void send(const NotificationRequest& req, std::function<void(bool, QString)> cb) override;
diff --git a/fincept-qt/src/services/notifications/providers/PushbulletProvider.h b/fincept-qt/src/services/notifications/providers/PushbulletProvider.h
index 07a437196..010e1bd2f 100644
--- a/fincept-qt/src/services/notifications/providers/PushbulletProvider.h
+++ b/fincept-qt/src/services/notifications/providers/PushbulletProvider.h
@@ -7,7 +7,7 @@ class PushbulletProvider final : public BaseProvider {
public:
QString provider_id() const override { return "pushbullet"; }
QString display_name() const override { return "Pushbullet"; }
- QString icon() const override { return "🔵"; }
+ QString icon() const override { return ""; }
bool is_configured() const override { return !api_key_.isEmpty(); }
void send(const NotificationRequest& req, std::function<void(bool, QString)> cb) override;
diff --git a/fincept-qt/src/services/notifications/providers/PushoverProvider.h b/fincept-qt/src/services/notifications/providers/PushoverProvider.h
index cc6f662c5..83aafbee4 100644
--- a/fincept-qt/src/services/notifications/providers/PushoverProvider.h
+++ b/fincept-qt/src/services/notifications/providers/PushoverProvider.h
@@ -7,7 +7,7 @@ class PushoverProvider final : public BaseProvider {
public:
QString provider_id() const override { return "pushover"; }
QString display_name() const override { return "Pushover"; }
- QString icon() const override { return "🔔"; }
+ QString icon() const override { return ""; }
bool is_configured() const override { return !api_token_.isEmpty() && !user_key_.isEmpty(); }
void send(const NotificationRequest& req, std::function<void(bool, QString)> cb) override;
diff --git a/fincept-qt/src/services/notifications/providers/SMSProvider.h b/fincept-qt/src/services/notifications/providers/SMSProvider.h
index 5b2b6fce2..7894fca2c 100644
--- a/fincept-qt/src/services/notifications/providers/SMSProvider.h
+++ b/fincept-qt/src/services/notifications/providers/SMSProvider.h
@@ -8,7 +8,7 @@ class SMSProvider final : public BaseProvider {
public:
QString provider_id() const override { return "sms"; }
QString display_name() const override { return "SMS (Twilio)"; }
- QString icon() const override { return "💬"; }
+ QString icon() const override { return ""; }
bool is_configured() const override {
return !account_sid_.isEmpty() && !auth_token_.isEmpty() && !from_number_.isEmpty() && !to_number_.isEmpty();
}
diff --git a/fincept-qt/src/services/notifications/providers/SlackProvider.h b/fincept-qt/src/services/notifications/providers/SlackProvider.h
index b3e357fd2..2c1aa51fb 100644
--- a/fincept-qt/src/services/notifications/providers/SlackProvider.h
+++ b/fincept-qt/src/services/notifications/providers/SlackProvider.h
@@ -7,7 +7,7 @@ class SlackProvider final : public BaseProvider {
public:
QString provider_id() const override { return "slack"; }
QString display_name() const override { return "Slack"; }
- QString icon() const override { return "💬"; }
+ QString icon() const override { return ""; }
bool is_configured() const override { return !webhook_url_.isEmpty(); }
void send(const NotificationRequest& req, std::function<void(bool, QString)> cb) override;
diff --git a/fincept-qt/src/services/notifications/providers/TeamsProvider.h b/fincept-qt/src/services/notifications/providers/TeamsProvider.h
index 3182cf5bd..c5483668c 100644
--- a/fincept-qt/src/services/notifications/providers/TeamsProvider.h
+++ b/fincept-qt/src/services/notifications/providers/TeamsProvider.h
@@ -7,7 +7,7 @@ class TeamsProvider final : public BaseProvider {
public:
QString provider_id() const override { return "teams"; }
QString display_name() const override { return "MS Teams"; }
- QString icon() const override { return "🟪"; }
+ QString icon() const override { return ""; }
bool is_configured() const override { return !webhook_url_.isEmpty(); }
void send(const NotificationRequest& req, std::function<void(bool, QString)> cb) override;
diff --git a/fincept-qt/src/services/notifications/providers/WebhookProvider.h b/fincept-qt/src/services/notifications/providers/WebhookProvider.h
index 57374602e..2e1be52d9 100644
--- a/fincept-qt/src/services/notifications/providers/WebhookProvider.h
+++ b/fincept-qt/src/services/notifications/providers/WebhookProvider.h
@@ -8,7 +8,7 @@ class WebhookProvider final : public BaseProvider {
public:
QString provider_id() const override { return "webhook"; }
QString display_name() const override { return "Webhook"; }
- QString icon() const override { return "🌐"; }
+ QString icon() const override { return ""; }
bool is_configured() const override { return !url_.isEmpty(); }
void send(const NotificationRequest& req, std::function<void(bool, QString)> cb) override;
diff --git a/fincept-qt/src/services/notifications/providers/WhatsAppProvider.h b/fincept-qt/src/services/notifications/providers/WhatsAppProvider.h
index 6fd22cba1..1b55f2db1 100644
--- a/fincept-qt/src/services/notifications/providers/WhatsAppProvider.h
+++ b/fincept-qt/src/services/notifications/providers/WhatsAppProvider.h
@@ -8,7 +8,7 @@ class WhatsAppProvider final : public BaseProvider {
public:
QString provider_id() const override { return "whatsapp"; }
QString display_name() const override { return "WhatsApp"; }
- QString icon() const override { return "📱"; }
+ QString icon() const override { return ""; }
bool is_configured() const override {
return !account_sid_.isEmpty() && !auth_token_.isEmpty() && !from_number_.isEmpty() && !to_number_.isEmpty();
}
diff --git a/fincept-qt/src/storage/secure/SecureStorage.cpp b/fincept-qt/src/storage/secure/SecureStorage.cpp
index 5777d70a0..cca4e0424 100644
--- a/fincept-qt/src/storage/secure/SecureStorage.cpp
+++ b/fincept-qt/src/storage/secure/SecureStorage.cpp
@@ -208,7 +208,7 @@ Result<void> SecureStorage::store(const QString& key, const QString& value) {
return Result<void>::err("Encryption failed");
}
- QSqlQuery q(db.raw_db());
+ QSqlQuery q(db.connection()); // per-thread connection (see retrieve) — thread-safe
q.prepare(R"sql(
INSERT INTO secure_credentials (key, ciphertext, iv, tag, updated_at)
VALUES (?, ?, ?, ?, datetime('now'))
@@ -235,7 +235,10 @@ Result<QString> SecureStorage::retrieve(const QString& key) {
if (!db.is_open())
return Result<QString>::err("Database not open");
- QSqlQuery q(db.raw_db());
+ // Use the per-thread connection, NOT the shared raw_db(): credential reads run
+ // on worker threads (algo quote polling, candle warm-up, order placement), and
+ // sharing one SQLite handle across threads corrupts the parser → SIGSEGV.
+ QSqlQuery q(db.connection());
q.prepare("SELECT ciphertext, iv, tag FROM secure_credentials WHERE key = ?");
q.addBindValue(key);
if (!q.exec()) {
@@ -269,7 +272,7 @@ Result<void> SecureStorage::remove(const QString& key) {
if (!db.is_open())
return Result<void>::err("Database not open");
- QSqlQuery q(db.raw_db());
+ QSqlQuery q(db.connection()); // per-thread connection (see retrieve) — thread-safe
q.prepare("DELETE FROM secure_credentials WHERE key = ?");
q.addBindValue(key);
if (!q.exec()) {
diff --git a/fincept-qt/src/storage/sqlite/migrations/MigrationRunner.h b/fincept-qt/src/storage/sqlite/migrations/MigrationRunner.h
index 48fd577d6..f1922c168 100644
--- a/fincept-qt/src/storage/sqlite/migrations/MigrationRunner.h
+++ b/fincept-qt/src/storage/sqlite/migrations/MigrationRunner.h
@@ -85,5 +85,6 @@ void register_migration_v035();
void register_migration_v036();
void register_migration_v037();
void register_migration_v038();
+void register_migration_v039();
} // namespace fincept
diff --git a/fincept-qt/src/storage/sqlite/migrations/v039_algo_schema_fix.cpp b/fincept-qt/src/storage/sqlite/migrations/v039_algo_schema_fix.cpp
new file mode 100644
index 000000000..27e827c21
--- /dev/null
+++ b/fincept-qt/src/storage/sqlite/migrations/v039_algo_schema_fix.cpp
@@ -0,0 +1,66 @@
+// v039_algo_schema_fix — repair algo_trading schema drift on dev DBs that were
+// migrated to v23 by an OLDER v023 which predated the entry_side / current_price
+// ADD COLUMNs. Those ALTERs live in v023 now, but v23 is already marked applied on
+// existing DBs, so they never ran there. At runtime the deploy INSERT
+// (algo_deployments.entry_side) and the metrics UPSERT (algo_metrics.current_price)
+// then fail with "no such column" / "Parameter count mismatch", so deployments
+// never persist and metrics never save. Add the columns idempotently so freshly
+// created DBs (which already have them via v023) and drifted DBs converge.
+
+#include "storage/sqlite/migrations/MigrationRunner.h"
+
+#include <QSqlError>
+#include <QSqlQuery>
+
+namespace fincept {
+namespace {
+
+bool v039_column_exists(QSqlDatabase& db, const QString& table, const QString& column) {
+ QSqlQuery q(db);
+ q.exec(QString("PRAGMA table_info(%1)").arg(table));
+ while (q.next())
+ if (q.value(1).toString().compare(column, Qt::CaseInsensitive) == 0)
+ return true;
+ return false;
+}
+
+Result<void> v039_add_if_missing(QSqlDatabase& db, const QString& table, const QString& column,
+ const QString& decl) {
+ if (v039_column_exists(db, table, column))
+ return Result<void>::ok();
+ QSqlQuery q(db);
+ if (!q.exec(QString("ALTER TABLE %1 ADD COLUMN %2 %3").arg(table, column, decl)))
+ return Result<void>::err(q.lastError().text().toStdString());
+ return Result<void>::ok();
+}
+
+Result<void> apply_v039(QSqlDatabase& db) {
+ struct Col {
+ const char* table;
+ const char* column;
+ const char* decl;
+ };
+ const Col cols[] = {
+ {"algo_deployments", "entry_side", "TEXT DEFAULT 'BUY'"},
+ {"algo_metrics", "current_price", "REAL DEFAULT 0"},
+ {"algo_metrics", "entry_side", "TEXT DEFAULT 'BUY'"},
+ };
+ for (const auto& c : cols) {
+ auto r = v039_add_if_missing(db, c.table, c.column, c.decl);
+ if (r.is_err())
+ return r;
+ }
+ return Result<void>::ok();
+}
+
+} // namespace
+
+void register_migration_v039() {
+ static bool done = false;
+ if (done)
+ return;
+ done = true;
+ MigrationRunner::register_migration({39, "algo_schema_fix", apply_v039});
+}
+
+} // namespace fincept
diff --git a/fincept-qt/src/trading/AccountManager.cpp b/fincept-qt/src/trading/AccountManager.cpp
index e4c57869a..ab1ca2678 100644
--- a/fincept-qt/src/trading/AccountManager.cpp
+++ b/fincept-qt/src/trading/AccountManager.cpp
@@ -82,6 +82,14 @@ void AccountManager::load_from_db() {
}
}
+void AccountManager::reload_from_db() {
+ {
+ QMutexLocker lock(&mutex_);
+ accounts_.clear();
+ }
+ load_from_db(); // re-acquires the lock internally
+}
+
// ── Legacy credential migration ─────────────────────────────────────────────
void AccountManager::migrate_legacy_credentials() {
@@ -367,6 +375,14 @@ void AccountManager::save_credentials(const QString& account_id, const BrokerCre
secure.store(acct_key(account_id, "refresh_token"), creds.refresh_token);
secure.store(acct_key(account_id, "user_id"), creds.user_id);
secure.store(acct_key(account_id, "additional_data"), creds.additional_data);
+
+ // The live token just changed. Notify listeners (DataStreamManager) so any
+ // running stream is rebuilt with the new credentials: WebSocket adapters
+ // capture the access token at construction and have no setter, so without a
+ // rebuild they keep resolving/subscribing with the stale token (HTTP 401)
+ // and never stream ticks — the cause of price data stalling after a daily
+ // re-auth until the next slow REST poll happened to reload the new token.
+ emit credentials_changed(account_id);
}
BrokerCredentials AccountManager::load_credentials(const QString& account_id) const {
diff --git a/fincept-qt/src/trading/AccountManager.h b/fincept-qt/src/trading/AccountManager.h
index ac9ba45a1..db0ae2052 100644
--- a/fincept-qt/src/trading/AccountManager.h
+++ b/fincept-qt/src/trading/AccountManager.h
@@ -67,10 +67,23 @@ class AccountManager : public QObject {
// Also runs one sweep immediately. Safe to call more than once.
void start_session_monitor();
+ // Reload the in-memory account map from the database. The singleton loads
+ // eagerly in its constructor on first access — but if that first access
+ // happens before Database::open() (the constructor's find_all() then returns
+ // nothing), the map stays empty for the entire session and configured
+ // brokers appear to "vanish" on restart. Call this once on the main thread
+ // right after the DB is open to guarantee accounts are loaded. Idempotent.
+ void reload_from_db();
+
signals:
void account_added(const QString& account_id);
void account_removed(const QString& account_id);
void account_updated(const QString& account_id);
+ // Emitted whenever an account's stored credentials change — manual re-auth
+ // or silent token refresh. DataStreamManager listens to rebuild any live
+ // stream so WebSocket adapters that capture the access token at construction
+ // pick up the fresh token instead of streaming on a now-dead one.
+ void credentials_changed(const QString& account_id);
void connection_state_changed(const QString& account_id, ConnectionState state);
private:
diff --git a/fincept-qt/src/trading/DataStreamManager.cpp b/fincept-qt/src/trading/DataStreamManager.cpp
index 419e2df85..bae1131b8 100644
--- a/fincept-qt/src/trading/DataStreamManager.cpp
+++ b/fincept-qt/src/trading/DataStreamManager.cpp
@@ -44,6 +44,21 @@ DataStreamManager::DataStreamManager() {
connect(expiry_check_timer_, &QTimer::timeout, this,
&DataStreamManager::check_indian_token_expiry);
expiry_check_timer_->start();
+
+ // When an account's token is re-authenticated or silently refreshed, rebuild
+ // its live stream so the WebSocket adapter (which captures the token at
+ // construction with no setter) reconnects with the fresh token. Without this,
+ // a stream started with a now-expired token keeps getting HTTP 401 on
+ // resolve/subscribe and never streams ticks. Only rebuild streams that
+ // already exist — don't spin up streams for accounts the user hasn't opened.
+ connect(&AccountManager::instance(), &AccountManager::credentials_changed,
+ this, [this](const QString& account_id) {
+ if (!streams_.contains(account_id))
+ return;
+ LOG_INFO(DSM_TAG, QString("Credentials changed for %1 — rebuilding stream "
+ "with fresh token").arg(account_id));
+ restart_stream(account_id);
+ });
}
void DataStreamManager::check_indian_token_expiry() {
@@ -119,6 +134,15 @@ void DataStreamManager::stop_stream(const QString& account_id) {
LOG_INFO(DSM_TAG, QString("Stopped data stream for account %1").arg(account_id));
}
+void DataStreamManager::restart_stream(const QString& account_id) {
+ // stop_stream() tears down the old AccountDataStream (and its WebSocket, which
+ // caches the access token at construction); start_stream() then rebuilds it so
+ // ws_init() reloads the latest credentials from AccountManager. If no stream
+ // exists yet, stop_stream() is a no-op and start_stream() creates a fresh one.
+ stop_stream(account_id);
+ start_stream(account_id);
+}
+
void DataStreamManager::start_all_active() {
const auto accounts = AccountManager::instance().active_accounts();
for (const auto& account : accounts) {
diff --git a/fincept-qt/src/trading/DataStreamManager.h b/fincept-qt/src/trading/DataStreamManager.h
index b65d65b1c..6897af615 100644
--- a/fincept-qt/src/trading/DataStreamManager.h
+++ b/fincept-qt/src/trading/DataStreamManager.h
@@ -26,6 +26,10 @@ class DataStreamManager : public QObject
AccountDataStream* stream_for(const QString& account_id);
void start_stream(const QString& account_id);
void stop_stream(const QString& account_id);
+ // Tear down and recreate a stream so AccountDataStream::ws_init() reloads the
+ // latest credentials. Use after a token re-auth/refresh — plain start_stream()
+ // only resume()s an existing stream and would keep the stale cached token.
+ void restart_stream(const QString& account_id);
void start_all_active();
void stop_all();
diff --git a/fincept-qt/src/ui/charts/KLineChartWidget.cpp b/fincept-qt/src/ui/charts/KLineChartWidget.cpp
index 704804380..a6413bb88 100644
--- a/fincept-qt/src/ui/charts/KLineChartWidget.cpp
+++ b/fincept-qt/src/ui/charts/KLineChartWidget.cpp
@@ -7,17 +7,47 @@
#include <QWebEnginePage>
#endif
+#include <QContextMenuEvent>
#include <QCoreApplication>
#include <QDateTime>
#include <QJsonDocument>
#include <QJsonObject>
#include <QLabel>
+#include <QMenu>
+#include <QMouseEvent>
+#include <QPointer>
#include <QShowEvent>
+#include <QTimer>
#include <QUrl>
#include <QVBoxLayout>
namespace fincept::ui {
+#ifdef HAS_QT_WEBENGINE
+namespace {
+// QWebEngineView delivers context-menu events to the view subclass in Qt 6, so
+// we override contextMenuEvent to replace the default web menu with our native
+// trading menu. The price under the cursor is resolved asynchronously via JS.
+class ChartWebView : public QWebEngineView {
+ public:
+ explicit ChartWebView(KLineChartWidget* host) : QWebEngineView(host), host_(host) {}
+
+ protected:
+ void contextMenuEvent(QContextMenuEvent* e) override {
+ if (host_ && host_->trading_menu_enabled()) {
+ host_->show_chart_context_menu(e->pos().y(), e->globalPos());
+ e->accept();
+ return; // suppress the default WebEngine context menu
+ }
+ QWebEngineView::contextMenuEvent(e);
+ }
+
+ private:
+ KLineChartWidget* host_;
+};
+} // namespace
+#endif
+
KLineChartWidget::KLineChartWidget(QWidget* parent) : QWidget(parent) {
setObjectName("klineChartWidget");
@@ -45,6 +75,7 @@ bool KLineChartWidget::is_available() const {
void KLineChartWidget::showEvent(QShowEvent* e) {
QWidget::showEvent(e);
ensure_web_view();
+ install_chart_event_filter();
}
void KLineChartWidget::ensure_web_view() {
@@ -53,7 +84,7 @@ void KLineChartWidget::ensure_web_view() {
return;
initialized_ = true;
- web_view_ = new QWebEngineView(this);
+ web_view_ = new ChartWebView(this);
web_view_->setObjectName("klineWebView");
// The bundled chart html/js is local and changes across releases — never
@@ -82,6 +113,7 @@ void KLineChartWidget::on_load_finished(bool ok) {
if (!ok) return;
page_ready_ = true;
flush_pending();
+ install_chart_event_filter(); // render widget exists by now
emit chart_ready();
}
@@ -169,4 +201,102 @@ void KLineChartWidget::clear() {
run_js(QStringLiteral("window.clearChart()"));
}
+void KLineChartWidget::show_chart_context_menu(int local_y, const QPoint& global_pos) {
+ if (menu_open_)
+ return; // a paired event for the same right-click — ignore
+ menu_open_ = true;
+
+ // The menu MUST be shown synchronously, in direct response to the right-click
+ // event. On macOS a QMenu popped later (e.g. from an async runJavaScript
+ // callback) silently fails to display. So exec() here, then resolve the
+ // cursor price asynchronously only once the user has actually chosen Buy/Sell.
+ QMenu menu;
+ QAction* buy_act = menu.addAction(tr("Buy"));
+ menu.addAction(tr("Sell")); // non-buy, non-watchlist choice ⇒ Sell (see below)
+ menu.addSeparator();
+ QAction* wl_act = menu.addAction(tr("Add to watchlist"));
+
+ QAction* chosen = menu.exec(global_pos);
+ // Clear the guard after this event burst so the right-click's paired event
+ // (some platforms deliver both a mouse-press and a ContextMenu) can't pop a
+ // second menu, but the next genuine right-click can.
+ QPointer<KLineChartWidget> self = this;
+ QTimer::singleShot(0, this, [self] { if (self) self->menu_open_ = false; });
+
+ if (!chosen)
+ return;
+ if (chosen == wl_act) {
+ emit add_to_watchlist_requested();
+ return;
+ }
+ const bool is_buy = (chosen == buy_act);
+
+#ifdef HAS_QT_WEBENGINE
+ if (web_view_ && page_ready_) {
+ QPointer<KLineChartWidget> self = this;
+ web_view_->page()->runJavaScript(
+ QStringLiteral("window.priceAtY(%1)").arg(local_y),
+ [self, is_buy](const QVariant& v) {
+ if (!self)
+ return;
+ bool ok = false;
+ const double price = v.toDouble(&ok);
+ self->emit_trade(is_buy, (ok && price > 0) ? price : -1.0);
+ });
+ return;
+ }
+#endif
+ Q_UNUSED(local_y);
+ emit_trade(is_buy, -1.0); // no chart price — the ticket falls back to the LTP
+}
+
+void KLineChartWidget::emit_trade(bool is_buy, double price) {
+ if (is_buy)
+ emit buy_requested(price);
+ else
+ emit sell_requested(price);
+}
+
+void KLineChartWidget::install_chart_event_filter() {
+#ifdef HAS_QT_WEBENGINE
+ if (!web_view_ || !trading_menu_)
+ return;
+ // The render widget (focusProxy) is created lazily — after the page's render
+ // process is up. Retry until it exists, then filter it for right-clicks.
+ QWidget* proxy = web_view_->focusProxy();
+ if (!proxy) {
+ QPointer<KLineChartWidget> self = this;
+ QTimer::singleShot(50, this, [self] { if (self) self->install_chart_event_filter(); });
+ return;
+ }
+ if (proxy == filtered_proxy_)
+ return; // already filtering this one
+ if (filtered_proxy_)
+ filtered_proxy_->removeEventFilter(this);
+ proxy->installEventFilter(this);
+ filtered_proxy_ = proxy;
+#endif
+}
+
+bool KLineChartWidget::eventFilter(QObject* obj, QEvent* ev) {
+#ifdef HAS_QT_WEBENGINE
+ if (trading_menu_ && obj == filtered_proxy_) {
+ if (ev->type() == QEvent::ContextMenu) {
+ auto* cme = static_cast<QContextMenuEvent*>(ev);
+ show_chart_context_menu(cme->pos().y(), cme->globalPos());
+ return true; // consume — no default Chromium menu
+ }
+ if (ev->type() == QEvent::MouseButtonPress) {
+ auto* me = static_cast<QMouseEvent*>(ev);
+ if (me->button() == Qt::RightButton) {
+ show_chart_context_menu(static_cast<int>(me->position().y()),
+ me->globalPosition().toPoint());
+ return true;
+ }
+ }
+ }
+#endif
+ return QWidget::eventFilter(obj, ev);
+}
+
} // namespace fincept::ui
diff --git a/fincept-qt/src/ui/charts/KLineChartWidget.h b/fincept-qt/src/ui/charts/KLineChartWidget.h
index 8c383b21b..ad81b0025 100644
--- a/fincept-qt/src/ui/charts/KLineChartWidget.h
+++ b/fincept-qt/src/ui/charts/KLineChartWidget.h
@@ -1,6 +1,8 @@
#pragma once
#include <QJsonArray>
+#include <QPoint>
+#include <QPointer>
#include <QQueue>
#include <QString>
#include <QWidget>
@@ -27,14 +29,32 @@ public:
bool is_available() const;
+ // Enable the right-click trading menu (Buy/Sell @ cursor price + watchlist).
+ // Off by default so non-trading charts (e.g. Equity Research) are unaffected.
+ void set_trading_menu_enabled(bool on) { trading_menu_ = on; }
+ bool trading_menu_enabled() const { return trading_menu_; }
+ // Called by the internal web view on right-click: looks up the price under
+ // `local_y` (view coords) via JS, then pops the trade menu at `global_pos`.
+ void show_chart_context_menu(int local_y, const QPoint& global_pos);
+
signals:
void chart_ready();
+ void buy_requested(double price);
+ void sell_requested(double price);
+ void add_to_watchlist_requested();
protected:
void showEvent(QShowEvent* e) override;
+ // QWebEngineView routes input to an internal render widget (its focusProxy),
+ // so QWebEngineView::contextMenuEvent never fires for our subclass — the
+ // right-click is swallowed by Chromium. We instead filter the proxy's raw
+ // right mouse-press to drive the trading menu reliably (incl. on macOS).
+ bool eventFilter(QObject* obj, QEvent* ev) override;
private:
void ensure_web_view();
+ void install_chart_event_filter(); // (re)attach the proxy filter once it exists
+ void emit_trade(bool is_buy, double price);
void run_js(const QString& js);
void flush_pending();
void on_load_finished(bool ok);
@@ -44,6 +64,9 @@ private:
#endif
bool page_ready_ = false;
bool initialized_ = false;
+ bool trading_menu_ = false;
+ bool menu_open_ = false; // re-entrancy guard (avoid double menus)
+ QPointer<QWidget> filtered_proxy_; // the render widget we've filtered
QQueue<QString> pending_js_;
};
diff --git a/fincept-qt/src/ui/theme/StyleSheets.cpp b/fincept-qt/src/ui/theme/StyleSheets.cpp
index ad83e0131..53036ee26 100644
--- a/fincept-qt/src/ui/theme/StyleSheets.cpp
+++ b/fincept-qt/src/ui/theme/StyleSheets.cpp
@@ -671,54 +671,76 @@ QString equity_trading_styles() {
"#eqOeHeader { background: %8; border-bottom: 1px solid %3; }"
"#eqOeTitle { color: %12; font-weight: 700; font-size: 11px; "
" letter-spacing: 0.5px; background: transparent; border: none; }"
- "#eqOeMode { font-weight: 700; font-size: 11px; letter-spacing: 0.5px; "
+ "#eqOeMode { font-weight: 700; font-size: 10px; letter-spacing: 0.5px; "
+ " background: %1; border: 1px solid %3; border-radius: 3px; padding: 2px 8px; }"
+ "#eqOeScroll { background: %2; border: none; }"
+ "#eqOeContent { background: %2; }"
+ "#eqOeSep { background: %3; border: none; }"
+
+ /* BUY / SELL — filled segmented toggle */
+ "#eqBuyTab { background: %1; color: %7; border: 1px solid %3; border-right: none; "
+ " border-top-left-radius: 4px; border-bottom-left-radius: 4px; "
+ " font-size: 13px; font-weight: 800; letter-spacing: 1px; }"
+ "#eqBuyTab:hover { color: %15; background: %17; }"
+ "#eqBuyTab[active=\"true\"] { background: %15; color: #ffffff; border-color: %15; }"
+ "#eqSellTab { background: %1; color: %7; border: 1px solid %3; "
+ " border-top-right-radius: 4px; border-bottom-right-radius: 4px; "
+ " font-size: 13px; font-weight: 800; letter-spacing: 1px; }"
+ "#eqSellTab:hover { color: %11; background: %18; }"
+ "#eqSellTab[active=\"true\"] { background: %11; color: #ffffff; border-color: %11; }"
+
+ /* Order type — filled chips */
+ "#eqOeTypeBtn { background: %1; color: %7; border: 1px solid %3; border-radius: 3px; "
+ " padding: 2px 4px; font-size: 11px; font-weight: 700; }"
+ "#eqOeTypeBtn:hover { color: %4; border-color: %5; }"
+ "#eqOeTypeBtn[active=\"true\"] { background: %12; color: #ffffff; border-color: %12; }"
+
+ /* Symbol context line */
+ "#eqOeSymbol { color: %4; font-size: 12px; font-weight: 700; letter-spacing: 0.5px; "
+ " background: transparent; border: none; padding: 1px 0; }"
+
+ /* Live info box — LTP + balance, bright */
+ "#eqOeInfo { background: %1; border: 1px solid %3; border-radius: 4px; }"
+ "#eqOeMarketPrice { color: %14; font-size: 13px; font-weight: 700; "
+ " background: transparent; border: none; }"
+ "#eqOeBalance { color: %4; font-size: 13px; font-weight: 700; "
" background: transparent; border: none; }"
-
- "#eqBuyTab { background: transparent; color: %6; border: none; "
- " border-bottom: 2px solid transparent; padding: 4px 0; "
- " font-size: 12px; font-weight: 700; }"
- "#eqBuyTab:hover { color: %15; }"
- "#eqBuyTab[active=\"true\"] { color: %15; border-bottom-color: %15; }"
- "#eqSellTab { background: transparent; color: %6; border: none; "
- " border-bottom: 2px solid transparent; padding: 4px 0; "
- " font-size: 12px; font-weight: 700; }"
- "#eqSellTab:hover { color: %11; }"
- "#eqSellTab[active=\"true\"] { color: %11; border-bottom-color: %11; }"
-
- "#eqOeTypeBtn { background: transparent; color: %6; border: none; "
- " border-bottom: 2px solid transparent; padding: 1px 6px; "
- " font-size: 10px; font-weight: 700; }"
- "#eqOeTypeBtn:hover { color: %7; }"
- "#eqOeTypeBtn[active=\"true\"] { color: %4; border-bottom-color: %12; }"
"#eqOeLabel { color: %7; font-size: 11px; font-weight: 700; "
" letter-spacing: 0.5px; background: transparent; border: none; }"
"#eqOeInput { background: %1; border: 1px solid %3; color: %4; "
- " padding: 3px 6px; font-size: 12px; }"
+ " border-radius: 3px; padding: 4px 6px; font-size: 13px; }"
"#eqOeInput:focus { border-color: %5; }"
- "#eqOeInput:disabled { color: %9; }"
+ "#eqOeInput:disabled { color: %9; background: %2; }"
"#eqOeCombo { background: %1; border: 1px solid %3; color: %4; "
- " padding: 3px 6px; font-size: 12px; }"
+ " border-radius: 3px; padding: 4px 6px; font-size: 13px; }"
"#eqOeCombo:focus { border-color: %5; }"
+ "#eqOeCombo::drop-down { border: none; width: 18px; }"
"#eqOeCombo QAbstractItemView { background: %2; color: %4; "
" selection-background-color: %13; border: 1px solid %3; }"
- "#eqOeBalance { color: %14; font-size: 12px; font-weight: 700; "
+ "#eqOeBrokerage { color: %7; font-size: 11px; background: transparent; border: none; }"
+
+ /* Cost / margin summary */
+ "#eqOeSummary { background: %1; border: 1px solid %3; border-radius: 4px; }"
+ "#eqOeCost { color: %4; font-size: 13px; font-weight: 700; "
" background: transparent; border: none; }"
- "#eqOeMarketPrice { color: %6; font-size: 11px; background: transparent; border: none; }"
- "#eqOeCost { color: %6; font-size: 11px; background: transparent; border: none; }"
- "#eqOeStatus { font-size: 11px; background: transparent; border: none; }"
-
- "#eqBuySubmit { background: %17; color: %15; "
- " border: 1px solid %19; padding: 8px; font-weight: 700; font-size: 13px; }"
- "#eqBuySubmit:hover { background: %15; color: %1; }"
- "#eqSellSubmit { background: %18; color: %11; "
- " border: 1px solid %20; padding: 8px; font-weight: 700; font-size: 13px; }"
- "#eqSellSubmit:hover { background: %11; color: %4; }"
-
- "#eqAdvToggle { background: transparent; color: %6; border: none; "
- " font-size: 10px; font-weight: 700; letter-spacing: 0.5px; padding: 2px 0; }"
- "#eqAdvToggle:hover { color: %7; }"
+ "#eqOeMargin { color: %7; font-size: 11px; background: transparent; border: none; }"
+ "#eqOeStatus { font-size: 11px; font-weight: 600; background: transparent; border: none; }"
+
+ /* Submit — filled buy/sell */
+ "#eqBuySubmit { background: %15; color: #ffffff; "
+ " border: 1px solid %15; border-radius: 4px; padding: 10px; "
+ " font-weight: 800; font-size: 13px; letter-spacing: 0.5px; }"
+ "#eqBuySubmit:hover { background: %15; border-color: %4; }"
+ "#eqSellSubmit { background: %11; color: #ffffff; "
+ " border: 1px solid %11; border-radius: 4px; padding: 10px; "
+ " font-weight: 800; font-size: 13px; letter-spacing: 0.5px; }"
+ "#eqSellSubmit:hover { background: %11; border-color: %4; }"
+
+ "#eqAdvToggle { background: transparent; color: %7; border: none; "
+ " font-size: 11px; font-weight: 700; letter-spacing: 0.5px; padding: 3px 0; text-align: left; }"
+ "#eqAdvToggle:hover { color: %12; }"
/* ── Bottom panel ── */
"#eqBottomPanel { background: %2; border: 1px solid %3; }"
diff --git a/fincept-qt/src/ui/theme/ThemeManager.cpp b/fincept-qt/src/ui/theme/ThemeManager.cpp
index 11ea99571..55b668a76 100644
--- a/fincept-qt/src/ui/theme/ThemeManager.cpp
+++ b/fincept-qt/src/ui/theme/ThemeManager.cpp
@@ -102,6 +102,16 @@ QStringList ThemeManager::build_font_chain(const QString& preferred) {
if (name.endsWith('\'') || name.endsWith('"'))
name.chop(1);
name = name.trimmed();
+ // Reject private/system families (macOS exposes hidden families
+ // prefixed with '.', e.g. ".Apple Color Emoji UI",
+ // ".AppleSystemUIFont") and emoji/symbol fonts. The emoji font in
+ // particular *does* carry ASCII digit glyphs (keycap-emoji bases)
+ // but renders them grossly letter-spaced, so if it lands first in
+ // the chain every number in the UI renders mangled while letters
+ // fall through to the next family. Never let one poison the data
+ // font, even if a stale setting asks for it.
+ if (name.startsWith('.') || name.contains("emoji", Qt::CaseInsensitive))
+ continue;
if (!name.isEmpty() && !chain.contains(name, Qt::CaseInsensitive))
chain.append(name);
}
diff --git a/fincept-qt/src/ui/widgets/algo/ConditionBlock.cpp b/fincept-qt/src/ui/widgets/algo/ConditionBlock.cpp
index 6f1ceadae..bd26b73b7 100644
--- a/fincept-qt/src/ui/widgets/algo/ConditionBlock.cpp
+++ b/fincept-qt/src/ui/widgets/algo/ConditionBlock.cpp
@@ -55,6 +55,11 @@ void ConditionBlock::build_ui() {
remove_btn_->setObjectName(QStringLiteral("condBlockRemove"));
remove_btn_->setFixedSize(24, 24);
remove_btn_->setToolTip(tr("Remove condition"));
+ // Icon/close button: never take keyboard focus. Otherwise clicking it focuses
+ // the button, and when this block is deleted Qt hands focus to the next widget —
+ // the neighbouring row's editable indicator combo — which then shows a text
+ // caret, making "close" look like it opened a text field instead of removing.
+ remove_btn_->setFocusPolicy(Qt::NoFocus);
line1->addWidget(remove_btn_);
main_layout->addLayout(line1);
diff --git a/fincept-qt/src/ui/widgets/algo/GroupBlock.cpp b/fincept-qt/src/ui/widgets/algo/GroupBlock.cpp
index ee2908b0d..85e63ba21 100644
--- a/fincept-qt/src/ui/widgets/algo/GroupBlock.cpp
+++ b/fincept-qt/src/ui/widgets/algo/GroupBlock.cpp
@@ -63,6 +63,9 @@ void GroupBlock::build_ui() {
remove_btn_->setObjectName(QStringLiteral("condBlockRemove"));
remove_btn_->setFixedSize(24, 22);
remove_btn_->setToolTip(tr("Remove group"));
+ // See ConditionBlock: keep focus off the close button so deleting the group
+ // doesn't transfer the caret into an adjacent editable combo.
+ remove_btn_->setFocusPolicy(Qt::NoFocus);
header->addWidget(add_cond_btn_);
header->addWidget(add_group_btn_);
header->addWidget(remove_btn_);
diff --git a/fincept-qt/src/ui/widgets/algo/OperandEditor.cpp b/fincept-qt/src/ui/widgets/algo/OperandEditor.cpp
index 805bde744..9400012af 100644
--- a/fincept-qt/src/ui/widgets/algo/OperandEditor.cpp
+++ b/fincept-qt/src/ui/widgets/algo/OperandEditor.cpp
@@ -1,6 +1,9 @@
// src/ui/widgets/algo/OperandEditor.cpp
#include "ui/widgets/algo/OperandEditor.h"
+#include "ui/theme/Theme.h"
+
+#include <QAbstractItemView>
#include <QCompleter>
#include <QLineEdit>
#include <QVBoxLayout>
@@ -76,10 +79,26 @@ void OperandEditor::build_ui() {
indicator_combo_->setEditable(true);
indicator_combo_->setInsertPolicy(QComboBox::NoInsert);
indicator_combo_->lineEdit()->setPlaceholderText(tr("Search indicator…"));
+ // The drop-down view and the type-to-search completer popup are separate
+ // top-level list widgets the global stylesheet never reaches, so by default
+ // their rows render with near-invisible, vertically-clipped text. Style both
+ // to the dark theme explicitly: opaque background, readable row height, and
+ // clear hover/selection states.
+ const QString list_qss =
+ QString("QAbstractItemView { background:%1; color:%2; border:1px solid %3; "
+ "outline:0; selection-background-color:%4; selection-color:%5; }"
+ "QAbstractItemView::item { min-height:22px; padding:3px 8px; border:0; }"
+ "QAbstractItemView::item:hover { background:%6; }")
+ .arg(ui::colors::BG_RAISED(), ui::colors::TEXT_PRIMARY(), ui::colors::BORDER_MED())
+ .arg(ui::colors::ACCENT_BG(), ui::colors::TEXT_PRIMARY(), ui::colors::BG_HOVER());
+ if (auto* view = indicator_combo_->view())
+ view->setStyleSheet(list_qss);
if (auto* c = indicator_combo_->completer()) {
c->setCompletionMode(QCompleter::PopupCompletion);
c->setFilterMode(Qt::MatchContains);
c->setCaseSensitivity(Qt::CaseInsensitive);
+ if (auto* popup = c->popup())
+ popup->setStyleSheet(list_qss);
}
row->addWidget(indicator_combo_);
diff --git a/fincept-qt/src/ui/widgets/algo/SymbolSearchCombo.cpp b/fincept-qt/src/ui/widgets/algo/SymbolSearchCombo.cpp
index 3780f4b14..1e1bcdc76 100644
--- a/fincept-qt/src/ui/widgets/algo/SymbolSearchCombo.cpp
+++ b/fincept-qt/src/ui/widgets/algo/SymbolSearchCombo.cpp
@@ -1,6 +1,9 @@
// src/ui/widgets/algo/SymbolSearchCombo.cpp
#include "ui/widgets/algo/SymbolSearchCombo.h"
#include "services/algo_trading/AlgoTradingTypes.h"
+#include "ui/theme/Theme.h"
+
+#include <QAbstractItemView>
namespace fincept::ui::algo {
@@ -16,6 +19,21 @@ SymbolSearchCombo::SymbolSearchCombo(QWidget* parent)
completer_->setFilterMode(Qt::MatchContains);
setCompleter(completer_);
+ // The drop-down view and the completer popup are separate top-level lists the
+ // global stylesheet never reaches; style both so their rows stay readable in
+ // the dark theme instead of rendering near-invisible, clipped text.
+ const QString list_qss =
+ QString("QAbstractItemView { background:%1; color:%2; border:1px solid %3; "
+ "outline:0; selection-background-color:%4; selection-color:%5; }"
+ "QAbstractItemView::item { min-height:22px; padding:3px 8px; border:0; }"
+ "QAbstractItemView::item:hover { background:%6; }")
+ .arg(ui::colors::BG_RAISED(), ui::colors::TEXT_PRIMARY(), ui::colors::BORDER_MED())
+ .arg(ui::colors::ACCENT_BG(), ui::colors::TEXT_PRIMARY(), ui::colors::BG_HOVER());
+ if (auto* v = view())
+ v->setStyleSheet(list_qss);
+ if (auto* popup = completer_->popup())
+ popup->setStyleSheet(list_qss);
+
QStringList defaults;
defaults << services::algo::nifty50_symbols() << services::algo::bank_nifty_symbols();
defaults.removeDuplicates();